<template>
  <el-form ref="form" :model="form" :rules="rules">
    <ele-pro-table
      ref="table"
      :needPage="false"
      :columns="columns"
      :toolkit="[]"
      max-height="500px"
      :datasource="form.datasource"
      cache-key="systemRoleTable17"
      class="time-form"
      :selection.sync="selection"
    >

      <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:supplierIds="scope">
        <el-form-item prop="supplierIds">
          <el-select v-model="scope.row['supplierIds']" clearable filterable multiple collapse-tags @change="handleSupplierSelect(scope.row)">
            <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">
          <!-- <div style="display: flex"> -->
          <span>{{ item.label }}</span>
          <fileUpload
            v-model="item.files"
            module="main"
            :showLib="false"
            :limit="1"
          />
          <!-- </div> -->
        </el-form-item>
      </template>
      <!-- </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>

    <!-- <head-list ref="headRef" @changeParent="changeAnswer"></head-list> -->
  </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 headList from '@/views/saleManage/businessOpportunity/components/headList.vue';
export default {
  mixins: [dictMixins],
  components: {
    fileMain,
    fileUpload
    // headList
  },
  props: {
    acceptUnpack: {
      default: ''
    },
    isSupplier: {
      default:true
    }
  },
  data() {
    const defaultForm = {
      key: null,
      endTime: '',
      isFirst: 0,
      name: ''
    };

    return {
      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
        },
        {
          minWidth: 100,
          prop: 'productCategoryName',
          label: '分类',
          slot: 'productCategoryName',
          showOverflowTooltip: true,
          align: "center"
        },
        {
          minWidth: 100,
          prop: 'productCode',
          label: '编码',
          slot: 'productCode',
          showOverflowTooltip: true,
          align: "center"
        },
        {
          minWidth: 140,
          prop: 'productName',
          label: '名称',
          slot: 'productName',
          headerSlot: 'productNameHeader',
          showOverflowTooltip: true,
          align: "center"
        },
        
        {
          minWidth: 200,
          prop: 'supplierIds',
          label: '供应商选择',
          slot: 'supplierIds',
          showOverflowTooltip: true,
          align: "center"
        },
        {
          minWidth: 100,
          prop: 'productBrand',
          label: '牌号',
          slot: 'productBrand',
          showOverflowTooltip: true,
          align: "center"
        },
        {
          minWidth: 80,
          prop: 'totalCount',
          label: '数量',
          slot: 'totalCount',
          showOverflowTooltip: true,
          align: "center"
        },
        {
          minWidth: 80,
          prop: 'availableCountBase',
          label: '库存数量',
          slot: 'availableCountBase',
          align: "center"
        },
        {
            width: 120,
            prop: 'totalWeight',
            label: '重量',
            slot: 'totalWeight',
            align: 'center'
          },
        {
          minWidth: 150,
          prop: 'taskName',
          label: '工序',
          slot: 'taskName',
          align: "center"
        },
        {
          width: 110,
          prop: 'batchNo',
          label: '批次号',
          slot: 'batchNo',
          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: 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) => {
            return row.produceType && row.produceType.length ? row.produceType.map(item => this.getDictV('productionType', item)).join(',') : ''
          }
        },
        {
          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.getDictList('productionType')
  },
  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]]
        }
      })
    },
    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;
    },

    //修改回显
    async putTableValue(data) {
      if (data && data?.length) {
        this.form.datasource = data;
        let codeList = this.form.datasource.map(item => item.productCode)
        //获取仓库库存
        let inventoryTotalList = await getInventoryTotalAPI(codeList);
        this.form.datasource.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);
        });
        this.$refs.table.reload()
      }

    },
    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 = [];
    },

    // 添加
    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>
