<template>
  <el-dialog :title="'批次号：' + baseLot.lotCode" v-model="visible" width="1200px" append-to-body draggable @close="close">
    <div class="form-container in-batches-dialog">

      <el-form ref="lotFormRef" v-loading="loading" class="master-container" :model="baseLot" label-width="130px"
        @submit.native.prevent>
        <el-row :gutter="20">
          <el-col :span="24">
            <div>基础信息</div>
            <el-divider />
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户简称：" prop="companyAlias">
              <div>{{ baseLot.companyAlias }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产计划单号：" prop="productionPlanNo">
              <div>{{ baseLot.productionPlanNo }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次号：" prop="lotCode">
              <div>{{ baseLot.lotCode }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品描述：" prop="productDescription">
              <div>{{ baseLot.productDescription }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="图纸版本：" prop="technologyVersion">
              <div>{{ baseLot.technologyVersion }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次投产量：" prop="productionQuantity">
              <div>{{ baseLot.productionQuantity }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="下达日期：" prop="date">
              <div>{{ baseLot.issueDate }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="当前工段：">
              <div>{{ baseLot.currentDept }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="当前工序投产量：">
              <div>{{ baseLot.prodNum }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工序合格数量：">
              <div>{{ baseLot.qualifiedNum }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="当前载具：">
              <div>{{ baseLot.carriers.map(v => v.code).join(',') }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div style="display: flex; flex-direction: row;">
              <div style="line-height: 32px;">分批信息</div>
              <el-form-item label="分批数量">
                <el-input-number v-model="baseLot.sparateNum" :controls="false" :min="2" :max="10" step="1"
                  step-strictly />
              </el-form-item>
              <el-form-item label-width="20px">
                <el-button type="primary" @click="handleNumBlur">计算</el-button>
              </el-form-item>
            </div>
            <el-divider />
            <el-row v-for="(e, i) in baseLot.sparateList" :key="i">
              <el-col :span="6">
                <el-form-item label="分批批次号：">
                  <el-input disabled v-model="e.lotCode" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="分批数量：">
                  <el-input-number v-model="e.lotNumber" :controls="false" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="合格数量：">
                  <el-input-number v-model="e.qualifiedNum" :controls="false" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="分批载具：">
                  <!-- <el-select-v2 v-model="e.carrierSelection"
                    :disabled="e.id === baseLot.id || baseLot.currentDept == null" multiple filterable
                    collapse-tags-tooltip collapse-tags clearable :options="carriers" placeholder="请选择载具"
                    style="width: 100%" /> -->
                  <el-select v-model="e.carrierSelection" :disabled="e.id === baseLot.id || baseLot.currentDept == null"
                    multiple filterable remote reserve-keyword placeholder="请选择载具" collapse-tags-tooltip collapse-tags
                    :remote-method="(arg) => remoteCarriers(arg, e.carriers)" :loading="loadingCarrier"
                    @change="(arg) => handleCarrierChange(arg, e)">
                    <el-option v-for="item in carriers" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <el-button type="primary" icon="Check" @click="handleSave">确 定</el-button>
      <el-button icon="Close" @click="close">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { getLotInfoForInBatches, listCarriers, saveInBatches } from '@/api/business/lot'
import { toRefs } from 'vue';
// import {}
const { proxy } = getCurrentInstance();
const props = defineProps({
  getList: {
    type: Function,
    default: () => { }
  }
})
const { getList } = toRefs(props);
/**工段弹窗变量 */
const total = ref(0)
const baseLot = ref({
  carriers: []
})
const selections = ref([]);
const visible = ref(false);
const deptIds = ref([])
const loading = ref(false);
const carriers = ref([])
const loadingCarrier = ref(true)
/**查询对象 */
const data = reactive({
  queryParams: {
    pageSize: 10,
    pageNum: 1,
  },
});

const { queryParams } = toRefs(data);
/***********************  方法区  ****************************/

/**
 * 对话框打开 事件
 */
function open(data) {
  baseLot.value = { ...data, id: data.lotId, carriers: [] }
  visible.value = true;
  loadLot();
  getCarriers()
}

function getCarriers() {
  listCarriers({ isAbandoned: 0, pageSize: 200 }).then(res => {
    if (res.code === 200) {
      carriers.value.push(...res.rows.map(v => ({ value: v.id, label: v.code })))
    }
  })
}

function remoteCarriers(queryString, choiced) {
  loadingCarrier.value = true
  listCarriers({ isAbandoned: 0, pageSize: 200, code: queryString != '' ? queryString : null }).then(res => {
    if (res.code === 200) {
      carriers.value = res.rows.map(v => ({ value: v.id, label: v.code }))
      carriers.value.push(...choiced.filter(v => !carriers.value.map(e => e.value).includes(v.id)).map(v => ({ value: v.id, label: v.code })))
    } else {
      carriers.value = []
      carriers.value.push(...choiced)
    }
    console.log(carriers.value)
    loadingCarrier.value = false
  })
}

function handleCarrierChange(arg, item) {
  item.carriers = carriers.value.filter(v => arg.includes(v.value)).map(v => ({ id: v.value, code: v.label }))
}


function loadLot() {
  getLotInfoForInBatches({ id: baseLot.value.id }).then(res => {
    if (res.code === 200) {
      baseLot.value.issueDate = res.data.issueDate
      baseLot.value.prodNum = res.data.prodNum
      baseLot.value.currentDept = res.data.currentDept
      baseLot.value.sparateList = []
      baseLot.value.qualifiedNum = res.data.qualifiedNum
      baseLot.value.carriers = res.data.carriers
      baseLot.value.sparateNum = 0
      baseLot.value.latestLotCode = res.data.latestLotCode
      baseLot.value.productId = res.data.productId
      baseLot.value.isAmend = res.data.isAmend
      baseLot.value.isWasteRecycling = res.data.isWasteRecycling
      baseLot.value.requisitionDepartmentName = res.data.requisitionDepartmentName
      baseLot.value.requisitionDepartmentId = res.data.requisitionDepartmentId
      baseLot.value.splitCount = res.data.splitCount
      baseLot.value.fromCount = res.data.fromCount
      carriers.value.push(...res.data.carriers.map(v => ({ value: v.id, label: v.code })))
    }
  })
}

/**
 * 对话框关闭 事件
 */
function close() {
  visible.value = false;
}

/**
 * 列表checkbox列选择 事件
 */
function handleSelectionChange(selection) {
  selections.value = selection;
}

/** 多选事件 */
function handleMultipleSelected() {
  if (multipleSelected.value) {
    multipleSelected.value(selections.value);
  }
  close();
}

function handleSave() {
  // console.log(baseLot.value)
  // 保存时判断下分批数量和是否等于投产数量。不等要提示一下
  let num = 0
  let qualified = 0
  baseLot.value.sparateList.forEach(e => {
    num += e.lotNumber
    qualified += e.qualifiedNum
  })
  const prodNum = !!baseLot.value.prodNum ? baseLot.value.prodNum : baseLot.value.productionQuantity
  const qualifiedNum = !!baseLot.value.qualifiedNum ? baseLot.value.qualifiedNum : 0
  if (num != prodNum) {
    proxy.$message({
      type: 'warning',
      message: '分批数量需等于总投入数量'
    })
    return
  }
  if (qualified != qualifiedNum) {
    proxy.$message({
      type: 'warning',
      message: '分批合格数量需等于总合格数量'
    })
    return
  }
  // const saveDate = { ...baseLot.value, sparateList: baseLot.value.sparateList.map(v => ({ ...v, carriers: v.id === baseLot.id ? v.carriers : v.carrierSelection.map(e => ({ id: e })) })) }
  // const saveDate = { ...baseLot.value }
  const saveDate = { id: baseLot.value.id, isAmend: baseLot.value.isAmend, isWasteRecycling: baseLot.value.isWasteRecycling, requisitionDepartmentName: baseLot.value.requisitionDepartmentName, requisitionDepartmentId: baseLot.value.requisitionDepartmentId, lotCode: baseLot.value.lotCode, splitCount: baseLot.value.splitCount, fromCount: baseLot.value.fromCount, sparateList: baseLot.value.sparateList.map(v => ({ id: v.id, fromId: v.fromId, lotNumber: v.lotNumber, qualifiedNum: v.qualifiedNum, productionPlanDetailId: v.productionPlanDetailId, technologicalProcessId: v.technologicalProcessId, isAmend: baseLot.value.isAmend, isWasteRecycling: baseLot.value.isWasteRecycling, requisitionDepartmentName: baseLot.value.requisitionDepartmentName, requisitionDepartmentId: baseLot.value.requisitionDepartmentId, technologyVersion: v.technologyVersion, productId: v.productId, productionQuantity: v.lotNumber, lotCode: v.lotCode, carriers: v.id === baseLot.id ? v.carriers : v.carrierSelection.map(e => ({ id: e })), splitCount: v.splitCount })) }

  // 提交分批结果
  saveInBatches(saveDate).then(res => {
    if (res.code === 200) {
      proxy.$message({
        type: 'success',
        message: '分批成功'
      })
      close()
      getList.value()
    } else {
      proxy.$message({
        type: 'error',
        message: res.message
      })
    }
  })
}

function handleNumBlur() {
  // 分批数量修改
  baseLot.value.sparateList = []
  const prodNum = !!baseLot.value.prodNum ? baseLot.value.prodNum : baseLot.value.productionQuantity
  const qualifiedNum = !!baseLot.value.qualifiedNum ? baseLot.value.qualifiedNum : 0
  const arg = baseLot.value.sparateNum
  const latestLotCode = baseLot.value.latestLotCode
  // debugger
  if ((Number(latestLotCode.charAt(latestLotCode.length - 1)) + arg - 1) > 9) {
    proxy.$message({
      type: 'warning',
      message: '总分批书里不能大于9'
    })
    return
  }
  for (let i = 0; i < arg; i++) {
    const item = { ...baseLot.value }
    if (i === 0) {
      // 第一条
      item.lotNumber = Math.ceil(prodNum / arg)
      item.qualifiedNum = Math.ceil(qualifiedNum / arg)
      item.carrierSelection = baseLot.value.carriers.map(v => v.id)
    } else if ((i + 1) === arg) {
      item.lotNumber = prodNum - (Math.ceil(prodNum / arg) * (arg - 1))
      item.lotCode = baseLot.value.latestLotCode.slice(0, -1) + (Number(latestLotCode.charAt(latestLotCode.length - 1)) + i)
      item.qualifiedNum = qualifiedNum - (Math.ceil(qualifiedNum / arg) * (arg - 1))
      item.fromId = baseLot.value.id
      item.id = null
      item.lotId = null
      item.last = 0
      item.carrierSelection = []
    } else {
      item.id = null
      item.lotId = null
      item.fromId = baseLot.value.id
      item.lotCode = baseLot.value.latestLotCode.slice(0, -1) + (Number(latestLotCode.charAt(latestLotCode.length - 1)) + i)
      item.lotNumber = Math.ceil(prodNum / arg)
      item.qualifiedNum = Math.ceil(qualifiedNum / arg)
      item.fromId = baseLot.value.id
      item.last = 0
      item.carrierSelection = []
    }
    baseLot.value.sparateList.push(item)
  }
}

defineExpose({
  open,
});
</script>
<style>
.in-batches-dialog .el-form-item--default .el-form-item__content {
  line-height: 32px;
  display: inline-block;
}
</style>
