<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="purchaseInNo"><el-input v-model="formData.purchaseInNo" readonly placeholder="请选择采购入库订单"><template #append><el-button @click="openPurchaseInSelect"><Icon icon="ep:search" /></el-button></template></el-input></el-form-item>
          <el-form-item label="应付单号" prop="apoCode"><el-input v-model="formData.apoCode" placeholder="请输入应付单号" /></el-form-item>
          <el-form-item label="供应商" prop="supplier"><el-input v-model="formData.supplier" placeholder="请输入供应商" /></el-form-item>
          <el-form-item label="单据日期" prop="billDate"><el-date-picker v-model="formData.billDate" type="date" value-format="x" placeholder="选择单据日期" style="width:100%" /></el-form-item>
          <el-form-item label="已付金额" prop="paymentPrice"><el-input v-model="formData.paymentPrice" placeholder="请输入已付金额" /></el-form-item>
          <el-form-item label="总金额" prop="totalAmount"><el-input v-model="formData.totalAmount" placeholder="请输入总金额" /></el-form-item>
          <el-form-item label="备注" prop="remark"><el-input v-model="formData.remark" 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="100px" v-loading="formLoading">
      <el-form-item label="采购入库订单" prop="purchaseInNo">
        <el-input v-model="formData.purchaseInNo" readonly placeholder="请选择采购入库订单">
          <template #append>
            <el-button @click="openPurchaseInSelect"> <Icon icon="ep:search" /> 选择 </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="应付单号" prop="apoCode">
        <el-input v-model="formData.apoCode" placeholder="请输入应付单号" />
      </el-form-item>
      <el-form-item label="供应商" prop="supplier">
        <el-input v-model="formData.supplier" placeholder="请输入供应商" />
      </el-form-item>
      <el-form-item label="单据日期" prop="billDate">
        <el-date-picker
          v-model="formData.billDate"
          type="date"
          value-format="x"
          placeholder="选择单据日期"
        />
      </el-form-item>
      <!-- <el-form-item label="到期付款日期" label-width="120px" prop="dueDate">
        <el-date-picker
          v-model="formData.dueDate"
          type="date"
          value-format="x"
          placeholder="选择到期付款日期"
        />
      </el-form-item> -->
      <el-form-item label="已付金额" prop="paymentPrice">
        <el-input v-model="formData.paymentPrice" placeholder="请输入已付金额" />
      </el-form-item>
      <el-form-item label="总金额" prop="totalAmount">
        <el-input v-model="formData.totalAmount" placeholder="请输入总金额" />
      </el-form-item>
      <!-- <el-form-item label="税额" prop="taxAmount">
        <el-input v-model="formData.taxAmount" placeholder="请输入税额" />
      </el-form-item> -->
      <!-- <el-form-item label="不含税金额" prop="nonTaxAmount">
        <el-input v-model="formData.nonTaxAmount" placeholder="请输入不含税金额" />
      </el-form-item>
      <el-form-item label="会计科目" prop="subjectId">
        <el-tree-select
          v-model="formData.subjectId"
          :data="subjectTree"
          placeholder="请选择会计科目"
          :props="{ label: 'name', value: 'id', children: 'children' }"
          check-strictly
          clearable
          filterable
        />
      </el-form-item>
      <el-form-item label="单据类型" prop="billType">
        <el-select v-model="formData.billType" placeholder="请选择单据类型">
          <el-option label="增值税专用发票" value="1" />
          <el-option label="增值税普通发票" value="2" />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio value="1">请选择字典生成</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
      <!-- <el-form-item label="审核人" prop="auditUser">
        <el-input v-model="formData.auditUser" placeholder="请输入审核人" />
      </el-form-item>
      <el-form-item label="审核时间" prop="auditTime">
        <el-date-picker
          v-model="formData.auditTime"
          type="date"
          value-format="x"
          placeholder="选择审核时间"
        />
      </el-form-item> -->
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <!-- 采购入库选择弹窗 -->
  <PurchaseInPaymentEnableList ref="purchaseInSelectRef" @success="onPurchaseInSelected" />
</template>
<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { PayableOrderApi, PayableOrder } from '@/api/erp/finance/payableorder'
import PurchaseInPaymentEnableList from '@/views/erp/purchase/in/components/PurchaseInPaymentEnableList.vue'
import { PurchaseInVO } from '@/api/erp/purchase/in'
import { formatToDate } from '@/utils/dateUtil'
import { SubjectApi, SubjectVO } from '@/api/erp/finance/subject'
import { useWindowSize } from '@vueuse/core'

/** 应付单 表单 */
defineOptions({ name: 'PayableOrderForm' })

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 - 修改
type PurchaseInRow = PurchaseInVO & { supplierName?: string; paymentPrice?: number }
const subjectTree = ref<SubjectVO[]>([]) // 科目树
const formData = ref({
  id: undefined,
  apoCode: undefined,
  purchaseInNo: undefined,
  supplier: undefined,
  supplierId: undefined,
  billDate: undefined,
  dueDate: undefined,
  totalAmount: undefined,
  paymentPrice: undefined,
  taxAmount: undefined,
  nonTaxAmount: undefined,
  subjectId: undefined,
  billType: undefined,
  status: undefined,
  remark: undefined,
  auditUser: undefined,
  auditTime: undefined,
  summary: undefined
})
// const formRules = reactive({
//   apoCode: [
//     { required: true, message: '应付单号（唯一，如AP20260115001）不能为空', trigger: 'blur' }
//   ],
//   supplierId: [
//     { required: true, message: '供应商ID（外键关联supplier表）不能为空', trigger: 'blur' }
//   ],
//   billDate: [{ required: true, message: '单据日期不能为空', trigger: 'blur' }],
//   dueDate: [{ required: true, message: '到期付款日期不能为空', trigger: 'blur' }],
//   totalAmount: [{ required: true, message: '应付总金额不能为空', trigger: 'blur' }],
//   taxAmount: [{ required: true, message: '税额不能为空', trigger: 'blur' }],
//   nonTaxAmount: [{ required: true, message: '不含税金额不能为空', trigger: 'blur' }],
//   billType: [
//     {
//       required: true,
//       message: '单据类型：1-采购发票，2-费用账单，3-其他应付不能为空',
//       trigger: 'change'
//     }
//   ],
//   status: [
//     {
//       required: true,
//       message: '状态：0-草稿，1-待审核，2-已审核，3-已核销，4-已取消不能为空',
//       trigger: 'blur'
//     }
//   ]
// })
const formRef = ref() // 表单 Ref
const purchaseInSelectRef = ref()

const normalizeDateToTimestamp = (val: any) => {
  if (val == null || val === '') return val
  if (Array.isArray(val) && val.length === 3 && val.every((it) => Number.isInteger(it))) {
    const [y, m, d] = val as number[]
    return new Date(y, m - 1, d).getTime()
  }
  if (typeof val === 'string') {
    if (/^\d{4},\d{1,2},\d{1,2}$/.test(val)) {
      const [y, m, d] = val.split(',').map((item) => Number(item))
      return new Date(y, m - 1, d).getTime()
    }
    if (/^\d{4}-\d{1,2}-\d{1,2}/.test(val)) {
      return new Date(val.slice(0, 10)).getTime()
    }
    const n = Number(val)
    if (!Number.isNaN(n)) {
      return n < 1e12 ? n * 1000 : n
    }
  }
  if (typeof val === 'number') {
    return val < 1e12 ? val * 1000 : val
  }
  return val
}

const formatDateForApi = (val: any) => {
  if (val == null || val === '') return val
  return formatToDate(val)
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  await getSubjectTree()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await PayableOrderApi.getPayableOrder(id)
      if (data) {
        data.billDate = normalizeDateToTimestamp(data.billDate)
        data.dueDate = normalizeDateToTimestamp(data.dueDate)
        data.auditTime = normalizeDateToTimestamp(data.auditTime)
        if (!data.purchaseInNo && data.apoCode) {
          data.purchaseInNo = data.apoCode
        }
      }
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 获取科目树 */
const getSubjectTree = async () => {
  try {
    subjectTree.value = await SubjectApi.getSubjectTree()
  } catch (error) {
    console.error('获取会计科目失败', error)
    message.error('获取会计科目失败')
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = {
      ...formData.value,
      billDate: formatDateForApi(formData.value.billDate),
      dueDate: formatDateForApi(formData.value.dueDate),
      auditTime: formatDateForApi(formData.value.auditTime)
    } as unknown as PayableOrder
    if (formType.value === 'create') {
      await PayableOrderApi.createPayableOrder(data)
      message.success(t('common.createSuccess'))
    } else {
      await PayableOrderApi.updatePayableOrder(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 打开采购入库选择弹窗 */
const openPurchaseInSelect = () => {
  purchaseInSelectRef.value?.open(formData.value.supplierId as number)
}

/** 采购入库选择回调 */
const onPurchaseInSelected = (orders: PurchaseInRow[]) => {
  if (!orders || orders.length === 0) {
    return
  }
  const order = orders[0]
  formData.value.purchaseInNo = order.no
  formData.value.apoCode = order.no
  formData.value.supplier = order.supplierName || formData.value.supplier
  formData.value.supplierId = order.supplierId
  formData.value.billDate = normalizeDateToTimestamp(order.inTime)
  formData.value.paymentPrice = order.paymentPrice ?? formData.value.paymentPrice
  formData.value.totalAmount = order.totalPrice ?? formData.value.totalAmount
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    apoCode: undefined,
    purchaseInNo: undefined,
    supplier: undefined,
    supplierId: undefined,
    billDate: undefined,
    dueDate: undefined,
    totalAmount: undefined,
    paymentPrice: undefined,
    taxAmount: undefined,
    nonTaxAmount: undefined,
    subjectId: undefined,
    billType: undefined,
    status: undefined,
    remark: undefined,
    auditUser: undefined,
    auditTime: undefined
  }
  formRef.value?.resetFields()
}
</script>
