<template>
  <el-form ref="form" :model="form" :rules="rules">
    <ele-pro-table
      ref="table"
      :needPage="false"
      :columns="columns"
      max-height="500px"
      :datasource="form.datasource"
      class="time-form"
      :selection.sync="selection"
      @columns-change="handleColumnChange"
      :cache-key="cacheKeyUrl"
    >
      <template v-slot:files="scope">
        <el-form-item prop="files">
          <fileMain v-model="scope.row.files" type="view"></fileMain>
        </el-form-item>
      </template>
      <template v-slot:taskName="scope">
        <el-form-item
          style="margin-bottom: 20px"
          :prop="'datasource.' + scope.$index + '.taskName'"
        >
          <el-input
            v-model="scope.row.taskName"
            placeholder="请选择"
            style="width: 60%; margin-right: 10px"
            disabled
          ></el-input>
          <el-button
            v-if="scope.row.productCode"
            size="small"
            type="primary"
            @click.native="handleTaskinstance(scope.row, scope.$index)"
            >选择
          </el-button>
        </el-form-item>
      </template>
      <template v-slot:supplierIds="scope">
        <el-form-item prop="supplierIds">
          <el-select
            v-model="scope.row['supplierIds']"
            clearable
            filterable
            multiple
            collapse-tags
          >
            <el-option
              v-for="i in scope.row.supplierList"
              :key="i.id"
              :value="i.id"
              :label="i.name"
            ></el-option>
          </el-select>
        </el-form-item>
      </template>

      <!-- 操作列 -->

      <!-- <template v-slot:[item.slot]="scope" v-for="item in supplierList">
        <el-form-item
          style="margin-bottom: 20px"
          :prop="'datasource.' + scope.$index + '.' + item.prop"
          :rules="{
            required: true,
            message: '请输入',
            trigger: 'blur'
          }"
        >
          <el-input
            type="input"
            v-model="scope.row[item.prop]"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </template>
      <template v-slot:[item.headerSlot]="scope" v-for="item in supplierList">
        <el-form-item style="margin-bottom: 20px">
          <span>{{ item.label }}</span>
          <fileUpload
            v-model="item.files"
            module="main"
            :showLib="false"
            :limit="1"
          />
        </el-form-item>
      </template> -->
      <template v-slot:add="scope">
        <el-form-item style="margin-bottom: 20px">
          <el-button type="primary" @click="openSupplier(scope.row)"
            >新增报价单</el-button
          >
        </el-form-item>
      </template>

      <template v-slot:action="scope">
        <el-popconfirm
          class="ele-action"
          title="确定要删除吗？"
          @confirm="remove(scope.$index, scope.row.productCode)"
        >
          <template v-slot:reference>
            <el-link type="danger" :underline="false" icon="el-icon-delete">
              删除
            </el-link>
          </template>
        </el-popconfirm>
      </template>
    </ele-pro-table>
    <taskinstance-dialog
      ref="taskinstanceDialogRef"
      v-if="taskinstanceDialogFlag"
      @saveTaskInstance="saveTaskInstance"
      :visible.sync="taskinstanceDialogFlag"
    ></taskinstance-dialog>
  </el-form>
</template>
<script>
  import { numberReg } from 'ele-admin';
  import dictMixins from '@/mixins/dictMixins';
  import fileUpload from '@/components/upload/fileUpload';
  import { getFile } from '@/api/system/file';
  import { getInventoryTotalAPI } from '@/api/wms';
  import { getByCode } from '@/api/system/dictionary-data';
  // import fileMain from '@/components/addDoc/index.vue';
  import taskinstanceDialog from '@/BIZComponents/procedure/taskinstanceDialog.vue';
  import { lbjtList } from '@/enum/dict.js';
  import tabMixins from '@/mixins/tableColumnsMixin';
  import { levelList } from '@/enum/dict.js';

  export default {
    mixins: [dictMixins,tabMixins],
    components: {
      // fileMain,
      fileUpload,
      taskinstanceDialog
    },
    props: {
      acceptUnpack: {
        default: ''
      },
      isSupplier: {
        default: true
      }
    },
    data() {
      const defaultForm = {
        key: null,
        endTime: '',
        isFirst: 0,
        name: ''
      };

      return {
        taskinstanceDialogFlag: false,
        cacheKeyUrl:"eom-purchasingManage-inventoryTable",
        numberReg,
        defaultForm,
        supplierList: [],
        selection: [],
        // resultList:'',
        form: {
          datasource: []
        },
        dictList: {},
        files: [],
        rules: {}
      };
    },
    computed: {
      canHandl() {
        return this.form.datasource.length;
      },
      columns() {
        return [
          {
            width: 50,
            label: '序号',
            type: 'index',
            columnKey: 'index',
            align: 'center',
            fixed: 'left'
          },
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            fixed: 'left',
            show: this.isSupplier,
            selectable: (row, index) => {
              return row.isInquiry != 2;
            }
          },
          {
            minWidth: 180,
            slot: 'add',
            label: '新增报价',
            showOverflowTooltip: true,
            fixed: 'left',
            align: 'center'
          },
          {
            minWidth: 100,
            label: '状态',
            fixed: 'left',
            filters: [
              { value: 0, text: '未核价' },
              { value: 1, text: '部分核价' },
              { value: 2, text: '全部核价完成' }
            ],
            filterMethod: this.isInquiryFn,
            // sortable: true,
            formatter: (row, column) => {
              return row.isInquiry==1?'部分核价':row.isInquiry==2?'全部核价完成':row.isInquiry==3?'核价中':'未核价'
            },
            align: 'center'
          },
          {
            minWidth: 100,
            prop: 'productCategoryName',
            label: '分类',
            slot: 'productCategoryName',
            showOverflowTooltip: true,
            fixed: 'left',
            align: 'center'
          },
          {
            minWidth: 100,
            prop: 'productCode',
            label: '编码',
            fixed: 'left',
            slot: 'productCode',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 140,
            prop: 'productName',
            fixed: 'left',
            label: '名称',
            slot: 'productName',
            headerSlot: 'productNameHeader',
            showOverflowTooltip: true,
            align: 'center'
          },

          {
            minWidth: 200,
            prop: 'supplierIds',
            label: '供应商选择',
            slot: 'supplierIds',
            showOverflowTooltip: true,
            align: 'center',
            filters: this.supplierList,
            filterMethod: this.filterMethod
          },
          {
            minWidth: 100,
            prop: 'productBrand',
            label: '牌号',
            slot: 'productBrand',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 80,
            prop: 'totalCount',
            label: '数量',
            slot: 'totalCount',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 120,
            prop: 'goodsLevel',
            label: '物品级别',
            formatter: (_row, _column, cellValue) => {
              return levelList.find((item) => item.value == _row.goodsLevel)
                ?.label;
            },
            align: 'center'
          },
          {
            minWidth: 80,
            prop: 'availableCountBase',
            label: '库存数量',
            slot: 'availableCountBase',
            align: 'center'
          },
          {
            minWidth: 80,
            prop: 'measuringUnit',
            label: '单位',
            slot: 'measuringUnit',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 130,
            prop: 'modelType',
            label: '型号',
            slot: 'modelType',
            showOverflowTooltip: true,
            align: 'center'
          },

          {
            minWidth: 120,
            prop: 'specification',
            label: '规格',
            slot: 'specification',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            width: 150,
            prop: 'inquiryNum',
            label: '已核价数量',
            align: 'center'
          },
        
          {
            width: 120,
            prop: 'totalWeight',
            label: '重量',
            slot: 'totalWeight',
            align: 'center'
          },
          {
            width: 150,
            prop: 'inquiryWeight',
            label: '已核价重量',
            align: 'center'
          },
          {
            minWidth: 220,
            prop: 'taskName',
            label: '工序',
            slot: 'taskName',
            align: 'center'
          },
          {
            width: 110,
            prop: 'batchNo',
            label: '批次号',
            slot: 'batchNo',
            align: 'center'
          },
          {
            prop: 'provenance',
            label: '产地',
            slot: 'provenance',
            align: 'center',
            minWidth: 200,
            showOverflowTooltip: true,
            formatter: (row, column) => {
       
              return row.provenance && row.provenance.length
                ? row.provenance
                    .map((item) => this.getDictValue('产地', item ))
                    .join(',')
                : '';
            }
          },
  
          // {
          //     width: 120,
          //     prop: 'singleWeight',
          //     label: '单重',
          //     slot: 'singleWeight',
          //     align: 'center'
          //   },

          {
            minWidth: 120,
            prop: 'imgCode',
            align: 'center',
            label: '图号/件号',
            showOverflowTooltip: true
          },
          {
            minWidth: 120,
            prop: 'produceType',
            align: 'center',
            label: '属性类型',
            showOverflowTooltip: true,
            formatter: (row, column) => {
              if(row.produceType){
                return row.produceType.map(item=>{
                  return lbjtList[item]
                }).toString()
              }
          
            }
          },
          // {
          //   minWidth: 120,
          //   prop: 'approvalNumber',
          //   align: 'center',
          //   label: '批准文号',
          //   showOverflowTooltip: true
          // },
          
          {
            minWidth: 120,
            prop: 'packingSpecification',
            align: 'center',
            label: '包装规格',
            showOverflowTooltip: true
          },
          // {
          //   width: 130,
          //   prop: 'brand',
          //   label: '品牌',
          //   slot: 'brand'
          // },
          {
            minWidth: 170,
            prop: 'expectReceiveDate',
            label: '到货日期',
            slot: 'expectReceiveDate',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 140,
            prop: 'files',
            label: '附件',
            slot: 'files',
            align: 'center'
          },
          {
            minWidth: 220,
            prop: 'remark',
            label: '备注',
            slot: 'remark',
            showOverflowTooltip: true,
            align: 'center'
          }
          // {
          //   columnKey: 'action',
          //   label: '操作',
          //   width: 120,
          //   align: 'center',
          //   resizable: false,
          //   slot: 'action',
          //   fixed: 'right',
          //   showOverflowTooltip: true
          // }
        ];
      }
    },
    created() {
     
      this.requestDict('生产类型');
    },
    methods: {
      getDictV(code, val) {
        if (!this.dictList[code]) return '';
        return this.dictList[code].find((item) => item.value == val)?.label;
      },
      async getDictList(code) {
        let { data: res } = await getByCode(code);
        this.dictList[code] = res.map((item) => {
          let values = Object.keys(item);
          return {
            value: values[0],
            label: item[values[0]]
          };
        });
      },
      setIsInquiry(list) {
        // return;

        this.form.datasource.forEach((productItem, index) => {
          //产品清单
          let isInquiry = 0,
            totalCountS = [];
          list.forEach((item) => {
            //供应商列表
            item.resultList.forEach((val) => {
              //供应商产品
              if (val.productCode == productItem.productCode&&val.batchNo == productItem.batchNo&&val.taskId == productItem.taskId) {
                totalCountS.push(
                  Number(val.totalCount || 0) +
                    Number(productItem.doneTotalCount || 0)
                );
              }
            });
          });
          if (totalCountS.length > 0) {
            this.$set(
              this.form.datasource[index],
              'isInquiry',

              Math.max(...totalCountS) >= productItem.totalCount ? 2 : 1
            );
          } else {
            // this.$set(this.form.datasource[index], 'isInquiry', 0);
          }
          console.log(totalCountS, 'codeS');
        });
      },
      downloadFile(file) {
        getFile({ objectName: file.storePath }, file.name);
      },
      // 返回列表数据
      getTableValue() {
        let comitDatasource = this.form.datasource;
        if (comitDatasource.length === 0) return [];
        comitDatasource.forEach((v) => {
          v.totalPrice = (v.totalCount * v.singlePrice)?.toFixed(2) || 0;

          v.files = v.files || null;
        });
        return comitDatasource;
      },
      filterMethod(value, row, column) {
        let ids = row.supplierIds;
        if (ids.length > 0 && ids.includes(value)) {
          return row;
        }
      },
      isInquiryFn(value, row, column) {
        if (value == row.isInquiry) {
          return row;
        }
      },
      //修改回显
      async putTableValue(data) {
        if (data && data?.length) {
          let supplierList = [],
            supplierIds = [];
          this.form.datasource = data;
          let codeList = this.form.datasource.filter((item) => item.productCode).map((item) => item.productCode);
          //获取仓库库存
          let inventoryTotalList = await getInventoryTotalAPI(codeList);
          this.form.datasource.filter((item) => item.productCode).forEach((item, index) => {
            let find =
              inventoryTotalList.find((key) => key.code == item.productCode) ||
              {};
            // item.availableCountBase = find.availableCountBase;
            this.$set(
              this.form.datasource[index],
              'availableCountBase',
              find.availableCountBase
            );
            supplierList.push(...item.supplierList);
          });
          supplierIds = Array.from(
            new Set(supplierList.map((item) => item.id))
          );
          this.supplierList = supplierIds.map((id) => {
            let data = supplierList.find((item) => item.id == id);
            return {
              text: data.name,
              value: data.id
            };
          });

          console.log(this.supplierList, 'supplierList');
          this.$refs.table.reload();
        }
      },
      handleTaskinstance(row, index) {
        this.taskinstanceDialogFlag = true;
        this.$nextTick(() => {
          this.$refs.taskinstanceDialogRef.open(row, index);
        });
      },
      saveTaskInstance(row = {}) {
        this.$set(this.form.datasource[row.index], 'taskId', row.id);
        this.$set(this.form.datasource[row.index], 'taskName', row.name);
        this.$set(
          this.form.datasource[row.index],
          'routingId',
          row.produceRoutingId
        );
      },
      handleSupplierSelect(row) {
        this.$emit('supplierSelect', row);
      },
      //选择产品
      handParent() {
        this.$refs.productListRef.open();
      },
      //选择产品回调
      changeParent(obj, idx) {
        obj['productBrand'] = obj.brandNum;
        obj['productCode'] = obj.code;
        obj['productName'] = obj.name;
        obj['productCategoryName'] = obj.categoryLevelPath;
        obj['productCategoryId'] = obj.categoryLevelId;
        this.form.datasource.push(obj);
      },
      remove(i, productCode) {
        if (!this.acceptUnpack) {
          this.$message.warning('本采购计划不能拆单');
          return;
        }

        this.form.datasource.splice(i, 1);

        this.$emit('delList', productCode);
      },
      // 清空表格
      restTable() {
        this.form.datasource = [];
      },
      openSupplier(row) {
        this.$emit('supplierSelect', row);
      },
      // 添加
      handlAdd() {
        let item = JSON.parse(JSON.stringify(this.defaultForm));
        item.key = this.form.datasource.length + 1;
        this.form.datasource.push(item);
      },

      validateForm(callback) {
        //开始表单校验
        this.$refs.form.validate((valid) => {
          callback(valid);
        });
      }
    }
  };
</script>
<style lang="scss" scoped>
  .headbox {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .amount {
      font-size: 14px;
      font-weight: bold;
    }
  }

  .time-form .el-form-item {
    margin-bottom: 0 !important;
  }

  ::v-deep .period {
    display: flex;

    .borderleftnone {
      .el-input--medium .el-input__inner {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
      }
    }

    .borderrightnone {
      .el-input--medium .el-input__inner {
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
      }
    }
  }

  ::v-deep .time-form tbody > tr:hover > td {
    background-color: transparent !important;
  }

  ::v-deep .time-form .el-table tr {
    background-color: #ffffff;
  }
</style>
