<template>
  <!-- 移动端布局 -->
  <el-drawer v-if="isMobile" v-model="dialogVisible" :title="dialogTitle" direction="rtl" size="100%" :close-on-press-escape="true" :destroy-on-close="true" :append-to-body="true" class="mobile-form-drawer">
    <div class="mobile-form" v-loading="formLoading">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-position="top">
        <div class="mobile-form__section">
          <div class="mobile-form__section-title">发票信息</div>
          <el-form-item label="发票日期" prop="invoiceDate"><el-date-picker v-model="formData.invoiceDate" type="date" value-format="x" placeholder="选择发票日期" style="width:100%" /></el-form-item>
          <el-form-item label="发票类别" prop="invoiceCategory"><el-select v-model="formData.invoiceCategory" placeholder="请选择发票类别" style="width:100%"><el-option v-for="dict in getStrDictOptions(DICT_TYPE.ERP_FINANCE_INVOICE_INOUT_TYPE)" :key="dict.value" :label="dict.label" :value="dict.value" /></el-select></el-form-item>
          <el-form-item label="发票类型" prop="invoiceType"><el-select v-model="formData.invoiceType" placeholder="请选择发票类型" style="width:100%"><el-option v-for="dict in getStrDictOptions(DICT_TYPE.ERP_FINANCE_INVOICE_TYPE)" :key="dict.value" :label="dict.label" :value="dict.value" /></el-select></el-form-item>
          <el-form-item label="会计科目" prop="accountSubjects" required><el-select v-model="formData.accountSubjects" placeholder="请选择会计科目" style="width:100%"><el-option v-for="dict in getStrDictOptions(DICT_TYPE.ERP_FINANCE_SUBJECT_TYPE)" :key="dict.value" :label="dict.label" :value="dict.value" /></el-select></el-form-item>
          <el-form-item label="发票号码" prop="invoiceNo"><el-input v-model="formData.invoiceNo" placeholder="发票号码" /></el-form-item>
          <el-form-item label="发票方" prop="counterpartyName"><el-input v-model="formData.counterpartyName" placeholder="客户/供应商名称" /></el-form-item>
          <el-form-item label="金额(不含税)" prop="amountWithoutTax"><el-input v-model="formData.amountWithoutTax" placeholder="不含税金额" /></el-form-item>
          <el-form-item label="税率(%)" prop="taxRate"><el-input v-model="formData.taxRate" placeholder="税率 %" /></el-form-item>
          <el-form-item label="发票附件" prop="attachment"><UploadFile v-model="formData.attachment" :limit="1" :fileType="['pdf', 'png', 'jpg', 'jpeg']" :fileSize="10" /></el-form-item>
          <el-form-item label="发票状态" prop="invoiceStatus"><el-radio-group v-model="formData.invoiceStatus"><el-radio label="待认证">待认证</el-radio><el-radio label="已认证">已认证</el-radio></el-radio-group></el-form-item>
          <el-form-item label="备注" prop="remark"><el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" /></el-form-item>
        </div>
      </el-form>
    </div>
    <template #footer>
      <div class="mobile-form__footer">
        <el-button @click="dialogVisible = false" style="flex:1">取 消</el-button>
        <el-button @click="submitForm" type="primary" :disabled="formLoading" style="flex:2">确 定</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- PC端布局 -->
  <Dialog v-else :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="110px" v-loading="formLoading">
      <el-row :gutter="16">
        <el-col :span="12">
          <!-- <el-form-item label="发票日期" prop="invoiceDate">
              <el-date-picker
                v-model="formData.invoiceDate"
                type="date"
                value-format="x"
                placeholder="选择发票日期"
              />
            </el-form-item> -->
          <el-form-item label="发票日期" prop="invoiceDate">
            <el-date-picker
              v-model="formData.invoiceDate"
              type="date"
              value-format="x"
              placeholder="选择发票日期"
              class="w-100"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发票类别" prop="invoiceCategory">
            <el-select v-model="formData.invoiceCategory" placeholder="请选择发票类别">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.ERP_FINANCE_INVOICE_INOUT_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="发票类型" prop="invoiceType">
            <el-select v-model="formData.invoiceType" placeholder="请选择发票类型">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.ERP_FINANCE_INVOICE_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="会计科目" prop="accountSubjects" required>
            <el-select v-model="formData.accountSubjects" placeholder="请选择会计科目">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.ERP_FINANCE_SUBJECT_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="会计科目" prop="subjectId">
            <el-select v-model="formData.subjectId" placeholder="请选择会计科目" clearable>
              <el-option
                v-for="s in subjects"
                :key="s.id"
                :label="s.code ? (s.code + ' - ' + s.name) : s.name"
                :value="s.id"
              />
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="发票号码" prop="invoiceNo">
            <el-input v-model="formData.invoiceNo" placeholder="发票号码" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="发票方" prop="counterpartyName">
            <el-input v-model="formData.counterpartyName" placeholder="客户/供应商名称" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
            <el-form-item label="记账期间" prop="accountingPeriod">
              <el-input v-model="formData.accountingPeriod" placeholder="如 2026-01" />
            </el-form-item>
          </el-col> -->

        <el-col :span="12">
          <el-form-item label="金额(不含税)" prop="amountWithoutTax">
            <el-input v-model="formData.amountWithoutTax" placeholder="不含税金额" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="税率(%)" prop="taxRate">
            <el-input v-model="formData.taxRate" placeholder="税率 %" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
            <el-form-item label="税额" prop="taxAmount">
              <el-input v-model="formData.taxAmount" placeholder="税额" />
            </el-form-item>
          </el-col> -->

        <!-- <el-col :span="12">
            <el-form-item label="价税合计" prop="totalAmount">
              <el-input v-model="formData.totalAmount" placeholder="价税合计" />
            </el-form-item>
          </el-col> -->

        <el-col :span="12">
          <el-form-item label="发票附件" prop="attachment">
            <UploadFile
              v-model="formData.attachment"
              :limit="1"
              :fileType="['pdf', 'png', 'jpg', 'jpeg']"
              :fileSize="10"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="发票状态" prop="invoiceStatus">
            <el-radio-group v-model="formData.invoiceStatus">
              <el-radio label="待认证">待认证</el-radio>
              <el-radio label="已认证">已认证</el-radio>
              <!-- <el-radio label="已作废">已作废</el-radio> -->
            </el-radio-group>
          </el-form-item>
        </el-col>

        <!-- <el-col :span="12">
          <el-form-item v-if="formType === 'update'" label="认证日期" prop="certificationDate">
            <el-date-picker
              v-model="formData.certificationDate"
              type="date"
              value-format="x"
              placeholder="认证日期"
            />
          </el-form-item>
        </el-col> -->

        <!-- <el-col :span="12">
            <el-form-item label="凭证字号" prop="voucherNo">
              <el-input v-model="formData.voucherNo" placeholder="凭证字号" />
            </el-form-item>
          </el-col> -->

        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { InvoiceApi, Invoice } from '@/api/erp/finance/invoice'
import UploadFile from '@/components/UploadFile/src/UploadFile.vue'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import { SubjectApi } from '@/api/erp/finance/subject'
import { useWindowSize } from '@vueuse/core'

/** 财务发票主 表单 */
defineOptions({ name: 'InvoiceForm' })

const { width } = useWindowSize()
const isMobile = computed(() => width.value < 768)

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  invoiceDate: undefined,
  invoiceCategory: undefined,
  invoiceType: undefined,
  accountSubjects: undefined,
  subjectId: undefined,
  invoiceNo: undefined,
  counterpartyName: undefined,
  amountWithoutTax: undefined,
  taxRate: undefined,
  taxAmount: undefined,
  totalAmount: undefined,
  attachment: '',
  invoiceStatus: undefined,
  certificationDate: undefined,
  voucherNo: undefined,
  accountingPeriod: undefined,
  remark: undefined
})
const formRules = reactive({
  invoiceDate: [{ required: true, message: '发票日期不能为空', trigger: 'blur' }],
  invoiceCategory: [
    { required: true, message: '发票类别（进项发票/销项发票）不能为空', trigger: 'blur' }
  ],
  invoiceType: [
    { required: true, message: '发票类型（增值税专用发票/普通发票）不能为空', trigger: 'change' }
  ],
  accountSubjects: [{ required: true, message: '会计科目不能为空', trigger: 'change' }],
  invoiceNo: [{ required: true, message: '发票号码不能为空', trigger: 'blur' }],
  counterpartyName: [{ required: true, message: '客户/供应商名称不能为空', trigger: 'blur' }],
  amountWithoutTax: [{ required: true, message: '金额（不含税）不能为空', trigger: 'blur' }],
  taxRate: [{ required: true, message: '税率（%）不能为空', trigger: 'blur' }],
  taxAmount: [{ required: true, message: '税额不能为空', trigger: 'blur' }],
  totalAmount: [{ required: true, message: '价税合计不能为空', trigger: 'blur' }],
  invoiceStatus: [
    { required: true, message: '发票状态（待接收/已认证）不能为空', trigger: 'blur' }
  ],
  accountingPeriod: [{ required: true, message: '记账期间不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const subjects = ref<any[]>([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 加载会计科目选项（用于下拉）
  try {
    const list = await SubjectApi.getSubjectSimpleList()
    subjects.value = Array.isArray(list) ? list : list || []
  } catch (err) {
    console.error('加载会计科目失败', err)
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const res = await InvoiceApi.getInvoice(id)
      // normalize time values to timestamp(ms) for date-picker (value-format="x")
      const normalize = (v: any) => {
        if (v == null) return undefined
        if (Array.isArray(v) && v.length === 3 && v.every((it) => Number.isInteger(it))) {
          const [y, m, d] = v as number[]
          return new Date(y, m - 1, d).getTime()
        }
        if (Array.isArray(v)) return v.map((it) => normalize(it))
        const n = Number(v)
        if (!Number.isNaN(n)) return n < 1e12 ? n * 1000 : n
        const t = new Date(v).getTime()
        return Number.isNaN(t) ? undefined : t
      }
      const normalizeDictValue = (v: any) => {
        if (v == null) return undefined
        if (Array.isArray(v)) return v.map((it) => String(it))
        return String(v)
      }
      formData.value = {
        ...res,
        invoiceDate: normalize((res as any).invoiceDate),
        certificationDate: normalize((res as any).certificationDate),
        accountSubjects: normalizeDictValue((res as any).accountSubjects)
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const raw = formData.value as unknown as any
    // convert date-picker timestamps to formatted strings before sending
    const toDateOnly = (v: any): any => {
      if (v == null) return undefined
      if (Array.isArray(v)) return v.map((it) => toDateOnly(it))
      const n = Number(v)
      if (!Number.isNaN(n)) {
        const ms = n < 1e12 ? n * 1000 : n
        return formatDate(new Date(ms), 'YYYY-MM-DD')
      }
      return typeof v === 'string' ? v : undefined
    }
    const data: any = {
      ...raw,
      invoiceDate: toDateOnly(raw.invoiceDate),
      certificationDate: toDateOnly(raw.certificationDate),
      accountSubjects:
        raw.accountSubjects == null
          ? undefined
          : Array.isArray(raw.accountSubjects)
            ? raw.accountSubjects.map((it: any) => String(it))
            : String(raw.accountSubjects)
    }
    if (formType.value === 'create') {
      await InvoiceApi.createInvoice(data)
      message.success(t('common.createSuccess'))
    } else {
      await InvoiceApi.updateInvoice(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    invoiceDate: undefined,
    invoiceCategory: undefined,
    invoiceType: undefined,
    accountSubjects: undefined,
    subjectId: undefined,
    invoiceNo: undefined,
    counterpartyName: undefined,
    amountWithoutTax: undefined,
    taxRate: undefined,
    taxAmount: undefined,
    totalAmount: undefined,
    attachment: '',
    invoiceStatus: undefined,
    certificationDate: undefined,
    voucherNo: undefined,
    accountingPeriod: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
}
</script>
