<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="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-item label="储蓄账户类型" prop="debitType">
          <el-select v-model="queryParams.debitType" placeholder="请选择储蓄账户类型" clearable>
            <el-option v-for="dict in debit_type" :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 label="储蓄账户名称" align="center" width="180" prop="name" />
          <el-table-column label="储蓄账户卡号" align="center" prop="code" />
          <el-table-column label="储蓄账户类型" width="150" align="center" prop="debitType">
            <template #default="scope">
              <dict-tag :options="debit_type" :value="scope.row.debitType" />
            </template>
          </el-table-column>
          <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="openingBank" />
          <el-table-column label="开户日期" align="center" prop="activationDate" width="150">
            <template #default="scope">
              <span>{{ parseTime(scope.row.activationDate, '{y}-{m}-{d}') }}</span>
            </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, prev, pager, next" :total="total" @current-change="handleCurrentChange" />
      </div>
    </div>
    <!-- 添加或修改储蓄账户信息对话框 -->
    <el-dialog :title="title" v-model="open" width="880px" append-to-body>
      <el-form ref="bankcardRef" :model="form" :inline="true" :rules="rules" label-width="120px">
        <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="debitType">
          <el-select v-model="form.debitType" placeholder="请选择储蓄账户类型">
            <el-option v-for="dict in debit_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </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="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" 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="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="备注" 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="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="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="120">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.effectDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="调整类型" align="center" width="120" prop="adjustType">
                <template #default="scope">
                  <dict-tag :options="adjust_type" :value="scope.row.adjustType" />
                </template>
              </el-table-column>
              <el-table-column label="调整后额度" align="center" width="100" prop="afterLimit" />
              <el-table-column label="调整幅度" align="center" width="100" prop="adjustLimit" />
              <el-table-column label="备注" align="center" prop="remark" />
              <el-table-column label="操作" align="center" width="120" 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>
  </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'
// eslint-disable-next-line no-unused-vars
import { require } from '@/utils/require'
const { proxy } = getCurrentInstance()
const { bank_card_type, debit_type, account_status } = proxy.useDict('bank_card_type', 'debit_type', 'account_status')
const { limit_history_type, adjust_type } = proxy.useDict('limit_history_type', 'adjust_type')
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 detailOpen = ref(false)
const openDetail = ref(false)
const titleDetail = ref('')
const limitHistoryList = ref([])
const currentcardId = ref('')
const currentBeforeLimit = ref('0')

const operateList = ref([
  { id: 'view', icon: 'View', 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,
    name: null,
    status: null,
    debitType: null,
    type: '1'
  },
  rules: {
    name: [{ required: true, message: '储蓄账户名称不能为空', trigger: 'blur' }],
    code: [{ required: true, message: '储蓄账户卡号不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '账户状态不能为空', trigger: 'blur' }],
    debitType: [{ required: true, message: '储蓄账户类型不能为空', trigger: 'blur' }],
    balance: [{ required: true, message: '余额不能为空', trigger: 'blur' }]
  },
  rulesDetail: {
    afterLimit: [{ required: true, message: '调整后额度不能为空', trigger: 'blur' }],
    adjustTime: [{ required: true, message: '调整时间不能为空', trigger: 'blur' }],
    adjustType: [{ required: true, message: '调整类型不能为空', trigger: 'change' }]
  }
})

const handleOperate = (operate, row) => {
  switch (operate) {
    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: '3',
    bankCardLendId: null,
    afterLimit: 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 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: '1',
    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,
    status: 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()
}

// 多选框选中数据
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 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`
  )
}

getList()
</script>
