<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="lendType">
          <el-select v-model="queryParams.lendType" placeholder="请选择类型" clearable>
            <el-option v-for="dict in lend_type" :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" prop="name" />
          <el-table-column label="编号" align="center" prop="code" />
          <el-table-column label="银行" align="center" prop="bankName" />
          <el-table-column label="开通日期" align="center" prop="activationDate" 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="lendType">
            <template #default="scope">
              <dict-tag :options="lend_type" :value="scope.row.lendType" />
            </template>
          </el-table-column>
          <el-table-column label="余额" align="center" prop="balance" />
          <el-table-column label="账户状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :options="account_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" />
          <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 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="activationDate">
          <el-date-picker clearable v-model="form.activationDate" type="date" value-format="YYYY-MM-DD" 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-form-item>
        <el-form-item label="账号" prop="code">
          <el-input v-model="form.code" placeholder="请输入账号" />
        </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="lendType">
          <el-select v-model="form.lendType" placeholder="请选择类型">
            <el-option v-for="dict in lend_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </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="备注" 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>
  </div>
</template>

<script setup name="BankcardLend">
import { listBankcardLend, getBankcardLend, delBankcardLend, addBankcardLend, updateBankcardLend } from '@/api/invest/bankcardlend'
import { listBankBaseInfo } from '@/api/invest/bankBaseInfo'
// eslint-disable-next-line no-unused-vars
import { require } from '@/utils/require'
const { proxy } = getCurrentInstance()
const { bank_card_type, lend_type, account_status } = proxy.useDict('bank_card_type', 'lend_type', 'account_status')

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 bankList = ref([])
const operateList = ref([
  { id: 'view', icon: 'View', title: '查看', hasPermi: ['invest:bankcard:query'] },
  { id: 'edit', icon: 'Edit', title: '修改', hasPermi: ['invest:bankcard:edit'] },
  { id: 'delete', icon: 'Delete', title: '删除', hasPermi: ['invest:bankcard:remove'] }
])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    status: null,
    bankId: null,
    lendType: null,
    type: '3'
  },
  rules: {
    name: [{ required: true, message: '借贷名称不能为空', trigger: 'blur' }],
    code: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
    activationDate: [{ required: true, message: '开通日期不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '账户状态不能为空', trigger: 'blur' }],
    lendType: [{ required: true, message: '类型不能为空', trigger: 'blur' }],
    balance: [{ required: true, message: '余额不能为空', trigger: 'blur' }]
  }
})

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

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

/** 查询借贷账户信息列表 */
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: '3',
    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,
    lendType: null,
    status: 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) {
      // 处理空字符串，将空字符串转为null
      const formData = { ...form.value }
      if (formData.effectiveDate === '') {
        formData.effectiveDate = null
      }
      if (formData.activationDate === '') {
        formData.activationDate = null
      }

      if (formData.id != null) {
        updateBankcardLend(formData).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addBankcardLend(formData).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>
