<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="futureStocksId">
          <el-select v-model="queryParams.futureStocksId" placeholder="请选择期货账户" clearable>
            <el-option v-for="futureStocks in futureStocksList" :key="futureStocks.id" :label="futureStocks.nameCode" :value="futureStocks.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="账单名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入账单名称" clearable @keyup.enter="handleQuery" />
        </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:futureStocksBill:add']">新增</el-button>
          <el-button @click="handleUpdateBill" icon="Refresh" v-hasPermi="['invest:creditCardBill:add']">手动更新账单</el-button>
          <el-button :disabled="multiple" icon="Delete" @click="handleDelete" v-hasPermi="['invest:futureStocksBill:remove']">删除</el-button>
          <!-- <el-button @click="handleExport" icon="Download" v-hasPermi="['invest:futureStocksBill:export']">导出</el-button> -->
        </div>
      </div>
      <div class="content-con" v-loading="loading">
        <el-table v-loading="loading" :data="futureStocksBillList" @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="futureStocksNameCode" />
          <el-table-column label="账单名称" align="center" prop="name" />
          <el-table-column label="账单周期" align="center" prop="billDatePeriod" />
          <el-table-column label="期货收益" align="center" prop="billAmount" />
          <el-table-column label="数据更新时间" align="center" prop="updateTime" />
          <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="500px" append-to-body>
      <el-form ref="futureStocksBillRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="期货账户" prop="futureStocksId">
          <el-select v-model="form.futureStocksId" placeholder="请选择期货账户" clearable>
            <el-option v-for="futureStocks in futureStocksList" :key="futureStocks.id" :label="futureStocks.nameCode" :value="futureStocks.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="账单日" prop="billDate">
          <el-date-picker clearable v-model="form.billDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择账单日"> </el-date-picker>
        </el-form-item>
        <el-form-item label="期货收益" prop="billAmount">
          <el-input v-model="form.billAmount" type="number" 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>
    <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"
            disabled
            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 profit_loss" :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="profit_loss" :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>
  </div>
</template>

<script setup name="FutureStocksBill">
import {
  listFutureStocksBill,
  getFutureStocksBill,
  delFutureStocksBill,
  addFutureStocksBill,
  updateFutureStocksBill,
  updateLastFutureStocksBill
} from '@/api/invest/futureStocksBill'
import { listFutureStocks } from '@/api/invest/futureStocks'
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 { future_stock_type, profit_loss, deal_category } = proxy.useDict('future_stock_type', 'profit_loss', 'deal_category')

const futureStocksBillList = 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 futureStocksList = ref([])
const operateList = ref([
  { id: 'view', icon: 'View', title: '查看', hasPermi: ['invest:futureStocksBill:query'] },
  { id: 'edit', icon: 'Edit', title: '修改', hasPermi: ['invest:futureStocksBill:edit'] },
  { id: 'delete', icon: 'Delete', title: '删除', hasPermi: ['invest:futureStocksBill:remove'] },
  { id: 'detail', icon: 'Tickets', title: '账单明细', hasPermi: ['invest:futureStocksBill:query'] }
])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    billDate: null,
    futureStocksId: null,
    billDatePeriod: null,
    billAmount: null,
    type: '1'
  },
  queryFutureStocksListParams: {
    pageNum: 1,
    type: '1',
    status: '1',
    pageSize: 1000
  },
  rules: {
    billDate: [{ required: true, message: '账单日不能为空', trigger: 'blur' }],
    futureStocksId: [{ required: true, message: '期货账户不能为空', trigger: 'blur' }],
    billAmount: [{ 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 'detail':
      handleDealRecord(row)
      break
    default:
      break
  }
}

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

/** 历史数据按钮操作 */
function handleDealRecord(row) {
  const _id = row.futureStocksId
  queryDealRecordParams.value.time = row.billDatePeriod.split('~')
  queryDealRecordParams.value.dealType = ''
  queryDealRecordParams.value.dealCategory = '2'
  titleDealRecord.value = row.futureStocksNameCode + '账单收益明细【' + row.billAmount + '】'
  currentAccountId.value = _id
  getDealRecordList(1)
  openDealRecord.value = true
}

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

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

const resetDealRecordQuery = () => {
  proxy.resetForm('queryDealRecordRef')
  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 getFutureStocksList() {
  listFutureStocks(queryFutureStocksListParams.value).then((response) => {
    futureStocksList.value = response.rows
  })
}

/** 查询期货账单列表 */
function getList() {
  loading.value = true
  listFutureStocksBill(queryParams.value).then((response) => {
    futureStocksBillList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 手动更新按钮操作 */
function handleUpdateBill() {
  updateLastFutureStocksBill()
  setTimeout(() => {
    // 一秒后执行的操作
    getList()
    proxy.$modal.msgSuccess('手动更新账单成功')
  }, 1000)
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    billDate: null,
    futureStocksId: null,
    billDatePeriod: null,
    billAmount: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    type: '1',
    remark: null,
    billYear: null,
    billMonth: null
  }
  proxy.resetForm('futureStocksBillRef')
}

/** 搜索按钮操作 */
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 handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getFutureStocksBill(_id).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改期货账单'
  })
}

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

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