<template>
  <div>
    <div class="title_box rx-bc mt6">
      <div class="name">在制品 </div>

      <div class="rx-bc"> </div>
    </div>

    <ele-pro-table
      ref="table"
      :needPage="false"
      :columns="columns"
      :datasource="list"
      class="time-form"
      max-height="600"
      @columns-change="handleColumnChange"
      :cache-key="cacheKeyUrl"
      row-key="id"
    >
      <template v-slot:name="{ row, $index }">
        <span>{{ row.name + '-在制品' }}</span>
      </template>

      <template v-slot:batchNo="{ row, $index }">
        <el-input
          size="mini"
          class="content_num"
          v-model="row.batchNo"
          placeholder="批次号"
          :disabled="isEdit"
        >
        </el-input>
      </template>

      <template v-slot:extInfo="{ row, $index }">
        <span v-if="row.extInfo">
          {{ row.extInfo.sourceQuantity || 0 }}
          {{ row.unit }}</span
        >
      </template>

      <template v-slot:newWeight="{ row, $index }">
        <span v-if="row.extInfo.newWeight">
          {{ row.extInfo.newWeight || 0 }}
          {{ row.extInfo.weightUnit }}
        </span>
      </template>
      <!--
      <template v-slot:feedQuantity="{ row, $index }">
        <el-input
          size="mini"
          v-model="row.feedQuantity"
          type="digit"
          @input="maxFeedQuantity(row)"
          disabled
          placeholder="请输入投料数量"
        />
      </template> -->

      <template v-slot:action="{ row, $index }">
        <el-link
          type="text"
          @click="openBatch(row, $index)"
          v-if="row.extInfo.sourceQuantity > 1"
          >拆批</el-link
        >
        <el-link type="danger" @click="deleteBatch(row, $index)">删除</el-link>
      </template>
    </ele-pro-table>

    <el-dialog
      title="拆批数"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="拆批数">
          <el-input v-model="form.quantity"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="asyncgetQualityParam"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import tabMixins from '@/mixins/tableColumnsMixin';
  import { splitBatch } from '@/api/produce/feeding';
  export default {
    name: 'productsBom',
    mixins: [tabMixins],
    props: {
      itemObj: {
        type: Object,
        default: () => {}
      },
      productsArr: {
        type: Array,
        default: () => {}
      },
      isEdit: {
        type: Boolean,
        default: false
      }
    },

    data() {
      return {
        list: [],
        cacheKeyUrl: 'batch-products-bom',
        dialogVisible: false,
        form: {
          quantity: ''
        },
        itemData: {},
        itemIndex: ''
      };
    },

    mounted() {
      console.log(this.itemObj, 'this.itemObj');
      if (this.itemObj.product) {
        this.list.push(...this.itemObj.product);
        this.list.forEach((item) => {
          if (!item.batchNo) {
            item.batchNo = this.itemObj.batchNo;
          }
          item.childBatch = 0;
        });
      } else {
        this.list.push(...this.itemObj.inProductList);
      }

      console.log(this.list, 'this.list');

      console.log(this.itemObj, 'this.itemObj');
    },

    computed: {
      columns() {
        let action = {};

        if (!this.isEdit) {
          action = {
            columnKey: 'action',
            label: '操作',
            width: 120,
            align: 'center',
            resizable: false,
            slot: 'action',
            fixed: 'right',
            showOverflowTooltip: true,
            show: true
          };
        }

        return [
          {
            width: 55,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            label: '序号',
            fixed: 'left'
          },
          {
            minWidth: 120,
            slot: 'batchNo',
            prop: 'batchNo',
            align: 'center',
            label: '批次号'
          },
          {
            minWidth: 120,
            prop: 'name',
            slot: 'name',
            label: '名称',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            minWidth: 120,
            prop: 'brandNu',
            label: '牌号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            minWidth: 120,
            prop: 'modelType',
            label: '型号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            minWidth: 120,
            prop: 'extInfo',
            slot: 'extInfo',
            label: '数量',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            minWidth: 120,
            prop: 'feedQuantity',
            slot: 'feedQuantity',
            label: '投料数量',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            minWidth: 120,
            prop: 'newWeight',
            slot: 'newWeight',
            label: '重量',
            align: 'center',
            showOverflowTooltip: true
          },
          action
          // {
          //   columnKey: 'action',
          //   label: '操作',
          //   width: 120,
          //   align: 'center',
          //   resizable: false,
          //   slot: 'action',
          //   fixed: 'right',
          //   showOverflowTooltip: true
          // }
        ];
      }
    },

    methods: {
      maxFeedQuantity(item) {
        if (item.feedQuantity > this.itemObj.formingNum) {
          this.$set(item, 'feedQuantity', this.itemObj.formingNum);
        }
      },

      openBatch(row, index) {
        this.form.quantity = '';
        this.itemData = row;
        this.itemIndex = index;
        this.dialogVisible = true;
      },

      async asyncgetQualityParam() {
        console.log(this.itemIndex, 'index');
        if (this.form.quantity) {
          if (this.itemData.extInfo.sourceQuantity <= this.form.quantity) {
            this.$message.warning('拆批数不能大于数量');
            return;
          }

          let dataList = [];
          await splitBatch({
            product: this.itemData,
            splitQt: Number(this.form.quantity)
          }).then((res) => {
            res.forEach((item) => {
              dataList.push(this.deepCopy(item));
            });

            this.refreshData(dataList);
          });
        }
        this.dialogVisible = false;
      },

      refreshData(list) {
        const number =
          Number(this.list[this.itemIndex].extInfo.sourceQuantity) -
          Number(this.form.quantity);
        this.list[this.itemIndex].extInfo.sourceQuantity = number;
        this.list[this.itemIndex].feedQuantity = number;

        list.forEach((item) => {
          item.childBatch = 1;
        });
        let _arr = [...this.list, ...list];

        this.list = _arr;

        this.$set(this.itemObj, 'product', _arr);
      },

      deleteBatch(row, index) {
        this.list.splice(index, 1);

        this.$set(this.itemObj, 'product', this.list);
      },

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

      handleClose() {
        this.dialogVisible = false;
      }
    }
  };
</script>

<style scoped lang="scss"></style>
