<template>
  <el-form ref="form" :model="form">
    <ele-pro-table
      ref="table"
      :needPage="false"
      :columns="columns"
      :toolkit="[]"
      :datasource="form.datasource"
      cache-key="systemRoleTable17"
      class="time-form"
    >
      <!-- 表头工具栏 -->
      <template v-slot:toolbar>
        <div class="headbox">
          <el-button
            v-if="type != 'view'"
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="handlAdd"
          >
            新增
          </el-button>
        </div>
      </template>
      <template v-slot:totalCount="scope">
        <el-form-item
          :prop="'datasource.' + scope.$index + '.totalCount'"
          :rules="[
            { required: true, message: '请输入数字', trigger: 'blur' },
            { validator: validateTotalCount(scope.row), trigger: 'blur' }
          ]"
        >
          <el-input
            :disabled="type == 'view'"
            v-model="scope.row.totalCount"
            @input="totalCountChange"
          ></el-input>
        </el-form-item>
      </template>
      <template v-slot:warehouseList="scope">
        <el-form-item
          :prop="'datasource.' + scope.$index + '.warehouseId'"
          :rules="[{ required: true, message: '请选择仓库', trigger: 'blur' }]"
        >
          <el-select
            v-model="scope.row.warehouseId"
            placeholder="请选择"
            @change="warehouseChange(scope.$index, scope.row)"
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </template>
      <template v-slot:headerTotalCount="{ column }">
        <span class="is-required">{{ column.label }}</span>
      </template>

      <!-- 操作列 -->
      <template v-slot:action="scope">
        <el-popconfirm
          class="ele-action"
          title="确定要删除吗？"
          @confirm="remove(scope.$index)"
        >
          <template v-slot:reference>
            <el-link type="danger" :underline="false" icon="el-icon-delete">
              删除
            </el-link>
          </template>
        </el-popconfirm>
      </template>
    </ele-pro-table>
    <!--    <product-list-->
    <!--      ref="productListRef"-->
    <!--      :orderId="orderId"-->
    <!--      type="purchase"-->
    <!--      @changeParent="changeParent"-->
    <!--    ></product-list>-->
    <!--    &lt;!&ndash;入库详情&ndash;&gt;-->
    <!--    <innertboundDetailsDialog-->
    <!--      v-if="innerboundDetailsDialogFlag"-->
    <!--      ref="innerboundDetailsDialogRef"-->
    <!--      :innerboundDetailsDialogFlag.sync="innerboundDetailsDialogFlag"-->
    <!--      @saveDate="saveInnerDate"-->
    <!--    ></innertboundDetailsDialog>-->
    <!--    &lt;!&ndash; 库存台账   &ndash;&gt;-->
    <!--    <stock-ledger-dialog-->
    <!--      v-if="stockLedgerDialogFlag"-->
    <!--      :stock-ledger-dialog-flag.sync="stockLedgerDialogFlag"-->
    <!--      ref="stockLedgerDialogRef"-->
    <!--      @getStockLedger="getStockLedger"-->
    <!--    ></stock-ledger-dialog>-->
    <select-stock-ledger-dialog
      ref="selectStockLedgerDialogRef"
      @changeParent="changeParent"
    ></select-stock-ledger-dialog>
  </el-form>
</template>
<script>
  import { numberReg } from 'ele-admin';
  import dictMixins from '@/mixins/dictMixins';
  import productList from './product-list.vue';
  import {
    getWarehouseList,
    getWarehouseOutStock
  } from '@/api/saleManage/saleorder';

  import { copyObj } from '@/utils/util';
  import { getFile } from '@/api/system/file';
  import innertboundDetailsDialog from '@/BIZComponents/innerboundDetailsDialog.vue';
  import stockLedgerDialog from './stockLedger/stockLedgerDialog.vue';
  import { fieldModelAPI } from '@/api/main';
  import getDynamicsColumns from '@/mixins/getDynamicsColumns';
  import SelectStockLedgerDialog from '@/BIZComponents/selectStockLedger/selectStockLedgerDialog.vue';
  export default {
    mixins: [dictMixins, getDynamicsColumns, SelectStockLedgerDialog],
    props: {
      orderId: String,
      isShowAdd: {
        type: Boolean,
        default: true
      },
      type: {
        type: String,
        default: ''
      }
    },
    components: {
      SelectStockLedgerDialog,
      innertboundDetailsDialog,
      productList,
      stockLedgerDialog
    },
    data() {
      const defaultForm = {
        key: null,
        endTime: '',
        isFirst: 0,
        name: '',
        startTime: '',
        workHour: '',
        technicalDrawings: []
        // warehouseCode:"",
        // warehouseId:'',
        // warehouseName:'',
      };
      return {
        childrenColumns: [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center'
          },
          {
            width: 45,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            fixed: 'left'
          },
          {
            minWidth: 100,
            prop: 'code',
            label: '编码',
            align: 'center'
          },
          {
            minWidth: 140,
            prop: 'barcodes',
            label: '发货条码',
            align: 'center'
          },
          {
            minWidth: 100,
            prop: 'engrave',
            label: '刻码',
            align: 'center'
          }
        ],
        selection: [],
        discountTotalPrice: 0.0,
        allPrice: 0.0,
        curIndex: null,
        innerboundDetailsDialogFlag: false,
        stockLedgerDialogFlag: false,
        numberReg,
        defaultForm,
        warehouseList: [],
        dynamicsColumns: [],

        form: {
          datasource: []
        },
        rules: {}
      };
    },
    created() {
      getWarehouseList().then((res) => {
        this.warehouseList = res;
      });
    },
    computed: {
      canHandl() {
        return this.form.datasource.length;
      },
      columns() {
        return [
          {
            width: 45,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            fixed: 'left'
          },
          {
            minWidth: 200,
            prop: 'productName',
            label: '名称',
            slot: 'productName',
            align: 'center'
          },
          {
            minWidth: 120,
            prop: 'productCode',
            label: '编码',
            slot: 'productCode',
            align: 'center'
          },

          {
            minWidth: 160,
            prop: 'productBrand',
            label: '牌号',
            slot: 'productBrand',
            align: 'center'
          },
          {
            minWidth: 120,
            prop: 'modelType',
            label: '型号',
            slot: 'modelType',
            align: 'center'
          },
          {
            minWidth: 120,
            prop: 'specification',
            label: '规格',
            slot: 'specification',
            align: 'center'
          },
          {
            minWidth: 200,
            prop: 'warehouseName',
            label: '仓库名称',
            slot: 'warehouseList',
            align: 'center'
          },
          {
            width: 120,
            prop: 'totalCount',
            label: '使用数量',
            slot: 'totalCount',
            headerSlot: 'headerTotalCount',
            align: 'center'
          },
          {
            width: 120,
            prop: 'warehouseNum',
            label: '仓库数量',
            slot: 'warehouseNum',
            align: 'center'
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 120,
            align: 'center',
            resizable: false,
            slot: 'action',
            fixed: 'right',
            showOverflowTooltip: true
          }
        ];
      }
    },
    methods: {
      downloadFile(file) {
        getFile({ objectName: file.storePath }, file.name);
      },

      //选择调
      changeParent(obj = []) {
        let list = _.cloneDeep(obj);

        this.form.datasource.push(
          ...list.map((item) => {
            item['warehouseNum'] = item.measureQuantity;
            item['provenance'] = [];
            return item;
          })
        );

        this.totalCountChange();
      },
      validateTotalCount(row) {
        return (rule, value, callback) => {
          if (isNaN(value) || Number(value) <= 0) {
            callback(new Error('请输入大于0的数字'));
          } else {
            callback();
          }
        };
      },
      async warehouseChange(index, row) {
        let warehouseIds =
          this.form.datasource
            .filter(
              (item, i) => row.productCode == item.productCode && index != i
            )
            .map((item) => item.warehouseId) || [];
        const data = this.warehouseList.find(
          (item) => item.id == row.warehouseId
        );
        // if (warehouseIds.length > 0 && warehouseIds.includes(row.warehouseId)) {
        //   row.warehouseId = '';
        //   return this.$message.error('只能选择同产品仓库的托盘');
        // }

        this.$set(this.form.datasource[index], 'warehouseName', data.id);
        this.$set(this.form.datasource[index], 'warehouseCode', data.code);
        const warehouseOutStock = await getWarehouseOutStock({
          warehouseId: data.id,
          code: row.productCode
        });
        this.$set(
          this.form.datasource[index],
          'warehouseNum',
          warehouseOutStock
        );
      },
      // 返回列表数据
      getTableValue() {
        let comitDatasource = this.form.datasource;
        if (comitDatasource.length === 0) return [];
        comitDatasource.forEach(async (v) => {
          v.totalCount = Number(v.totalCount);
        });
        return comitDatasource;
      },
      totalCountChange() {
        let num = 0;
        this.form.datasource.forEach((item) => {
          num += Number(item.totalCount);
        });
        this.$emit('totalCountChange', num);
      },
      //修改回显
      putTableValue(data = []) {
        if (data) {
          this.form.datasource = data;
          data.forEach(async (item, index) => {
            if (item.warehouseId) {
              this.$set(
                this.form.datasource[index],
                'warehouseNum',
                await getWarehouseOutStock({
                  warehouseId: item.warehouseId,
                  code: item.productCode
                })
              );
            }
          });
        }
      },

      remove(i) {
        this.form.datasource.splice(i, 1);
        this.setSort();
        this.totalCountChange();
      },

      // 重新排序
      setSort() {
        this.form.datasource.forEach((n, index) => {
          n.key = index + 1;
        });
      },
      // 添加
      handlAdd() {
        this.$refs.selectStockLedgerDialogRef.open();
      },

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

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

  .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;
  }

  .pricebox {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-weight: bold;
  }
</style>
