<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
    <el-form-item :label="t('ProductionPlan.Plan.dialogTaskLabel')" prop="taskId">
        <el-select
          disabled
          v-model="formData.taskId"
          clearable
          filterable
          :placeholder="t('ProductionPlan.Plan.dialogTaskPlaceholder')"
          @change="handleTaskChange"
        >
          <el-option
            v-for="item in taskList"
            :key="item.id"
            :label="item.code"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.Plan.dialogTaskDetailLabel')" prop="taskId">
        <el-select
          disabled
          v-model="formData.taskDetailId"
          clearable
          filterable
          :placeholder="t('ProductionPlan.Plan.dialogTaskDetailPlaceholder')"
          @change="handleTaskDetailChange"
        >
          <el-option
            v-for="item in taskDetailList"
            :key="item.id"
            :label="item.productName+'-未计划:'+(item.number-item.planNumber)"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="code">
  <template #label>
    <span>
      {{ t('ProductionPlan.Plan.dialogCodeLabel') }}
      <el-tooltip :content="t('ProductionPlan.Plan.dialogCodeTooltip')" placement="top">
        <Icon icon="ep:question-filled" />
      </el-tooltip>
    </span>
  </template>
  <el-row :gutter="10" class="!w-full">
    <el-col :xs="24" :sm="18" :md="16" :lg="14" :xl="12">
      <el-input 
        :disabled="formData.isCode == true || formType === 'update'" 
        v-model="formData.code" 
        :placeholder="t('ProductionPlan.Plan.dialogCodePlaceholder')"
      />
    </el-col>
    <el-col :xs="24" :sm="6" :md="4" :lg="3" :xl="2">
      <div>
        <el-switch 
          v-model="formData.isCode" 
          :disabled="formType === 'update'"
        />
      </div>
    </el-col>
  </el-row>
</el-form-item>
      <el-form-item :label="t('ProductionPlan.Plan.dialogFeedingPipelineLabel')" prop="feedingPipeline">
        <el-tree-select
                  v-model="formData.feedingPipeline"
                  :data="organizationTree"
                  :props="defaultProps"
                  check-strictly
                  default-expand-all
                  :placeholder="t('ProductionPlan.Plan.dialogFeedingPipelinePlaceholder')"
                />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.Plan.dialogWorkerLabel')" prop="workerId">
        <el-select
          v-model="formData.workerId"
          clearable
          filterable
          :placeholder="t('ProductionPlan.Plan.dialogWorkerPlaceholder')"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="产品" prop="productId">-->
<!--        <el-select-->
<!--          :disabled='editDisable'-->
<!--          v-model="formData.productId"-->
<!--          clearable-->
<!--          filterable-->
<!--          placeholder="请选择产品"-->
<!--          class="!w-1/1"-->
<!--        >-->
<!--          <el-option-->
<!--            v-for="item in productList"-->
<!--            :key="item.id"-->
<!--            :label="item.name"-->
<!--            :value="item.id"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item :label="t('ProductionPlan.Plan.dialogPlanNumberLabel')" prop="planNumber">
        <el-input v-model="formData.planNumber"  />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.Plan.dialogPreProductionLabel')" prop="isPreProduction">
        <el-radio-group v-model="formData.isPreProduction">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.MES_PRE_PRODUCTION)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item label="热压数量" prop="reyaNumber">
        <el-input v-model="formData.reyaNumber" />
      </el-form-item> -->
      <el-form-item :label="t('ProductionPlan.Plan.dialogPlanStartLabel')" prop="planStartTime">
        <el-date-picker
          v-model="formData.planStartTime"
          type="date"
          value-format="x"
          :placeholder="t('ProductionPlan.Plan.dialogPlanStartPlaceholder')"
          class="!w-full"
        />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.Plan.dialogPlanEndLabel')" prop="planEndTime">
        <el-date-picker
          v-model="formData.planEndTime"
          type="date"
          value-format="x"
          :placeholder="t('ProductionPlan.Plan.dialogPlanEndPlaceholder')"
          class="!w-full"
        />
      </el-form-item>
      <!-- <el-form-item label="班别" prop="groupType">
        <el-radio-group v-model="formData.groupType">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.MES_GROUP_TYPE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item :label="t('ProductionPlan.Plan.dialogRemarkLabel')" prop="remark">
        <el-input type="textarea" v-model="formData.remark" :placeholder="t('ProductionPlan.Plan.dialogRemarkPlaceholder')" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('ProductionPlan.Plan.dialogSubmitButtonText') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('ProductionPlan.Plan.dialogCancelButtonText') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">

import { PlanApi, PlanVO } from '@/api/mes/plan'
import * as UserApi from "@/api/system/user";
import { TaskApi, TaskDetailVO, TaskVO} from "@/api/mes/task";
import { ProductVO } from "@/api/erp/product/product";
import { defaultProps, handleTree } from '@/utils/tree';
import { OrganizationApi } from '@/api/mes/organization';
import {WorkTeamApi} from "@/api/mes/workteam";
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import { StockOutApi, StockOutVO } from '@/api/erp/stock/out'

/** 生产计划 表单 */
defineOptions({ name: 'PlanForm' })
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
const productList = ref<ProductVO[]>([]) // 产品列表
const taskList = ref<TaskVO[]>([]) // 用户列表
const taskDetailList = ref<TaskDetailVO[]>([]) // 用户列表
const organizationTree = ref() // 树形结构

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const editDisable = ref(false) // 编辑状态禁用

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  code: undefined,
  productId: undefined,
  taskDetailId: undefined,
  taskId: undefined,
  planNumber: undefined,
  reyaNumber: undefined,
  finishNumber: undefined,
  status: undefined,
  planStartTime: undefined,
  planEndTime: undefined,
  startTime: undefined,
  endTime: undefined,
  productionManagerId: undefined,
  remark: undefined,
  groupType: undefined,
  isEnable: undefined,
  feedingPipeline: undefined,
  workerId: undefined,
  isPreProduction: undefined,
  isCode: undefined
})
const formRules = reactive({
  taskDetailId: [{ required: true, message: t('ProductionPlan.Plan.validatorTaskDetailRequired'), trigger: 'blur' }],
  taskId: [{ required: true, message: t('ProductionPlan.Plan.validatorTaskRequired'), trigger: 'blur' }],
  planNumber: [{ required: true, message: t('ProductionPlan.Plan.validatorPlanNumberRequired'), trigger: 'blur' }],
  // reyaNumber: [{ required: true, message: t('ProductionPlan.Plan.validatorReyaNumberRequired'), trigger: 'blur' }],
  planStartTime: [{ required: true, message: t('ProductionPlan.Plan.validatorPlanStartRequired'), trigger: 'blur' }],
  planEndTime: [{ required: true, message: t('ProductionPlan.Plan.validatorPlanEndRequired'), trigger: 'blur' }],
  feedingPipeline: [{ required: true, message: t('ProductionPlan.Plan.validatorFeedingPipelineRequired'), trigger: 'blur' }],
  workerId: [{ required: true, message: t('ProductionPlan.Plan.validatorWorkerRequired'), trigger: 'blur' }],
  isPreProduction: [{ required: true, message: t('ProductionPlan.Plan.validatorPreProductionRequired'), trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number,
                    taskId?: number, productId?: number, number?: number, taskDetailId?:string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  editDisable.value = false
  resetForm()
  if(taskId) {
   formData.value.taskId = taskId
    taskDetailList.value =await TaskApi.getTaskDetailListByTaskId(formData.value.taskId)
   if(taskDetailId){
    const taskDetails = taskDetailList.value.filter(item => item.id === Number(taskDetailId.split(',')[0]))
    if(taskDetails && taskDetails.length > 0 && taskDetails[0].id) {
        formData.value.taskDetailId = taskDetails[0].id
    }      
  }  
  } 
  if(productId)
    formData.value.productId = productId
  if(number){
    formData.value.planNumber = number
    formData.value.reyaNumber = number
  }
  if(type==='update'){
    editDisable.value = true
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await PlanApi.getPlan(id)
    } finally {
      formLoading.value = false
    }
  }
  // 加载用户列表
  //userList.value = await UserApi.getSimpleUserList()
  // 列表
  //productList.value = await ProductApi.getMesProductSimpleList()
  // 列表
  taskList.value = await TaskApi.getPlanTaskList()
  // 获得制浆工人列表
  userList.value = await WorkTeamApi.getUserList("zhijiang", '')
  await getOrganizationTree()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PlanVO
    if (formType.value === 'create') {
      await PlanApi.createPlan(data)
      message.success(t('common.createSuccess'))
    } else {
      await PlanApi.updatePlan(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    productId: undefined,
    taskDetailId: undefined,
    taskId: undefined,
    planNumber: 0,
    finishNumber: 0,
    status: undefined,
    planStartTime: undefined,
    planEndTime: undefined,
    startTime: undefined,
    endTime: undefined,
    productionManagerId: undefined,
    remark: undefined,
    groupType: undefined,
    isEnable: undefined,
    isPreProduction: 0,
    isCode: true
  }
  formRef.value?.resetFields()
}

/** 任务单变化 */
const handleTaskChange = async(e) => {
  taskDetailList.value =await TaskApi.getTaskDetailListByTaskId(formData.value.taskId)
}
/** 明细变化 */
const handleTaskDetailChange = async(e) => {
  console.log(e)
}

/** 获得产线工位树 */
const getOrganizationTree = async () => {
  organizationTree.value = []
  const req = {orgClass:'pipeline'}
  const data = await OrganizationApi.getOrganizationList(req)
  const root: Tree = { id: 0, name: '顶级组织', children: [] }
  root.children = handleTree(data, 'id', 'parentId')
  organizationTree.value.push(root)
}
</script>


