<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
    <el-form-item v-show="false" :label="t('ProductionPlan.Plan.dispatchDialogPlanLabel')" prop="planId">
        <el-input v-model="formData.planId" :placeholder="t('ProductionPlan.Plan.dispatchDialogPlanPlaceholder')" />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.Plan.dispatchDialogFeedingPipelineLabel')" prop="feedingPipeline">
        <el-tree-select
                  v-model="formData.feedingPipeline"
                  :data="organizationTree"
                  :props="defaultProps"
                  check-strictly
                  default-expand-all
                  :placeholder="t('ProductionPlan.Plan.dispatchDialogFeedingPipelinePlaceholder')"
                />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.Plan.dispatchDialogWorkerLabel')" prop="workerId">
        <el-select
          v-model="formData.workerId"
          clearable
          filterable
          :placeholder="t('ProductionPlan.Plan.dispatchDialogWorkerPlaceholder')"
        >
          <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="t('ProductionPlan.Plan.dispatchDialogRequisitionDateLabel')" prop="requisitionDate">
        <el-date-picker
          v-model="formData.requisitionDate"
          type="date"
          value-format="x"
          :placeholder="t('ProductionPlan.Plan.dispatchDialogRequisitionDatePlaceholder')"
        />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.Plan.dispatchDialogRemarkLabel')" prop="remark">
        <el-input v-model="formData.remark" :placeholder="t('ProductionPlan.Plan.dispatchDialogRemarkPlaceholder')" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('ProductionPlan.Plan.dispatchDialogSubmitButtonText') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('ProductionPlan.Plan.dispatchDialogCancelButtonText') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ItemRequisitionVO } from '@/api/mes/itemrequisition'
import {PlanApi} from "@/api/mes/plan";
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: 'Paigong' })

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({
  planId: [{ required: true, message: t('ProductionPlan.Plan.validatorDispatchPlanRequired'), trigger: 'blur' }],
  feedingPipeline: [{ required: true, message: t('ProductionPlan.Plan.validatorDispatchFeedingPipelineRequired'), trigger: 'blur' }],
  workerId: [{ required: true, message: t('ProductionPlan.Plan.validatorDispatchWorkerRequired'), 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.arrangePlan(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
  }
  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>
