<template>
  <ResizePageWrapper :formLeftWidth="320">
    <template #resizeLeft>
      <div class="left-box">
        <div class="left-btn-box">
          <a-button type="primary" v-auth="'BOM:import'" @click="handleImport"
            >导入产品BOM</a-button
          >
          <a-button v-auth="'BOM:export'" @click="handleExport">导出产品BOM</a-button>
          <a-button type="primary" v-auth="'BOM:add'" @click="handleCreate(true)">新增</a-button>
        </div>
        <ProductTree ref="treeRef" @select="handleSelect" />
      </div>
    </template>

    <template #resizeRight>
      <div class="rounded-2xl h-162px overflow-hidden">
        <div class="title">当前物料信息</div>
        <BasicTable @register="registerCurrentTable" class="current-box" v-if="hasMaterialInfo">
          <template #action="{ record }">
            <TableAction
              :actions="[
                {
                  label: '编辑',
                  auth: 'currentBOM:edit',
                  onClick: handleCurrentEdit.bind(null, record),
                },
                {
                  label: '删除',
                  auth: 'currentBOM:delete',
                  color: 'error',
                  onClick: handleDelete.bind(null, record),
                },
              ]"
            />
          </template>
        </BasicTable>
      </div>
      <div class="sub-box rounded-2xl">
        <div class="title relative"
          >子级物料信息
          <a-button
            type="primary"
            v-auth="'subBOM:add'"
            @click="handleCreate(false)"
            class="!absolute right-4 top-2 w-20 !rounded"
          >
            {{ t('新增') }}
          </a-button></div
        >
        <BasicTable @register="registerSubTable" v-if="hasMaterialInfo">
          <template #action="{ record }">
            <TableAction
              :actions="[
                {
                  label: '编辑',
                  auth: 'subBOM:edit',
                  onClick: handleSubEdit.bind(null, record),
                },
                {
                  label: '删除',
                  auth: 'subBOM:delete',
                  color: 'error',
                  onClick: handleDelete.bind(null, record),
                },
              ]"
            />
          </template>
        </BasicTable>
      </div>
    </template>
    <ImportModal
      @register="registerImportModal"
      importUrl="/caseErpBom/caseErpBom/import"
      @success="reload"
    />
    <ProductModal @register="registerModal" @success="reload" />
  </ResizePageWrapper>
</template>
<script lang="ts" setup>
  import { ref, createVNode, nextTick } from 'vue';
  import { BasicTable, useTable, TableAction, BasicColumn } from '/@/components/Table';
  import {
    getBomInfo,
    exportInfo,
    downloadTemplate,
    deleteBomMaterial,
  } from '/@/api/erp/bom/product';
  import { ResizePageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ImportModal } from '/@/components/Import';
  import { useModal } from '/@/components/Modal';
  import { downloadByData } from '/@/utils/file/download';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import ProductModal from './components/ProductModal.vue';
  import ProductTree from './components/ProductTree.vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';

  const { t } = useI18n();
  const columns: BasicColumn[] = [
    {
      title: '物料编号',
      dataIndex: 'code',
      resizable: true,
    },
    {
      title: '物料名称',
      dataIndex: 'name',
      resizable: true,
    },
    {
      title: '规格型号',
      dataIndex: 'model',
      width: 100,
      resizable: true,
    },
    {
      title: '物料类别',
      dataIndex: 'typeName',
      width: 150,
      resizable: true,
    },
    {
      title: '数量',
      dataIndex: 'count',
      width: 100,
      resizable: true,
    },
    {
      title: '单位',
      dataIndex: 'unitName',
      width: 100,
      resizable: true,
    },
    {
      title: '物料属性',
      dataIndex: 'propertyName',
      resizable: true,
    },
  ];

  const { notification } = useMessage();
  const { hasPermission } = usePermission();

  const selectBomId = ref('');
  const subDataSource = ref([]);
  const treeRef = ref();
  const hasMaterialInfo = ref(false);

  const [registerModal, { openModal }] = useModal();
  const [registerImportModal, { openModal: openImportModal }] = useModal();

  const [registerCurrentTable, { reload: reloadCurrentTable }] = useTable({
    //title: '当前物料信息',
    api: getBomInfo,
    rowKey: 'id',
    columns,
    beforeFetch: () => {
      return { id: selectBomId.value };
    },
    afterFetch: (res) => {
      subDataSource.value = res.length ? res[0].childList || [] : [];
    },
    striped: false,
    showIndexColumn: false,
    useSearchForm: false,
    pagination: false,
    actionColumn: {
      width: 88,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    customRow: (record) => {
      return {
        ondblclick: () => {
          if (hasPermission('currentBOM:edit')) {
            handleCurrentEdit(record);
          }
        },
      };
    },
  });
  const [registerSubTable, { reload: reloadSubTable }] = useTable({
    //title: '子级物料信息',
    dataSource: subDataSource,
    rowKey: 'id',
    columns,
    striped: false,
    showIndexColumn: false,
    useSearchForm: false,
    pagination: false,
    actionColumn: {
      width: 88,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    customRow: (record) => {
      return {
        ondblclick: () => {
          if (hasPermission('subBOM:edit')) {
            handleSubEdit(record);
          }
        },
      };
    },
  });

  function handleCreate(isFirst) {
    openModal(true, {
      isUpdate: false,
      parentId: isFirst ? '' : selectBomId.value,
    });
  }

  function handleSubEdit(record: Recordable) {
    openModal(true, {
      id: record.id,
      isUpdate: true,
      parentId: selectBomId.value,
    });
  }

  function handleCurrentEdit(record: Recordable) {
    openModal(true, {
      id: record.id,
      isUpdate: true,
    });
  }

  const handleDelete = (record: Recordable) => {
    Modal.confirm({
      title: t('提示信息'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('是否确认删除？'),
      okText: t('确认'),
      cancelText: t('取消'),
      async onOk() {
        await deleteBomMaterial(record.id);
        notification.success({
          message: t('提示'),
          description: t('删除成功'),
        });
        reload();
      },
      onCancel() {},
    });
  };

  const handleSelect = (id = '') => {
    selectBomId.value = id;
    hasMaterialInfo.value = !!selectBomId.value;
    if (hasMaterialInfo.value) {
      nextTick(() => {
        reloadCurrentTable();
      });
    }
  };

  const handleImport = () => {
    openImportModal(true, {
      title: t('快速导入'),
      api: downloadTemplate,
      templateTitle: '产品BOM模板',
    });
  };
  const handleExport = async () => {
    const res = await exportInfo();
    downloadByData(
      res.data,
      '产品BOM.xlsx',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
  };

  const reload = () => {
    reloadCurrentTable();
    reloadSubTable();
    treeRef.value.fetch();
  };
</script>
<style lang="less" scoped>
  .left-box {
    overflow: hidden;
    height: 100%;

    .left-btn-box {
      padding: 10px 16px 0;
      border-bottom: 1px solid #eee;

      :deep(.ant-btn) {
        padding: 4px 12px;
        font-size: 12px;
        border-radius: 3px;
        margin-right: 8px;
        margin-bottom: 10px;

        &:nth-child(2) {
          color: #fff;
          background: #e6a23c;
          border-color: #e6a23c;
        }
      }
    }
  }

  .current-box {
    height: 180px;
    overflow: hidden;

    :deep(.ant-table) {
      height: auto !important;
    }
  }

  .sub-box {
    height: calc(100% - 162px);

    :deep(.ant-table-container) {
      height: calc(100% - 50px);
    }
  }

  .title {
    display: flex;
    padding: 18px 0 14px 16px;
    background: #fff;
    border-bottom: 1px solid #ddd;
    border-radius: 16px 16px 0 0;
    height: 50px;

    &::before {
      width: 4px;
      height: 16px;
      background: @primary-color;
      border-radius: 2px;
      content: '';
      margin-right: 8px;
      display: block;
      margin-top: 4px;
    }
  }

  :deep(.ant-table.ant-table-middle .ant-table-thead > tr > th:first-child) {
    border-radius: 0 !important;
  }

  :deep(.ant-table.ant-table-middle .ant-table-header .ant-table-thead tr th:nth-last-child(2)) {
    border-radius: 0;
  }

  :deep(.vben-basic-table .ant-table-tbody > tr > td) {
    &:first-child {
      border-bottom-left-radius: 16px;
    }

    &:last-child {
      border-bottom-right-radius: 16px;
    }
  }
</style>
