<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-row :gutter="8" class="w-full">
          <el-col :span="20">
            <el-input v-model="formData.code" :placeholder="t('QualityManagement.ZjTask.placeholderFormCode')" :disabled="Boolean(formData.isCode) || formType === 'update'" />
          </el-col>
          <el-col :span="4">
            <el-switch v-model="formData.isCode" :disabled="formType === 'update'" @change="handleCodeAutoChange" />
          </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" :disabled="lockedFields.ticketType">
          <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 v-if="formData.ticketType" :label="t('QualityManagement.ZjTask.formTicket')" prop="ticket">
        <el-select v-model="formData.ticket" clearable filterable :disabled="lockedFields.ticket"
          :placeholder="t('QualityManagement.ZjTask.placeholderFormTicket')" @change="fetchProductIdByTicket" @visible-change="handleTicketVisibleChange">
          <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.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 v-if="formData.ticket" :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.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" sortable />
      <el-table-column :label="t('QualityManagement.ZjSchema.type')" prop="type" sortable>
        <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 lockedFields = ref<{ ticketType?: boolean; ticket?: boolean }>({})

const formData = ref<{ [key: string]: any }>({
  id: undefined,
  code: undefined,
  isCode: true,
  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, validator: (_rule, value, callback) => {
    if (Boolean(formData.value.isCode)) {
      callback()
      return
    }
    if (value === undefined || value === null || String(value).trim() === '') {
      callback(new Error(t('QualityManagement.ZjTask.validatorCodeRequired')))
      return
    }
    callback()
  }, 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 currentProductId = ref<number | undefined>(undefined)
const orgTypeOptions = getStrDictOptions(DICT_TYPE.MES_ORG_TYPE)
const userList = ref<UserApi.UserVO[]>([])

const handleCodeAutoChange = (value: boolean) => {
  if (value) {
    formData.value.code = undefined
  }
  formRef.value?.clearValidate('code')
}

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 () => {
  schemaLoading.value = true
  try {
    const params: any = {}
    if (formData.value.ticketType === 1 && currentProductId.value) {
      params.productId = currentProductId.value
    }
    const data = await ZjSchemaApi.getZjSchemaList(params)
    schemaList.value = data || []
  } finally {
    schemaLoading.value = false
  }
}

const openSchemaDialog = async () => {
  schemaDialogVisible.value = true
  schemaList.value = []
  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,
    isCode: true,
    name: undefined,
    type: undefined,
    schemaId: undefined,
    schemaName: undefined,
    ticket: undefined,
    orgType: undefined,
    remark: undefined,
    managerId: undefined,
    managerName: undefined,
    ticketType: undefined
  }
  selectedSchemaId.value = undefined
  lockedFields.value = {}
  currentProductId.value = undefined
  formRef.value?.resetFields()
}

const open = async (type: string, record?: ZjTaskVO, preset?: { ticketType?: number; ticket?: number; ticketName?: string; productId?: number }) => {
  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,
      ticketType: record.ticketType,
      remark: record.remark,
      managerId: record.managerId,
      managerName: record.managerName,
    }
    selectedSchemaId.value = record.schemaId
  }
  if (preset) {
    if (preset.ticketType !== undefined) {
      formData.value.ticketType = preset.ticketType
      lockedFields.value.ticketType = true
    }
    if (preset.ticket !== undefined) {
      formData.value.ticket = preset.ticket
      lockedFields.value.ticket = true
      planList.value = [{ id: preset.ticket, code: preset.ticketName || '' }] as PlanVO[]
    }
    if (preset.productId !== undefined) {
      currentProductId.value = preset.productId
    }
  }
}

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 () => {
  formData.value.ticket = undefined
  currentProductId.value = undefined
  if (formData.value.ticketType != undefined) {
    const type = formData.value.ticketType === 1 ? 8 : formData.value.ticketType
    const data = await PlanApi.getPlanByTicketType(type)
    planList.value = data || []
  }
}

const fetchProductIdByTicket = async () => {
  if (!formData.value.ticket) return
  const plan = planList.value.find((item: any) => item.id === formData.value.ticket)
  if (plan?.productId) {
    currentProductId.value = plan.productId
  }
}

const handleTicketVisibleChange = async (visible: boolean) => {
  if (!visible || !formData.value.ticketType) return
  const type = formData.value.ticketType === 1 ? 8 : formData.value.ticketType
  const data = await PlanApi.getPlanByTicketType(type)
  planList.value = data || []
}
</script>
