<template>
  <el-config-provider :locale="zhCn">
    <el-container class="content">
      <div class="work-area">
        <fieldset class="search-area">
          <el-form ref="inventoryRequestFormRef" :model="inventoryRequestFormEntity" :label-position="labelPosition"
                   label-width="158px"
                   style="max-width: 100%" :rules="requestRules" status-icon>
            <div style="display: flex; justify-content: space-between;">
              <el-row>
                <el-form-item label="箱号" prop="vehicleId">
                  <el-input v-model="inventoryRequestFormEntity.vehicleId" ref="vehicleId" clearable/>
                </el-form-item>
                <el-form-item label="料号" prop="goodsId">
                  <el-input v-model="inventoryRequestFormEntity.goodsId" ref="goodsId" clearable/>
                </el-form-item>
                <el-form-item label="特殊库存" prop="specialStock">
                  <el-input v-model="inventoryRequestFormEntity.specialStock" ref="specialStock" clearable/>
                </el-form-item>
                <el-form-item label="特殊库存号" prop="specialStockNo">
                  <el-input v-model="inventoryRequestFormEntity.specialStockNo" ref="specialStockNo" clearable/>
                </el-form-item>
                <el-form-item label="特殊库存item号" prop="specialStockItemNo">
                  <el-input v-model="inventoryRequestFormEntity.specialStockItemNo" ref="specialStockItemNo" clearable/>
                </el-form-item>
                <el-form-item label="批次号" prop="batchNo">
                  <el-input v-model="inventoryRequestFormEntity.batchNo" ref="batchNo" clearable/>
                </el-form-item>
              </el-row>
              <el-row>
                <el-button type="primary"
                           style="height: 50px; width: 100px; margin: auto 5px auto 5px; font-size: large; color: black;"
                           @click="sendInventoryRequest()">下发盘点
                </el-button>
                <el-button type="warning"
                           style="height: 50px; width: 100px; margin: auto 5px auto 5px; font-size: large; color: black;"
                           @click="clearInput()">清除输入
                </el-button>
              </el-row>
            </div>
          </el-form>
        </fieldset>

        <!-- 参考goodsOut.vue改为三个并排框 -->
        <div style="display: flex; margin-top: 10px;">
          <div v-for="(entity, index) in confirmEntities" :key="index" style="width: 32%; margin: 0 10px;">
            <fieldset class="confirm-area">
              <div style="text-align: center; font-size: 18px; font-weight: bold; margin-bottom: 0; color: #333;">
                {{ getChildStandIdByIndex(index) }}
              </div>
              <el-form ref="confirmRef" :model="entity" :label-position="labelPosition" label-width="158px"
                       style="max-width: 100%" :rules="confirmRules" status-icon>
                <div style="display: flex; flex-wrap: wrap;">
                  <div style="width: 50%; display: flex; flex-direction: column;">
                    <el-form-item label="盘点任务号" prop="inventoryId">
                      <el-input v-model="entity.inventoryId" disabled/>
                    </el-form-item>
                    <el-form-item label="特殊库存" prop="specialStock" class="special-inventory-item">
                      <el-input v-model="entity.specialStock" disabled/>
                    </el-form-item>
                    <el-form-item label="特殊库存号" prop="specialStockNo" class="special-inventory-item">
                      <el-input v-model="entity.specialStockNo" disabled/>
                    </el-form-item>
                    <el-form-item label="系统数量" prop="stockNum">
                      <el-input v-model="entity.stockNum" disabled/>
                    </el-form-item>
                    <el-form-item label="箱号" prop="vehicleId">
                      <el-input v-model="entity.vehicleId" disabled/>
                    </el-form-item>

                  </div>
                  <div style="width: 50%; display: flex; flex-direction: column;">
                    <el-form-item label="物料号" prop="goodsId" class="special-inventory-item">
                      <el-input v-model="entity.goodsId" disabled/>
                    </el-form-item>
                    <el-form-item label="特殊库存item号" prop="specialStockItemNo" class="special-inventory-item">
                      <el-input v-model="entity.specialStockItemNo" disabled/>
                    </el-form-item>
                    <el-form-item label="批次号" prop="batchNo" class="special-inventory-item">
                      <el-input v-model="entity.batchNo" disabled/>
                    </el-form-item>
                    <el-form-item label="确认数量" prop="confirmNum">
                      <el-input-number style="width: 196px" v-model.number="entity.confirmNum"
                                       controls-position="right" :min="0" clearable/>
                    </el-form-item>
                  </div>
                </div>
                <div style="display: flex; justify-content: center; gap: 80px; margin-top: 20px;">
                  <el-button type="success"
                             style="height: 50px; width: 100px; margin: auto 5px auto 5px; font-size: large; color: black;"
                             @click="confirmOrRelease(index)">确认/放行
                  </el-button>
                </div>
              </el-form>
            </fieldset>
          </div>
        </div>

        <el-dialog v-model="showUploadDialog" title="上传盘点清单" width="40%" draggable :show-close="true">
          <fieldset class="search-area">
            <legend>上传盘点清单</legend>
            <UploadExcelInventory></UploadExcelInventory>
          </fieldset>
        </el-dialog>
      </div>
    </el-container>
  </el-config-provider>
</template>

<script setup>
import store from '@/store'
import {nextTick, onBeforeUnmount, onMounted, reactive, ref, watch} from 'vue'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import {useRoute} from "vue-router";
import {errorBox, warningBox} from "@/utils/myMessageBox";
import {ElMessage} from "element-plus";
import {confirmInventory, getInventoryConfirm, requestInventory} from "@/api/task";
import {labelPosition} from "@/constant/form";
import UploadExcelInventory from "@/excel/UploadExcelInventory.vue";
import {loading} from "@/utils/loading";

const STAND_ID = store.getters.getStandId
const USER_NAME = store.getters.getUserName
let timer = ref()
const route = useRoute()// 路由
let inventoryRequestFormRef = ref()
let inventoryRequestFormEntity = reactive({
  goodsId: '',
  vehicleId: '',
  specialStock: '',
  specialStockNo: '',
  specialStockItemNo: '',
  batchNo: ''
})
const requestRules = reactive({})
let confirmRef = ref()

// 创建三个确认实体
let confirmEntities = reactive([
  {
    inventoryId: '',
    vehicleId: '',
    goodsId: '',
    stockNum: null,
    confirmNum: null,
    specialStock: '',
    specialStockNo: '',
    specialStockItemNo: '',
    batchNo: ''
  },
  {
    inventoryId: '',
    vehicleId: '',
    goodsId: '',
    stockNum: null,
    confirmNum: null,
    specialStock: '',
    specialStockNo: '',
    specialStockItemNo: '',
    batchNo: ''
  },
  {
    inventoryId: '',
    vehicleId: '',
    goodsId: '',
    stockNum: null,
    confirmNum: null,
    specialStock: '',
    specialStockNo: '',
    specialStockItemNo: '',
    batchNo: ''
  }
])

const confirmRules = reactive({})
let pauseGetPickFlag = ref(false)
let showUploadDialog = ref(false)

// 系统
onMounted(() => {
  nextTick(() => {
    timer.value = setInterval(() => {
      timerTask_1()
    }, 1000)
  })
})
onBeforeUnmount(() => {
  clearInterval(timer.value)
})
// 监视路由
watch(() => route.path, (newVal, oldVal) => {
  if (newVal === '/inventory') {
    timer.value = setInterval(() => {
      timerTask_1()
    }, 1000)
  } else {
    clearInterval(timer.value)
  }
})
// 定时器任务1
const timerTask_1 = () => {
  // 查询盘点列表
  getInventory()
}
// 查询盘点信息
const getInventory = () => {
  if (pauseGetPickFlag.value) {
    return
  }

  // 根据主站台ID确定需要显示的子站台顺序
  let childStandOrder = []
  if (STAND_ID === 'P1') {
    childStandOrder = ['P13', 'P12', 'P11']
  } else if (STAND_ID === 'P2') {
    childStandOrder = ['P16', 'P15', 'P14']
  } else if (STAND_ID === 'P3') {
    childStandOrder = ['P19', 'P18', 'P17']
  }

  // 获取所有子站台的盘点信息
  const promises = childStandOrder.map(STAND_ID => {
    const request = {
      standId: STAND_ID,
      userName: USER_NAME
    }
    return getInventoryConfirm(request)
  })

  Promise.all(promises).then(responses => {
    responses.forEach((res, index) => {
      const response = res.data
      if (response.code === 0) {
        const confirmVo = response.data
        // 设置form
        const entity = confirmEntities[index]
        entity.inventoryId = confirmVo.inventoryId
        entity.goodsId = confirmVo.goodsId
        entity.vehicleId = confirmVo.vehicleId
        entity.stockNum = confirmVo.stockNum
        entity.confirmNum = confirmVo.confirmNum
        entity.specialStock = confirmVo.specialStock || ''
        entity.specialStockNo = confirmVo.specialStockNo || ''
        entity.specialStockItemNo = confirmVo.specialStockItemNo || ''
        entity.batchNo = confirmVo.batchNo || ''
      } else if (response.code === 400) {
        // 警告，清空对应实体
        clearConfirmEntity(index)
        warningBox(response.message)
      }
    })
    pauseGetPickFlag.value = true
  }).catch(err => {
    console.log(err)
    pauseGetPickFlag.value = true
    errorBox('请求错误，请检查完原因后刷新界面。')
  })
}

// 根据索引获取子站台ID
const getChildStandIdByIndex = (index) => {
  // 根据主站台ID确定需要显示的子站台顺序
  let childStandOrder = []
  if (STAND_ID === 'P1') {
    childStandOrder = ['P13', 'P12', 'P11']
  } else if (STAND_ID === 'P2') {
    childStandOrder = ['P16', 'P15', 'P14']
  } else if (STAND_ID === 'P3') {
    childStandOrder = ['P19', 'P18', 'P17']
  }

  return childStandOrder[index] || ''
}

// 清空指定索引的确认信息
const clearConfirmEntity = (index) => {
  if (index >= 0 && index < confirmEntities.length) {
    const entity = confirmEntities[index]
    entity.inventoryId = ''
    entity.goodsId = ''
    entity.vehicleId = ''
    entity.stockNum = null
    entity.confirmNum = null
    entity.specialStock = ''
    entity.specialStockNo = ''
    entity.specialStockItemNo = ''
    entity.batchNo = ''
  }
}

// 下发盘点任务
const sendInventoryRequest = () => {
  inventoryRequestFormEntity.goodsId = inventoryRequestFormEntity.goodsId.trim().toUpperCase()
  inventoryRequestFormEntity.vehicleId = inventoryRequestFormEntity.vehicleId.trim().toUpperCase()
  inventoryRequestFormEntity.specialStock = inventoryRequestFormEntity.specialStock.trim().toUpperCase()
  inventoryRequestFormEntity.specialStockNo = inventoryRequestFormEntity.specialStockNo.trim().toUpperCase()
  inventoryRequestFormEntity.specialStockItemNo = inventoryRequestFormEntity.specialStockItemNo.trim().toUpperCase()
  inventoryRequestFormEntity.batchNo = inventoryRequestFormEntity.batchNo.trim().toUpperCase()
  if (inventoryRequestFormEntity.goodsId === '') {
    ElMessage.error("料号为必须项。")
    return
  }
  const request = {
    goodsId: inventoryRequestFormEntity.goodsId,
    vehicleId: inventoryRequestFormEntity.vehicleId,
    specialStock: inventoryRequestFormEntity.specialStock,
    specialStockNo: inventoryRequestFormEntity.specialStockNo,
    specialStockItemNo: inventoryRequestFormEntity.specialStockItemNo,
    batchNo: inventoryRequestFormEntity.batchNo,
    standId: STAND_ID,
    userName: USER_NAME
  }
  loading.open('处理中...')
  requestInventory(request).then(res => {
    const response = res.data
    if (response.code === 0) {
      ElMessage.success(response.message)
      pauseGetPickFlag.value = false
    } else {
      errorBox(response.message)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error("发生异常。")
  }).finally(() => {
    loading.close()
  })
}

// 确认/放行 (修改为支持索引)
const confirmOrRelease = (index) => {
  const entity = confirmEntities[index]
  // 确认放行---与配料工作区分开来
  const request = {
    inventoryId: entity.inventoryId,
    goodsId: entity.goodsId,
    vehicleId: entity.vehicleId,
    confirmNum: entity.confirmNum,
    standId: getChildStandIdByIndex(index),
    userName: USER_NAME
  }
  loading.open('处理中...')
  confirmInventory(request).then(res => {
    const response = res.data
    if (response.code === 0) {
      // 设置form
      clearConfirmEntity(index)
      ElMessage.success(response.message)
      pauseGetPickFlag.value = false
    } else if (response.code === 400) {
      // 设置form
      clearConfirmEntity(index)
      warningBox(response.message)
      pauseGetPickFlag.value = false
    } else {
      // 错误，弹框
      errorBox(response.message)
    }
  }).catch(err => {
    console.log(err)
    errorBox('请求错误，请检查完原因后刷新界面。')
  }).finally(() => {
    loading.close()
  })
}

// 清空下发信息
const clearInput = () => {
  inventoryRequestFormEntity.goodsId = ''
  inventoryRequestFormEntity.vehicleId = ''
  inventoryRequestFormEntity.specialStock = ''
  inventoryRequestFormEntity.specialStockNo = ''
  inventoryRequestFormEntity.specialStockItemNo = ''
  inventoryRequestFormEntity.batchNo = ''
}

// 打开上传界面
const openUploadDialog = () => {
  showUploadDialog.value = true
}
</script>

<style scoped>
.content {
  display: flex;
  width: 100%;
}

.work-area {
  width: 100%;
}

.search-area {
  margin: auto;
  min-height: fit-content;
  max-height: 90%;
  margin-bottom: 10px;
  min-width: inherit;
  border: solid 1px;
  border-radius: 10px;
  box-shadow: 0px 15px 10px -15px #000;
  overflow: auto;
  padding: 10px;
}

.confirm-area {
  margin: auto;
  min-height: fit-content;
  max-height: 100%;
  margin-bottom: 10px;
  min-width: inherit;
  border: solid 1px;
  border-radius: 10px;
  box-shadow: 0px 15px 10px -15px #000;
  overflow: auto;
  padding: 10px;
}

.el-form-item {
  margin: 10px 5px 10px 5px;
}

.el-form-item .el-input {
  width: 196px;
}

.table-class {
  margin: 5px 5px 5px 5px;
  width: inherit;
}

/* 特殊库存字段标红醒目显示 */
.special-inventory-item :deep(.el-form-item__label) {
  color: #ff8888;
  font-weight: bold;
}
</style>
