<template>
  <a-modal
    :visible="visible"
    title="付款申请"
    width="800px"
    :footer="false"
    @cancel="handleCancel"
    @update:visible="handleVisibleChange"
  >
    <div class="payment-application-container">
      <!-- 设备基本信息 -->
      <a-card title="设备信息" class="info-card" :bordered="false">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="设备名称">
            {{ equipmentData?.equipmentName }}
          </a-descriptions-item>
          <a-descriptions-item label="设备型号">
            {{ equipmentData?.equipmentModel }}
          </a-descriptions-item>
          <a-descriptions-item label="供应商">
            {{ equipmentData?.supplierName }}
          </a-descriptions-item>
          <a-descriptions-item label="采购价格">
            ¥{{ formatPrice(equipmentData?.purchasePrice || 0) }}
          </a-descriptions-item>
        </a-descriptions>
      </a-card>

      <!-- 付款申请信息 -->
      <a-card title="付款申请信息" class="info-card" :bordered="false">
        <a-form
          ref="paymentFormRef"
          :model="paymentForm"
          :rules="paymentRules"
          layout="vertical"
        >
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="申请日期" name="applicationDate">
                <a-date-picker
                  v-model="paymentForm.applicationDate"
                  placeholder="请选择申请日期"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="部门" name="department">
                <a-input
                  v-model="paymentForm.department"
                  placeholder="请输入部门名称"
                  allow-clear
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="归属项目" name="projectName">
                <a-input
                  v-model="paymentForm.projectName"
                  placeholder="请输入项目名称"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="支出类别" name="expenseCategory">
                <a-select
                  v-model="paymentForm.expenseCategory"
                  placeholder="请选择支出类别"
                  allow-clear
                >
                  <a-option value="EXPENSE_TRANSPORT">a.费用支出-交通费</a-option>
                  <a-option value="EXPENSE_ACCOMMODATION">a.费用支出-住宿费</a-option>
                  <a-option value="EXPENSE_TOOLS">a.费用支出-小工具</a-option>
                  <a-option value="EXPENSE_VEHICLE_MAINTENANCE">a.费用支出-车辆保养</a-option>
                  <a-option value="PROCUREMENT_DRONE">b.采购支出-设备采购-无人机</a-option>
                  <a-option value="PROCUREMENT_VEHICLE">b.采购支出-设备采购-车</a-option>
                  <a-option value="PROCUREMENT_COMPUTER">b.采购支出-设备采购-计算机</a-option>
                  <a-option value="SALARY">c.工资支出</a-option>
                  <a-option value="TAX">d.税款支出</a-option>
                  <a-option value="OTHER">f.其他支出</a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="事由" name="reason">
                <a-textarea
                  v-model="paymentForm.reason"
                  placeholder="请输入付款事由"
                  :rows="3"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="经手人" name="handler">
                <a-input
                  v-model="paymentForm.handler"
                  placeholder="请输入经手人姓名"
                  allow-clear
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="金额" name="amount">
                <a-input-number
                  v-model="paymentForm.amount"
                  placeholder="请输入付款金额"
                  :precision="2"
                  :min="0"
                  style="width: 100%"
                  addon-before="¥"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="收款单位" name="payeeUnit">
                <a-input
                  v-model="paymentForm.payeeUnit"
                  placeholder="请输入收款单位名称"
                  allow-clear
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item label="收款账号" name="payeeAccount">
            <a-input
              v-model="paymentForm.payeeAccount"
              placeholder="请输入收款账号"
              allow-clear
            />
          </a-form-item>

          <!-- 发票附件及其他附件 -->
          <a-form-item label="发票附件" name="invoiceAttachments">
            <a-upload
              v-model:file-list="paymentForm.invoiceAttachments"
              :action="uploadAction"
              :headers="uploadHeaders"
              :before-upload="beforeUpload"
              :on-success="onInvoiceUploadSuccess"
              :on-error="onUploadError"
              accept=".pdf,.jpg,.jpeg,.png"
              :max-count="5"
            >
              <a-button>
                <template #icon>
                  <IconUpload />
                </template>
                上传发票附件
              </a-button>
              <template #itemRender="{ file }">
                <a-space>
                  <IconFile />
                  <span>{{ file.name }}</span>
                  <a-button
                    type="text"
                    size="small"
                    status="danger"
                    @click="removeInvoiceAttachment(file)"
                  >
                    删除
                  </a-button>
                </a-space>
              </template>
            </a-upload>
          </a-form-item>

          <!-- 银行付款凭证 -->
          <a-form-item label="银行付款凭证" name="bankPaymentVouchers">
            <a-upload
              v-model:file-list="paymentForm.bankPaymentVouchers"
              :action="uploadAction"
              :headers="uploadHeaders"
              :before-upload="beforeUpload"
              :on-success="onBankVoucherUploadSuccess"
              :on-error="onUploadError"
              accept=".pdf,.jpg,.jpeg,.png"
              :max-count="3"
            >
              <a-button>
                <template #icon>
                  <IconUpload />
                </template>
                上传银行付款凭证
              </a-button>
              <template #itemRender="{ file }">
                <a-space>
                  <IconFile />
                  <span>{{ file.name }}</span>
                  <a-button
                    type="text"
                    size="small"
                    status="danger"
                    @click="removeBankVoucher(file)"
                  >
                    删除
                  </a-button>
                </a-space>
              </template>
            </a-upload>
          </a-form-item>

          <a-form-item label="备注" name="remarks">
            <a-textarea
              v-model="paymentForm.remarks"
              placeholder="请输入备注信息"
              :rows="3"
              allow-clear
            />
          </a-form-item>
        </a-form>
      </a-card>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <a-space>
          <a-button @click="handleCancel">取消</a-button>
          <a-button type="primary" @click="handleSubmit" :loading="submitting">
            提交付款申请
          </a-button>
        </a-space>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { IconUpload, IconFile } from '@arco-design/web-vue/es/icon'
import message from '@arco-design/web-vue/es/message'
import type { EquipmentResp } from '@/apis/equipment/type'

interface Props {
  visible: boolean
  equipmentData: EquipmentResp | null
}

interface PaymentForm {
  applicationDate: string | null
  department: string
  projectName: string
  expenseCategory: string
  reason: string
  handler: string
  amount: number | null
  payeeUnit: string
  payeeAccount: string
  invoiceAttachments: any[]
  bankPaymentVouchers: any[]
  remarks: string
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'success': []
}>()

// 表单引用
const paymentFormRef = ref()

// 提交状态
const submitting = ref(false)

// 付款申请表单
const paymentForm = reactive<PaymentForm>({
  applicationDate: null,
  department: '',
  projectName: '',
  expenseCategory: '',
  reason: '',
  handler: '',
  amount: null,
  payeeUnit: '',
  payeeAccount: '',
  invoiceAttachments: [],
  bankPaymentVouchers: [],
  remarks: ''
})

// 表单验证规则
const paymentRules = {
  applicationDate: [
    { required: true, message: '请选择申请日期', trigger: 'change' }
  ],
  department: [
    { required: true, message: '请输入部门名称', trigger: 'blur' }
  ],
  projectName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
  expenseCategory: [
    { required: true, message: '请选择支出类别', trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请输入付款事由', trigger: 'blur' }
  ],
  handler: [
    { required: true, message: '请输入经手人姓名', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: '请输入付款金额', trigger: 'blur' }
  ],
  payeeUnit: [
    { required: true, message: '请输入收款单位名称', trigger: 'blur' }
  ],
  payeeAccount: [
    { required: true, message: '请输入收款账号', trigger: 'blur' }
  ]
}

// 上传配置
const uploadAction = '/api/file/upload'
const uploadHeaders = {
  // 根据实际需求设置上传头
}

// 格式化价格
const formatPrice = (price: number) => {
  return price.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })
}

// 上传前检查
const beforeUpload = (file: File) => {
  const isValidSize = file.size / 1024 / 1024 < 10 // 10MB限制
  if (!isValidSize) {
    message.error('文件大小不能超过10MB')
    return false
  }
  return true
}

// 发票附件上传成功
const onInvoiceUploadSuccess = (response: any, file: any) => {
  console.log('发票附件上传成功:', response, file)
  message.success('发票附件上传成功')
}

// 银行付款凭证上传成功
const onBankVoucherUploadSuccess = (response: any, file: any) => {
  console.log('银行付款凭证上传成功:', response, file)
  message.success('银行付款凭证上传成功')
}

// 上传失败
const onUploadError = (error: any) => {
  console.error('文件上传失败:', error)
  message.error('文件上传失败')
}

// 删除发票附件
const removeInvoiceAttachment = (file: any) => {
  const index = paymentForm.invoiceAttachments.findIndex(f => f.uid === file.uid)
  if (index > -1) {
    paymentForm.invoiceAttachments.splice(index, 1)
  }
}

// 删除银行付款凭证
const removeBankVoucher = (file: any) => {
  const index = paymentForm.bankPaymentVouchers.findIndex(f => f.uid === file.uid)
  if (index > -1) {
    paymentForm.bankPaymentVouchers.splice(index, 1)
  }
}

// 取消
const handleCancel = () => {
  emit('update:visible', false)
}

// 处理 visible 变化
const handleVisibleChange = (newVisible: boolean) => {
  emit('update:visible', newVisible)
}

// 提交付款申请
const handleSubmit = async () => {
  try {
    submitting.value = true
    
    // 验证表单
    await paymentFormRef.value?.validate()
    
    // 这里调用API提交付款申请
    console.log('提交付款申请:', {
      ...paymentForm,
      equipmentId: props.equipmentData?.equipmentId
    })
    
    message.success('付款申请提交成功')
    emit('success')
    emit('update:visible', false)
    
  } catch (error) {
    console.error('提交失败:', error)
    message.error('提交失败，请检查表单信息')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped lang="scss">
.payment-application-container {
  .info-card {
    margin-bottom: 16px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .action-buttons {
    text-align: center;
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid var(--color-border);
  }
}
</style>
