<template>
  <div class="app-container">
    <!-- 这里是自定义头部，切换视图类型和切换日期 -->
    <div class="calendarHeader">
      <div class="header_left">
        <h1>{{ calendarTitle }}</h1>
      </div>
      <div class="header_right">
        <el-select v-model="type" placeholder="视图类型" style="width: 80px" size="default" class="header_select" @change="handleChangeType">
          <el-option label="月" value="1" />
          <el-option label="周" value="2" />
        </el-select>
        <!-- 选择月份的日期框 -->
        <el-date-picker
          v-if="type === '1'"
          v-model="showMonth"
          type="month"
          size="default"
          :clearable="false"
          placeholder="请选择日期"
          style="margin-left: 10px; vertical-align: middle"
          @change="changeDate"
        />

        <el-button-group v-if="type !== '3' && isShowBack" style="margin-left: 10px">
          <el-button type="primary" size="default" icon="RefreshRight" @click="getToday()">返回本月</el-button>
        </el-button-group>
        <el-button-group v-if="type === '2'" style="margin-left: 10px">
          <el-button size="default" type="primary" icon="ArrowLeft" @click="getPrev()">上一周</el-button>
          <el-button style="margin-left: 2px" size="default" type="primary" icon="ArrowRight" @click="getNext()">下一周</el-button>
        </el-button-group>
      </div>
    </div>
    <!-- 月视图和周视图显示，列视图显示表格形式 -->
    <div v-show="type !== '3'" ref="fullcalendar" class="card" />
    <!-- 信用卡账单 -->
    <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 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" width="200" prop="accountName" />
        <el-table-column label="交易时间" align="center" prop="createTime" />
        <el-table-column label="交易金额" align="center" width="100" prop="amount" />
        <el-table-column label="当前余额" align="center" prop="currentBalance" />
        <el-table-column label="交易类型" align="center" width="80" 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="300" 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="PlanManagement">
import { reactive, toRefs, ref, onMounted, getCurrentInstance } from 'vue'
import { Calendar } from '@fullcalendar/core'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import listPlugin from '@fullcalendar/list'
import interactionPlugin from '@fullcalendar/interaction'
import dayjs from 'dayjs'
import { getAccountCalendarInfo } from '@/api/invest/accountAnalysis.js'
import { listAccountDealRecord } from '@/api/invest/accountDealRecord'

const { proxy } = getCurrentInstance()
const { account_state, account_type, deal_type, deal_category, debit_type, transfer_type, bill_state } = proxy.useDict(
  'account_state',
  'account_type',
  'deal_type',
  'deal_category',
  'debit_type',
  'transfer_type',
  'bill_state'
)
const loading = ref(true)
const isShowBack = ref(false)
const infoList = ref([])
const type = ref('1')

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 data = reactive({
  calendarTitle: new Date().getFullYear() + '年' + Number(new Date().getMonth() + 1) + '月', // 日历头部显示文
  showMonth: new Date(), // 显示月份
  Tcalendar: null,
  fullcalendar: ref()
})
onMounted(() => {
  initCalendar()
  getCalendarList()
})
const { showMonth, fullcalendar, Tcalendar, calendarTitle } = toRefs(data)
const initCalendar = () => {
  Tcalendar.value = new Calendar(fullcalendar.value, {
    plugins: [dayGridPlugin, timeGridPlugin, listPlugin, interactionPlugin],
    initialView: 'dayGridMonth',
    aspectRatio: 2.2,
    locale: 'zh-cn',
    handleWindowResize: true,
    editable: true, // 允许编辑表格
    droppable: true,
    eventDisplay: 'block',
    // height: 'auto',
    // 限制事件最大数量
    // 事件数量超出时更多显示链接汉化
    moreLinkContent: '+ 更多',
    // 显示事件开始时间
    displayEventTime: false,
    // 显示事件结束时间
    displayEventEnd: false,
    // 关闭全天区域显示
    allDaySlot: true,
    // 开始时间段
    slotMinTime: '00:00:00',
    // 结束时间段
    slotMaxTime: '00:00:00',
    eventOrder: 'type,color,start',
    eventDurationEditable: true,
    eventResizableFromStart: true,
    selectable: true, // 允许用户通过单击和拖动来突出显示多个日期或时间段
    firstDay: 1, // 设置一周中显示的第一天是哪天，周日是0，周一是1，类推。
    unselectAuto: true, // 当点击页面日历以外的位置时，是否自动取消当前的选中状态
    unselectCancel: '.el-drawer',
    // dayMaxEvents: true,
    // eventLimit: true,
    headerToolbar: false,
    buttonText: {
      today: '回到今天',
      month: '月',
      week: '周',
      list: '列',
      day: '日'
    },
    allDayText: '全天',
    events: infoList.value,
    eventClassNames: function (arg) {
      // 添加自定义class
      return [arg.event.extendedProps.class]
    },
    eventContent: function (arg) {
      const italicEl = document.createElement('div')
      if (arg.event.extendedProps.startDateMinute && type.value === '1') {
        const childEl = document.createElement('span')
        childEl.innerHTML = arg.event.extendedProps.startDateMinute
        italicEl.append(childEl)
      }
      italicEl.append(arg.event.title)
      italicEl.setAttribute('class', `plan_title ${arg.event.extendedProps.class}`)
      return { domNodes: [italicEl] }
    },
    eventClick: function (info) {
      // 点击查看时触发
      handleClick(info)
    },
    select: function (info) {
      // 视图选择日期触发
      handleSelectDate(info)
    }

    // select: function (info) {}
  })
  Tcalendar.value.render()
}
// 上一月、周、日
const getPrev = () => {
  Tcalendar.value.prev()
  calendarTitle.value = Tcalendar.value.view.title
  getCalendarList()
}
// 下一月、周、日
const getNext = () => {
  Tcalendar.value.next()
  calendarTitle.value = Tcalendar.value.view.title
  getCalendarList()
}
// 回到今天
const getToday = () => {
  Tcalendar.value.today()
  calendarTitle.value = Tcalendar.value.view.title
  isShowBack.value = false
  showMonth.value = new Date()
  getCalendarList()
}
const getCalendarList = () => {
  const currentEnd = dayjs(Tcalendar.value.view.currentEnd).add(-1, 'day')
  const params = {
    startTime: dayjs(Tcalendar.value.view.currentStart).format('YYYY-MM-DD'),
    endTime: dayjs(currentEnd).format('YYYY-MM-DD'),
    type: type.value
  }
  loading.value = true
  Tcalendar.value.getEventSources().forEach((item) => {
    item.remove()
  })

  getAccountCalendarInfo(params).then((res) => {
    loading.value = false
    if (res) {
      infoList.value = res.data
      Tcalendar.value.addEventSource(infoList.value)
    }
  })
}
// 切换视图类型
const handleChangeType = (val) => {
  if (val === '1') {
    Tcalendar.value.changeView('dayGridMonth')
    showMonth.value = new Date()
  } else if (val === '2') {
    Tcalendar.value.changeView('dayGridWeek')
  }
  isShowBack.value = false
  calendarTitle.value = Tcalendar.value.view.title
  getToday()
}

// 切换月份和日期
const changeDate = (date) => {
  Tcalendar.value.gotoDate(date)
  // 判断不是当前月份，显示返回当前月
  if (date.getMonth() !== new Date().getMonth() || new Date().getFullYear() !== new Date(date).getFullYear()) {
    isShowBack.value = true
  } else {
    isShowBack.value = false
  }
  calendarTitle.value = Tcalendar.value.view.title
  getCalendarList()
}
// 点击计划查看
const handleClick = (info) => {
  const date = info.event.startStr
  const type = info.event._def.extendedProps.type
  const accountId = info.event._def.extendedProps.accountId
  const billDatePeriod = info.event._def.extendedProps.billDatePeriod
  //信用卡账单日
  if (type === 1) {
    const _id = accountId
    queryDealRecordParams.value.time = billDatePeriod.split('~')
    queryDealRecordParams.value.dealType = ''
    queryDealRecordParams.value.dealCategory = ''
    titleDealRecord.value = info.event._def.title
    currentAccountId.value = _id
    getDealRecordList(1)
    openDealRecord.value = true
  }
  //贷款已还
  if (type === 4) {
    const _id = accountId
    queryDealRecordParams.value.time = [date, date]
    queryDealRecordParams.value.dealType = '1'
    queryDealRecordParams.value.dealCategory = '9'
    titleDealRecord.value = info.event._def.title
    currentAccountId.value = _id
    getDealRecordList(1)
    openDealRecord.value = true
  }
  //日常支出
  if (type === 5) {
    queryDealRecordParams.value.time = [date, date]
    queryDealRecordParams.value.dealType = '2'
    queryDealRecordParams.value.dealCategory = '1'
    titleDealRecord.value = info.event._def.title
    currentAccountId.value = null
    getDealRecordList(1)
    openDealRecord.value = true
  }

  //投资收益
  if (type === 6) {
    queryDealRecordParams.value.time = [date, date]
    queryDealRecordParams.value.dealType = ''
    queryDealRecordParams.value.dealCategory = '2'
    titleDealRecord.value = info.event._def.title
    currentAccountId.value = null
    getDealRecordList(1)
    openDealRecord.value = true
  }
  //POS机刷卡
  if (type === 7) {
    queryDealRecordParams.value.time = [date, date]
    queryDealRecordParams.value.dealType = '2'
    queryDealRecordParams.value.dealCategory = '5'
    titleDealRecord.value = info.event._def.title
    currentAccountId.value = null
    getDealRecordList(1)
    openDealRecord.value = true
  }

  //工资收入
  if (type === 8) {
    queryDealRecordParams.value.time = [date, date]
    queryDealRecordParams.value.dealType = ''
    queryDealRecordParams.value.dealCategory = '11'
    titleDealRecord.value = info.event._def.title
    currentAccountId.value = null
    getDealRecordList(1)
    openDealRecord.value = true
  }
}
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
  })
}

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

const resetDealRecordQuery = () => {
  proxy.resetForm('queryDealRecordRef')
  queryDealRecordParams.value.dealType = ''
  queryDealRecordParams.value.dealCategory = ''
  dealRecordTotal.value = 0
  currentAccountId.value = null
  getDealRecordList(1)
}

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

function isDateGreaterThanSpecifiedDate(date, specifiedDate) {
  return date > specifiedDate
}

// 拖拽触发
const handleSelectDate = (info) => {
  titleDealRecord.value = ''
  queryDealRecordParams.value.dealType = ''
  queryDealRecordParams.value.dealCategory = ''
  const date = info.startStr
  // 使用方法
  const currentDate = new Date()
  const specifiedDate = new Date(date)
  const result = isDateGreaterThanSpecifiedDate(currentDate, specifiedDate)
  if (result) {
    queryDealRecordParams.value.time = [date, date]
    currentAccountId.value = null
    getDealRecordList(1)
    openDealRecord.value = true
  }
}
</script>
<style lang="scss" scoped>
.calendarHeader {
  margin: 0px 0px 5px 0px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  .header_select {
    margin: 0 0 0 10px;
    display: inline-block;
    vertical-align: middle;
  }
}
h1 {
  font-size: 20px;
  font-weight: 500;
  line-height: 32px;
  margin: 0 0 0 0;
  text-align: left;
  vertical-align: middle;
  display: inline-block;
  color: #303133;
}
</style>
