<template>
  <div class="app-container">
    <div class="search-con">
      <div class="title">查询条件</div>
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="信用卡名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入信用卡名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="银行" prop="bankId">
          <el-select v-model="queryParams.bankId" placeholder="请选择银行" clearable filterable>
            <el-option v-for="item in bankList" :key="item.id" :label="item.bankName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="卡片等级" prop="cardTier">
          <el-select v-model="queryParams.cardTier" placeholder="请选择卡片等级" clearable>
            <el-option v-for="dict in card_tier" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="账户状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择账户状态" clearable>
            <el-option v-for="dict in account_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="search-btn-con">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button type="info" icon="Refresh" @click="resetQuery">重置</el-button>
      </div>
    </div>
    <div class="main-con">
      <div class="title-con">
        <div class="title">基本信息</div>
        <div class="operate-btn-con">
          <el-button @click="handleAdd" icon="Plus" v-hasPermi="['invest:bankcard:add']">新增</el-button>
          <el-button :disabled="multiple" icon="Delete" @click="handleDelete" v-hasPermi="['invest:bankcard:remove']">删除</el-button>
          <!-- <el-button @click="handleExport" icon="Download" v-hasPermi="['invest:bankcard:export']">导出</el-button> -->
        </div>
      </div>
      <div class="content-con" v-loading="loading">
        <el-table v-loading="loading" :data="bankcardList" @selection-change="handleSelectionChange" height="calc(100% - 0.62rem)">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" label="序号" :index="indexMethod" width="50"></el-table-column>
          <el-table-column label="信用卡名称" align="center" width="150" prop="name" />
          <el-table-column label="信用卡卡号" align="center" prop="code" />
          <el-table-column label="开户日期" align="center" prop="activationDate" width="100"> </el-table-column>
          <el-table-column label="账单日" align="center" width="80" prop="billDateName" />
          <el-table-column label="还款日" align="center" width="80" prop="payDateName" />
          <el-table-column label="延缓期限" align="center" width="90" prop="delayPeriod" />
          <el-table-column label="卡片等级" align="center" width="100" prop="cardTier">
            <template #default="scope">
              <dict-tag :options="card_tier" :value="scope.row.cardTier" />
            </template>
          </el-table-column>
          <el-table-column label="信用卡额度" align="center" prop="creditLimit" />
          <el-table-column label="可用额度" align="center" prop="availableLimit" width="100" />
          <el-table-column label="有效期" align="center" prop="effectiveDate" width="100">
            <template #default="scope">
              <span>{{ parseTime(scope.row.effectiveDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="账单日消费" align="center" prop="isNextBillDate">
            <template #default="scope">
              <dict-tag :options="is_next_bill_date" :value="scope.row.isNextBillDate" />
            </template>
          </el-table-column>
          <!-- <el-table-column label="0账单操作" align="center" prop="isZeroBill">
            <template #default="scope">
              <dict-tag :options="is_zero_bill" :value="scope.row.isZeroBill" />
            </template>
          </el-table-column> -->
          <el-table-column label="账户状态" width="100" align="center" prop="status">
            <template #default="scope">
              <dict-tag :options="account_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="210" align="center" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <div class="ctrl-btn d-flex">
                <el-tooltip v-for="item in operateList" :key="item.id" class="item" effect="dark" :content="item.title" placement="top">
                  <el-button :icon="item.icon" v-hasPermi="item.hasPermi" circle @click="handleOperate(item.id, scope.row)"></el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          small
          background
          layout="total,sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加或修改信用卡信息对话框 -->
    <el-dialog :title="title" v-model="open" width="880px" append-to-body>
      <el-form ref="bankcardRef" :model="form" :rules="rules" :inline="true" label-width="120px">
        <el-form-item label="银行" prop="bankId">
          <el-select v-model="form.bankId" placeholder="请选择银行" clearable filterable @change="handleBankChange">
            <el-option v-for="item in bankList" :key="item.id" :label="item.bankName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="信用卡名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入信用卡名称" />
        </el-form-item>
        <el-form-item label="信用卡卡号" prop="code">
          <el-input v-model="form.code" placeholder="请输入信用卡卡号" />
        </el-form-item>
        <el-form-item label="信用卡额度" prop="creditLimit">
          <el-input v-model="form.creditLimit" type="number" placeholder="请输入信用卡额度" />
        </el-form-item>

        <el-form-item label="卡片等级" prop="cardTier">
          <el-select v-model="form.cardTier" placeholder="请选择卡片等级" clearable>
            <el-option v-for="dict in card_tier" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="账户状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择账户状态">
            <el-option v-for="dict in account_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账单日" prop="billDate">
          <el-input-number v-model="form.billDate" placeholder="账单日" />
        </el-form-item>
        <el-form-item label="还款日" prop="payDate">
          <el-input-number v-model="form.payDate" placeholder="还款日" />
        </el-form-item>
        <el-form-item label="余额" prop="balance">
          <el-input v-model="form.balance" type="number" placeholder="请输入余额" />
        </el-form-item>
        <el-form-item label="可用额度" prop="availableLimit">
          <el-input v-model="form.availableLimit" type="number" placeholder="请输入可用额度" />
        </el-form-item>
        <el-form-item label="账单日消费" prop="isNextBillDate">
          <el-select v-model="form.isNextBillDate" placeholder="请选择账单日消费">
            <el-option v-for="dict in is_next_bill_date" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="信用卡安全码" prop="cvv">
          <el-input v-model="form.cvv" placeholder="请输入信用卡安全码" />
        </el-form-item>
        <el-form-item label="开户行" prop="openingBank">
          <el-input v-model="form.openingBank" placeholder="请输入开户行" />
        </el-form-item>
        <el-form-item label="开户日期" prop="activationDate">
          <el-date-picker clearable v-model="form.activationDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择开户日期"> </el-date-picker>
        </el-form-item>
        <el-form-item label="宽限期" prop="delayPeriod">
          <el-input v-model="form.delayPeriod" placeholder="请输入延缓期限" />
        </el-form-item>
        <el-form-item label="有效期" prop="effectiveDate">
          <el-date-picker clearable v-model="form.effectiveDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择有效期"> </el-date-picker>
        </el-form-item>
        <el-form-item label="账单日时间" prop="nextBillDateTime">
          <el-input v-model="form.nextBillDateTime" placeholder="请输入账单日时间" />
        </el-form-item>
        <el-form-item label="0账单操作" prop="isZeroBill">
          <el-select v-model="form.isZeroBill" placeholder="请选择0账单操作">
            <el-option v-for="dict in is_zero_bill" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="卡面" prop="cardFace">
          <el-input v-model="form.cardFace" placeholder="请输入卡面" />
        </el-form-item>
        <el-form-item label="备注" style="width: 792px" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template v-if="title !== '查看信用卡信息'" #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改分期历史调额记录对话框 -->
    <el-dialog :title="titleDetail" v-model="openDetail" width="500px" append-to-body>
      <el-form ref="limitHistoryRef" :model="formDetail" :rules="rulesDetail" label-width="120px">
        <el-form-item label="调额类型" prop="type">
          <el-select v-model="formDetail.type" placeholder="请选择调额类型">
            <el-option v-for="dict in limit_history_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调整类型" prop="adjustType">
          <el-select v-model="formDetail.adjustType" placeholder="请选择调整类型">
            <el-option v-for="dict in adjust_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调整后额度" prop="afterLimit">
          <el-input v-model="formDetail.afterLimit" type="number" @change="handlePriceChange" placeholder="请输入调整后额度">
            <template #suffix>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="调整时间" prop="adjustTime">
          <el-date-picker clearable v-model="formDetail.adjustTime" type="datetime" value-format="YYYY-MM-DD  HH:mm:ss" placeholder="请选择调整时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="生效日期" prop="effectDate">
          <el-date-picker clearable v-model="formDetail.effectDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择生效日期"> </el-date-picker>
        </el-form-item>
        <el-form-item label="失效日期" prop="deadlineDate">
          <el-date-picker clearable v-model="formDetail.deadlineDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择失效日期"> </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formDetail.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormDetail">确 定</el-button>
          <el-button @click="cancelDetail">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改分期历史调额记录对话框 -->
    <el-dialog title="查看添加调额记录" v-model="detailOpen" width="1150px" append-to-body>
      <div class="basic-information">
        <div class="main-con">
          <div class="title-con">
            <div class="title">基本信息</div>
            <div class="operate-btn-con">
              <el-button @click="handleAddDetail" icon="Plus" v-hasPermi="['invest:bankcard:add']">新增</el-button>
            </div>
          </div>
          <div class="content-con">
            <el-table v-loading="loading" :data="limitHistoryList">
              <el-table-column label="调整时间" align="center" prop="adjustTime" width="180"> </el-table-column>
              <el-table-column label="生效日期" align="center" prop="effectDate" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.effectDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="失效日期" align="center" prop="deadlineDate" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.deadlineDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="调额类型" align="center" prop="type">
                <template #default="scope">
                  <dict-tag :options="limit_history_type" :value="scope.row.type" />
                </template>
              </el-table-column>
              <el-table-column label="调整类型" align="center" prop="adjustType">
                <template #default="scope">
                  <dict-tag :options="adjust_type" :value="scope.row.adjustType" />
                </template>
              </el-table-column>
              <el-table-column label="调整后额度" align="center" prop="afterLimit" />
              <el-table-column label="调整幅度" align="center" prop="adjustLimit" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template v-slot="scope">
                  <div class="ctrl-btn d-flex">
                    <el-tooltip v-for="item in operateDetailList" :key="item.id" class="item" effect="dark" :content="item.title" placement="top">
                      <el-button :icon="item.icon" v-hasPermi="item.hasPermi" circle @click="handleDetailOperate(item.id, scope.row)"></el-button>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <template #footer> </template>
    </el-dialog>

    <el-dialog :title="titleDealRecord" v-model="openDealRecord" width="1200px" append-to-body destroy-on-close>
      <el-form :model="queryDealRecordParams" ref="queryDealRecordRef" inline>
        <el-form-item label="交易时间" prop="time">
          <el-date-picker v-model="queryDealRecordParams.time" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>
        <el-form-item label="交易类型" style="width: 220px" prop="dealType">
          <el-select v-model="queryDealRecordParams.dealType" placeholder="请选择交易类型" clearable>
            <el-option v-for="dict in deal_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="交易类别" style="width: 220px" prop="dealCategory">
          <el-select v-model="queryDealRecordParams.dealCategory" placeholder="请选择交易类别" clearable>
            <el-option v-for="dict in deal_category" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" icon="Search" @click="handleDealRecordQuery">搜索</el-button>
          <el-button type="info" icon="Refresh" @click="resetDealRecordQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loadingDealRecord" :data="tableDealRecordData">
        <el-table-column label="交易时间" align="center" prop="createTime" width="180" />
        <el-table-column label="交易金额" align="center" prop="amount" />
        <el-table-column label="当前余额" align="center" prop="currentBalance" />
        <el-table-column label="交易类型" width="120" align="center" prop="dealType">
          <template #default="scope">
            <dict-tag :options="deal_type" :value="scope.row.dealType" />
          </template>
        </el-table-column>
        <el-table-column label="交易类别" width="150" align="center" prop="dealCategory">
          <template #default="scope">
            <dict-tag :options="deal_category" :value="scope.row.dealCategory" />
          </template>
        </el-table-column>
        <el-table-column label="交易子类别" width="150" align="center" prop="childCategoryName" />
        <el-table-column label="备注" align="center" width="300" prop="remark" />
      </el-table>
      <el-pagination small background layout="total, prev, pager, next" :total="dealRecordTotal" @current-change="handleCurrentDealRecordChange" />
    </el-dialog>
  </div>
</template>

<script setup name="BankcardLend">
import { listBankcardLend, getBankcardLend, delBankcardLend, addBankcardLend, updateBankcardLend } from '@/api/invest/bankcardlend'
import { listLimitHistory, getLimitHistory, delLimitHistory, addLimitHistory, updateLimitHistory } from '@/api/invest/limitHistory'
import { listBankBaseInfo } from '@/api/invest/bankBaseInfo'
import { listAccountDealRecord } from '@/api/invest/accountDealRecord'
import dayjs from 'dayjs'
// eslint-disable-next-line no-unused-vars
import { require } from '@/utils/require'
const { proxy } = getCurrentInstance()
const { is_zero_bill, is_next_bill_date, account_status, card_tier } = proxy.useDict('is_zero_bill', 'is_next_bill_date', 'account_status', 'card_tier')
const { limit_history_type, adjust_type } = proxy.useDict('limit_history_type', 'adjust_type')
const { deal_type, deal_category } = proxy.useDict('deal_type', 'deal_category')
const bankcardList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const titleDealRecord = ref('')
const openDealRecord = ref(false)
const currentAccountId = ref('')
const loadingDealRecord = ref(false)
const tableDealRecordData = ref([])
const dealRecordTotal = ref(0)
const queryDealRecordParams = ref({
  time: '',
  dealType: null,
  dealCategory: null,
  pageNum: 1,
  pageSize: 10
})

const detailOpen = ref(false)
const openDetail = ref(false)
const titleDetail = ref('')
const limitHistoryList = ref([])
const currentcardId = ref('')
const currentBeforeLimit = ref('0')
const bankList = ref([])

const operateList = ref([
  { id: 'view', icon: 'View', title: '查看', hasPermi: ['invest:bankcard:query'] },
  { id: 'dealRecord', icon: 'Tickets', title: '交易明细', hasPermi: ['invest:bankcard:query'] },
  { id: 'limit', icon: 'Grid', title: '调额记录', hasPermi: ['invest:bankcard:edit'] },
  { id: 'edit', icon: 'Edit', title: '修改', hasPermi: ['invest:bankcard:edit'] },
  { id: 'delete', icon: 'Delete', title: '删除', hasPermi: ['invest:bankcard:remove'] }
])
const operateDetailList = ref([
  //{ id: 'edit', icon: 'Edit', title: '修改', hasPermi: ['invest:bankcard:edit'] },
  { id: 'delete', icon: 'Delete', title: '删除', hasPermi: ['invest:bankcard:remove'] }
])
const data = reactive({
  form: {},
  formDetail: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: null,
    name: null,
    bankId: null,
    cardTier: null,
    type: '2'
  },
  rules: {
    name: [{ required: true, message: '信用卡名称不能为空', trigger: 'blur' }],
    code: [{ required: true, message: '信用卡卡号不能为空', trigger: 'blur' }],
    billDate: [{ required: true, message: '账单日不能为空', trigger: 'blur' }],
    payDate: [{ required: true, message: '还款日不能为空', trigger: 'blur' }],
    bankId: [{ required: true, message: '银行不能为空', trigger: 'blur' }],
    isNextBillDate: [{ required: true, message: '账单日消费不能为空', trigger: 'blur' }],
    creditLimit: [{ required: true, message: '信用卡额度不能为空', trigger: 'blur' }],
    balance: [{ required: true, message: '余额不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '账户状态不能为空', trigger: 'blur' }],
    availableLimit: [{ required: true, message: '可用额度不能为空', trigger: 'blur' }]
  },
  rulesDetail: {
    afterLimit: [{ required: true, message: '调整后额度不能为空', trigger: 'blur' }],
    adjustTime: [{ required: true, message: '调整时间不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '调额类型不能为空', trigger: 'change' }],
    adjustType: [{ required: true, message: '调整类型不能为空', trigger: 'change' }]
  }
})

const handleOperate = (operate, row) => {
  switch (operate) {
    case 'dealRecord':
      handleDealRecord(row)
      break
    case 'limit':
      handleDetail(row)
      break
    case 'view':
      handleView(row)
      break
    case 'edit':
      handleUpdate(row)
      break
    case 'delete':
      handleDelete(row)
      break
    default:
      break
  }
}

const { queryParams, form, formDetail, rules, rulesDetail } = toRefs(data)

/** 新增按钮操作 */
function handleAddDetail() {
  resetDetail()
  titleDetail.value = '添加调额记录'
  openDetail.value = true
}

const handleDetailOperate = (operate, row) => {
  switch (operate) {
    case 'edit':
      handleUpdateDetail(row)
      break
    case 'delete':
      handleDeleteDetail(row)
      break
    default:
      break
  }
}

// 取消按钮
function cancelDetail() {
  openDetail.value = false
  resetDetail()
}

/** 删除按钮操作 */
function handleDeleteDetail(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delLimitHistory(_ids)
    })
    .then(() => {
      listLimitHistory({ bankCardLendId: currentcardId.value, pageNum: 1, pageSize: 1000 }).then((response) => {
        limitHistoryList.value = response.rows
      })
      proxy.$modal.msgSuccess('删除调额记录成功')
    })
    .catch(() => {})
}

/** 提交按钮 */
function submitFormDetail() {
  formDetail.value.bankCardLendId = currentcardId.value
  formDetail.value.beforeLimit = currentBeforeLimit
  proxy.$refs.limitHistoryRef.validate((valid) => {
    if (valid) {
      if (formDetail.value.id != null) {
        updateLimitHistory(formDetail.value).then((response) => {
          proxy.$modal.msgSuccess('修改调额记录成功')
          openDetail.value = false
          listLimitHistory({ bankCardLendId: currentcardId.value, pageNum: 1, pageSize: 1000 }).then((response) => {
            limitHistoryList.value = response.rows
          })
        })
      } else {
        addLimitHistory(formDetail.value).then((response) => {
          proxy.$modal.msgSuccess('新增调额记录成功')
          openDetail.value = false
          listLimitHistory({ bankCardLendId: currentcardId.value, pageNum: 1, pageSize: 1000 }).then((response) => {
            limitHistoryList.value = response.rows
          })
        })
      }
    }
  })
}

/** 修改按钮操作 */
function handleUpdateDetail(row) {
  resetDetail()
  getLimitHistory(row.id).then((response) => {
    formDetail.value = response.data
    openDetail.value = true
    titleDetail.value = '修改调额记录'
  })
}

// 表单重置
function resetDetail() {
  formDetail.value = {
    id: null,
    name: null,
    type: null,
    bankCardLendId: null,
    afterLimit: null,
    bankId: null,
    cardTier: '0',
    cardFace: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    adjustTime: null,
    effectDate: null,
    deadlineDate: null,
    adjustType: null,
    beforeLimit: null,
    adjustLimit: null
  }
  proxy.resetForm('limitHistoryRef')
}
/** 新增按钮操作 */
function handleDetail(row) {
  detailOpen.value = true
  currentcardId.value = row.id
  currentBeforeLimit.value = row.creditLimit
  listLimitHistory({ bankCardLendId: row.id, pageNum: 1, pageSize: 1000 }).then((response) => {
    limitHistoryList.value = response.rows
  })
}

/** 交易明细按钮操作 */
function handleDealRecord(row) {
  queryDealRecordParams.value.time = ''
  queryDealRecordParams.value.dealType = ''
  queryDealRecordParams.value.dealCategory = ''
  titleDealRecord.value = `${row.name}${row.code ? '【' + row.code + '】' : ''}交易明细`
  currentAccountId.value = row.id || ids.value
  getDealRecordList(1)
  openDealRecord.value = true
}

const handleCurrentDealRecordChange = (num) => {
  getDealRecordList(num)
}

const handleDealRecordQuery = () => {
  getDealRecordList(1)
}

const resetDealRecordQuery = () => {
  proxy.resetForm('queryDealRecordRef')
  queryDealRecordParams.value.time = ''
  queryDealRecordParams.value.dealType = ''
  queryDealRecordParams.value.dealCategory = ''
  dealRecordTotal.value = 0
  getDealRecordList(1)
}

const getDealRecordList = (num) => {
  loadingDealRecord.value = true
  const timeRange = queryDealRecordParams.value.time
  let st = ''
  let et = ''
  if (timeRange && timeRange.length === 2) {
    st = dayjs(timeRange[0]).format('YYYY-MM-DD')
    et = dayjs(timeRange[1]).format('YYYY-MM-DD')
  }
  queryDealRecordParams.value.startTime = st
  queryDealRecordParams.value.endTime = et
  queryDealRecordParams.value.pageNum = num
  queryDealRecordParams.value.accountId = currentAccountId.value
  listAccountDealRecord(queryDealRecordParams.value).then((response) => {
    loadingDealRecord.value = false
    tableDealRecordData.value = response.rows
    dealRecordTotal.value = response.total
  })
}

/** 查询信用卡信息列表 */
function getList() {
  loading.value = true
  listBankcardLend(queryParams.value).then((response) => {
    bankcardList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    type: '2',
    code: null,
    openingBank: null,
    activationDate: null,
    billDate: null,
    payDate: null,
    delayPeriod: null,
    balance: null,
    creditLimit: null,
    availableLimit: null,
    effectiveDate: null,
    cvv: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    debitType: null,
    isNextBillDate: null,
    nextBillDateTime: null,
    isZeroBill: null,
    status: null,
    cardFace: null,
    cardTier: null,
    bankId: null
  }
  proxy.resetForm('bankcardRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

// 分页
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

//每页显示条数改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}
// 序号翻页递增
const indexMethod = (index) => {
  const nowPage = queryParams.value.pageNum //当前第几页，根据组件取值即可
  const nowLimit = queryParams.value.pageSize //当前每页显示几条，根据组件取值即可
  return index + 1 + (nowPage - 1) * nowLimit // 这里可以理解成一个公式
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 查看
const handleView = (row) => {
  title.value = '查看信用卡信息'
  form.value = row
  open.value = true
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加信用卡信息'
}

/** 银行选择变更 */
function handleBankChange(bankId) {
  // 只在新增时自动填充名称
  if (title.value === '添加信用卡信息' && bankId) {
    const selectedBank = bankList.value.find((bank) => bank.id === bankId)
    if (selectedBank) {
      form.value.name = selectedBank.bankName
    }
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getBankcardLend(_id).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改信用卡信息'
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs.bankcardRef.validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateBankcardLend(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addBankcardLend(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delBankcardLend(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'invest/bankcard/export',
    {
      ...queryParams.value
    },
    `bankcard_${new Date().getTime()}.xlsx`
  )
}

/** 获取银行列表 */
function getBankList() {
  listBankBaseInfo({ pageNum: 1, pageSize: 1000 }).then((response) => {
    bankList.value = response.rows
  })
}

getList()
getBankList()
</script>
