<template>
  <w-card class="material-master">
    <div v-if="visible">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <w-form @keyup.enter.native="searchQuery" layout="inline">
          <w-row :gutter="10">
            <w-col :xl="5" :lg="5" :md="8" :sm="24">
              <w-auto-complete
                v-model="nameComp"
                placeholder="请选择企业"
                :pageSize="20"
                :params="{ type: '1' }"
                format="name"
                url="sys/tenant/queryDict"
                @change="handleChange"
                @getSelectedObj="handleGetSelectedObj"
              />
            </w-col>
            <w-col :xl="5" :lg="5" :md="8" :sm="24">
              <j-multi-select-tag
                v-model="queryParam.status"
                dict-code="MergerMaterialMasterStatus"
                placeholder="请选择状态"
              />
            </w-col>
            <w-col :xl="5" :lg="5" :md="8" :sm="24">
              <w-input v-model="queryParam.copImgNo" placeholder="请输入料号" />
            </w-col>

            <template v-if="toggleSearchStatus">
              <w-col :xl="5" :lg="5" :md="8" :sm="24">
                <w-input v-model="queryParam.codeTs" placeholder="请输入商品编码" />
              </w-col>
              <w-col :xl="5" :lg="5" :md="8" :sm="24">
                <AppprovalUserSelect v-model="queryParam.demanderId" placeholder="请选择需求人" />
              </w-col>
            </template>

            <w-col :xl="5" :lg="5" :md="8" :sm="24">
              <span v-has="'MaterialMaster:query'" class="table-page-search-submitButtons">
                <w-button @click="searchQuery" type="primary" icon="search">搜索</w-button>
                <w-button @click="searchReset" type="primary">重置</w-button>
                <j-super-query ref="superQueryModal" :field-list="refColumns" @handleSuperQuery="handleSuperQuery" />
                <a class="unfold-fold-status" @click="handleToggleSearch">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
                </a>
              </span>
            </w-col>

            <div v-has="'MaterialMaster:export'" class="leftArea">
              <div class="filterBox">
                <span @click="exportExcel()" class="iconfont icon-download-2"></span>
              </div>
            </div>
          </w-row>
        </w-form>
      </div>
      <!-- 查询区域-END -->

      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <!-- <w-button @click="handleAdd" v-has="'MaterialMaster:add'" type="primary"> 新增 </w-button> -->
        <w-button @click="handleCollect" v-has="'MaterialMaster:collect'" type="primary"> 要素采集 </w-button>
        <w-button @click="handleElementComplete" v-has="'MaterialMaster:elementComplete'" type="primary">
          要素采集完成
        </w-button>
        <w-button @click="handleCopy" v-has="'MaterialMaster:copy'" type="primary"> 复制 </w-button>
        <w-button @click="handleConfirm" v-has="'MaterialMaster:confirm'" type="primary"> 确认 </w-button>
        <w-button @click="handleElemImport" v-has="'MaterialMaster:elemImport'" type="primary"> 申报要素导入 </w-button>
        <w-button @click="handleElemExport" v-has="'MaterialMaster:elemExport'" type="primary"> 申报要素导出 </w-button>
        <!-- <w-button @click="batchDel" type="danger" v-has="'MaterialMaster:del'">删除</w-button> -->
      </div>

      <!-- table区域-begin -->
      <div>
        <w-fit-container :fit-size="185" element-type="grid">
          <a-table
            ref="table"
            :id="refColumnsKey"
            :scroll="getTableScroll(1200)"
            :columns="refColumns"
            :data-source="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :custom-header-row="customHeaderRow"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            @change="handleTableChange"
            size="middle"
            :components="resizableComponents"
            bordered
            :custom-row="selectRow"
            row-key="id"
            class="j-table-force-nowrap"
            :rowClassName="rowClassName"
          >
            <!-- <template slot="copImgNo" slot-scope="text, record">
              <a @click="handleEdit(record)">{{ record.copImgNo }}</a>
            </template> -->

            <template slot="codeTs" slot-scope="text, record">
              <a-popover placement="top" trigger="click" arrow-point-at-center>
                <template slot="content">
                  <div v-if="showContent[record.id]">
                    <p>商品描述：{{ showContent[record.id].gname ?? '-' }}</p>
                    <p>申报要素：{{ showContent[record.id].elementNames ?? '-' }}</p>
                  </div>
                </template>
                <a @click="loadPopoverContent(record)">{{ record.codeTs }}</a>
              </a-popover>
            </template>

            <span slot="action" slot-scope="text, record">
              <a @click="handleEdit(record)" v-has="'MaterialMaster:edit'">编辑</a>
              <!-- <span v-has="'MaterialMaster:del'">
                <w-divider type="vertical" />
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </span> -->
            </span>
          </a-table>
        </w-fit-container>
      </div>
    </div>
    <w-table-columns-win ref="choose" @columnsChange="columnsChange" @resetColumns="resetColumns" :columns="columns" />
    <MaterialMasterModal ref="modalForm" @ok="modalFormOk" @close="modalFormClose" />
    <MaterialMasterModalCopy ref="MaterialMasterModalCopy" @ok="modalFormOk" @close="modalFormClose" />
    <MaterialMasterModalCollect ref="MaterialMasterModalCollect" @ok="modalFormOk" @close="modalFormClose" />
    <excel-import-model ref="importModel" />
    <ExcelExportModel ref="excelExport" :hidden-columns="hiddenColumns" />
  </w-card>
</template>

<script>
import { postAction } from '@/api/manage';
import { JeecgListMixin, WGridResizeByCssMixin } from '@/mixins/JeecgListMixin';
import { mixinDevice } from '@/utils/mixin';
import ExcelExportModel from '@/views/excel/modules/ExcelExportModel.vue';
import ExcelImportModel from '@/views/excel/modules/ExcelImportModel.vue';
import { filterDictTextByFormatCache, initeCusDictItemsFrom } from '@comp/dict/JDictSelectUtil';
import MaterialMasterModal from './modules/MaterialMasterModal.vue';
import MaterialMasterModalCopy from './modules/MaterialMasterModalCopy.vue';
import MaterialMasterModalCollect from './modules/MaterialMasterModalCollect.vue';
import AppprovalUserSelect from '@/components/AppprovalUserSelect/index';
import { getAction } from '@/api/manage';
import qs from 'qs';

export default {
  name: 'MaterialMaster',
  mixins: [JeecgListMixin, mixinDevice, WGridResizeByCssMixin],
  components: {
    MaterialMasterModal,
    MaterialMasterModalCopy,
    MaterialMasterModalCollect,
    ExcelExportModel,
    ExcelImportModel,
    AppprovalUserSelect,
  },
  data() {
    return {
      description: '物料主数据',
      initeLoadData: false,
      hiddenColumns: false,
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          ellipsis: true,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          title: '企业名称',
          align: 'left',
          width: 230,
          ellipsis: true,
          sorter: true,
          dataIndex: 'compName',
          // customRender: (text, record) => {
          //   if (record.compNo) {
          //     return record.compNo + '-' + record.compName
          //   } else {
          //     return '-'
          //   }
          // },
        },
        {
          title: '料号',
          align: 'center',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'copImgNo',
          scopedSlots: { customRender: 'copImgNo' },
        },
        {
          title: '状态',
          align: 'center',
          width: 120,
          ellipsis: true,
          sorter: true,
          dataIndex: 'status',
          customRender: (text) => {
            return filterDictTextByFormatCache('MergerMaterialMasterStatus', text);
          },
        },
        {
          title: '税号变更',
          align: 'center',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'taxChange',
          customRender: (text) => {
            return filterDictTextByFormatCache('yn', text);
          },
        },
        {
          title: '供应商名称',
          align: 'center',
          width: 200,
          ellipsis: true,
          sorter: true,
          dataIndex: 'supplierName',
          customRender: (text, record) => {
            if (record.supplierId) {
              return record.supplierId + '-' + record.supplierName;
            } else {
              return '-';
            }
          },
        },
        {
          title: '物料名称',
          align: 'left',
          width: 130,
          ellipsis: true,
          sorter: true,
          dataIndex: 'materialName',
        },
        {
          title: '物料描述',
          align: 'left',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'materialDesc',
        },
        {
          title: 'ERP单位',
          align: 'center',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'erpUnit',
        },
        {
          title: '研发分类',
          align: 'left',
          width: 160,
          ellipsis: true,
          sorter: true,
          dataIndex: 'developType',
        },
        {
          title: '供应商细化标志',
          align: 'center',
          width: 120,
          ellipsis: true,
          sorter: true,
          dataIndex: 'supplierRefineFlag',
          customRender: (text) => {
            return filterDictTextByFormatCache('yn', text);
          },
        },
        {
          title: '商品编码',
          align: 'center',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'codeTs',
          scopedSlots: { customRender: 'codeTs' },
        },
        {
          title: '商品名称',
          align: 'left',
          width: 140,
          ellipsis: true,
          sorter: true,
          dataIndex: 'gname',
        },
        {
          title: '报关成交单位',
          align: 'center',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'unit',
          customRender: (text, record) => {
            if (record.unit) {
              return record.unit + '-' + record.unitName;
            } else {
              return '-';
            }
          },
        },
        {
          title: '单位转换因子',
          align: 'center',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'unitConversionFactor',
        },
        {
          title: '监管类别名称',
          align: 'center',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'regulatoryType',
          customRender: (text, record) => {
            if (record.regulatoryType) {
              return record.regulatoryType + '-' + record.regulatoryTypeName;
            } else {
              return '-';
            }
          },
        },
        {
          title: '法定第一单位',
          align: 'center',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'unit1',
          customRender: (text, record) => {
            if (record.unit1) {
              return record.unit1 + '-' + record.unit1Name;
            } else {
              return '-';
            }
          },
        },
        {
          title: '法一转换因子',
          align: 'center',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'unit1ConversionFactor',
        },
        {
          title: '法定第二单位',
          align: 'center',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'unit2',
          customRender: (text, record) => {
            if (record.unit2) {
              return record.unit2 + '-' + record.unit2Name;
            } else {
              return '-';
            }
          },
        },
        {
          title: '法二转换因子',
          align: 'center',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'unit2ConversionFactor',
        },
        {
          title: '监管证件代码',
          align: 'center',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'controlMa',
        },
        {
          title: '商检证件代码',
          align: 'center',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'quanType',
        },
        {
          title: '规格型号',
          align: 'left',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'gmodel',
        },
        {
          title: '数据来源',
          align: 'center',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'dataSources_dictText',
          // dataIndex: 'dataSources',
          // customRender: (text) => {
          //   return filterDictTextByFormatCache('MergeSource', text)
          // },
        },
        {
          title: '需求人',
          align: 'center',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'demanderId',
          customRender: (text, record) => {
            if (record.demanderId) {
              return record.demanderId + '-' + record.demander;
            } else {
              return '-';
            }
          },
        },
        {
          title: '要素采集发起时间',
          align: 'center',
          width: 140,
          ellipsis: true,
          sorter: true,
          dataIndex: 'elementInitTime',
        },
        {
          title: '要素采集回复时间',
          align: 'center',
          width: 140,
          ellipsis: true,
          sorter: true,
          dataIndex: 'elementReplyTime',
        },
        {
          title: '确认时间',
          align: 'center',
          width: 140,
          ellipsis: true,
          sorter: true,
          dataIndex: 'confirmTime',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 80,
          ellipsis: true,
          scopedSlots: { customRender: 'action' },
          fixed: 'right',
        },
      ],
      url: {
        list: '/merger/mergerMaterialMaster/list',
        delete: '/merger/mergerMaterialMaster/delete',
        deleteBatch: '/merger/mergerMaterialMaster/deleteBatch',
        exportXlsUrl: '/merger/mergerMaterialMaster/exportXls',
        importExcelUrl: '/merger/mergerMaterialMaster/importExcel',
        confirmWarning: '/merger/mergerMaterialMaster/confirmWarning',
        confirm: 'merger/mergerMaterialMaster/confirm',
        elementFinishs: 'merger/mergerMaterialMaster/elementFinishs',
        // 申报要素
        elemExportXlsUrl: '/merger/mergerMaterialMaster/elementExportXls',
        elemImportExcelUrl: '/merger/mergerMaterialMaster/elementImportExcel',
      },
      // 用对象存储不同记录的popover内容，避免重复请求
      popoverContent: {},
      showContent: {},
      initQueryParam: {
        status: '000,010,020',
      },
      nameComp: '',
    };
  },
  created() {
    // 邮件链接跳转
    if (this.$route.query?.id) {
      this.$nextTick(() => {
        this.handleEdit({ id: this.$route.query.id });
      });
    }
    this.queryParam = {
      ...this.initQueryParam,
    };
  },
  methods: {
    /* 先加载字典、后加载数据 */
    async initDictConfig() {
      await initeCusDictItemsFrom('cus_country,code_name,cus_code');
      this.loadData();
    },
    /* 如果不存在要清掉 */
    handleChange(code) {
      if (!code) {
        this.handleGetSelectedObj(false);
      }
    },
    /* 获取选择的数据 */
    handleGetSelectedObj(obj) {
      if (obj && obj.name) {
        this.queryParam.compName = obj.name;
      } else {
        delete this.queryParam.compName;
      }
    },

    async loadPopoverContent(record) {
      this.$set(this, 'showContent', {});
      if (!record.codeTs) {
        return;
      }

      if (this.popoverContent[record.id]) {
        setTimeout(() => {
          this.$set(this.showContent, record.id, this.popoverContent[record.id]);
        }, 100);
        return;
      }

      const res = await getAction('/cusHscode/list', {
        codeTS: record.codeTs,
      });
      if (res.success && res.result.records.length > 0) {
        this.$set(this.popoverContent, record.id, {
          gname: res.result.records[0].gname,
          elementNames: res.result.records[0].elementNames,
        });
        this.$set(this.showContent, record.id, {
          gname: res.result.records[0].gname,
          elementNames: res.result.records[0].elementNames,
        });
      } else if (res.success && res.result.records.length === 0) {
        this.$message.warning('未查询到此商品编码的信息');
      } else {
        this.$message.warning(res.message);
      }
    },
    /* 表头的导出 */
    exportExcel() {
      this.hiddenColumns = false;
      const para = this.getQueryParams();
      para.ids = this.selectedRowKeys;
      this.$refs.excelExport.show(this.url.exportXlsUrl, para, this.columns, 'MERGER_MATERIAL_MASTER');
    },
    /* 复制 */
    handleCopy() {
      if (this.selectedRowKeys.length !== 1) {
        this.$message.warning('请选择仅一条数据进行操作！');
        return;
      }
      this.$nextTick(() => {
        this.$refs.MaterialMasterModalCopy.start(this.selectedRowKeys[0]);
      });
    },
    /* 要素采集 */
    handleCollect() {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning('请至少选择一条数据进行操作！');
        return;
      }
      if (this.selectedRowKeys.length > 50) {
        this.$message.warning('最多只能选择50条数据进行操作!');
        return;
      }
      this.$nextTick(() => {
        this.$refs.MaterialMasterModalCollect.start(this.selectedRowKeys.join(','));
      });
    },
    /* 要素采集完成 */
    handleElementComplete() {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning('请至少选择一条数据进行操作！');
        return;
      }
      if (this.selectedRowKeys.length > 50) {
        this.$message.warning('最多只能选择50条数据进行操作!');
        return;
      }
      const that = this;
      const ids = that.selectedRowKeys.join(',');
      that.$confirm({
        content: '请确认是否批量要素采集完成？',
        onOk: function () {
          that.loading = true;
          postAction(that.url.elementFinishs, qs.stringify({ ids }))
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message ? res.message : '批量要素采集成功！');
                that.loadData();
              } else {
                that.$message.warning(res.message);
              }
            })
            .finally(() => {
              that.loading = false;
            });
        },
      });
    },
    /* 确认 */
    handleConfirm() {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning('请选择至少一条数据进行操作！');
        return;
      }
      const that = this;
      that.$confirm({
        content: '是否确认数据？',
        onOk: function () {
          that.loading = true;
          postAction(that.url.confirmWarning, qs.stringify({ ids: that.selectedRowKeys.join(',') })).then((res) => {
            if (res.success) {
              that.handleConfirm2();
            } else {
              that.$confirm({
                content: `${res.message}，是否继续确认数据？`,
                onOk: function () {
                  that.handleConfirm2();
                },
                onCancel: function () {
                  that.loading = false;
                },
              });
            }
          });
        },
      });
    },
    handleConfirm2() {
      postAction(this.url.confirm, qs.stringify({ ids: this.selectedRowKeys.join(',') }))
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.loadData();
          } else {
            this.$message.warning(res.message);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    rowClassName(record) {
      if (record.taxChange === '1') {
        return 'addStyle';
      } else {
        return '';
      }
    },
    /* 申报要素导入 */
    handleElemImport() {
      this.$refs.importModel.show(this.url.elemImportExcelUrl, 'MERGER_MATERIAL_MASTER_ELEMENT', {
        // headId: this.head.id
      });
    },
    /* 申报要素导出 */
    handleElemExport() {
      this.hiddenColumns = true;
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning('请至少选择一条数据进行操作！');
        return;
      }
      if (this.selectedRowKeys.length > 50) {
        this.$message.warning('最多只能选择50条数据进行操作!');
        return;
      }
      this.$refs.excelExport.show(
        this.url.elemExportXlsUrl,
        {
          ids: this.selectedRowKeys,
          id: this.selectedRowKeys.join(','),
        },
        this.columns,
        'MERGER_MATERIAL_MASTER_ELEM_EXP'
      );
    },
    searchReset() {
      this.queryParam = {
        ...this.initQueryParam,
      };
      this.nameComp = '';
      this.$refs.superQueryModal.handleReset();
      this.onClearSelected();
    },
  },
};
</script>
<style lang="less">
.material-master {
  .addStyle {
    background-color: #fdd2d8;
  }
}
</style>
