<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="type">
          <el-select v-model="queryParams.type" placeholder="请选择账户类型" @change="handleQueryTypeChange" clearable>
            <el-option v-for="dict in account_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="账户状态" prop="state">
          <el-select v-model="queryParams.state" placeholder="请选择账户状态" clearable>
            <el-option v-for="dict in account_state" :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:accounts:add']">新增</el-button> -->
          <!-- <el-button :disabled="multiple" icon="Delete" @click="handleDelete" v-hasPermi="['invest:accounts:remove']">删除</el-button> -->
          <el-button @click="handleExport" icon="Download" v-hasPermi="['invest:accounts:export']">导出</el-button>
        </div>
      </div>
      <div class="content-con" v-loading="loading">
        <el-table v-loading="loading" :data="accountsList" @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" prop="type">
            <template #default="scope">
              <dict-tag :options="account_type" :value="scope.row.type" />
            </template>
          </el-table-column>
          <el-table-column label="账号" width="180" align="center" prop="code" />
          <el-table-column label="信用卡额度" align="center" v-if="queryParams.type === '2'" prop="creditLimit" />
          <el-table-column label="可用额度" align="center" prop="availableLimit" />
          <el-table-column label="余额" align="center" prop="balance" />
          <el-table-column label="储蓄卡类型" align="center" v-if="queryParams.type === '1'" prop="debitType">
            <template #default="scope">
              <dict-tag :options="debit_type" :value="scope.row.debitType" />
            </template>
          </el-table-column>
          <el-table-column label="账单日" align="center" v-if="queryParams.type === '2'" prop="billDateName" />
          <el-table-column label="还款日" align="center" v-if="queryParams.type === '2'" prop="payDateName" />

          <el-table-column label="账户状态" align="center" prop="state">
            <template #default="scope">
              <dict-tag :options="account_state" :value="scope.row.state" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="300" 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="500px" append-to-body>
      <el-form ref="accountsRef" :model="form" :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="type">
          <el-select v-model="form.type" placeholder="请选择账户类型">
            <el-option v-for="dict in account_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账号" prop="code">
          <el-input v-model="form.code" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="余额" prop="balance">
          <el-input v-model="form.balance" 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="state">
          <el-select v-model="form.state" placeholder="请选择账户状态">
            <el-option v-for="dict in account_state" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </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>
    <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" />
        <el-table-column label="交易金额" align="center" prop="amount" />
        <el-table-column label="当前余额" align="center" prop="currentBalance" />
        <el-table-column label="交易类型" align="center" prop="dealType">
          <template #default="scope">
            <dict-tag :options="deal_type" :value="scope.row.dealType" />
          </template>
        </el-table-column>
        <el-table-column label="交易类别" align="center" prop="dealCategory">
          <template #default="scope">
            <dict-tag :options="deal_category" :value="scope.row.dealCategory" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" width="380" prop="remark" />
      </el-table>
      <el-pagination small background layout="total, prev, pager, next" :total="dealRecordTotal" @current-change="handleCurrentDealRecordChange" />
    </el-dialog>

    <el-dialog :title="titleTransferRecord" v-model="openTransferRecord" width="1100px" append-to-body destroy-on-close>
      <el-form :model="queryTransferRecordParams" ref="queryTransferRecordRef" inline>
        <el-form-item label="转账时间" prop="time">
          <el-date-picker
            v-model="queryTransferRecordParams.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="转账类型" style="width: 220px" prop="type">
          <el-select v-model="queryTransferRecordParams.type" placeholder="请选择转账类型" clearable>
            <el-option v-for="dict in transfer_type" :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="handleTransferRecordQuery">搜索</el-button>
          <el-button type="info" icon="Refresh" @click="resetTransferRecordQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loadingTransferRecord" :data="tableTransferRecordData">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="名称" align="center" width="380" prop="name" />
        <el-table-column label="转出账户" align="center" prop="outAccountName" />
        <el-table-column label="转入账户" align="center" prop="inAccountName" />
        <el-table-column label="转账时间" align="center" width="160" prop="createTime" />
        <el-table-column label="转账金额" align="center" width="120" prop="amount" />
        <el-table-column label="转账类型" align="center" width="100" prop="type">
          <template #default="scope">
            <dict-tag :options="transfer_type" :value="scope.row.type" />
          </template>
        </el-table-column>
      </el-table>
      <el-pagination small background layout="total, prev, pager, next" :total="transferRecordTotal" @current-change="handleCurrentTransferRecordChange" />
    </el-dialog>
  </div>
</template>

<script setup name="Accounts">
import { listAccounts, getAccounts, delAccounts, addAccounts, updateAccounts } from '@/api/invest/accounts'
import { listAccountDealRecord } from '@/api/invest/accountDealRecord'
import { listAccountsTransferRecord } from '@/api/invest/accountsTransferRecord'

// eslint-disable-next-line no-unused-vars
import { require } from '@/utils/require'
import dayjs from 'dayjs'
const { proxy } = getCurrentInstance()
const { account_state, account_type, deal_type, deal_category, debit_type, transfer_type } = proxy.useDict(
  'account_state',
  'account_type',
  'deal_type',
  'deal_category',
  'debit_type',
  'transfer_type'
)
const accountsList = 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(false)
const loadingDealRecord = ref(false)
const tableDealRecordData = ref([])
const dealRecordTotal = ref(0)

const queryDealRecordParams = ref({
  time: '',
  dealType: null,
  dealCategory: null,
  pageNum: 1,
  pageSize: 10
})

const titleTransferRecord = ref('')
const openTransferRecord = ref(false)
const loadingTransferRecord = ref(false)
const tableTransferRecordData = ref([])
const transferRecordTotal = ref(0)
const queryTransferRecordParams = ref({
  time: '',
  type: '',
  pageNum: 1,
  pageSize: 10
})

const operateList = ref([
  { id: 'view', icon: 'View', title: '查看', hasPermi: ['invest:accounts:query'] },
  { id: 'edit', icon: 'Edit', title: '修改', hasPermi: ['invest:accounts:edit'] },
  // { id: 'delete', icon: 'Delete', title: '删除', hasPermi: ['invest:accounts:remove'] },
  { id: 'dealRecord', icon: 'Tickets', title: '交易记录', hasPermi: ['invest:accounts:query'] },
  { id: 'transDeal', icon: 'Cellphone', title: '转账记录', hasPermi: ['invest:accounts:query'] }
])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    type: null,
    state: null
  },
  rules: {
    name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '账户类型不能为空', trigger: 'change' }],
    code: [{ 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
    case 'dealRecord':
      handleDealRecord(row)
      break
    case 'transDeal':
      handleTransDeal(row)
      break
    default:
      break
  }
}

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

/** 查询记账账户列表 */
function getList() {
  loading.value = true
  listAccounts(queryParams.value).then((response) => {
    accountsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

const handleQueryTypeChange = (type) => {
  queryParams.value.type = type
  getList()
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    type: null,
    code: null,
    balance: null,
    creditLimit: null,
    availableLimit: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    accountId: null,
    state: null
  }
  proxy.resetForm('accountsRef')
}

/** 搜索按钮操作 */
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
  getAccounts(_id).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改记账账户'
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs.accountsRef.validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateAccounts(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addAccounts(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 delAccounts(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

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

/** 历史数据按钮操作 */
function handleDealRecord(row) {
  const _id = row.id || ids.value
  queryDealRecordParams.value.time = ''
  queryDealRecordParams.value.dealType = ''
  queryDealRecordParams.value.dealCategory = ''
  titleDealRecord.value = row.nameCode + '历史交易记录'
  currentAccountId.value = _id
  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, id) => {
  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((res) => {
    loadingDealRecord.value = false
    tableDealRecordData.value = res.rows
    dealRecordTotal.value = res.total
  })
}

/** 历史数据按钮操作 */
function handleTransDeal(row) {
  const _id = row.id || ids.value
  queryTransferRecordParams.value.time = ''
  queryTransferRecordParams.value.type = ''
  titleTransferRecord.value = row.nameCode + '历史转账记录'
  currentAccountId.value = _id
  getTransferRecordList(1)
  openTransferRecord.value = true
}

const handleCurrentTransferRecordChange = (num) => {
  getTransferRecordList(num)
}

const handleTransferRecordQuery = () => {
  getTransferRecordList(1)
}

const resetTransferRecordQuery = () => {
  queryTransferRecordParams.value.time = ''
  queryTransferRecordParams.value.type = ''
  transferRecordTotal.value = 0
  getTransferRecordList(1)
}

const getTransferRecordList = (num, id) => {
  loadingTransferRecord.value = true

  const timeRange = queryTransferRecordParams.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')
  }

  listAccountsTransferRecord({
    accountId: currentAccountId.value,
    startTime: st,
    endTime: et,
    pageNum: num,
    pageSize: 10,
    type: queryTransferRecordParams.value.type
  }).then((res) => {
    loadingTransferRecord.value = false
    tableTransferRecordData.value = res.rows
    transferRecordTotal.value = res.total
  })
}
getList()
</script>
