<template>
  <el-form ref="form" :model="form" :rules="rules">
    <ele-pro-table
      ref="table"
      :needPage="false"
      :columns="columns"
      :toolkit="[]"
      :datasource="form.datasource"
      cache-key="systemRoleTable17"
      class="time-form"
    >
      <template v-slot:technicalDrawings="{ row, $index }">
        <el-form-item
          style="margin-bottom: 20px"
          :prop="'datasource.' + $index + '.technicalDrawings'"
        >
          <div v-if="row.technicalDrawings && row.technicalDrawings?.length">
            <el-link
              v-for="link in row.technicalDrawings"
              :key="link.id"
              type="primary"
              :underline="false"
              @click="downloadFile(link)"
            >
              {{ link.name }}
            </el-link
            >
          </div>
        </el-form-item>
      </template>
      <template v-slot:remark="{ row, $index }">
        <el-form-item
          style="margin-bottom: 20px"
          :prop="'datasource.' + $index + '.remark'"
        >
          <el-input
            clearable
            v-model="row.remark"
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
      </template>
      <template v-slot:stockLedger="scope">
        <el-form-item
          style="margin-bottom: 20px">
          <el-popover
            @hide="()=>selection=[]"
            placement="right"
            width="60%"
            trigger="hover">
            <ele-pro-table :ref="'childrenTable'+scope.$index"
                           row-key="id"
                           max-height="300px"
                           :selection.sync="selection"
                           :needPage="false" :columns="childrenColumns" :toolkit="[]"
                           :datasource="scope.row.sendProductDetail"
                           cache-key="stockLedgerRoleTable" class="time-form">
              <!-- 表头工具栏 -->
              <template v-slot:toolbar="childrenScope">
                <div class="headbox">
                  <el-button
                    size="small"
                    type="primary"
                    icon="el-icon-plus"
                    class="ele-btn-icon"
                    @click="stockLedgerSelect(scope.row,scope.$index)">
                    选择
                  </el-button>

                  <el-button
                    size="small"
                    type="danger"
                    icon="el-icon-delete"
                    class="ele-btn-icon"
                    :disabled="!selection.length"
                    @click="stockLedgerRemove(scope.$index)">
                    删除
                  </el-button>

                </div>
              </template>
            </ele-pro-table>
            <el-button type="text" slot="reference">明细</el-button>

          </el-popover>
        </el-form-item>
      </template>
      <template v-slot:totalCount="scope">
        <el-form-item
          style="margin-bottom: 20px"
          :prop="'datasource.' + scope.$index + '.totalCount'"
          :rules="[
            { required: true, message: '请输入数字', trigger: 'blur' },
            { validator: validateTotalCount(scope.row), trigger: 'blur' }
          ]"
        >
          <el-input
            v-model="scope.row.totalCount"
            @input="(val) => changeNum(val, scope.$index)"
          ></el-input>
        </el-form-item>
      </template>
      <template v-slot:receiveTotalWeight="scope">
        <el-form-item
          style="margin-bottom: 20px"
          :prop="'datasource.' + scope.$index + '.receiveTotalWeight'"
          :rules="[
            { required: entrustedCode&&pricingWay==2, message: '请输入数字', trigger: 'blur' }
          ]"
        >
          <el-input v-model="scope.row.receiveTotalWeight" :disabled="!entrustedCode"
                    @blur="changeSendTotalWeight(scope.$index)"
                    style="width: 60%; margin-right: 10px">

          </el-input>
          <el-button
            size="small"
            type="primary"
            v-if="entrustedCode"
            @click.native="(e)=>handleInnerBound(e,scope.row,scope.$index)"
          >选择
          </el-button
          >
        </el-form-item>
      </template>
      <template v-slot:warehouseId="scope">
        <el-form-item
          style="margin-bottom: 20px"
          :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:warehouseNum="scope">
        <el-form-item style="margin-bottom: 20px">
          {{ scope.row.warehouseNum }}
        </el-form-item>
      </template>
      <template v-slot:headerWarehouseId="{ column }">
        <span class="is-required">{{ column.label }}</span>
      </template>
      <template v-slot:headerTotalCount="{ column }">
        <span :class="{'is-required':entrustedCode&&pricingWay==2}">{{ 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>
    <!--入库详情-->
    <innertboundDetailsDialog v-if="innerboundDetailsDialogFlag" ref="innerboundDetailsDialogRef"
                              :innerboundDetailsDialogFlag.sync="innerboundDetailsDialogFlag"
                              @saveDate="saveInnerDate"></innertboundDetailsDialog>
    <!-- 库存台账   -->
    <stock-ledger-dialog v-if="stockLedgerDialogFlag" :stock-ledger-dialog-flag.sync="stockLedgerDialogFlag"
                         ref="stockLedgerDialogRef" @getStockLedger="getStockLedger"></stock-ledger-dialog>
  </el-form>
</template>
<script>
import {numberReg} from 'ele-admin';
import dictMixins from '@/mixins/dictMixins';
import {getWarehouseList, getWarehouseOutStock} from '@/api/saleManage/saleorder';

import {copyObj} from '@/utils/util';
import {getFile} from "@/api/system/file";
import outboundDetailsDialog
  from "@/views/purchasingManage/purchaseOrder/returnGoods/components/innerboundDetailsDialog.vue";
import innertboundDetailsDialog
  from "@/views/purchasingManage/purchaseOrder/returnGoods/components/innerboundDetailsDialog.vue";
import stockLedgerDialog from "@/views/saleManage/saleOrder/invoice/components/stockLedger/stockLedgerDialog.vue";

export default {
  mixins: [dictMixins],
  props: {
    orderId: String,
    entrustedCode: String,
    pricingWay: [String, Number],
    isShowAdd: {
      type: Boolean,
      default: true
    }
  },
  components: {
    innertboundDetailsDialog,
    outboundDetailsDialog,
    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: [],
      form: {
        datasource: []
      },
      rules: {},

    };
  },
  created() {
    getWarehouseList().then((res) => {
      this.warehouseList = res;
    });
  },
  computed: {
    canHandl() {
      return this.form.datasource.length;
    },
    contractId() {
      return this.$store.state.order.contractId;
    },
    columns() {
      return [
        {
          width: 45,
          type: 'index',
          columnKey: 'index',
          align: 'center',
          fixed: 'left',
        },
        {
          width: 200,
          prop: 'productName',
          label: '名称',
          slot: 'productName',
          align: 'center',
        },
        {
          width: 120,
          prop: 'productCode',
          label: '编码',
          slot: 'productCode',
          align: 'center'
        },
        {
          width: 200,
          prop: 'productCategoryName',
          label: '类型',
          slot: 'productCategoryName',
          align: 'center'
        },
        {
          width: 160,
          prop: 'productBrand',
          label: '牌号',
          slot: 'productBrand',
          align: 'center'
        },
        {
          width: 120,
          prop: 'modelType',
          label: '型号',
          slot: 'modelType',
          align: 'center'
        },
        {
          width: 120,
          prop: 'customerMark',
          label: '客户代号',
          slot: 'customerMark',
          align: 'center',
        },
        {
          width: 120,
          prop: 'specification',
          label: '规格',
          slot: 'specification',
          align: 'center'
        },
        {
          width: 200,
          prop: 'warehouseId',
          label: '仓库名称',
          slot: 'warehouseId',
          headerSlot: 'headerWarehouseId',
          align: 'center'
        },
        {
          width: 100,
          prop: 'stockLedger',
          label: '发货明细',
          slot: 'stockLedger',
          align: 'center'
        },
        {
          width: 120,
          prop: 'totalCount',
          label: '发货数量',
          slot: 'totalCount',
          headerSlot: 'headerTotalCount',
          align: 'center'
        },
        {
          width: 120,
          prop: 'orderTotalCount',
          label: '订单数量',
          slot: 'orderTotalCount',
          align: 'center',
          // show: !!!this.entrustedCode
        },
        // {
        //   width: 120,
        //   prop: 'orderTotalCount',
        //   label: '委外收货总数量',
        //   slot: 'orderTotalCount',
        //   align: 'center',
        //   show: !!this.entrustedCode
        // },
        {
          width: 80,
          prop: 'measuringUnit',
          label: '计量单位',
          slot: 'measuringUnit',
          align: 'center'
        },
        {
          width: 120,
          prop: 'singleWeight',
          label: '单重',
          slot: 'singleWeight',
          align: "center"
        },
        {
          width: 200,
          prop: 'receiveTotalWeight',
          label: '收货总重',
          slot: 'receiveTotalWeight',
          align: "center",
          headerSlot: 'headerTotalCount'
        },
        {
          width: 100,
          prop: 'sendTotalWeight',
          label: '发货总重',
          slot: 'sendTotalWeight',
          align: "center",
        },

        {
          width: 100,
          prop: 'increaseTotalWeight',
          label: '增重重量',
          slot: 'increaseTotalWeight',
          align: "center"
        },
        {
          width: 100,
          prop: 'weightUnit',
          label: '重量单位',
          slot: 'weightUnit',
          align: "center"
        },
        {
          width: 160,
          prop: 'singlePrice',
          label: '单价',
          slot: 'singlePrice',
          align: 'center'
        },
        {
          width: 160,
          prop: 'discountSinglePrice',
          label: '折后单价',
          slot: 'discountSinglePrice',
          align: 'center'
        },
        {
          width: 120,
          prop: 'totalPrice',
          label: '合计',
          slot: 'totalPrice',
          align: 'center'
        },
        {
          width: 120,
          prop: 'discountTotalPrice',
          label: '折后合计',
          slot: 'discountTotalPrice',
          align: 'center'
        },
        {
          width: 80,
          prop: 'deliveryDays',
          label: '交期(天)',
          slot: 'deliveryDays',
          align: 'center'
        },
        {
          width: 160,
          prop: 'deliveryDeadline',
          label: '交期截止日期',
          slot: 'deliveryDeadline',
          align: 'center'
        },
        {
          width: 200,
          prop: 'guaranteePeriod',
          label: '质保期',
          slot: 'guaranteePeriod',
          formatter: (_row, _column, cellValue) => {
            return (_row.guaranteePeriod || '') + _row.guaranteePeriodUnitName;
          },
          align: 'center'
        },
        {
          width: 160,
          prop: 'guaranteePeriodDeadline',
          label: '质保截止日期',
          slot: 'guaranteePeriodDeadline',
          align: 'center'
        },
        {
          width: 130,
          prop: 'technicalAnswerName',
          label: '技术答疑人',
          slot: 'technicalAnswerName',
          align: 'center'
        },
        {
          width: 220,
          prop: 'technicalParams',
          label: '技术参数',
          slot: 'technicalParams',
          align: 'center'
        },
        {
          width: 240,
          prop: 'technicalDrawings',
          label: '技术图纸',
          slot: 'technicalDrawings',
          align: 'center'
        },
        {
          width: 220,
          prop: 'remark',
          label: '备注',
          slot: 'remark',
          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);
    },
    //发货明细选择
    stockLedgerSelect(row, index) {
      this.curIndex = index
      this.stockLedgerDialogFlag = true
      this.$nextTick(() => {
        this.$refs.stockLedgerDialogRef.init(row.sendProductDetail, row)
      })
    },
    //获取
    getStockLedger(sendProductDetail) {
      if (!this.form.datasource[this.curIndex].sendProductDetail) this.form.datasource[this.curIndex].sendProductDetail = []
      let row = this.form.datasource[this.curIndex]
      row.sendProductDetail.push(...sendProductDetail)
      this.form.datasource[this.curIndex] = row
      this.$refs['childrenTable' + this.curIndex].reload()
      this.$refs.table.reload()
    },
    //删除发货明细
    stockLedgerRemove(PIndex) {
      let row = this.form.datasource[PIndex]
      this.selection.forEach(item => {
        let index = row.sendProductDetail.findIndex(i => i.id == item.id)
        row.sendProductDetail.splice(index, 1)
      })
      this.form.datasource[PIndex] = row
      this.$refs['childrenTable' + PIndex].reload()
      this.$refs.table.reload()
      this.selection = []
    },


    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.name);
      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
      );
    },

    //修改发货总重
    changeSendTotalWeight(index) {
      this.curIndex = index
      this.setIcreaseTotalWeight()
    },
    //入库单详情
    handleInnerBound(e, rows, index) {
      this.curIndex = index
      this.innerboundDetailsDialogFlag = true
      this.$nextTick(() => {
        let row = {
          sendNo: this.entrustedCode,
          productCode: rows.productCode
        }
        this.$refs.innerboundDetailsDialogRef.init(row)
      })
    },
    //选择入库单信息
    saveInnerDate(data = []) {
      let totalWeight = data.reduce((num, row) => {
        num += Number(row.weight)
        return num
      }, 0)
      this.$set(this.form.datasource[this.curIndex], 'receiveTotalWeight', totalWeight);
      this.setIcreaseTotalWeight()
    },
    //修改数量更新合计/总重
    changeNum(val, index) {
      this.curIndex = index
      if (this.pricingWay == 2) {
        if (val != this.form.datasource[index].orderTotalCount) {
          this.$set(this.form.datasource[index], 'receiveTotalWeight', '')
          this.$set(this.form.datasource[index], 'sendTotalWeight', Number(val) * Number(this.form.datasource[index].singleWeight));
        } else {
          let find = this.oldReceiveTotalWeight.find(key => key.productCode == this.form.datasource[index].productCode) || {}
          this.$set(this.form.datasource[index], 'receiveTotalWeight', find.oldReceiveTotalWeight || '')
          this.$set(this.form.datasource[index], 'sendTotalWeight', Number(val) * Number(this.form.datasource[index].singleWeight));
        }
        this.setIcreaseTotalWeight()
        this.getWeightPrice()
      } else {
        this.$set(this.form.datasource[index], 'totalPrice', (Number(this.form.datasource[index].singlePrice) * val).toFixed(2));
        this.$set(this.form.datasource[index], 'discountTotalPrice', (Number(this.form.datasource[index].discountSinglePrice) * val).toFixed(2));
        this.$set(this.form.datasource[index], 'sendTotalWeight', Number(this.form.datasource[index].totalCount) * Number(this.form.datasource[index].singleWeight));
        this.$set(this.form.datasource[index], 'increaseTotalWeight', Number(this.form.datasource[index].totalCount) * Number(this.form.datasource[index].singleWeight));
      }
    },
    getWeightPrice() {
      let increaseTotalWeight = this.form.datasource[this.curIndex].increaseTotalWeight
      let singlePrice = this.form.datasource[this.curIndex].singlePrice
      let discountSinglePrice = this.form.datasource[this.curIndex].discountSinglePrice
      this.$set(this.form.datasource[this.curIndex], 'totalPrice', (Number(increaseTotalWeight) * Number(singlePrice)).toFixed(2));
      this.$set(this.form.datasource[this.curIndex], 'discountTotalPrice', (Number(discountSinglePrice) * Number(increaseTotalWeight)).toFixed(2));
    },
    //设置增重总重
    setIcreaseTotalWeight() {
      let receiveTotalWeight = Number(this.form.datasource[this.curIndex].receiveTotalWeight)
      let sendTotalWeight = Number(this.form.datasource[this.curIndex].sendTotalWeight)
      this.$set(this.form.datasource[this.curIndex], 'increaseTotalWeight', (sendTotalWeight - receiveTotalWeight).toFixed(2));
      if (this.pricingWay == 2) {
        this.getWeightPrice()
      }
      this.$refs.table.reload()
    },
    //选择产品回调
    changeParent(obj, idx) {
      obj.orderTotalCount = obj.totalCount;
      obj.id = '';
      this.$set(
        this.form.datasource,
        this.form.datasource.length,
        copyObj(obj)
      );
    },
    validateTotalCount(row) {
      return (rule, value, callback) => {
        if (isNaN(value) || Number(value) <= 0) {
          this.$message.error('请输入大于0的数');
          callback(new Error('请输入大于0的数字'));
        } else if (Number(value) > row.warehouseNum) {
          // this.$message.error('输入的数字不能大于仓库物品数');
          // callback(new Error('输入的数字不能大于仓库物品数'));
          callback();
        } else if (Number(value) > row.orderTotalCount) {
          this.$message.error('输入的数字不能大于最大发货值');
          callback(new Error('输入的数字不能大于最大发货值'));
        } else {
          callback();
        }
      };
    },
    // 返回列表数据
    getTableValue() {
      let comitDatasource = this.form.datasource;
      if (comitDatasource.length === 0) return [];
      comitDatasource.forEach(async (v) => {
        v.totalCount = Number(v.totalCount);
        v.technicalDrawings = Array.isArray(v.technicalDrawings)
          ? v.technicalDrawings
          : [];
        v.customerReqFiles = Array.isArray(v.customerReqFiles)
          ? v.customerReqFiles
          : [];
        v.industryArtFiles = v.industryArtFiles || [];
        v.otherFiles = v.otherFiles || [];
      });
      return comitDatasource;
    },
    getPrice() {
      return [this.allPrice];
    },

    //修改回显
    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
              })
            );
          }
          //保存初始收货总重
          this.oldReceiveTotalWeight = this.form.datasource.map(item => {
            return {
              productCode: item.productCode,
              oldReceiveTotalWeight: item.receiveTotalWeight
            }
          })
          this.form.datasource.forEach((item, index) => {
            item.sendTotalWeight = item.sendTotalWeight || (Number(item.totalCount) * Number(item.singleWeight)) || 0
            if (this.outsourceSendCode) {
              item.increaseTotalWeight = Number(item.receiveTotalWeight) - Number(item.sendTotalWeight)
            } else {
              item.increaseTotalWeight = item.increaseTotalWeight || item.receiveTotalWeight || 0
            }
            this.changeNum(item.totalCount, index)
          })
        });
      }
    },
    //选择产品
    handParent(row, index) {
      let item = {
        id: row.productCode
      };
      this.$refs.productListRef.open(item, index);
    },
    //选择技术人回调
    changeAnswer(obj, idx) {
      this.$set(this.form.datasource[idx], 'technicalAnswerId', obj.id);
      this.$set(this.form.datasource[idx], 'technicalAnswerName', obj.name);
    },
    handHead(row, index) {
      let item = {
        id: row.technicalAnswerId
      };
      this.$refs.headRef.open(item, index);
    },

    remove(i) {
      this.form.datasource.splice(i, 1);
      this.setSort();
    },
    // 清空表格
    restTable() {
      this.form.datasource = [];
    },
    // 重新排序
    setSort() {
      this.form.datasource.forEach((n, index) => {
        n.key = index + 1;
      });
    },
    // 添加
    handlAdd() {
      if (!this.orderId) return this.$message.error('请先选择订单');
      this.$refs.productListRef.open(this.form.datasource);
    },

    validateForm(callback) {
      //开始表单校验
      this.$refs.form.validate((valid) => {
        callback(valid);
      });
    }
  }
};
</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>
