<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="splitDialogFlag"
    title="拆分"
    :close-on-click-modal="false"
    width="80%"
    :before-close="cancel"
  >

    <el-form ref="form" :model="form" class="el-form-box" label-width="120px">
      <headerTitle title="基本信息">
        <!-- <el-button
                size="small"
                type="primary"
                icon="el-icon-s-grid"
                class="ele-btn-icon"
                @click="exportTable"
              >
               导出
              </el-button> -->
      </headerTitle>
      <expandPanel :contentStyle="{'height':'0px'}" :isExpand.sync="isExpand">
        <el-row>
          <el-col :span="12" style="height: 46px">
            <el-form-item label="需求单名称：" prop="requirementCode">
              <el-input v-model="form.requirementName" disabled></el-input>
            </el-form-item>

          </el-col>
          <el-col :span="12" style="height: 46px">
            <el-form-item label="计划单名称：" prop="planName">
              <el-input v-model="form.planName" disabled></el-input>
              <!-- {{ form.requirementCode }} -->
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="负责人：" prop="responsibleName">
              <el-input v-model="form.responsibleName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求类型：" prop="sourceTypeName">
              <el-input v-model="form.sourceTypeName" disabled></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="需求部门：" prop="requireDeptName">
              <el-input v-model="form.requireDeptName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求人：" prop="requireUserName">
              <el-input v-model="form.requireUserName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="remark" label="是否接受拆单：">
              <el-select v-model="form.acceptUnpack" placeholder="请选择" disabled style="width: 100%">
                <el-option label="接受" :value="1"></el-option>
                <el-option label="不接受" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
          <el-form-item
            label="用途"
            prop="requireUserName"
            style="margin-bottom: 22px"
          >
            {{ form.requireUserName }}
          </el-form-item>
        </el-col> -->
          <el-col :span="12">
            <el-form-item label="完结日期：" prop="receiveDate">
              <el-input v-model="form.receiveDate" disabled></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="remark" label="备注：">
              <el-input v-model="form.remark" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="askFile" label="附件：">
              <el-link
                v-if="form.files && form.files !== ''"
                type="primary"
                :underline="false"
                @click="downloadFile(form.files)"
              >
                {{ form.files.name }}
              </el-link
              >
            </el-form-item>
          </el-col>
        </el-row>
      </expandPanel>
      <headerTitle title="计划清单" style="margin-top: 15px"></headerTitle>
      <ele-pro-table
        ref="table"
        :needPage="false"
        :columns="columns"
        :toolkit="[]"
        max-height="500px"
        :datasource="form.detailList"
        row-key="id"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar="{row}">
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="handleSplit">
            拆分
          </el-button>
        </template>
        <template v-slot:expectReceiveDate="scope">
          <el-form-item
            v-if="scope.row.arrivalWay == 1"
            label-width="0px"
            :rules="{
            required: true,
            message: '请选择日期',
            trigger: 'blur'
          }"
          >
            <el-date-picker
              style="width: 100%"
              clearable
              v-model="scope.row.expectReceiveDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label-width="0px"
            v-if="scope.row.arrivalWay == 2"
          >
            <el-link
              type="primary"
              :underline="false"
              @click.native="handleMethod(scope.row,scope.$index,'','form')"
            >
              设置分批时间
            </el-link>
          </el-form-item>
        </template>
        <template v-slot:arrivalWay="scope">
          <el-form-item
            :rules="{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }"
            label-width="0px"
          >
            <el-select
              v-model="scope.row.arrivalWay"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in arrivalWayList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </template>
        <template v-slot:totalCount="scope">
          <span v-if="scope.row.totalCount">{{ scope.row.totalCount }}</span>
          <span v-else style="color: red">已全部拆完</span>
        </template>
        <template v-slot:technicalDrawings="{ row }">
          <div v-if="row.technicalDrawings && row.technicalDrawings?.length">
            <el-link
              v-for="link in row.technicalDrawings"
              :key="link.id"
              type="primary"
              :underline="false"
              @click="downloadFile(link)"
            >
              {{ link.name }}
            </el-link
            >
          </div>
        </template>
        <template v-slot:files="{ row }">
          <div v-if="row.files && row.files?.length">
            <el-link
              v-for="link in row.files"
              :key="link.id"
              type="primary"
              :underline="false"
              @click="downloadFile(link)"
            >
              {{ link.name }}
            </el-link
            >
          </div>
        </template>
      </ele-pro-table>
    </el-form>

    <headerTitle v-if="splitFormList.length" title="拆分明细"/>
    <el-form v-if="splitFormList.length" :key="index" class="el-form-box" v-for="(item,index) in splitFormList"
             :model="item">
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="责任人"
            prop="responsibleName"
            label-width="80px"
          >
            <el-input
              @click.native="openStaffSelection(index)" v-model="item.responsibleName"
              placeholder="请选择"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" style="display: flex;justify-content: flex-end">
          <el-button type="text" @click="handleMerge(index)" style="color: red"> 删除</el-button>
        </el-col>
      </el-row>

      <ele-pro-table
        ref="table"
        :needPage="false"
        :columns="splitColumns"
        :toolkit="[]"
        style="margin-bottom: 10px"
        :datasource="item.detailList"
        row-key="id">
        <template v-slot:totalCount="{row}">
          <el-input-number style="width: 100%" :min="0" :max="getCountMax(row)"
                           @change="handleTotalCount(row,index)"
                           v-model="row.totalCount"></el-input-number>
        </template>
        <template v-slot:technicalDrawings="{ row }">
          <div v-if="row.technicalDrawings && row.technicalDrawings?.length">
            <el-link
              v-for="link in row.technicalDrawings"
              :key="link.id"
              type="primary"
              :underline="false"
              @click="downloadFile(link)"
            >
              {{ link.name }}
            </el-link
            >
          </div>
        </template>
        <template v-slot:files="{ row }">
          <div v-if="row.files && row.files?.length">
            <el-link
              v-for="link in row.files"
              :key="link.id"
              type="primary"
              :underline="false"
              @click="downloadFile(link)"
            >
              {{ link.name }}
            </el-link
            >
          </div>
        </template>
        <template v-slot:expectReceiveDate="scope">
          <el-form-item
            v-if="scope.row.arrivalWay == 1"
            label-width="0px"
            :rules="{
            required: true,
            message: '请选择日期',
            trigger: 'blur'
          }"
          >
            <el-date-picker
              style="width: 100%"
              clearable
              v-model="scope.row.expectReceiveDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label-width="0px"
            v-if="scope.row.arrivalWay == 2"
          >
            <el-link
              type="primary"
              :underline="false"
              @click.native="handleMethod(scope.row,scope.$index,index,'splitForm')"
            >
              设置分批时间
            </el-link>
          </el-form-item>
        </template>
        <template v-slot:arrivalWay="scope">
          <el-form-item
            :rules="{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }"
            label-width="0px"
          >
            <el-select
              v-model="scope.row.arrivalWay"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in arrivalWayList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </template>
        <!-- 操作列 -->
        <template v-slot:action="scope">
          <el-popconfirm
            class="ele-action"
            title="确定要删除吗？"
            @confirm="handleRemove(index,scope.$index,scope.row)"
          >
            <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>
    <staffSelection
      ref="staffSelection"
      @confirm="confirmStaffSelection"
    ></staffSelection>
    <timeDialog @chooseTime="chooseTime" ref="timeDialogRef"></timeDialog>
    <div slot="footer" class="footer">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="cancel">返回</el-button>
    </div>
  </ele-modal>
</template>

<script>
import personSelect from "@/components/CommomSelect/person-select.vue";
import fileUpload from "@/components/upload/fileUpload.vue";
import {getplanDetail, savePurchasePlanCutAPI} from "@/api/purchasingManage/purchasePlanManage";
import {deepClone} from "@/utils";
import expandPanel from "@/components/Expand-Panel/index.vue";
import staffSelection from "@/views/purchasingManage/purchasePlanManage/components/staffSelection.vue";
import timeDialog from "@/components/timeDialog/index.vue";
import {copyObj} from "@/utils/util";

export default {
  name: "splitDialog",
  components: {timeDialog, staffSelection, fileUpload, personSelect, expandPanel},
  props: {
    splitDialogFlag: Boolean
  },
  data() {
    return {
      title: '',
      currentIndex: null,
      currentForm: null,
      isExpand: true,
      form: {},
      historyForm: {},
      splitFormList: [],
      rules: {},
      columns: [
        {
          width: 45,
          type: 'index',
          columnKey: 'index',
          align: 'center',
          fixed: 'left'
        },
        {
          minWidth: 120,
          prop: 'productCategoryName',
          label: '分类',
          slot: 'productCategoryName',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          minWidth: 120,
          prop: 'productCode',
          label: '编码',
          slot: 'productCode',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          minWidth: 150,
          prop: 'productName',
          label: '名称',
          slot: 'productName',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          minWidth: 150,
          prop: 'totalCount',
          label: '数量',
          slot: 'totalCount',
          align: 'center'
        },
        {
          width: 100,
          prop: 'measuringUnit',
          label: '单位',
          slot: 'measuringUnit',
          align: 'center'
        },
        {
          width: 170,
          prop: 'planStartDate',
          label: '计划开始日期',
          slot: 'planStartDate',
          align: 'center'
        },
        {
          width: 170,
          prop: 'planEndDate',
          label: '计划结束日期',
          slot: 'planEndDate',
          align: 'center'
        },
        {
          width: 160,
          prop: 'arrivalWay',
          label: '到货方式',
          slot: 'arrivalWay',
          align: 'center'
        },
        {
          width: 170,
          prop: 'expectReceiveDate',
          label: '到货日期',
          slot: 'expectReceiveDate',
          align: 'center'
        },
      ],
      arrivalWayList: [
        {label: '一次性到货', value: 1},
        {label: '分批到货', value: 2}
      ],
      splitColumns: [
        {
          width: 45,
          type: 'index',
          columnKey: 'index',
          align: 'center',
          fixed: 'left'
        },
        {
          minWidth: 120,
          prop: 'productCategoryName',
          label: '分类',
          slot: 'productCategoryName',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          minWidth: 120,
          prop: 'productCode',
          label: '编码',
          slot: 'productCode',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          minWidth: 150,
          prop: 'productName',
          label: '名称',
          slot: 'productName',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          minWidth: 160,
          prop: 'totalCount',
          label: '数量',
          slot: 'totalCount',
          align: 'center'
        },
        {
          width: 100,
          prop: 'measuringUnit',
          label: '单位',
          slot: 'measuringUnit',
          align: 'center'
        },
        {
          width: 170,
          prop: 'planStartDate',
          label: '计划开始日期',
          slot: 'planStartDate',
          align: 'center'
        },
        {
          width: 170,
          prop: 'planEndDate',
          label: '计划结束日期',
          slot: 'planEndDate',
          align: 'center'
        },
        {
          width: 150,
          prop: 'arrivalWay',
          label: '到货方式',
          slot: 'arrivalWay',
          align: 'center'
        },
        {
          width: 170,
          prop: 'expectReceiveDate',
          label: '到货日期',
          slot: 'expectReceiveDate',
          align: 'center'
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 120,
          align: 'center',
          resizable: false,
          slot: 'action',
          fixed: 'right',
          showOverflowTooltip: true
        }
      ],
    }
  },
  computed: {
    getCountMax() {
      return (row) => {
        let maxCount = this.historyForm.detailList.find(item => row.id == item.id)?.totalCount
        let usedCount = this.splitFormList.reduce((num, item) => {
          num += item.detailList.find(o => o.id == row.id)?.totalCount || 0
          return num
        }, 0)
        let remainCount = maxCount - usedCount
        let availableCount = remainCount + row.totalCount
        this.setFormCount(row.id, remainCount)
        return availableCount
      }
    }
  },
  methods: {
    init(row) {
      this.getPlanData(row.planId || row.id);
    },
    async getPlanData(id) {
      this.loading = true;
      const data = await getplanDetail(id);
      this.loading = false;
      if (data) {
        this.form = data;
        this.historyForm = deepClone(this.form)
        if (data.files && data.files.length > 0) {
          this.form.files = data.files[0];
        } else {
          this.form.files = null;
        }
      }
    },
    setFormCount(id, num) {
      let index = this.form.detailList.findIndex(item => item.id == id)
      this.$set(this.form.detailList[index], 'totalCount', num)
    },
    handleTotalCount(row, formIndex) {
      row.arrivalBatch = []
      let index = this.form.detailList.findIndex(item => item.id == row.id)
      if (index >= 0) {
        this.form.detailList[index].arrivalBatch = []
      }

      // this.splitFormList[formIndex].detailList.
    },
    handleSplit() {
      const form = deepClone(this.form)
      form.detailList.forEach(item => {
        item.totalCount = 0
        item.arrivalBatch = []
      })
      this.splitFormList.push(form)
    },
    handleRemove(formIndex, index, row) {
      this.splitFormList[formIndex].detailList.splice(index, 1)
      let count = this.form.detailList.find(item => item.id == row.id)?.totalCount
      count += row.totalCount
      this.setFormCount(row.id, count)
      if (this.splitFormList[formIndex].detailList.length == 0) {
        this.handleMerge(formIndex)
      }
    },
    handleMerge(index) {
      this.splitFormList.splice(index, 1)
      if (this.splitFormList.length == 0) {
        this.form = this.historyForm
      }
    },
    openStaffSelection(index) {
      this.$refs.staffSelection.open(
        this.form.responsibleName
          ? [{name: this.form.responsibleName, id: this.form.responsibleId}]
          : []
      );
      this.currentIndex = index
    },
    confirmStaffSelection(data) {
      // this.form.responsibleName = (data && data[0].name) || '';
      // this.form.responsibleId = (data && data[0].id) || '';
      this.$set(this.splitFormList[this.currentIndex], 'responsibleId', (data && data[0].id) || '')
      this.$set(this.splitFormList[this.currentIndex], 'responsibleName', (data && data[0].name) || '')
    },
    handleMethod(row, index, splitFormIndex, currentForm) {
      this.currentIndex = splitFormIndex
      this.currentForm = currentForm
      this.$refs.timeDialogRef.open(row, index);
    },
    chooseTime(row, arrivalBatch, index) {
      if (this.currentForm == 'splitForm') {
        this.$set(this.splitFormList[this.currentIndex].detailList[index], 'arrivalBatch', deepClone(arrivalBatch))
      } else {
        this.$set(this.form.detailList[index], 'arrivalBatch', deepClone(arrivalBatch))
      }

    },
    async save() {
      let copyList = deepClone(this.splitFormList)
      let isArrivalBatch = false
      copyList.push(deepClone(this.form))


      copyList.forEach((item, index) => {
        item.detailList = item.detailList.filter(i => i.totalCount > 0)
        item.detailList.forEach((i, _index) => {
          if (!i.arrivalBatch.length && i.arrivalWay == 2) {
            isArrivalBatch = true
          }
          i.id = ''
        })
        item.parentId = item.id
        item.id = ''
      })
      copyList = copyList.filter(item => item.detailList.length)
      if (isArrivalBatch) return this.$message.warning('因数量变化请重新设置分批到货时间')
      await savePurchasePlanCutAPI(copyList)
      this.$message.success('操作成功')
      this.cancel()
    },
    cancel() {
      this.$emit('update:splitDialogFlag', false)
    }
  }
}
</script>


<style scoped lang="scss">

</style>
