<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1200px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      :disabled="disabled"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item :label="t('ProductionPlan.Task.detailDialogProductLabel')" prop="productId">
            <el-select
              v-model="formData.productId"
              clearable
              filterable
              @change="onChangeProduct(formData.productId)"
              :placeholder="t('ProductionPlan.Task.detailDialogProductPlaceholder')"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="t('ProductionPlan.Task.detailDialogUnitLabel')" prop="unitName">
            <el-input v-model="formData.unitName" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="t('ProductionPlan.Task.detailDialogNumberLabel')" prop="number">
            <el-input-number
              v-model="formData.number"
              :min="0"
              class="!w-1/1"
              :placeholder="t('ProductionPlan.Task.detailDialogNumberPlaceholder')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item :label="t('ProductionPlan.Task.detailDialogProjectLabel')" prop="projectName">
            <el-input v-model="formData.projectName" :placeholder="t('ProductionPlan.Task.detailDialogProjectPlaceholder')" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="t('ProductionPlan.Task.detailDialogPackageSizeLabel')" prop="packageSize">
            <el-input-number
              v-model="formData.packageSize"
              :min="0"
              class="!w-1/1"
              :placeholder="t('ProductionPlan.Task.detailDialogPackageSizePlaceholder')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="t('ProductionPlan.Task.detailDialogPackageNumberLabel')" prop="packageNumber">
            <el-input-number
              v-model="formData.packageNumber"
              :min="0"
              class="!w-1/1"
              :placeholder="t('ProductionPlan.Task.detailDialogPackageNumberPlaceholder')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!-- <el-col :span="8">
          <el-form-item label="条码" prop="barCode">
            <el-input v-model="formData.barCode" placeholder="请输入条码" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item :label="t('ProductionPlan.Task.detailDialogTechRequirementsLabel')" prop="techRequirements">
            <el-input v-model="formData.techRequirements" :placeholder="t('ProductionPlan.Task.detailDialogTechRequirementsPlaceholder')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item :label="t('ProductionPlan.Task.detailFormDeliveryDateLabel')" prop="finishDate">
            <el-date-picker
              v-model="formData.finishDate"
              type="date"
              value-format="x"
              :placeholder="t('ProductionPlan.Task.detailFormDeliveryDatePlaceholder')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="t('ProductionPlan.Task.detailDialogBoxingDateLabel')" prop="boxingDate">
            <el-date-picker
              v-model="formData.boxingDate"
              type="date"
              value-format="x"
              :placeholder="t('ProductionPlan.Task.detailDialogBoxingDatePlaceholder')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="t('ProductionPlan.Task.detailDialogArriveDateLabel')" prop="arriveDate">
            <el-date-picker
              v-model="formData.arriveDate"
              type="date"
              value-format="x"
              :placeholder="t('ProductionPlan.Task.detailDialogArriveDatePlaceholder')"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item :label="t('ProductionPlan.Task.detailDialogRemarkLabel')" prop="remark">
        <Editor disabled="disabled" v-model="formData.remark" height="500px" />
      </el-form-item>
    </el-form>


    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('ProductionPlan.Task.detailDialogSubmitButtonText') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('ProductionPlan.Task.detailDialogCancelButtonText') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { TaskApi } from '@/api/mes/task'
import { ProductUnitApi, ProductUnitVO } from '@/api/erp/product/unit'
import {ProductApi, ProductVO} from "@/api/erp/product/product";

const unitList = ref<ProductUnitVO[]>([]) // 产品单位列表
const productList = ref<ProductVO[]>([]) // 产品列表
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改；detail 修改
const disabled = computed(() => formType.value === 'detail')
const formData = ref({
  id: undefined,
  productId: undefined,
  unitId: undefined,
  unitName: undefined,
  taskId: undefined,
  number: undefined,
  packageSize: undefined,
  projectName: undefined,
  techRequirements: undefined,
  remark: undefined,
  packageNumber: undefined,
  finishDate: undefined,
  boxingDate: undefined,
  arriveDate: undefined,
})
const formRules = reactive({
  productId: [{ required: true, message: t('ProductionPlan.Task.validatorDetailProductIdRequired'), trigger: 'blur' }],
  unitId: [{ required: true, message: t('ProductionPlan.Task.validatorDetailUnitIdRequired'), trigger: 'blur' }],
  taskId: [{ required: true, message: t('ProductionPlan.Task.validatorDetailTaskIdRequired'), trigger: 'blur' }],
  number: [{ required: true, message: t('ProductionPlan.Task.validatorDetailNumberRequired'), trigger: 'blur' }],
  packageSize: [{ required: true, message: t('ProductionPlan.Task.validatorDetailPackageSizeRequired'), trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number, taskId: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.taskId = taskId
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TaskApi.getTaskDetail(id)
      if(formData.value.remark === null || formData.value.remark === undefined){
        formData.value.remark =''
      }
    } finally {
      formLoading.value = false
    }
  }
  // 产品单位
  //unitList.value = await ProductUnitApi.getProductUnitSimpleList()
  // unitList.value= [
  //   {
  //     id: 5,
  //     name: '个',
  //   },
  // ]
  // formData.value.unitId = 5
  productList.value = await ProductApi.getMesProductSimpleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

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

/** 处理产品变更 */
const onChangeProduct = (productId) => {
  const product = productList.value.find((item) => item.id === productId)
  if (product) {
    formData.value.unitName = product.unitName
    formData.value.unitId = product.unitId
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    productId: undefined,
    unitId: undefined,
    taskId: undefined,
    number: undefined,
    packageSize: undefined,
    projectName: undefined,
    techRequirements: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
}
</script>
