<template>
  <ele-modal
    :visible.sync="visible"
    :title="title"
    v-if="visible"
    width="65vw"
    append-to-body
    :maxable="true"
  >
    <ele-pro-table
      ref="entrustCreateTable"
      :columns="columns"
      :datasource="goodsList"
      :selection.sync="selection"
      :current.sync="current"
      highlight-current-row
      row-key="id"
      height="40vh"
    >
      <template v-slot:quantity="{ row }">
        <span>{{ row.quantity }}{{ row.measuringUnit }}</span>
      </template>

      <!-- <template v-slot:receiveQuantity="{ row }">
        <el-input
          placeholder=""
          v-model="row.receiveQuantity"
          :disabled="type == 'detail' || type == 'send'"
        >
          <template slot="append">{{ row.measuringUnit }}</template>
        </el-input>
      </template> -->
      <template v-slot:receiveQuantity="{ row }">
        <el-input placeholder="" v-model="row.receiveQuantity" disabled>
          <template slot="append">{{ row.measuringUnit }}</template>
        </el-input>
      </template>

      <template v-slot:weight="{ row }">
        <span>{{ row.weight }}{{ row.weightUnit }}</span>
      </template>

      <template v-slot:rootCategoryLevelId="{ row }">
        <el-tag>{{ typeName[Number(row.rootCategoryLevelId)] }}</el-tag>
      </template>
    </ele-pro-table>

    <template v-slot:footer v-if="type != 'detail' && type != 'send'">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="rejectReason"> 驳回 </el-button>
      <el-button type="primary" @click="save"> 确认收货 </el-button>
    </template>

    <!-- 驳回原因弹窗 -->
    <el-dialog
      :visible.sync="rejectDialogVisible"
      v-if="rejectDialogVisible"
      title="请输入驳回原因"
      width="30vw"
      append-to-body
      :close-on-click-modal="false"
      :before-close="
        () => {
          rejectDialogVisible = false;
        }
      "
    >
      <el-form
        ref="rejectForm"
        :model="rejectForm"
        :rules="rejectRules"
        label-width="80px"
      >
        <el-form-item label="原因" prop="reason">
          <el-input
            type="textarea"
            v-model="rejectForm.reason"
            placeholder="请输入驳回原因"
            rows="4"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReject">确定</el-button>
      </span>
    </el-dialog>
  </ele-modal>
</template>

<script>
  import { pleaseEntrustGoodsDetail } from '@/api/entrust';
  import { confirmReceipt, rejectGoods } from '@/api/beEntrusted';
  import { typeName } from '@/views/produce/components/common.js';
  export default {
    data() {
      return {
        visible: false,
        goodsList: [],
        selection: [],
        current: null,
        typeName,
        id: '',
        type: '',
        title: '',
        loading: null,
        // 驳回弹窗
        rejectDialogVisible: false,
        rejectForm: { reason: '' },
        rejectRules: {
          reason: [
            { required: true, message: '请输入驳回原因', trigger: 'blur' }
          ]
        },
        itemData: {}
      };
    },

    computed: {
      columns() {
        return [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            reserveSelection: true
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'categoryName',
            label: '名称',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'brandNum',
            label: '牌号',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'batchNo',
            label: '批次号',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },

          // {
          //   prop: 'quantity',
          //   slot: 'quantity',
          //   label: '数量',
          //   align: 'center',
          //   minWidth: 110,
          //   showOverflowTooltip: true
          // },

          {
            prop: 'receiveQuantity',
            slot: 'receiveQuantity',
            label: '接收数量',
            align: 'center',
            minWidth: 150,
            showOverflowTooltip: true,
            show: this.type != 'send' ? true : false
          },

          {
            prop: 'workOrderCode',
            label: '生产工单号',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            label: '规格',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },

          {
            prop: 'modelType',
            label: '型号',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },

          // {
          //   prop: 'taskName',
          //   label: '工序',
          //   align: 'center',
          //   minWidth: 150,
          //   showOverflowTooltip: true
          // },
          {
            prop: 'categoryCode',
            label: '编码',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'weight',
            slot: 'weight',
            label: '重量',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'rootCategoryLevelId',
            slot: 'rootCategoryLevelId',
            label: '类型',
            align: 'center',
            showOverflowTooltip: true
          }
        ];
      }
    },

    methods: {
      open(item, type) {
        this.visible = true;
        this.id = item.id;
        this.itemData = item;
        this.type = type;
        this.title = this.type != 'send' ? '收货单' : '发货单';
        this.getDetail(item.id);
      },

      async getDetail(id) {
        const detailType = this.type != 'send' ? 1 : 2;
        await pleaseEntrustGoodsDetail({
          id,
          detailType
        }).then((res) => {
          this.goodsList = [];
          res.data.forEach((item) => {
            if (this.type != 'detail') {
              item.receiveQuantity = item.quantity;
            }
            item.sendStatus = 2;
            this.goodsList.push(this.deepCopy(item));
          });
        });
      },

      // save() {
      //   if (this.selection.length == 0) {
      //     return this.$message.warning('请先选择一条收货数据!');
      //   }

      //   const selectionIds = new Set(this.selection.map((it) => it.id));

      //   for (let item of this.goodsList) {
      //     if (!selectionIds.has(item.id)) {
      //       item.receiveQuantity = 0;
      //     }
      //   }

      //   if (
      //     Number(this.itemData.sendOutQuantity) <
      //     Number(this.itemData.formingNum)
      //   ) {
      //     this.$confirm('收货数量小于请托数量是否继续收货？', '提示', {
      //       type: 'warning'
      //     })
      //       .then(() => {
      //         this.loading = this.$loading({
      //           lock: true,
      //           text: '加载中',
      //           background: 'rgba(0, 0, 0, 0.7)'
      //         });
      //         confirmReceipt(this.goodsList)
      //           .then((res) => {
      //             this.loading.close();
      //             this.$message.success('收货成功');
      //             this.$emit('done');
      //             this.visible = false;
      //           })
      //           .catch(() => {
      //             this.loading.close();
      //           });
      //       })
      //       .catch(() => {});
      //   } else if (
      //     Number(this.itemData.sendOutQuantity) ==
      //     Number(this.itemData.formingNum)
      //   ) {
      //     this.loading = this.$loading({
      //       lock: true,
      //       text: '加载中',
      //       background: 'rgba(0, 0, 0, 0.7)'
      //     });
      //     confirmReceipt(this.goodsList)
      //       .then((res) => {
      //         this.loading.close();
      //         this.$message.success('收货成功');
      //         this.$emit('done');
      //         this.visible = false;
      //       })
      //       .catch(() => {
      //         this.loading.close();
      //       });
      //   } else if (
      //     Number(this.itemData.sendOutQuantity) >
      //     Number(this.itemData.formingNum)
      //   ) {
      //     this.$confirm('收货数量大于请托数量是否继续收货？', '提示', {
      //       type: 'warning'
      //     })
      //       .then(() => {
      //         this.loading = this.$loading({
      //           lock: true,
      //           text: '加载中',
      //           background: 'rgba(0, 0, 0, 0.7)'
      //         });
      //         confirmReceipt(this.goodsList)
      //           .then((res) => {
      //             this.loading.close();
      //             this.$message.success('收货成功');
      //             this.$emit('done');
      //             this.visible = false;
      //           })
      //           .catch(() => {
      //             this.loading.close();
      //           });
      //       })
      //       .catch(() => {});
      //   }
      // },

      save() {
        if (this.selection.length === 0) {
          return this.$message.warning('请先选择一条收货数据!');
        }

        const selectionIds = new Set(this.selection.map((it) => it.id));
        this.goodsList.forEach((item) => {
          if (!selectionIds.has(item.id)) {
            item.receiveQuantity = 0;
          }
        });

        const totalNum = this.selection.reduce(
          (total, pro) => total + Number(pro.receiveQuantity || 0),
          0
        );

        const formingNum = Number(this.itemData.sendOutQuantity);

        let confirmMessage = '';

        console.log(totalNum, formingNum, '8888');

        if (totalNum < formingNum) {
          confirmMessage = '收货数量小于请托数量，是否继续收货？';
        } else if (totalNum > formingNum) {
          confirmMessage = '收货数量大于请托数量，是否继续收货？';
        }

        const doConfirmReceipt = () => {
          this.loading = this.$loading({
            lock: true,
            text: '加载中',
            background: 'rgba(0, 0, 0, 0.7)'
          });

          confirmReceipt(this.goodsList)
            .then(() => {
              this.loading.close();
              this.$message.success('收货成功');
              this.$emit('done');
              this.visible = false;
            })
            .catch(() => {
              this.loading.close();
            });
        };

        if (confirmMessage) {
          this.$confirm(confirmMessage, '提示', { type: 'warning' })
            .then(() => doConfirmReceipt())
            .catch(() => {});
        } else {
          doConfirmReceipt();
        }
      },

      cancel() {
        this.visible = false;
      },

      rejectReason() {
        this.rejectDialogVisible = true;
      },

      confirmReject() {
        this.$refs.rejectForm.validate((valid) => {
          if (!valid) return;
          this.$confirm('确认要驳回该收货单吗？', '提示', { type: 'warning' })
            .then(() => {
              const ids = this.goodsList.map((it) => {
                return it.id;
              });

              console.log('7777');

              rejectGoods({
                ids,
                applyId: this.id,
                beReason: this.rejectForm.reason
              }).then(() => {
                this.$message.success('驳回成功');
                this.rejectDialogVisible = false;
                this.visible = false;
                this.$emit('done');
              });
            })
            .catch(() => {});
        });
      },

      chooseData(dataList) {
        this.goodsList = [];

        dataList.forEach((item) => {
          this.goodsList.push(this.deepCopy(item));
        });
      },

      deepCopy(obj, hash = new WeakMap()) {
        if (obj === null) return null;
        if (obj instanceof Date) return new Date(obj);
        if (obj instanceof RegExp) return new RegExp(obj);
        if (typeof obj !== 'object' && typeof obj !== 'function') return obj;
        if (hash.has(obj)) return hash.get(obj);

        const result = Array.isArray(obj) ? [] : {};
        hash.set(obj, result);

        return Object.keys(obj).reduce((acc, key) => {
          acc[key] = this.deepCopy(obj[key], hash);
          return acc;
        }, result);
      }
    }
  };
</script>

<style></style>
