<template>
  <ele-modal width="60vw" :visible.sync="visible" :close-on-click-modal="false" custom-class="ele-dialog-form"
    :title="'拆分工单'" :maxable="true">
    <div class="form-wrapper">
      <el-form :model="requestData" label-width="0" :show-message="false">
        <el-descriptions title="" :column="2" border>
          <el-descriptions-item label="工单号">
            {{ formData.code }}</el-descriptions-item>
          <el-descriptions-item label="物料编码">
            {{ formData.productCode }}</el-descriptions-item>
          <el-descriptions-item label="产品名称">{{
            formData.productName
          }}</el-descriptions-item>
          <el-descriptions-item label="牌号|型号">
            {{ formData.brandNo }}|{{ formData.model }}</el-descriptions-item>
          <el-descriptions-item label="要求生产数量">{{
            formData.formingNum
          }}</el-descriptions-item>
          <el-descriptions-item label="计划开始时间">{{
            formData.planStartTime
          }}</el-descriptions-item>
          <el-descriptions-item label="计划完成日期">{{
            formData.planCompleteTime
          }}</el-descriptions-item>
        </el-descriptions>
      </el-form>

      <headerTitle title="剩余拆单" class="mt20">
      </headerTitle>
      <el-form ref="form" :model="form" :rules="rules">
        <ele-pro-table ref="table" :needPage="false" :columns="columns" :datasource="form.surplusUnpack">

          <template v-slot:toolbar>
            <el-button size="small" type="primary" icon="el-icon-plus" class="ele-btn-icon"
              :disabled="formingNum == 0 ? true : false" @click="openUnpack">
              拆单
            </el-button>
          </template>


          <template v-slot:formingNum="scope">
            <el-form-item v-if="formingNum != 0" :prop="'surplusUnpack.' + scope.$index + '.formingNum'" :rules="[
              {
                required: true,
                message: '请输入要求生产数量',
                trigger: 'change'
              },
              {
                pattern: /^\d+(\.{0,1}\d+){0,1}$/, message: '拆单数超过生产数量', trigger: ['blur', 'change']
              }
            ]">
              <el-input disabled v-model="formingNum" placeholder="请输入"></el-input>
            </el-form-item>

            <el-form-item v-else>
              工单已全部拆完
            </el-form-item>
          </template>


          <template v-slot:planStartTime="scope">
            <el-form-item v-if="formingNum != 0" :prop="'surplusUnpack.' + scope.$index + '.planStartTime'" :rules="{
              required: true,
              message: '请选择开始计划时间',
              trigger: 'change'
            }">
              <el-date-picker class="w100" v-model="scope.row.planStartTime" type="date" disabled
                value-format="yyyy-MM-dd"></el-date-picker>

            </el-form-item>
          </template>


          <template v-slot:classeId="scope">
            <el-form-item v-if="formingNum != 0" :prop="'surplusUnpack.' + scope.$index + '.classeId'" :rules="{
              required: true,
              message: '请选择排班',
              trigger: 'change'
            }">

              <el-input readonly v-model="scope.row.classeName" disabled
                @click.native="openClasse(scope.row, 1, scope.$index)"></el-input>
            </el-form-item>
          </template>


        </ele-pro-table>



        <headerTitle title="拆单" class="mt20">
        </headerTitle>

        <ele-pro-table ref="table" :needPage="false" :columns="columns2" :datasource="form.unpackList">



          <template v-slot:formingNum="scope">
            <el-form-item :prop="'unpackList.' + scope.$index + '.formingNum'" :rules="{
              required: true,
              message: '请输入要求生产数量',
              trigger: 'change'
            }">
              <!-- <el-input-number type="number" @change="changeNum(scope.$index)" :min="0" v-model="scope.row.formingNum"
                placeholder="请输入"></el-input-number> -->
              <el-input v-model="scope.row.formingNum" type="number" @input="changeNum(scope.$index)" :min="0"
                placeholder="请输入内容"></el-input>

            </el-form-item>
          </template>


          <template v-slot:planStartTime="scope">
            <el-form-item :prop="'unpackList.' + scope.$index + '.planStartTime'" :rules="{
              required: true,
              message: '请选择开始计划时间',
              trigger: 'change'
            }">
              <el-date-picker class="w100" v-model="scope.row.planStartTime" type="date" value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"></el-date-picker>

            </el-form-item>
          </template>


          <template v-slot:classeId="scope">
            <el-form-item :prop="'unpackList.' + scope.$index + '.classeId'" :rules="[{
              required: true,
              message: '请选择排班',
              trigger: 'change'
            }]">

              <el-input readonly v-model="scope.row.classeName" @click.native="openClasse(scope.row, 2, scope.$index)"
                ></el-input>

            </el-form-item>
          </template>


          <template v-slot:action="{ $index }">
            <el-popconfirm class="ele-action" title="确定要删除此子单吗？" @confirm="remove($index)">
              <template v-slot:reference>
                <el-link type="danger" :underline="false" icon="el-icon-delete">
                  删除
                </el-link>
              </template>
            </el-popconfirm>


          </template>



        </ele-pro-table>


      </el-form>

      <scheduleDialog ref="scheduleRef" @changeProduct="changeProduct"></scheduleDialog>

    </div>
    <div slot="footer">
      <el-button plain @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </div>

  </ele-modal>
</template>

<script>
import { splitWork } from '@/api/produceOrder/index.js';
import scheduleDialog from './scheduleDialog.vue'

import { deepClone } from '@/utils';
export default {
  components: {
    scheduleDialog
  },
  data() {
    return {
      visible: false,

      formData: {},
      requestData: {
        deviceCode: '',
        deviceName: '',
        deviceId: ''
      },
      formingNum: 0,

      form: {
        surplusUnpack: [],
        unpackList: []
      },

      pickerOptions: {
        disabledDate: (time) => {
          // 根据某个条件动态设置最大日期
          if (this.formData.planStartTime) {
            const maxDate = new Date(this.formData.planStartTime); // 您的逻辑方法
            return time.getTime() <= maxDate.getTime();
          } else {
            return false;
          }

        }
      },

      pickerOptionsEnd: {
        disabledDate: (time) => {
          // 根据某个条件动态设置最大日期
          if (this.formData.planCompleteTime) {
            const maxDate = new Date(this.formData.planCompleteTime); // 您的逻辑方法
            return time.getTime() >= maxDate.getTime();
          } else {
            return false;
          }

        }
      },

      rules: {

      },



      columns: [
        {
          prop: 'originalCode',
          label: '工单号',
          align: 'center',
          minWidth: 200
        },
        {
          prop: 'formingNum',
          label: '要求生产数量',
          align: 'center',
          slot: 'formingNum',
          minWidth: 200
        },
        {
          prop: 'planStartTime',
          label: '计划开始时间',
          align: 'center',
          slot: 'planStartTime',
          minWidth: 200
        },
        {
          prop: 'classeId',
          label: '排班',
          align: 'center',
          slot: 'classeId',
          minWidth: 200
        },
      ],


      columns2: [
        {
          prop: 'originalCode',
          label: '工单号',
          align: 'center',
          minWidth: 200
        },
        {
          prop: 'formingNum',
          label: '要求生产数量',
          align: 'center',
          slot: 'formingNum',
          minWidth: 200
        },
        {
          prop: 'planStartTime',
          label: '计划开始时间',
          align: 'center',
          slot: 'planStartTime',
          minWidth: 200
        },
        {
          prop: 'classeId',
          label: '排班',
          align: 'center',
          slot: 'classeId',
          minWidth: 200
        }, {
          columnKey: 'action',
          label: '操作',
          width: 160,
          align: 'center',
          resizable: false,
          fixed: 'right',
          slot: 'action',
          showOverflowTooltip: true
        }


      ]

    };
  },
  methods: {
    open(row) {
      this.visible = true;
      this.formData = deepClone(row)
      this.formingNum = this.formData.formingNum


      this.form.surplusUnpack = []
      this.form.unpackList = []
      this.setSurplus()



    },

    setSurplus() {
      // this.form.surplusUnpack.push({ originalCode: this.formData.code, formingNum: this.formData.formingNum, planStartTime: '', classeId: '', isCopy:1  })
      this.form.surplusUnpack.push({ originalCode: this.formData.code, formingNum: this.formData.formingNum, planStartTime: this.formData.planStartTime, planCompleteTime: this.formData.planCompleteTime, isCopy: 1 })
    },

    openUnpack() {
      this.form.unpackList.push({ originalCode: this.formData.code, formingNum: '', planStartTime: '', classeId: '' })
    },

    changeNum(index) {
      let num = this.formData.formingNum
      this.form.unpackList.forEach((e) => {
        if (e.formingNum != null && e.formingNum != undefined) {
          num = num - Number(e.formingNum)
          if (num >= 0) {
            this.formingNum = num
          } else {

            this.$nextTick(() => {
              this.$set(this.form.unpackList[index], 'formingNum', 0)
            })
            this.$message.error('拆单数超过生产数量')

            return
          }
        }

      })
    },

    remove(index) {
      this.form.unpackList.splice(index, 1);
      if (this.form.unpackList.length == 0) {
        this.formingNum = this.formData.formingNum
      } else {
        this.changeNum(index)
      }

    },




    cancel() {
      this.formData = {};
      this.visible = false;
      this.$refs.form.resetFields();
    },


    openClasse(row, type, idx) {
      this.$refs.scheduleRef.open(row, type, idx)
    },

    changeProduct(list, type, idx) {

      if (type == 1) {
        this.$set(this.form.surplusUnpack[idx], 'classeId', list.id)
        this.$set(this.form.surplusUnpack[idx], 'classeName', list.name)
      } else if (type == 2) {
        this.$set(this.form.unpackList[idx], 'classeId', list.id)
        this.$set(this.form.unpackList[idx], 'classeName', list.name)
      }

    },
    confirm() {

      this.$refs.form.validate(async (value) => {
        if (value) {
          if (this.form.unpackList.length == 1 && this.form.unpackList[0].formingNum == this.formData.formingNum) {
            this.$message.info('拆单数要大于1')
            return false
          }

          if (this.form.surplusUnpack.length == 1 && this.form.unpackList.length == 0) {
            this.$message.info('拆单数要大于1')
            return false
          }


          let params = []
          if (this.formingNum != 0) {
            this.form.surplusUnpack[0].formingNum = this.formingNum
            params = [...this.form.unpackList, ...this.form.surplusUnpack]
          } else {
            params = this.form.unpackList
          }


          const res = await splitWork(params);
          if (res) {
            this.$message.success('拆分成功！');
            this.$emit('success');
            this.cancel();
          }

        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.mt20 {
  margin-top: 20px;
}

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