<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item :label="t('QualityManagement.ZjTask.formCode')" prop="code">
        <el-input
          v-model="formData.code"
          :placeholder="t('QualityManagement.ZjTask.placeholderFormCode')"
        />
      </el-form-item>
      <el-form-item :label="t('QualityManagement.ZjTask.formType')" prop="type">
        <el-select
          v-model="formData.type"
          clearable
          filterable
          :placeholder="t('QualityManagement.ZjTask.placeholderFormType')"
        >
          <el-option
v-for="dict in getStrDictOptions('mes_zj_task_type')" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('QualityManagement.ZjTask.formSchema')" prop="schemaId">
        <el-row :gutter="8" class="w-full">
          <el-col :span="22">
            <el-input
              v-model="formData.schemaName"
              :placeholder="t('QualityManagement.ZjTask.placeholderFormSchema')"
              readonly
            />
          </el-col>
          <el-col :span="2" class="text-right">
            <el-button type="primary" @click="openSchemaDialog">
              {{ t('action.select') }}
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item :label="t('QualityManagement.ZjTask.formTicketType')" prop="ticketType">
        <el-radio-group v-model="formData.ticketType" @change="ticketTypeChange">
          <el-radio :label="1">{{ t('QualityManagement.ZjTask.ticketTypeProcess') }}</el-radio>
          <el-radio :label="2">{{ t('QualityManagement.ZjTask.ticketTypeStorage') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="t('QualityManagement.ZjTask.formTicket')" prop="ticket">
        <el-select
          v-model="formData.ticket"
          clearable
          filterable
          :placeholder="t('QualityManagement.ZjTask.placeholderFormTicket')"
        >
          <el-option
            v-for="item in planList"
            :key="item.id"
            :label="item.code"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('QualityManagement.ZjTask.formOrgType')" prop="orgType" v-if="formData.ticketType === 1">
        <el-select
          v-model="formData.orgType"
          clearable
          :placeholder="t('QualityManagement.ZjTask.placeholderFormOrgType')"
        >
          <el-option v-for="item in orgTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('QualityManagement.ZjTask.formManager')" prop="managerId">
        <el-select
          v-model="formData.managerId"
          clearable
          filterable
          :placeholder="t('QualityManagement.ZjTask.placeholderFormManager')"
          @change="handleManagerChange"
        >
          <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('QualityManagement.ZjTask.formRemark')" prop="remark">
        <el-input
          v-model="formData.remark"
          :placeholder="t('QualityManagement.ZjTask.placeholderFormRemark')"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">
        {{ t('common.ok') }}
      </el-button>
      <el-button @click="dialogVisible = false">
        {{ t('common.cancel') }}
      </el-button>
    </template>
  </Dialog>
  <el-dialog
    v-model="schemaDialogVisible"
    :title="t('QualityManagement.ZjTask.formSchema')"
    width="1200px"
    draggable
  >
    <el-table :data="schemaList" v-loading="schemaLoading" height="400px" @row-click="handleSchemaRowClick">
      <el-table-column width="60">
        <template #default="scope">
          <el-radio :label="scope.row.id" v-model="selectedSchemaId">
            <span></span>
          </el-radio>
        </template>
      </el-table-column>
      <el-table-column :label="t('QualityManagement.ZjSchema.name')" type="index" width="80" />
      <el-table-column :label="t('QualityManagement.ZjSchema.name')" prop="name" />
      <el-table-column :label="t('QualityManagement.ZjSchema.type')" prop="type">
        <template #default="scope">
          <dict-tag type="mes_zj_schema_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column :label="t('QualityManagement.ZjSchema.sampleMethod')" prop="sampleMethod">
        <template #default="scope">
          <dict-tag type="mes_zj_schema_sample_method" :value="scope.row.sampleMethod" />
        </template>
      </el-table-column>
      <el-table-column :label="t('QualityManagement.ZjSchema.val')" prop="val">
        <template #default="scope">
          {{ formatSchemaVal(scope.row.val) }}
        </template>
      </el-table-column>
      <el-table-column :label="t('QualityManagement.ZjSchema.remark')" prop="remark" />
    </el-table>
    <template #footer>
      <el-button @click="schemaDialogVisible = false">
        {{ t('common.cancel') }}
      </el-button>
      <el-button type="primary" @click="confirmSelectSchema">
        {{ t('common.ok') }}
      </el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ZjTaskApi, ZjTaskVO } from '@/api/mes/zjtask'
import { ZjSchemaApi, ZjSchemaVO } from '@/api/mes/zjschema'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import * as UserApi from '@/api/system/user'
import { PlanApi, PlanVO } from '@/api/mes/plan'

defineOptions({ name: 'ZjTaskForm' })

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const planList = ref<PlanVO[]>([])

const formData = ref<{ [key: string]: any }>({
  id: undefined,
  code: undefined,
  name: undefined,
  type: undefined,
  schemaId: undefined,
  schemaName: undefined,
  ticket: undefined,
  orgType: undefined,
  remark: undefined,
  managerId: undefined,
  managerName: undefined,
  ticketType: undefined
})

const formRules = reactive({
  code: [{ required: true, message: t('QualityManagement.ZjTask.validatorCodeRequired'), trigger: 'blur' }],
  type: [{ required: true, message: t('QualityManagement.ZjTask.validatorTypeRequired'), trigger: 'change' }],
  schemaId: [{ required: true, message: t('QualityManagement.ZjTask.validatorSchemaRequired'), trigger: 'change' }],
  ticket: [{ required: true, message: t('QualityManagement.ZjTask.validatorTicketRequired'), trigger: 'blur' }],
  orgType: [{ required: true, message: t('QualityManagement.ZjTask.validatorOrgTypeRequired'), trigger: 'change' }],
  ticketType: [{ required: true, message: t('QualityManagement.ZjTask.validatorTicketTypeRequired'), trigger: 'change' }],
})

const formRef = ref()

const schemaDialogVisible = ref(false)
const schemaLoading = ref(false)
const schemaList = ref<ZjSchemaVO[]>([])
const selectedSchemaId = ref<number | undefined>(undefined)
const orgTypeOptions = getStrDictOptions(DICT_TYPE.MES_ORG_TYPE)
const userList = ref<UserApi.UserVO[]>([])

const formatSchemaVal = (val: string | number | null | undefined) => {
  if (val === null || val === undefined || val === '') return ''
  const text = String(val).trim()
  if (!text) return ''
  if (text.includes(',')) {
    const parts = text
      .split(',')
      .map((v) => v.trim())
      .filter((v) => v)
    const first = parts[0] ?? ''
    const second = parts[1] ?? ''
    return `每间隔${first}抽取${second}`
  }
  return `${text}%`
}

const loadSchemaList = async () => {
  if (schemaList.value.length) return
  schemaLoading.value = true
  try {
    const data = await ZjSchemaApi.getZjSchemaList()
    schemaList.value = data || []
  } finally {
    schemaLoading.value = false
  }
}

const openSchemaDialog = async () => {
  schemaDialogVisible.value = true
  await loadSchemaList()
}

const loadUserList = async () => {
  if (userList.value.length) return
  const data = await UserApi.getSimpleUserList()
  userList.value = data || []
}

const handleSchemaRowClick = (row: ZjSchemaVO) => {
  selectedSchemaId.value = row.id
}

const confirmSelectSchema = () => {
  if (!selectedSchemaId.value) return
  const matched = schemaList.value.find((item) => item.id === selectedSchemaId.value)
  if (!matched) return
  formData.value.schemaId = matched.id
  formData.value.schemaName = matched.name
  schemaDialogVisible.value = false
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    name: undefined,
    type: undefined,
    schemaId: undefined,
    schemaName: undefined,
    ticket: undefined,
    orgType: undefined,
    remark: undefined,
    managerId: undefined,
    managerName: undefined,
    ticketType: undefined
  }
  selectedSchemaId.value = undefined
  formRef.value?.resetFields()
}

const open = async (type: string, record?: ZjTaskVO) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  await loadUserList()
  if (type === 'update' && record) {
    formData.value = {
      id: record.id,
      code: record.code,
      name: record.name,
      type: record.type,
      schemaId: record.schemaId,
      schemaName: record.schemaName,
      ticket: record.ticket,
      orgType: record.orgType,
      remark: record.remark,
      managerId: record.managerId,
      managerName: record.managerName,
    }
    selectedSchemaId.value = record.schemaId
  }
}

const handleManagerChange = (value: number | undefined) => {
  if (!value) {
    formData.value.managerName = undefined
    return
  }
  const matched = userList.value.find((item) => item.id === value)
  formData.value.managerName = matched ? matched.nickname : undefined
}

defineExpose({ open })

const emit = defineEmits(['success'])

const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = formData.value as unknown as ZjTaskVO
    if (formType.value === 'create') {
      await ZjTaskApi.createZjTask(data)
      message.success(t('common.createSuccess'))
    } else {
      await ZjTaskApi.updateZjTask(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const ticketTypeChange = async () => {
  if (formData.value.ticketType !=  undefined) {
    const data = await PlanApi.getPlanByTicketType(formData.value.ticketType)
    planList.value = data || []
  }
}
</script>
