<template>
  <el-drawer
    v-model="dialogVisible"
    :title="dialogTitle"
    direction="rtl"
    size="100%"
    :destroy-on-close="true"
    :before-close="onClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <!-- 1. 单据信息 -->
      <el-divider content-position="left"><span style="font-size: 16px">单据信息</span></el-divider>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="送检单号" prop="inspectionNo">
            <el-input v-model="formData.inspectionNo" placeholder="请输入送检单号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="采购订单号" prop="purchaseOrderNo">
            <el-input v-model="formData.purchaseOrderNo" placeholder="请输入采购订单号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="批次号" prop="batchNo">
            <el-input v-model="formData.batchNo" placeholder="请输入批次号" clearable />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 2. 物料信息 -->
      <el-divider content-position="left"><span style="font-size: 16px">物料信息</span></el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物料编码" prop="materialCode">
            <el-input v-model="formData.materialCode" placeholder="请选择物料编码" readonly>
              <template #append>
                <el-button :icon="Search" @click="showMaterialDialog" />
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料使用部门" prop="materialUseDepartment">
            <el-input v-model="formData.materialUseDepartment" readonly />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 3. 供应商信息 -->
      <el-divider content-position="left"
        ><span style="font-size: 16px">供应商信息</span></el-divider
      >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input v-model="formData.supplierName" placeholder="请选择供应商" readonly>
              <template #append>
                <el-button :icon="Search" @click="showSupplierSelectDialog" />
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商编码" prop="supplierCode">
            <el-input v-model="formData.supplierCode" readonly />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 4. 检验信息 -->
      <el-divider content-position="left"><span style="font-size: 16px">检验信息</span></el-divider>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="检验批数量" prop="inspectionQuantity">
            <el-input-number
              v-model="formData.inspectionQuantity"
              :min="1"
              :precision="0"
              placeholder="请输入检验批数量"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="不合格数量" prop="unqualifiedQuantity">
            <el-input-number
              v-model="formData.unqualifiedQuantity"
              :min="0"
              :precision="0"
              :max="formData.inspectionQuantity"
              placeholder="请输入不合格数量"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="问题来源类型" prop="problemSourceType">
            <el-select
              v-model="formData.problemSourceType"
              placeholder="请选择问题来源类型"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in issueSourceTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 5. 不合格详情 -->
      <el-divider content-position="left"
        ><span style="font-size: 16px">不合格详情</span></el-divider
      >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="不合格原因" prop="unqualifiedReason">
            <el-input
              v-model="formData.unqualifiedReason"
              placeholder="请简要描述不合格原因"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="不合格描述" prop="unqualifiedDescription">
            <el-input
              v-model="formData.unqualifiedDescription"
              type="textarea"
              :rows="3"
              placeholder="请详细描述不合格情况"
              show-word-limit
              maxlength="500"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 6. 处理信息 -->
      <el-divider content-position="left"><span style="font-size: 16px">处理信息</span></el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="限制处理时间" prop="limitProcessingTime">
            <el-date-picker
              v-model="formData.limitProcessingTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm"
              value-format="x"
              placeholder="选择限制处理时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label-width="150px"
            label="供方异议是否接收"
            prop="isSupplierObjectionAccepted"
          >
            <el-radio-group v-model="formData.isSupplierObjectionAccepted">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 异议备注（条件显示） -->
      <el-row :gutter="20" v-if="formData.isSupplierObjectionAccepted === 0">
        <el-col :span="24">
          <el-form-item label="供方异议备注" prop="supplierObjectionRemark">
            <el-input
              v-model="formData.supplierObjectionRemark"
              type="textarea"
              :rows="2"
              placeholder="请输入供方异议的具体原因"
              show-word-limit
              maxlength="200"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 7. 附件信息 -->
      <el-divider content-position="left"><span style="font-size: 16px">附件信息</span></el-divider>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="检验报告" prop="attachmentInfo">
            <UploadFile
              :is-show-tip="true"
              v-model="formData.attachmentInfo"
              :limit="1"
              :fileType="['pdf']"
              tip="请上传PDF格式的检验报告，大小不超过10MB"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 处理措施表格 -->
    <div style="padding: 20px">
      <div class="table-header">
        <span class="table-title">处理措施</span>
        <el-button type="primary" size="small" @click="addMeasure">新增措施</el-button>
      </div>
      <el-table :data="formData.measures" border style="width: 100%; margin-bottom: 20px">
        <el-table-column prop="measure" label="处理措施" width="200">
          <template #default="{ row, $index }">
            <el-input
              v-model="row.measure"
              placeholder="请输入处理措施"
              @change="handleMeasureChange($index, 'measure', row.measure)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="responsiblePerson" label="责任人" width="150">
          <template #default="{ row, $index }">
            <el-input
              v-model="row.responsiblePerson"
              placeholder="请输入责任人"
              @change="handleMeasureChange($index, 'responsiblePerson', row.responsiblePerson)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="planTime" label="计划时间" width="180">
          <template #default="{ row, $index }">
            <el-date-picker
              v-model="row.plannedTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm"
              value-format="x"
              placeholder="选择计划时间"
              style="width: 100%"
              @change="handleMeasureChange($index, 'plannedTime', row.plannedTime)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="attachment" label="附件">
          <template #default="{ row, $index }">
            <span v-if="row.attachmentName">{{ row.attachmentName }}&nbsp;&nbsp;</span>
            <el-button
              class="p-r-8px"
              v-if="row.attachmentName"
              :icon="Download"
              circle
              type="default"
              :underline="false"
              @click="downloadFile(row.attachmentUrl, row.attachmentName)"
            />
            <el-button
              v-if="row.attachmentName"
              type="default"
              :icon="DocumentChecked"
              circle
              :underline="false"
              @click="previewFile(row.attachmentUrl, row.attachmentName)"
            />
            <el-button type="primary" size="small" @click="triggerClick($index)">
              {{ row.attachmentName ? '更换文件' : '新增文件' }}
            </el-button>
            <input
              type="file"
              :ref="(el) => setFileRef(el, $index)"
              style="display: none"
              @change="(e) => handleFileChange($index, e)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="completionTime" label="完成时间" width="180">
          <template #default="{ row, $index }">
            <el-date-picker
              v-model="row.completionTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm"
              value-format="x"
              placeholder="选择完成时间"
              style="width: 100%"
              @change="handleMeasureChange($index, 'completionTime', row.completionTime)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="{ $index }">
            <el-button
              type="danger"
              size="small"
              @click="removeMeasure($index)"
              :icon="Delete"
              circle
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 抽屉底部按钮 -->
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </template>
  </el-drawer>
  <!--   供应商选择弹框 -->
  <SelectSupplierDialog
    v-model="supplierSelectVisible"
    :title="supplierSelectTitle"
    :multiple="false"
    :selected="preselectedSuppliers"
    @confirm="handleSuppliersSelect"
  />
  <MaterialSelectDialog
    v-model="materialDialogVisible"
    :multiple="true"
    @confirm="handleMaterialSelect"
  />
  <PdfPreview ref="pdfPreviewRef" />
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { Delete, DocumentChecked, Download } from '@element-plus/icons-vue'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { QualityNoticeApi, QualityNoticeVO } from '@/api/contract/qualitynotice'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'
import { getUserProfile } from '@/api/system/user/profile'
import { Search } from '@element-plus/icons-vue'
import SelectSupplierDialog from '@/views/contract/supplier/SelectSupplier.vue'
import MaterialSelectDialog from '@/views/contract/qualitymaterial/SelectQualityMaterial.vue'
import { UploadFile } from '@/components/UploadFile'
import * as FileApi from '@/api/infra/file'
import { PdfPreview } from '@/components/Pdf'

const issueSourceTypeOptions = getStrDictOptions(DICT_TYPE.CONTRACT_QUALITY_ISSUE_SOURCE_TYPE)
defineOptions({ name: 'QualityIssueForm' })

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

// 抽屉控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref({
  id: undefined,
  inspectionNo: undefined,
  batchNo: undefined,
  materialCode: undefined,
  inspectionQuantity: undefined,
  unqualifiedReason: undefined,
  materialUseDepartment: undefined,
  attachmentInfo: '',
  unqualifiedDescription: undefined,
  purchaseOrderNo: undefined,
  supplierName: undefined,
  supplierCode: undefined,
  unqualifiedQuantity: undefined,
  problemSourceType: undefined,
  limitProcessingTime: undefined,
  isSupplierObjectionAccepted: 1,
  supplierObjectionRemark: '',
  measures: [] as Array<{
    measure: string
    responsiblePerson: string
    plannedTime: Date | undefined
    attachmentUrl: string
    attachmentName: string
    completionTime: Date | undefined
  }>
})

// 表单校验规则
const formRules = reactive({
  inspectionNo: [{ required: true, message: '送检单号不能为空', trigger: 'blur' }],
  batchNo: [{ required: true, message: '批次号不能为空', trigger: 'blur' }],
  materialCode: [{ required: true, message: '物料编码不能为空', trigger: 'blur' }],
  inspectionQuantity: [{ required: true, message: '检验批数量不能为空', trigger: 'blur' }]
})

const formRef = 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 QualityNoticeApi.getQualityNotice(id)
    } finally {
      formLoading.value = false
    }
  }
  // 如果是新增，自动填充 经办人 和 经办部门
  if (!id) {
    try {
      const profile = await getUserProfile()
      formData.value.materialUseDepartment = profile.dept.name || ''
    } catch (error) {
      console.warn('获取用户信息失败', error)
      // 可选择忽略，或提示
      message.warning('无法获取当前用户信息')
    }
  }
}

/** 关闭前确认 */
const onClose = () => {
  dialogVisible.value = false
}

defineExpose({ open })

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  await formRef.value.validate()
  console.log(formData.value.measures)
  // 验证措施数据
  for (const measure of formData.value.measures) {
    if (!measure.measure || !measure.responsiblePerson || !measure.plannedTime) {
      message.error('请完善所有处理措施信息')
      return
    }
  }
  formLoading.value = true
  try {
    const data = formData.value as unknown as QualityNoticeVO
    if (formType.value === 'create') {
      await QualityNoticeApi.createQualityNotice(data)
      message.success(t('common.createSuccess'))
    } else {
      await QualityNoticeApi.updateQualityNotice(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}
watch(
  () => formData.value.isSupplierObjectionAccepted,
  (newVal) => {
    if (newVal === 1) {
      formData.value.supplierObjectionRemark = '' // 选择 "是" 时清空备注
    }
  }
)
// 供应商单选模式
const supplierSelectVisible = ref(false)
const supplierSelectTitle = ref('选择供应商（单选）')
const selectedSupplier = ref(null)
const preselectedSuppliers = ref([])

const showSupplierSelectDialog = () => {
  supplierSelectVisible.value = true
  // 设置默认选中项（可选）
  preselectedSuppliers.value = selectedSupplier.value ? [selectedSupplier.value] : []
}

const handleSuppliersSelect = (supplier) => {
  // 供应商单选模式回调
  selectedSupplier.value = supplier
  formData.value.supplierCode = supplier.supplierCode
  formData.value.supplierName = supplier.supplierName
}
//物料选择
const materialDialogVisible = ref(false)

const showMaterialDialog = () => {
  materialDialogVisible.value = true
}

const handleMaterialSelect = (materials) => {
  formData.value.materialCode = materials[0].materialCode
}
// 添加处理措施
const addMeasure = () => {
  formData.value.measures.push({
    measure: '',
    responsiblePerson: '',
    plannedTime: undefined,
    attachmentUrl: '',
    attachmentName: '',
    completionTime: undefined
  })
}

// 删除处理措施
const removeMeasure = (index: number) => {
  formData.value.measures.splice(index, 1)
}

// 处理措施变更
const handleMeasureChange = (index: number, field: string, value: any) => {
  formData.value.measures[index][field] = value
}
const fileInputs = ref({})

const setFileRef = (el, index) => {
  if (el) {
    fileInputs.value[index] = el
  }
}

const triggerClick = (index) => {
  fileInputs.value[index]?.click()
}
// 处理文件上传
const handleFileChange = async (index: number, event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files && input.files[0]) {
    const file = input.files[0]
    const fileFormData = new FormData()
    fileFormData.append('file', file)

    try {
      formLoading.value = true
      const res = await FileApi.updateFile(fileFormData)

      formData.value.measures[index].attachmentName = file.name
      formData.value.measures[index].attachmentUrl = res.data
      message.success('附件上传成功')
    } catch (error) {
      message.error('上传失败')
    } finally {
      formLoading.value = false
      input.value = '' // Reset the input
    }
  }
}
const downloadFile = (fileUrl: string, fileName: string) => {
  message.info(`正在下载：${fileName}`)
  window.open(fileUrl, '_blank')
}
// 修改预览方法
const pdfPreviewRef = ref()
const previewFile = (fileUrl: string, fileName: string) => {
  if (fileName.toLowerCase().endsWith('.pdf')) {
    pdfPreviewRef.value.open(fileName, fileUrl)
  } else {
    message.warning('仅支持预览 PDF 文件')
  }
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    inspectionNo: undefined,
    batchNo: undefined,
    materialCode: undefined,
    inspectionQuantity: undefined,
    unqualifiedReason: undefined,
    materialUseDepartment: undefined,
    attachmentInfo: '',
    unqualifiedDescription: undefined,
    purchaseOrderNo: undefined,
    supplierName: undefined,
    supplierCode: undefined,
    unqualifiedQuantity: undefined,
    problemSourceType: undefined,
    limitProcessingTime: undefined,
    isSupplierObjectionAccepted: 1,
    supplierObjectionRemark: '',
    measures: []
  }
  formRef.value?.resetFields()
}
</script>

<style scoped>
.drawer-footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1;
  display: flex;
  padding: 15px;
  background-color: #fff;
  border-top: 1px solid #e8e8e8;
  gap: 10px;
  justify-content: flex-end;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
}
</style>
<style>
.el-drawer__body {
  padding-top: 0 !important;
}

.el-drawer__header {
  margin-bottom: 0 !important;
}
</style>
