<template>
  <ElDialog
    v-model="visible"
    :title="qualityPassed ? '质检通过' : '质检不通过'"
    width="450px"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    @close="handleClose"
  >
    <ElForm ref="formRef" :model="form" :rules="rules">
      <div class="mb-10">
        {{ qualityPassed ? '确定质检通过吗？' : '确定质检不通过吗？' }}
      </div>
      <ElFormItem v-if="!qualityPassed" label="原因" prop="reasonKey">
        <ElSelect
          v-model="form.reasonKey"
          placeholder="请选择不通过原因"
          style="width: 100%"
          clearable
          filterable
          @change="handleReasonChange"
        >
          <ElOption
            v-for="item in reasonOptions"
            :key="item.key"
            :label="item.value"
            :value="item.key"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem
        v-if="!qualityPassed && form.reasonKey === 5"
        label="具体原因"
        prop="qualify_problem_type"
      >
        <ElInput
          v-model="form.qualify_problem_type"
          placeholder="请输入不通过原因"
          clearable
        />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer" style="text-align: center">
        <ElButton @click="visible = false">取消</ElButton>
        <ElButton type="primary" :loading="submitLoading" @click="handleSubmit">
          确认
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import {
  getQualityTypeApi,
  qualityPodOrderOperationApi,
} from '@/api/factoryOrderNew'
import type { QualityTypeItem } from '@/types/api/factoryOrderNew'

const emit = defineEmits<{
  success: []
}>()

const visible = ref(false)
const submitLoading = ref(false)
const qualityPassed = ref(true)
const formRef = ref<FormInstance>()
const updateParams = ref<{ id: number; version?: number }[]>([])
const reasonOptions = ref<QualityTypeItem[]>([])

const form = reactive<{
  reasonKey: number | string | undefined
  qualify_problem_type: string
}>({
  reasonKey: undefined,
  qualify_problem_type: '',
})

const rules = computed<FormRules>(() => {
  if (qualityPassed.value) return {}
  const result: FormRules = {
    reasonKey: [
      { required: true, message: '请选择不通过原因', trigger: 'change' },
    ],
  }
  if (form.reasonKey && form.reasonKey === 5) {
    result.qualify_problem_type = [
      { required: true, message: '请输入不通过原因', trigger: 'blur' },
    ]
  }
  return result
})

const loadReasons = async () => {
  try {
    const res = await getQualityTypeApi()
    reasonOptions.value = res.data || []
  } catch (e) {
    console.error(e)
    reasonOptions.value = []
  }
}

const handleReasonChange = () => {
  form.qualify_problem_type = ''
  formRef.value?.clearValidate('qualify_problem_type')
}

/** qualityPassed: true 质检通过，false 质检不通过 */
const open = (rows: { id: number; version?: number }[], passed: boolean) => {
  updateParams.value = rows.map((row) => ({
    id: row.id,
    version: row.version,
  }))
  qualityPassed.value = passed
  form.reasonKey = undefined
  form.qualify_problem_type = ''
  visible.value = true
  if (!passed) void loadReasons()
}

const handleClose = () => {
  formRef.value?.resetFields()
  reasonOptions.value = []
}

const handleSubmit = async () => {
  if (!formRef.value) return
  if (!qualityPassed.value) {
    await formRef.value.validate()
  }
  const selected = reasonOptions.value.find(
    (item) => item.key === form.reasonKey,
  )
  submitLoading.value = true
  try {
    const params = {
      updateParams: updateParams.value,
      qualityIssues: qualityPassed.value ? '' : selected?.value || '',
      qualify_problem_type: qualityPassed.value
        ? ''
        : form.reasonKey === 5
        ? form.qualify_problem_type
        : (form.reasonKey as number | string),
      qualityPassed: qualityPassed.value,
    }
    console.log(params)
    return
    const res = await qualityPodOrderOperationApi(params)
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    visible.value = false
    emit('success')
  } catch (e) {
    console.error(e)
  } finally {
    submitLoading.value = false
  }
}

defineExpose({ open })
</script>
