<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.typeDispatchDialogPipelineLabel')" prop="pipeline">
        <el-tree-select
                  v-model="formData.pipeline"
                  :data="organizationTree"
                  :props="defaultProps"
                  check-strictly
                  default-expand-all
                  :placeholder="t('ProductionPlan.Plan.typeDispatchDialogPipelinePlaceholder')"
                />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.Plan.typeDispatchDialogPaigongNumLabel')" prop="paigongNum">
        <el-input v-model="formData.paigongNum" :placeholder="t('ProductionPlan.Plan.typeDispatchDialogPaigongNumPlaceholder')" />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.Plan.typeDispatchDialogPreProductionLabel')" 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>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('ProductionPlan.Plan.typeDispatchDialogSubmitButtonText') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('ProductionPlan.Plan.typeDispatchDialogCancelButtonText') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ItemRequisitionVO } from '@/api/mes/itemrequisition'
import {PlanApi} from "@/api/mes/plan";
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import * as UserApi from "@/api/system/user";
import {WorkTeamApi} from "@/api/mes/workteam";
import { OrganizationApi } from '@/api/mes/organization'
import { defaultProps, handleTree } from '@/utils/tree'


/** 生产领料 表单 */
defineOptions({ name: 'TypePaigong' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const organizationTree = ref() // 树形结构


const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
const formData = ref({
  requisitionDate: undefined,
  deliveryDate: undefined,
  planId: undefined,
  workerId: undefined,
  remark: undefined,
  feedingPipeline: undefined,
  pipeline: undefined,
  paigongNum: undefined,
  isPreProduction: undefined
})
const formRules = reactive({
  pipeline: [{ required: true, message: t('ProductionPlan.Plan.validatorTypeDispatchPipelineRequired'), trigger: 'blur' }],
  isPreProduction: [{ required: true, message: t('ProductionPlan.Plan.validatorTypeDispatchPreProductionRequired'), trigger: 'blur' }],
  paigongNum: [{ required: true, message: t('ProductionPlan.Plan.validatorTypeDispatchPaigongNumRequired'), trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (planCode: string, planId: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('ProductionPlan.Plan.dispatchDialogTitle', { code: planCode })
  resetForm()
  formLoading.value = true
  try {
    formData.value.planId = planId
  } finally {
    formLoading.value = false
  }
  // 获得制浆工人列表
  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 ItemRequisitionVO

    await PlanApi.arrangePlanNum(data)
    message.success(t('ProductionPlan.Plan.dispatchSuccessMessage'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    requisitionDate: undefined,
    deliveryDate: undefined,
    workerId: undefined,
    feedingPipeline: undefined,
    planId: undefined,
    remark: undefined,
    pipeline: undefined,
    paigongNum: undefined,
    isPreProduction: 0,
  }
  formRef.value?.resetFields()
}

/** 获得产线工位树 */
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>
