<template>
  <ElDialog
    v-model="visible"
    :title="qualityPassed ? '质检通过' : '质检不通过'"
    width="450px"
    top="30vh"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    @close="handleClose"
  >
    <div class="confirm-body">
      <ElIcon class="confirm-tip__icon" :size="24">
        <WarningFilled />
      </ElIcon>
      <ElForm ref="formRef" :model="form" :rules="rules" class="confirm-form">
        <div class="confirm-tip">
          {{ qualityPassed ? '确定质检通过吗？' : '确定质检不通过吗？' }}
        </div>
        <ElFormItem
          v-if="!qualityPassed"
          label="原因"
          prop="qualifyProblemType"
        >
          <ElSelect
            v-model="form.qualifyProblemType"
            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.qualifyProblemType === 5"
          label="具体原因"
          prop="qualityIssues"
        >
          <ElInput
            v-model="form.qualityIssues"
            placeholder="请输入不通过原因"
            maxlength="50"
            show-word-limit
            clearable
          />
        </ElFormItem>
      </ElForm>
    </div>
    <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 { WarningFilled } from '@element-plus/icons-vue'
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 source = ref(0) // 0 列表页，1 快捷质检
const formRef = ref<FormInstance>()
const updateParams = ref<{ id: number; version?: number }[]>([])
const reasonOptions = ref<QualityTypeItem[]>([])

const form = reactive<{
  qualifyProblemType: number | string
  qualityIssues: string
}>({
  qualifyProblemType: '',
  qualityIssues: '',
})

const rules = computed<FormRules>(() => {
  if (qualityPassed.value) return {}
  const result: FormRules = {
    qualifyProblemType: [
      { required: true, message: '请选择不通过原因', trigger: 'change' },
    ],
  }
  if (form.qualifyProblemType && form.qualifyProblemType === 5) {
    result.qualifyProblemType = [
      { 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.qualityIssues =
    form.qualifyProblemType === 5
      ? ''
      : reasonOptions.value.find((item) => item.key === form.qualifyProblemType)
          ?.value || ''

  formRef.value?.clearValidate('qualityIssues')
}

const open = (
  rows: { id: number; version?: number }[],
  passed: boolean,
  sourceType: number = 0,
) => {
  updateParams.value = rows.map((row) => ({
    id: row.id,
    version: row.version,
  }))
  qualityPassed.value = passed
  source.value = sourceType
  form.qualifyProblemType = ''
  form.qualityIssues = ''
  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()
  }

  submitLoading.value = true
  try {
    const params = {
      ...form,
      updateParams: updateParams.value,
      qualityPassed: qualityPassed.value,
      source: source.value,
    }
    const res = await qualityPodOrderOperationApi(params)
    if (res.code !== 200) return
    if (source.value !== 1) {
      ElMessage.success('操作成功')
    }
    visible.value = false
    emit('success')
  } catch (e) {
    console.error(e)
  } finally {
    submitLoading.value = false
  }
}

defineExpose({ open })
</script>

<style lang="scss" scoped>
.confirm-body {
  display: flex;
  gap: 12px;
}
.confirm-form {
  flex: 1;
  min-width: 0;
}

.confirm-tip {
  margin-bottom: 12px;
  line-height: 24px;
}

.confirm-tip__icon {
  flex-shrink: 0;
  color: var(--el-color-warning);
}
</style>
