<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()"
        v-if="!view"
        >新增
      </el-button>
      <span style="margin-left: 10px" v-if="!isAll"
        >待分配数量：<span style="color: #1890ff">{{ count }}</span></span
      >
      <el-table
        ref="multipleTable"
        :data="form.arrivalBatch"
        tooltip-effect="dark"
        style="width: 100%"
        stripe
        :header-cell-style="{ background: '#EEEEEE', border: 'none' }"
      >
        <el-table-column label="批次号" prop="batch" v-if="isBatch">
          <template slot-scope="{ row, $index }">
            <el-form-item
              :prop="'arrivalBatch.' + $index + '.batch'"
              :rules="tableFormRules.batch"
            >
              <el-input
                placeholder="请输入"
                clearable
                v-model="row.batch"
                :disabled="view"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="arriveCount">
          <template slot-scope="{ row, $index }">
            <el-form-item
              :prop="'arrivalBatch.' + $index + '.arriveCount'"
              :rules="tableFormRules.arriveCount"
            >
              <el-input-number
                :min="0"
                :max="getCountMax(row)"
                placeholder="请输入"
                clearable
                @change="handleChange"
                v-model="row.arriveCount"
                :disabled="view"
              ></el-input-number>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="到货时间">
          <template slot-scope="{ row, $index }">
            <el-form-item
              :prop="'arrivalBatch.' + $index + '.arriveDate'"
              :rules="tableFormRules.arriveDate"
            >
              <el-date-picker
                clearable
                v-model="row.arriveDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择日期"
                :disabled="view"
              >
              </el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="操作" prop="action" width="80" v-if="!view">
          <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 { copyObj } from '@/utils/util';

  export default {
    components: {},
    props: {
      view: {
        default: false
      },
      isBatch: {
        default: false
      },
      isAll: {
        default: false
      }
    },
    computed: {
      getCountMax() {
    
        return (row) => {
          if (this.isAll) {
          return 100000000;
        }
          let maxCount = this.current.totalCount * 1 || 0;
          let usedCount = this.form.arrivalBatch.reduce((n, item) => {
            n += item.arriveCount * 1;
            return n;
          }, 0);
          return maxCount - usedCount + row.arriveCount * 1;
        };
      }
    },
    data() {
      return {
        visible: false,
        title: '设置分批时间',
        count: 0,
        current: null,
        currentIndex: null,
        form: {
          arrivalBatch: [
            {
              arriveDate: null,
              arriveCount: null
            }
          ]
        },

        tableFormRules: {
          arriveCount: {
            required: true,
            message: '请输入数量',
            trigger: 'blur'
          },

          arriveDate: {
            required: true,
            message: '请选择日期',
            trigger: 'change'
          },

          batch: {
            required: true,
            message: '请输入批次号',
            trigger: 'change'
          }
        }
      };
    },
    methods: {
      open(row, index) {
        console.log(row);
        this.form.arrivalBatch =
          (row.arrivalBatch && copyObj(row.arrivalBatch)) || [];
        this.current = { ...row };
        this.currentIndex = index;
        this.visible = true;
        this.setCount();
      },
      setCount() {
        if (this.form.arrivalBatch.length) {
          let num = this.form.arrivalBatch.reduce((n, item) => {
            n += item.arriveCount * 1;
            return n;
          }, 0);
          this.count = this.current.totalCount * 1 - num || 0;
        } else {
          this.count = this.current.totalCount * 1 || 0;
        }
      },
      handleChange() {
        this.setCount();
      },
      handleAdd() {
        this.form.arrivalBatch.push({
          arriveDate: null,
          arriveCount: null,
          batch: null
        });
      },

      handleDel(index) {
        this.count += this.form.arrivalBatch[index].arriveCount;
        this.form.arrivalBatch.splice(index, 1);
      },

      handleOk() {
        if (this.count !== 0&&!this.isAll)
          return this.$message.warning('分配数量有误，请检查！');
        let batchS = this.form.arrivalBatch.map((item) => item.batch);
        if (
          new Set(batchS).size != this.form.arrivalBatch.length &&
          this.isBatch
        ) {
          return this.$message.warning('批次号不能重复！');
        }
        this.$refs.tableForm.validate((valid) => {
          if (valid) {
            this.$emit('chooseTime', {
              arrivalBatch: copyObj(this.form.arrivalBatch),
              index: this.currentIndex
            });
            this.handleClose();
          }
        });
      },

      handleClose() {
        this.$refs.tableForm && this.$refs.tableForm.resetFields();
        this.visible = false;
      }
    }
  };
</script>

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

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