<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="任务单" prop="taskId">
        <el-select
          disabled
          v-model="formData.taskId"
          clearable
          filterable
          placeholder="请选择"
          @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="明细项" prop="taskId">
        <el-select
          disabled
          v-model="formData.taskDetailId"
          clearable
          filterable
          placeholder="请选择"
          @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>
      计划编码
      <el-tooltip content="生产计划编码" placement="top">
        <Icon icon="ep:question-filled" />
      </el-tooltip>
    </span>
  </template>
  <div style="display: flex; align-items: center; gap: 10px">
    <el-input 
      :disabled="formData.isCode == true || formType === 'update'" 
      v-model="formData.code" 
      placeholder="编码保存后自动生成"
      style="min-width: 600px"
    />
    <el-switch v-model="formData.isCode" :disabled="formType === 'update'"/>
  </div>
</el-form-item>
      <el-form-item label="生产线" prop="feedingPipeline">
        <el-tree-select
                  v-model="formData.feedingPipeline"
                  :data="organizationTree"
                  :props="defaultProps"
                  check-strictly
                  default-expand-all
                  placeholder="请选择生产线"
                />
      </el-form-item>
      <el-form-item label="领料人" prop="workerId">
        <el-select
          v-model="formData.workerId"
          clearable
          filterable
          placeholder="请选择领料人"
        >
          <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="数量" prop="planNumber">
        <el-input v-model="formData.planNumber"  />
      </el-form-item>
      <el-form-item label="是否试生产" 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="计划开始" prop="planStartTime">
        <el-date-picker
          v-model="formData.planStartTime"
          type="date"
          value-format="x"
          placeholder="选择计划开始时间"
        />
      </el-form-item>
      <el-form-item label="计划结束" prop="planEndTime">
        <el-date-picker
          v-model="formData.planEndTime"
          type="date"
          value-format="x"
          placeholder="选择计划结束时间"
        />
      </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="备注" prop="remark">
        <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</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: '明细项不能为空', trigger: 'blur' }],
  taskId: [{ required: true, message: '任务单不能为空', trigger: 'blur' }],
  planNumber: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
  // reyaNumber: [{ required: true, message: '热压数量不能为空', trigger: 'blur' }],
  planStartTime: [{ required: true, message: '计划开始时间不能为空', trigger: 'blur' }],
  planEndTime: [{ required: true, message: '计划结束时间不能为空', trigger: 'blur' }],
  feedingPipeline: [{ required: true, message: '生产线不能为空', trigger: 'blur' }],
  workerId: [{ required: true, message: '下料工人不能为空', trigger: 'blur' }],
  isPreProduction: [{ required: true, message: '试生产不能为空', 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>
