<template>
  <div>
    <ele-pro-table
      ref="table"
      :columns="bankColumns"
      :datasource="datasource"
      :need-page="false"
      class="table_list"
      @refresh="getMatterList"
      cache-key="user-setting-matter-process-2510181058"
    >
      <template v-slot:toolbar>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          class="ele-btn-icon"
          @click="openAddMatter"
        >
          新建
        </el-button>
      </template>

      <!-- 操作列 -->
      <template v-slot:action="{ row }">
        <el-popconfirm
          class="ele-action"
          title="确定要删除此事项吗？"
          @confirm="delMatter(row)"
        >
          <template v-slot:reference>
            <el-link type="danger" :underline="false" icon="el-icon-delete">
              删除
            </el-link>
          </template>
        </el-popconfirm>
        <el-link
          type="primary"
          :underline="false"
          icon="el-icon-edit"
          @click="openEditMatter(row)"
        >
          详情
        </el-link>
      </template>
    </ele-pro-table>

    <userSettingMatterAdd
      ref="userSettingMatterAddRef"
      @addMatter="addMatter"
      @editMatter="editMatter"
      notProduceTaskConfig
    />

    <ProductModal
      ref="ProductModalCorrelationRef"
      @changeProduct="changeRelateProduct"
      multiple
    ></ProductModal>
  </div>
</template>

<script>
  import {
    produceTaskRecordRules,
    produceTaskRecordRulesBatchSave,
    produceTaskRecordRulesGetById
  } from '@/api/producetaskrecordrules';
  import tableColumnsMixin from '@/mixins/tableColumnsMixin';
  import dictMixins from '@/mixins/dictMixins';
  import userSettingMatterAdd from './user-setting-matter-add.vue';
  import { mapGetters } from 'vuex';
  import { getTreeByPid } from '@/api/classifyManage';
  import ProductModal from '@/components/selectProduct/ProductModal.vue';

  export default {
    name: 'UserSettingMatter',
    mixins: [dictMixins, tableColumnsMixin],
    components: { userSettingMatterAdd, ProductModal },
    props: {
      // 工序id
      produceTaskId: {
        type: String,
        required: true
      },
      // 工序名称
      produceTaskName: {
        type: String,
        required: true
      }
    },
    data() {
      return {
        // 	记录规则报工类型 产前、过程、产后
        reportWorkType: '2',
        // 事项列表
        matterList: [],
        // 表格列
        bankColumns: [
          {
            columnKey: 'index',
            type: 'index',
            width: 45,
            align: 'center'
          },
          {
            prop: 'itemType',
            label: '类型',
            align: 'center',
            formatter: (row) => {
              return this.getDictValue('记录规则事项类型', row.itemType);
            }
          },
          {
            prop: 'executeMethod',
            label: '执行方式',
            align: 'center',
            formatter: (row) => {
              return this.getDictValue('记录规则执行方式', row.executeMethod);
            }
          },
          {
            prop: 'rulesName',
            label: '名称',
            align: 'center',
            formatter: (row) => {
              return row.rulesName || row.itemTaskName;
            }
          },
          {
            columnKey: 'action',
            label: '操作',
            align: 'center',
            slot: 'action'
          }
        ],
        // 添加事项列表
        addPOs: [],
        deletedIds: [],
        updatePOs: [],
        butLoading: false,
        relateProductMethod: null,
        params: {
          categoryLevels: [],
          products: []
        },
        relateProductMethodOpeions: [
          { label: '不关联', value: 0 },
          { label: '关联分类', value: 1 },
          { label: '关联产品', value: 2 }
        ],
        // 产品分类
        productCategory: []
      };
    },
    computed: {
      ...mapGetters(['dict']),
      // 根据报工类型过滤事项
      datasource() {
        return this.matterList.filter(
          (item) => item.reportWorkType == this.reportWorkType
        );
      },
      tabPaneList() {
        const list = this.dict['record_rules_report_work_type'] || [];
        // 只显示过程监测
        return list.filter((item) => item.dictCode + '' == '2');
      },
      productColumns() {
        return [
          {
            columnKey: 'index',
            type: 'index',
            width: 45,
            align: 'center',
            reserveSelection: true
          },
          {
            prop: 'code',
            label: '产品编码'
          },
          {
            prop: 'name',
            label: '产品名称',
            showOverflowTooltip: true
          },
          {
            prop: 'brandNum',
            label: '牌号'
          },
          {
            prop: 'modelType',
            label: '型号'
          },
          {
            prop: 'measuringUnit',
            label: '计量单位'
          },
          {
            prop: 'packingUnit',
            label: '包装单位'
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 110,
            align: 'center',
            resizable: false,
            slot: 'action',
            fixed: 'right'
          }
        ];
      }
    },
    created() {
      this.getProductCategory();
      this.getMatterList();
    },
    methods: {
      // 获取产品分类
      async getProductCategory() {
        let { data } = await getTreeByPid(9);
        console.log('产品分类', data);
        this.productCategory = data;
      },
      // 查询事项数据
      async getMatterList() {
        const { list } = await produceTaskRecordRules({
          // 工序id
          produceTaskId: this.produceTaskId,
          pageNum: 1,
          size: 9999,
          reportWorkType: this.reportWorkType
        });
        console.log('list', list);
        // 表格数据
        this.matterList = list;
      },
      // 删除事项
      async delMatter(row) {
        if (row.isUsing) {
          return this.$message.warning('事项正在使用中，无法删除');
        }

        // 事项列表过滤
        this.matterList = this.matterList.filter((item) => item.id !== row.id);
        // 如果是临时id，直接前端删除
        if (row.id.includes('tem')) {
          this.addPOs = this.addPOs.filter((item) => item.id !== row.id);
        } else {
          this.deletedIds.push(row.id);
        }
        // updatePOs 过滤
        this.updatePOs = this.updatePOs.filter((item) => item.id !== row.id);
      },
      // 打开添加事项
      openAddMatter() {
        this.$refs.userSettingMatterAddRef.openAdd();
      },
      openEditMatter(row) {
        this.$refs.userSettingMatterAddRef.openEdit(row);
      },
      addMatter(matter) {
        console.log('matter', matter);
        const id = 'tem' + new Date().getTime();
        // 添加事项
        this.matterList.push({
          ...matter,
          id: id,
          produceTaskId: this.produceTaskId,
          produceTaskName: this.produceTaskName,
          reportWorkType: this.reportWorkType
        });
        this.addPOs.push({
          ...matter,
          id: id,
          produceTaskId: this.produceTaskId,
          produceTaskName: this.produceTaskName,
          reportWorkType: this.reportWorkType
        });
        this.handleSort();
      },
      editMatter(matter) {
        console.log('matter', matter);
        // 编辑事项
        this.matterList = this.matterList.map((item) => {
          if (item.id === matter.id) {
            return {
              ...item,
              ...matter
            };
          }
          return item;
        });
        // 如果不是临时id，加入updatePOs
        if (!matter.id.includes('tem')) {
          // 先过滤掉之前的
          this.updatePOs = this.updatePOs.filter(
            (item) => item.id !== matter.id
          );
          this.updatePOs.push({
            ...matter,
            produceTaskId: this.produceTaskId,
            produceTaskName: this.produceTaskName,
            reportWorkType: this.reportWorkType
          });
        } else {
          // 如果是临时id，直接更新addPOs
          this.addPOs = this.addPOs.map((item) => {
            if (item.id === matter.id) {
              return {
                ...item,
                ...matter
              };
            }
            return item;
          });
        }
        this.handleSort();
      },
      // 事项排序 根据matterList的顺序
      handleSort() {
        this.matterList = this.matterList.map((item, index) => {
          item.sortNum = index;
          return item;
        });
        this.addPOs = this.addPOs.map((item) => {
          const matter = this.matterList.find((m) => m.id === item.id);
          if (matter) {
            return {
              ...item,
              sortNum: matter.sortNum
            };
          }
          return item;
        });
        this.updatePOs = this.updatePOs.map((item) => {
          const matter = this.matterList.find((m) => m.id === item.id);
          if (matter) {
            return {
              ...item,
              sortNum: matter.sortNum
            };
          }
          return item;
        });
      },
      // 确定保存事项
      async saveMatterList() {
        console.log('this.matterList', this.matterList);
        try {
          this.butLoading = true;

          await produceTaskRecordRulesBatchSave({
            addPOs: this.addPOs,
            deletedIds: this.deletedIds,
            produceTaskId: this.produceTaskId,
            produceTaskName: this.produceTaskName,
            updatePOs: this.updatePOs
          });
          this.handleClose();

          this.butLoading = false;
        } catch (error) {
          this.butLoading = false;
        }
      },
      // 关闭弹窗、清空数据
      handleClose() {
        this.getMatterList();
        this.addPOs = [];
        this.deletedIds = [];
        this.updatePOs = [];
        this.butLoading = false;
        this.reportWorkType = '2';
      },
      // 关联产品
      relateProductSelect() {
        this.$refs.ProductModalCorrelationRef.open(this.params.products);
      },
      changeRelateProduct(array) {
        console.log('paroduct list ', array);

        this.params.products = [
          ...this.params.products,
          ...array.filter(
            (i) => !this.params.products.some((cat) => cat.id === i.id)
          )
        ];
      }
    }
  };
</script>

<style scoped></style>
