<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="转入账户" style="width: 500px" prop="inAccountId">
          <el-select v-model="queryParams.inAccountId" placeholder="请选择转入账户" clearable>
            <el-option v-for="lend in lendList" :key="lend.id" :label="lend.nameCodeAvailableLimit" :value="lend.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="转出账户" style="width: 500px" prop="outAccountId">
          <el-select v-model="queryParams.outAccountId" placeholder="请选择转出账户" clearable>
            <el-option v-for="lend in lendList" :key="lend.id" :label="lend.nameCodeAvailableLimit" :value="lend.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="借贷时间" prop="time">
          <el-date-picker v-model="queryParams.time" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
        </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:accountsTransferRecord:add']">新增</el-button>
          <!-- <el-button
              :disabled="multiple"
              icon="Delete"
              @click="handleDelete"
              v-hasPermi="['invest:accountsTransferRecord:remove']"
          >删除</el-button> -->
          <!-- <el-button @click="handleExport" icon="Download" v-hasPermi="['invest:accountsTransferRecord:export']">导出</el-button> -->
        </div>
      </div>
      <div class="content-con" v-loading="loading">
        <el-table v-loading="loading" :data="accountsTransferRecordList" @selection-change="handleSelectionChange" height="calc(100% - 0.62rem)">
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <el-table-column label="名称" align="center" prop="name" />
          <el-table-column label="交易类型" align="center" width="100" prop="dealType">
            <template #default="scope">
              <dict-tag :options="record_lend_type" :value="scope.row.dealType" />
            </template>
          </el-table-column>
          <el-table-column label="转出账户" align="center" width="250" prop="outAccountName" />
          <el-table-column label="转入账户" align="center" width="250" prop="inAccountName" />
          <el-table-column label="借贷时间" width="180" align="center" prop="createTime" />
          <el-table-column label="借贷金额" width="150" align="center" prop="amount" />
          <el-table-column label="还款利息" width="150" align="center" prop="commission" />
          <el-table-column label="操作" width="150" 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="600px" append-to-body>
      <el-form ref="accountsTransferRecordRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="借贷账户" prop="outAccountId">
          <el-select v-model="form.outAccountId" placeholder="请选择借贷账户" clearable>
            <el-option v-for="lend in lendList" :key="lend.id" :label="lend.nameCodeAvailableLimit" :value="lend.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="储蓄账户" prop="inAccountId">
          <el-select v-model="form.inAccountId" placeholder="请选择储蓄账户" clearable>
            <el-option v-for="debit in debitCardList" :key="debit.id" :label="debit.nameCodeAvailableLimit" :value="debit.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="交易类型" prop="dealType">
          <el-select v-model="form.dealType" placeholder="请选择交易类型" @change="handleDealTypehange">
            <el-option v-for="dict in record_lend_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="createTimeLabel" prop="createTime">
          <el-date-picker clearable v-model="form.createTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择时间"> </el-date-picker>
        </el-form-item>
        <el-form-item :label="amountLabel" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item v-show="commissionShow" label="还款利息" prop="commission">
          <el-input v-model="form.commission" placeholder="请输入还款利息" />
        </el-form-item>
        <el-form-item label="备注" 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="AccountsTransferRecord">
import {
  listAccountsTransferRecord,
  getAccountsTransferRecord,
  delAccountsTransferRecord,
  addAccountsTransferRecord,
  updateAccountsTransferRecord
} from '@/api/invest/accountsTransferRecord'
import { listAccounts } from '@/api/invest/accounts'
import dayjs from 'dayjs'
// eslint-disable-next-line no-unused-vars
import { require } from '@/utils/require'
const { proxy } = getCurrentInstance()
const { transfer_type, deal_type, record_lend_type } = proxy.useDict('transfer_type', 'deal_type', 'record_lend_type')

const accountsTransferRecordList = 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 debitCardList = ref([])
const lendList = ref([])
const title = ref('')
const commissionShow = ref(false)
const createTimeLabel = ref('借贷时间')
const amountLabel = ref('借贷金额')
const operateList = ref([
  { id: 'view', icon: 'View', title: '查看', hasPermi: ['invest:accountsTransferRecord:query'] },
  // { id: 'edit', icon: 'Edit', title: '修改', hasPermi: ['invest:accountsTransferRecord:edit'] },
  { id: 'delete', icon: 'Delete', title: '删除', hasPermi: ['invest:accountsTransferRecord:remove'] }
])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    type: '5',
    time: '',
    posId: null,
    inAccountId: null,
    outAccountId: null,
    dealType: null
  },
  queryLendParams: {
    pageNum: 1,
    type: '3',
    status: '1',
    pageSize: 1000
  },
  queryDebitParams: {
    pageNum: 1,
    type: '1',
    status: '1',
    state: '1',
    repayFlag: '1',
    pageSize: 1000
  },
  rules: {
    inAccountId: [{ required: true, message: '借贷账户不能为空', trigger: 'blur' }],
    outAccountId: [{ required: true, message: '储蓄账户不能为空', trigger: 'blur' }],
    dealType: [{ required: true, message: '交易类型不能为空', trigger: 'blur' }],
    amount: [{ required: true, message: '借贷金额不能为空', trigger: 'blur' }],
    commission: [{ required: true, message: '还款利息不能为空', trigger: 'blur' }],
    createTime: [{ 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, queryLendParams, queryDebitParams, form, rules } = toRefs(data)

const handleDealTypehange = (type) => {
  //1表示借款，2表示还款
  if (type === '1') {
    commissionShow.value = false
    createTimeLabel.value = '借款时间'
    amountLabel.value = '借款金额'
  } else if (type === '2') {
    amountLabel.value = '还款本金'
    createTimeLabel.value = '还款时间'
    commissionShow.value = true
  }
}

/** 查询借贷账户管理列表 */
function getLendList() {
  listAccounts(queryLendParams.value).then((response) => {
    lendList.value = response.rows
  })
}

/** 查询储蓄账户卡管理列表 */
function getDebitList() {
  listAccounts(queryDebitParams.value).then((response) => {
    debitCardList.value = response.rows
  })
}

/** 查询借贷记账列表 */
function getList() {
  loading.value = true
  const timeRange = queryParams.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')
  }
  queryParams.value.startTime = st
  queryParams.value.endTime = et
  listAccountsTransferRecord(queryParams.value).then((response) => {
    accountsTransferRecordList.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: '5',
    outAccountId: null,
    inAccountId: null,
    posId: null,
    commission: 0,
    amount: null,
    actualAmount: null,
    dealType: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null
  }
  proxy.resetForm('accountsTransferRecordRef')
}

/** 搜索按钮操作 */
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 = '查看借贷记账'
  //1表示借款，2表示还款
  if (row.dealType === '1') {
    commissionShow.value = false
    createTimeLabel.value = '借款时间'
    amountLabel.value = '借款金额'
  } else if (row.dealType === '2') {
    amountLabel.value = '还款本金'
    createTimeLabel.value = '还款时间'
    commissionShow.value = true
  }
  form.value = row
  open.value = true
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加借贷记账'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getAccountsTransferRecord(_id).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改借贷记账'
  })
}

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

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

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'invest/accountsTransferRecord/export',
    {
      ...queryParams.value
    },
    `accountsTransferRecord_${new Date().getTime()}.xlsx`
  )
}
getDebitList()
getLendList()
getList()
</script>
