<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="transactionNo"><el-input v-model="formData.transactionNo" placeholder="请输入交易流水号" /></el-form-item>
          <el-form-item label="结算账户" prop="accountId"><el-select v-model="formData.accountId" placeholder="请选择结算账户" style="width:100%" @change="handleAccountChange"><el-option v-for="item in accountList" :key="item.id" :label="item.name" :value="item.id" /></el-select></el-form-item>
          <el-form-item label="账户号" prop="accountNo"><el-input v-model="formData.accountNo" placeholder="请输入账户号" /></el-form-item>
          <el-form-item label="交易机构" prop="transactionInstitution"><el-input v-model="formData.transactionInstitution" placeholder="请输入交易机构" /></el-form-item>
          <el-form-item label="交易金额" prop="transactionAmount"><el-input-number v-model="formData.transactionAmount" :precision="2" :min="0" placeholder="请输入交易金额" style="width:100%" /></el-form-item>
          <el-form-item label="交易类型" prop="transactionType"><el-radio-group v-model="formData.transactionType"><el-radio :value="1">收入</el-radio><el-radio :value="2">支出</el-radio></el-radio-group></el-form-item>
          <el-form-item label="交易对手账户" prop="counterpartyAccount"><el-input v-model="formData.counterpartyAccount" 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="counterpartyBank"><el-input v-model="formData.counterpartyBank" placeholder="请输入交易对手银行" /></el-form-item>
          <el-form-item label="操作柜员" prop="operatorTeller"><el-input v-model="formData.operatorTeller" placeholder="请输入操作柜员" /></el-form-item>
          <el-form-item label="交易时间" prop="transactionTime"><el-date-picker v-model="formData.transactionTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择交易时间" style="width:100%" /></el-form-item>
          <el-form-item label="摘要" prop="summary"><el-input v-model="formData.summary" placeholder="请输入摘要" /></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" width="700px">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" v-loading="formLoading">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="交易流水号" prop="transactionNo">
            <el-input v-model="formData.transactionNo" placeholder="请输入交易流水号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结算账户" prop="accountId">
            <el-select v-model="formData.accountId" placeholder="请选择结算账户" class="!w-full" @change="handleAccountChange">
              <el-option
                v-for="item in accountList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="账户号" prop="accountNo">
            <el-input v-model="formData.accountNo" placeholder="请输入账户号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="交易机构" prop="transactionInstitution">
            <el-input v-model="formData.transactionInstitution" placeholder="请输入交易机构" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="交易金额" prop="transactionAmount">
            <el-input-number
              v-model="formData.transactionAmount"
              :precision="2"
              :min="0"
              placeholder="请输入交易金额"
              class="!w-full"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="交易类型" prop="transactionType">
            <el-radio-group v-model="formData.transactionType">
              <el-radio :value="1">收入</el-radio>
              <el-radio :value="2">支出</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="交易对手账户" prop="counterpartyAccount">
            <el-input v-model="formData.counterpartyAccount" 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-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="交易对手银行" prop="counterpartyBank">
            <el-input v-model="formData.counterpartyBank" placeholder="请输入交易对手银行" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="操作柜员" prop="operatorTeller">
            <el-input v-model="formData.operatorTeller" placeholder="请输入操作柜员" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="交易时间" prop="transactionTime">
            <el-date-picker
              v-model="formData.transactionTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择交易时间"
              class="!w-full"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="摘要" prop="summary">
            <el-input v-model="formData.summary" placeholder="请输入摘要" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注信息" prop="remark">
        <el-input v-model="formData.remark" type="textarea" :rows="3" 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>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { BankTransactionApi, BankTransactionVO } from '@/api/erp/finance/bank'
import { AccountApi } from '@/api/erp/finance/account'
import { useWindowSize } from '@vueuse/core'

/** ERP 银行流水 表单 */
defineOptions({ name: 'BankTransactionForm' })

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,
  transactionNo: undefined,
  accountId: undefined,
  accountNo: undefined,
  transactionInstitution: undefined,
  transactionAmount: undefined,
  transactionType: 1,
  counterpartyAccount: undefined,
  counterpartyName: undefined,
  counterpartyBank: undefined,
  operatorTeller: undefined,
  summary: undefined,
  remark: undefined,
  transactionTime: undefined
})
const formRules = reactive({
  transactionNo: [{ required: true, message: '交易流水号不能为空', trigger: 'blur' }],
  accountId: [{ required: true, message: '结算账户不能为空', trigger: 'change' }],
  transactionAmount: [{ required: true, message: '交易金额不能为空', trigger: 'blur' }],
  transactionType: [{ required: true, message: '交易类型不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
const accountList = ref<any[]>([]) // 结算账户列表

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 获取结算账户列表
  accountList.value = await AccountApi.getAccountSimpleList()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BankTransactionApi.getBankTransaction(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 账户变更处理 */
const handleAccountChange = (accountId: number) => {
  // 根据账户ID获取账户号
  const account = accountList.value.find(item => item.id === accountId)
  if (account) {
    formData.value.accountNo = account.no
  }
}

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

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    transactionNo: undefined,
    accountId: undefined,
    accountNo: undefined,
    transactionInstitution: undefined,
    transactionAmount: undefined,
    transactionType: 1,
    counterpartyAccount: undefined,
    counterpartyName: undefined,
    counterpartyBank: undefined,
    operatorTeller: undefined,
    summary: undefined,
    remark: undefined,
    transactionTime: undefined
  }
  formRef.value?.resetFields()
}
</script>
