<template>
  <ele-modal
    :visible.sync="visible"
    :title="title"
    v-if="visible"
    width="65vw"
    append-to-body
    :maxable="true"
  >
    <el-button
      size="small"
      type="primary"
      icon="el-icon-plus"
      class="ele-btn-icon"
      @click="addGoods"
      style="margin-bottom: 10px"
      v-if="type != 'detail' && type != 'receipt'"
    >
      新增在制品
    </el-button>

    <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:weight="{ row }">
        <span>{{ row.weight }}{{ row.weightUnit }}</span>
      </template>

      <template v-slot:receiveQuantity="{ row }">
        <el-input
          placeholder=""
          v-model="row.receiveQuantity"
          :disabled="type == 'receipt' && itemData.sendStatus == 4"
        >
          <template slot="append">{{ row.measuringUnit }}</template>
        </el-input>
      </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' && itemData.sendStatus != 4">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="save"> 确定 </el-button>
    </template>

    <add-invoice ref="addInvoiceRef" @chooseData="chooseData"></add-invoice>
  </ele-modal>
</template>

<script>
  import {
    pleaseEntrustGoodsDetail,
    pleaseEntrustSaveDetail,
    pleaseTReceiveGoods
  } from '@/api/entrust';
  import { typeName } from '@/views/produce/components/common.js';

  import addInvoice from './addInvoice.vue';
  export default {
    components: {
      addInvoice
    },

    data() {
      return {
        visible: false,
        goodsList: [],
        selection: [],
        current: null,
        typeName,
        id: '',
        title: '',
        type: '',
        itemData: {},
        loading: null
      };
    },

    computed: {
      columns() {
        return [
          {
            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: 140,
            showOverflowTooltip: true
          },

          {
            prop: 'workOrderCode',
            label: '生产工单号',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'receiveQuantity',
            slot: 'receiveQuantity',
            label: '接收数量',
            align: 'center',
            minWidth: 150,
            showOverflowTooltip: true,
            show: this.type == 'receipt' ? true : false
          },
          {
            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.type = type;
        this.title = this.type != 'receipt' ? '发货单' : '收货单';
        this.itemData = item;
        this.id = item.id;
        this.getDetail(item.id);
      },

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

      save() {
        if (this.type != 'receipt') {
          if (this.goodsList.length == 0) {
            return this.$message.warning('请先新增一条在制品数据!');
          }

          this.loading = this.$loading({
            lock: true,
            text: '加载中',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          pleaseEntrustSaveDetail(this.goodsList)
            .then((res) => {
              this.loading.close();
              this.$message.success('发货成功');
              this.$emit('done');
              this.visible = false;
            })
            .catch(() => {
              this.loading.close();
            });
        } else if (this.type == 'receipt') {
          this.loading = this.$loading({
            lock: true,
            text: '加载中',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          pleaseTReceiveGoods(this.goodsList)
            .then((res) => {
              this.loading.close();
              this.$message.success('收货成功');
              this.$emit('done');
              this.visible = false;
            })
            .catch(() => {
              this.loading.close();
            });
        }
      },

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

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

      addGoods() {
        this.$refs.addInvoiceRef.open(this.id, this.goodsList);
      }
    }
  };
</script>

<style></style>
