<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    width="35%"
  >
    <el-form
      :model="form"
      ref="tableForm"
      class="tableForm"
      :rules="tableFormRules"
    >
      <el-button
        type="primary"
        size="small"
        style="margin-bottom: 10px"
        @click="handleAdd()"
        >新增</el-button
      >
      <span style="margin-left: 10px" v-if="!isAll"
        >待分配数量：<span style="color: #1890ff">{{ num }}</span></span
      >
      <el-table
        ref="multipleTable"
        :data="form.timeList"
        tooltip-effect="dark"
        style="width: 100%"
        stripe
        :header-cell-style="{ background: '#EEEEEE', border: 'none' }"
      >
        <el-table-column label="批次号" prop="batchNo">
          <template slot-scope="{ row, $index }">
            <el-form-item
              :prop="'timeList.' + $index + '.batchNo'"
              :rules="tableFormRules.batchNo"
            >
              <el-input
                placeholder="请输入"
                clearable
                v-model="row.batchNo"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="数量" prop="purchaseQuantity">
          <template slot-scope="{ row, $index }">
            <el-form-item
              :prop="'timeList.' + $index + '.purchaseQuantity'"
              :rules="tableFormRules.purchaseQuantity"
            >
              <el-input
                placeholder="请输入"
                clearable
                type="number"
                v-model="row.purchaseQuantity"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="到货时间">
          <template slot-scope="{ row, $index }">
            <el-form-item
              :prop="'timeList.' + $index + '.requireDeliveryTime'"
              :rules="tableFormRules.requireDeliveryTime"
            >
              <el-date-picker
                clearable
                v-model="row.requireDeliveryTime"
                value-format="timestamp"
                placeholder="请选择日期"
                :pickerOptions="{
                  disabledDate: (time) =>
                    time.getTime() <
                    new Date(new Date().setHours(0, 0, 0, 0)).getTime()
                }"
              >
              </el-date-picker>
            </el-form-item> </template
        ></el-table-column>

        <el-table-column label="操作" prop="action" width="80">
          <template slot-scope="{ $index }">
            <el-link
              type="primary"
              :underline="false"
              @click="handleDel($index)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <div class="btns">
      <el-button type="primary" size="small" @click="handleOk">确认</el-button>
      <el-button size="small" @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { getCode } from '@/api/codeManagement';

  export default {
    components: {},

    data() {
      return {
        visible: false,
        title: '设置分批时间',
        isAll: false,
        current: null,
        form: {
          timeList: [
            {
              requireDeliveryTime: null,
              purchaseQuantity: null,
              batchNo: null
            }
          ]
        },

        tableFormRules: {
          purchaseQuantity: {
            required: true,
            message: '请输入数量',
            trigger: 'blur'
          },
          batchNo: {
            required: true,
            message: '请输入批次号',
            trigger: 'blur'
          },
          requireDeliveryTime: {
            required: true,
            message: '请选择日期',
            trigger: 'change'
          }
        },
        currentIndex: '',
        count: 0
      };
    },

    watch: {},
    computed: {
      num() {
        console.log(this.form.timeList, 'this.form.timeList');
        return (
          this.count -
            this.form.timeList.reduce((pre, cur) => {
              return pre + (Number(cur.purchaseQuantity) || 0);
            }, 0) || 0
        );
      }
    },
    methods: {
      open(row, index, isAll) {
        this.isAll = isAll;
        console.log(row, 'row', index);
        if (row) {
          let row1 = JSON.parse(JSON.stringify(row));
          this.count = row1.demandQuantity || 0;
          this.form.timeList = row1.timeList || [];
          this.form.timeList?.forEach(async (item, index) => {
            if (!item.batchNo) {
              this.$set(
                this.form.timeList[index],
                'batchNo',
                await getCode('lot_number_code')
              );
            }
          });
          this.current = row1;
          this.currentIndex = index;
        }
        this.visible = true;
      },

      async handleAdd() {
        this.form.timeList.push({
          requireDeliveryTime: null,
          purchaseQuantity: null,
          batchNo: await getCode('lot_number_code')
        });
      },

      handleDel(index) {
        this.form.timeList.splice(index, 1);
      },

      handleOk() {
        this.$refs.tableForm.validate((valid) => {
          if (valid) {
            const clonedTimeList = JSON.parse(
              JSON.stringify(this.form.timeList)
            );
            if (!this.isAll) {
              if (this.num < 0) {
                return this.$message.warning('分配数量不能大于需求数量！');
              }
              if (this.num > 0) {
                return this.$message.warning('需求数量还未分配完，请检查！');
              }
            }

            this.$emit(
              'chooseTime',
              this.current,
              clonedTimeList,
              this.currentIndex
            );
            this.handleClose();
          }
        });
      },

      handleClose() {
        this.visible = false;
        this.form.timeList = [
          {
            requireDeliveryTime: null,
            purchaseQuantity: null
          }
        ];
      }
    }
  };
</script>

<style lang="scss" scoped>
  .btns {
    margin-top: 20px;
    text-align: center;
  }

  .el-form-item {
    margin-bottom: 20px !important;
  }
</style>
