<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1000px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="单号" prop="code">
        <el-input :disabled="editDisable" v-model="formData.flowCode" placeholder="保存自动生成" />
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="模具型号" prop="brandId">
            <el-select
              :disabled='editDisable'
              v-model="formData.brandId"
              clearable
              filterable
              placeholder="请选择模具型号"
              @change="changeBrand"
            >
              <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.code+'/'+item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="模具" prop="moldId">
            <el-select
              :disabled='editDisable'
              v-model="formData.moldId"
              clearable
              filterable
              placeholder="请选择模具"
            >
              <el-option
                v-for="item in moldList"
                :key="item.id"
                :label="item.code+'/'+item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="单据类型" prop="recordType">
        <el-radio-group v-model="formData.recordType">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.MES_MOLD_RECORD_TYPE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-row v-if="formData.recordType=='换模'">
        <el-col :span="12">
          <el-form-item label="机台" prop="machineId">
            <el-select
              v-model="formData.machineId"
              clearable
              filterable
              placeholder="请选择机台"
            >
              <el-option
                v-for="item in machineList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="前模具" prop="oldMoldId">
            <el-input v-model="formData.oldMoldId" placeholder="请输入前模具" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="负责人" prop="userId">
            <el-select v-model="formData.userId" 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-col>
        <el-col :span="8">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="formData.startTime"
              type="date"
              value-format="x"
              placeholder="选择开始时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              type="date"
              value-format="x"
              placeholder="选择结束时间"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">

        <Editor v-model="formData.remark" height="200px" />
      </el-form-item>
    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="模具维保明细" name="moldRecordSubjectDetail">
        <MoldRecordSubjectDetailForm ref="moldRecordSubjectDetailFormRef" :record-id="formData.id" />
      </el-tab-pane>
    </el-tabs>
    <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 { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { MoldRecordApi, MoldRecordVO } from '@/api/mes/moldrecord'
import MoldRecordSubjectDetailForm from './components/MoldRecordSubjectDetailForm.vue'
import {MoldBrandApi, MoldBrandVO, MoldVO} from "@/api/erp/mold";
import * as UserApi from "@/api/system/user";
import {MachineComponentApi, MachineComponentVO} from "@/api/mes/machine";

/** 模具维保 表单 */
defineOptions({ name: 'MoldRecordForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const editDisable = ref(false)
const brandList = ref<MoldBrandVO[]>([]) // 模具型号列表
const moldList = ref<MoldVO[]>([]) // 模具列表
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
const machineList = ref<MachineComponentVO[]>([]) // 模具列表

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  flowCode: undefined,
  brandId: undefined,
  moldId: undefined,
  oldMoldId: undefined,
  machineId: undefined,
  userId: undefined,
  recordType: undefined,
  recordStatus: undefined,
  remark: undefined
})
const formRules = reactive({
  brandId: [{ required: true, message: '模具型号ID不能为空', trigger: 'blur' }],
  moldId: [{ required: true, message: '模具ID不能为空', trigger: 'blur' }],
  userId: [{ required: true, message: '负责人ID不能为空', trigger: 'blur' }],
  recordType: [{ required: true, message: '单据类型不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('moldRecordSubjectDetail')
const moldRecordSubjectDetailFormRef = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MoldRecordApi.getMoldRecord(id)
      editDisable.value = true
    } finally {
      formLoading.value = false
    }
  }
  // 加载列表
  brandList.value = await MoldBrandApi.getBrandList()
  // 获得用户列表
  userList.value = await UserApi.getSimpleUserList()
  // 获得用户列表
  machineList.value = await MachineComponentApi.getMachineComponentList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await moldRecordSubjectDetailFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'moldRecordSubjectDetail'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MoldRecordVO
    // 拼接子表的数据
    data.moldRecordSubjectDetails = moldRecordSubjectDetailFormRef.value.getData()
    if (formType.value === 'create') {
      await MoldRecordApi.createMoldRecord(data)
      message.success(t('common.createSuccess'))
    } else {
      await MoldRecordApi.updateMoldRecord(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    flowCode: undefined,
    brandId: undefined,
    moldId: undefined,
    oldMoldId: undefined,
    machineId: undefined,
    userId: undefined,
    recordType: undefined,
    recordStatus: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
}

const query = reactive({
  brandId: undefined
})
const changeBrand = async(e) => {
  query.brandId = formData.value.brandId
  // 加载列表
  moldList.value = await MoldBrandApi.getMoldList(query)
}

</script>
