<script>
import {
  exportXlsx,
  getApprovedScoreStatByParams,
  getScoreStatByParams,
  getSettledStatByParams,
  listReceiverNames,
  listRootScorePackageSenders,
  search
} from "@/api/score_package";
import scorePackageStatusDict from "@/utils/dict/ScorePackageStatus";
import dayjs from "@/plugins/dayjs";
import ColumnsSelect from "@/components/ColumnsSelect/index.vue";

export default {
  name: 'ScorePackage',
  components: {ColumnsSelect},
  data() {
    return {
      searchForm: {
        nameOrId: null,
        rootPackageSendPackageDeptId: null,
        rootPackageCreateTimeRange: null,
        packageFinishTimeRange: [dayjs().startOf('year').toDate(), dayjs().toDate()],
        settleNotifyTimeRange: null,
        scorePackageStatus: null,
        receiverName:null,
      },
      searchParams: {
        nameOrId: null,
        rootPackageSendPackageDeptId: null,
        rootPackageCreateTimeGe: null,
        rootPackageCreateTimeLe: null,
        packageFinishTimeGe: null,
        packageFinishTimeLe: null,
        settleNotifyTimeGe: null,
        settleNotifyTimeLe: null,
        scorePackageStatus: null,
        receiverName:null,
      },
      data: null,
      pageSize: 10,
      rootScorePackageSenders: [],
      scorePackageStatusDict,
      showLevel: -1,
      nextId:0,
      loading:false,
      scoreStat:{},
      approvedScoreStat:{},
      settledStat:{},
      receiverNames:[],
      loadingReceiverNames:false,
      columns: [
        { key: 0, label: `积分包名称`, visible: true },
        { key: 1, label: `发包对象`, visible: true },
        { key: 2, label: `接包对象`, visible: true },
        { key: 3, label: `发布日期`, visible: true },
        { key: 4, label: `积分包值`, visible: true },
        { key: 5, label: `积分包状态`, visible: true },
        { key: 6, label: `核准积分包值`, visible: true },
        { key: 7, label: `核准时间`, visible: true },
        { key: 8, label: `结算总金额（元）`, visible: true },
        { key: 9, label: `实际支付金额（元）`, visible: true },
        { key: 10, label: `结算成功时间`, visible: true }
      ],
    }
  },
  computed: {
    hasSearchParams() {
      for (const key of Object.keys(this.searchParams)) {
        const value = this.searchParams[key]
        if (value === null || value === undefined) {
          continue
        }
        if (typeof value === 'string') {
          if (value.trim().length > 0) {
            return true
          }
        } else if (Array.isArray(value)) {
          if (value.length > 0) {
            return true
          }
        }
      }
      return false
    }
  },
  watch:{
    showLevel(){
      this.search()
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init(){
      await Promise.all([this.loadRootScorePackageSenders(),this.searchReceiverNames(),this.search()])
    },
    async search() {
      this.scoreStat={}
      this.approvedScoreStat={}
      this.settledStat={}
      this.searchParams = {
        nameOrId: this.searchForm.nameOrId,
        rootPackageSendPackageDeptId: this.searchForm.rootPackageSendPackageDeptId,
        rootPackageCreateTimeGe: this.searchForm.rootPackageCreateTimeRange ? this.formatStartDate(this.searchForm.rootPackageCreateTimeRange[0]) : null,
        rootPackageCreateTimeLe: this.searchForm.rootPackageCreateTimeRange ? this.formatEndDate(this.searchForm.rootPackageCreateTimeRange[1]) : null,
        packageFinishTimeGe: this.searchForm.packageFinishTimeRange ? this.formatStartDate(this.searchForm.packageFinishTimeRange[0]) : null,
        packageFinishTimeLe: this.searchForm.packageFinishTimeRange ? this.formatEndDate(this.searchForm.packageFinishTimeRange[1]) : null,
        settleNotifyTimeGe: this.searchForm.settleNotifyTimeRange ? this.formatStartDate(this.searchForm.settleNotifyTimeRange[0]) : null,
        settleNotifyTimeLe: this.searchForm.settleNotifyTimeRange ? this.formatEndDate(this.searchForm.settleNotifyTimeRange[1]) : null,
        scorePackageStatus: this.searchForm.scorePackageStatus,
        receiverName:this.searchForm.receiverName,
      }
      await this.loadData(1)
      await this.loadStat()
    },
    formatStartDate(value){
      return dayjs(value).startOf('date').toISOString()
    },
    formatEndDate(value){
      return dayjs(value).endOf('date').toISOString()
    },
    async loadData(page) {
      this.loading=true
      this.data=null
      try {
        const params = {
          page: page - 1,
          size: this.pageSize,
          ...this.searchParams
        }
        if (this.showLevel === -1 && !this.hasSearchParams) {
          params.level = 0
        } else if (this.showLevel === 0) {
          params.typeid = ['1']
        } else if (this.showLevel === 1) {
          params.typeid = ['2']
        } else if (this.showLevel === 2) {
          params.typeid = ['3', '4', '5']
        }
        params.fetchChildrenCount = this.showLevel === -1
        const data = await search(params)
        for(let i=0;i<data.content.length;i++){
          const row=data.content[i]
          row.no = (data.page * data.size + i + 1) + ""
          this.processRow(row)
        }
        this.data = data
      } finally {
        this.loading=false
      }
    },
    async loadStat(){
      const params = {
        ...this.searchParams
      }
      if (this.showLevel === 0) {
        params.typeid = ['1']
      } else if (this.showLevel === 1) {
        params.typeid = ['2']
      } else if (this.showLevel === 2) {
        params.typeid = ['3', '4', '5']
      }
      this.scoreStat=await getScoreStatByParams(params)
      this.approvedScoreStat=await getApprovedScoreStatByParams(params)
      this.settledStat=await getSettledStatByParams(params)
    },
    processRow(row){
      row.rid=++this.nextId
      if (this.showLevel === -1) {
        row.hasChildren = row.childrenCount>0
      }
      if(row.typeid==='3'||row.typeid==='4'||row.typeid==='5'){
        row.receiverName=row.user
      }else{
        row.receiverName=row.dept?row.dept.name:''
      }
      row.createTime=dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
      const scorePackageStatusItem=scorePackageStatusDict.find(i=>i.value===row.scorePackageStatus)
      row.scorePackageStatusLabel=scorePackageStatusItem?scorePackageStatusItem.label:''
      if(row.packageFinishTime){
        row.packageFinishTime=dayjs(row.packageFinishTime).format('YYYY-MM-DD HH:mm:ss')
      }
      if(row.settleNotifyTime){
        row.settleNotifyTime=dayjs(row.settleNotifyTime).format('YYYY-MM-DD HH:mm:ss')
      }
    },
    async loadRootScorePackageSenders() {
      this.rootScorePackageSenders = await listRootScorePackageSenders()
    },
    async loadChildren(row, treeNode, resolve) {
      const data = await search({
        page: 0,
        size: 10000,
        relationScoreId: row.id,
        fetchChildrenCount: this.showLevel === -1
      })
      const parentNo=row.no
      for(let i=0;i<data.content.length;i++){
        const row=data.content[i]
        row.no = parentNo+"."+(data.page * data.size + i + 1)
        this.processRow(row)
      }
      resolve(data.content)
    },
    async exportXlsx() {
      this.$modal.loading("正在导出数据，请稍后...")
      try {
        const params = {
          ...this.searchParams
        }
        if (this.showLevel === 0) {
          params.typeid = ['1']
        } else if (this.showLevel === 1) {
          params.typeid = ['2']
        } else if (this.showLevel === 2) {
          params.typeid = ['3', '4', '5']
        }
        const filename = await exportXlsx(params)
        this.$download.name(filename, true)
      } finally {
        this.$modal.closeLoading()
      }
    },
    formatNumber(value){
      if(typeof value!=='number'){
        return value
      }else{
        return new Intl.NumberFormat('zh-CN',{}).format(value)
      }
    },
    formatMoney(value){
      if(typeof value!=='number'){
        return value
      }else{
        return new Intl.NumberFormat('zh-CN',{maximumFractionDigits:0}).format(value)
      }
    },
    async handleSizeChange(val){
      this.pageSize=val
      await this.search()
    },
    async searchReceiverNames(query){
      this.loadingReceiverNames=true
      try {
        this.receiverNames = await listReceiverNames({
          keyword: query,
          limit: 100
        })
      } finally {
        this.loadingReceiverNames=false
      }
    }
  }
}
</script>

<template>
  <div class="app-container">
    <el-form inline v-model="searchForm">
      <el-form-item label="积分包名称/编号">
        <el-input v-model="searchForm.nameOrId"></el-input>
      </el-form-item>
      <el-form-item label="源头包发包对象">
        <el-select
          v-model="searchForm.rootPackageSendPackageDeptId"
          multiple
          filterable
          reserve-keyword
          placeholder="请输入关键词">
          <el-option
            v-for="item in rootScorePackageSenders"
            :key="item.deptId"
            :label="item.name"
            :value="item.deptId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="接包对象">
        <el-select
          v-model="searchForm.receiverName"
          multiple
          filterable
          remote
          reserve-keyword
          :remote-method="searchReceiverNames"
          :loading="loadingReceiverNames"
          placeholder="请输入关键词">
          <el-option
            v-for="item in receiverNames"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="源头包发包时间">
        <el-date-picker v-model="searchForm.rootPackageCreateTimeRange" type="daterange" style="width: 230px;"></el-date-picker>
      </el-form-item>
      <el-form-item label="核准时间">
        <el-date-picker v-model="searchForm.packageFinishTimeRange" type="daterange" style="width: 230px;"></el-date-picker>
      </el-form-item>
      <el-form-item label="结算成功时间">
        <el-date-picker v-model="searchForm.settleNotifyTimeRange" type="daterange" style="width: 230px;"></el-date-picker>
      </el-form-item>
      <el-form-item label="个人包状态">
        <el-select
          v-model="searchForm.scorePackageStatus"
          multiple
          filterable
          reserve-keyword
          placeholder="请输入关键词">
          <el-option
            v-for="item in scorePackageStatusDict"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="search" type="primary">检索</el-button>
      </el-form-item>
    </el-form>
    <div class="statistic-list">
      <div class="statistic-item">
        <div class="statistic-item-title">下发积分包总值</div>
        <div class="statistic-item-value">{{formatNumber(scoreStat.totalScore)}}</div>
        <div class="statistic-item-fields">
          <span>企业包</span>
          <span>{{formatNumber(scoreStat.entScore)}}分</span>
          <span>{{formatNumber(scoreStat.entCount)}}个</span>
        </div>
        <div class="statistic-item-fields">
          <span style="padding-left: 15px;">CSO1包</span>
          <span>{{formatNumber(scoreStat.cso1Score)}}分</span>
          <span>{{formatNumber(scoreStat.cso1Count)}}个</span>
        </div>
        <div class="statistic-item-fields">
          <span style="padding-left: 15px;">CSO2包</span>
          <span>{{formatNumber(scoreStat.cso2Score)}}分</span>
          <span>{{formatNumber(scoreStat.cso2Count)}}个</span>
        </div>
        <div class="statistic-item-fields">
          <span>个人包</span>
          <span>{{formatNumber(scoreStat.userScore)}}分</span>
          <span>{{formatNumber(scoreStat.userCount)}}个</span>
        </div>
      </div>
      <div class="statistic-item" style="width: 330px;">
        <div class="statistic-item-title">核准积分包总值</div>
        <div class="statistic-item-value">{{formatNumber(approvedScoreStat.totalScore)}}</div>
        <div class="statistic-item-fields" style="width: 300px;">
          <span>企业包</span>
          <span>{{formatNumber(approvedScoreStat.entScore)}}分</span>
          <span>{{formatNumber(approvedScoreStat.entCount)}}个</span>
          <span>{{formatNumber(approvedScoreStat.entUserCount)}}人</span>
        </div>
        <div class="statistic-item-fields" style="width: 300px;">
          <span style="padding-left: 15px;">CSO1包</span>
          <span>{{formatNumber(approvedScoreStat.cso1Score)}}分</span>
          <span>{{formatNumber(approvedScoreStat.cso1Count)}}个</span>
          <span>{{formatNumber(approvedScoreStat.cso1UserCount)}}人</span>
        </div>
        <div class="statistic-item-fields" style="width: 300px;">
          <span style="padding-left: 15px;">CSO2包</span>
          <span>{{formatNumber(approvedScoreStat.cso2Score)}}分</span>
          <span>{{formatNumber(approvedScoreStat.cso2Count)}}个</span>
          <span>{{formatNumber(approvedScoreStat.cso2UserCount)}}人</span>
        </div>
        <div class="statistic-item-fields" style="width: 300px;">
          <span>个人包</span>
          <span>{{formatNumber(approvedScoreStat.userScore)}}分</span>
          <span>{{formatNumber(approvedScoreStat.userCount)}}个</span>
          <span>{{formatNumber(approvedScoreStat.userUserCount)}}人</span>
        </div>
      </div>
      <div class="statistic-item">
        <div class="statistic-item-title">结算成功积分包总值</div>
        <div class="statistic-item-value">{{formatNumber(settledStat.totalScore)}}分</div>
        <div class="statistic-item-value2">{{formatNumber(settledStat.totalPackages)}}个</div>
      </div>
      <div class="statistic-item">
        <div class="statistic-item-title">结算成功总金额</div>
        <div class="statistic-item-value">{{formatMoney(settledStat.totalAmount)}}元</div>
        <div class="statistic-item-value2">{{formatNumber(settledStat.totalUsers)}}人</div>
        <div class="statistic-item-title">支付成功总金额</div>
        <div class="statistic-item-value">{{formatMoney(settledStat.totalActualAmount)}}元</div>
      </div>
    </div>
    <div class="table-toolbar">
      <div class="table-toolbar-left">
        <el-form inline size="mini" class="no-errors">
          <el-form-item label="显示层级">
            <el-radio-group v-model="showLevel">
              <el-radio-button :label="-1">所有</el-radio-button>
              <el-radio-button :label="0">一级包</el-radio-button>
              <el-radio-button :label="1">二级包</el-radio-button>
              <el-radio-button :label="2">三级包</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <div class="table-toolbar-right">
        <el-button icon="el-icon-download" size="mini" @click="exportXlsx">导出</el-button>
        <columns-select :columns="columns"/>
      </div>
    </div>
    <div>
      <el-table v-loading="loading" :data="data?data.content:[]" style="width: 100%" row-key="rid" border lazy :load="loadChildren" max-height="600">
        <el-table-column prop="no" label="序号" width="120"></el-table-column>
        <el-table-column prop="scorePackageName" label="积分包名称" width="150" v-if="columns[0].visible"></el-table-column>
        <el-table-column prop="sendPackageDept.name" label="发包对象" width="150" v-if="columns[1].visible"></el-table-column>
        <el-table-column prop="receiverName" label="接包对象" width="150" v-if="columns[2].visible"></el-table-column>
        <el-table-column prop="createTime" label="发布日期" width="160" v-if="columns[3].visible"></el-table-column>
        <el-table-column prop="score" label="积分包值" v-if="columns[4].visible">
          <span slot-scope="{row}">{{formatNumber(row.score)}}</span>
        </el-table-column>
        <el-table-column prop="scorePackageStatusLabel" label="积分包状态" width="90" v-if="columns[5].visible"></el-table-column>
        <el-table-column prop="approvedScore" label="核准积分包值" width="80" v-if="columns[6].visible">
          <span slot-scope="{row}">{{formatNumber(row.approvedScore)}}</span>
        </el-table-column>
        <el-table-column prop="packageFinishTime" label="核准时间" width="160" v-if="columns[7].visible"></el-table-column>
        <el-table-column prop="totalAmount" label="结算总金额（元）" width="100" v-if="columns[8].visible">
          <span slot-scope="{row}">{{formatMoney(row.totalAmount)}}{{row.settleCount>1?'('+row.settleCount+')':''}}</span>
        </el-table-column>
        <el-table-column prop="settleActualAmount" label="实际支付金额（元）" width="100" v-if="columns[9].visible">
          <span slot-scope="{row}">{{formatMoney(row.settleActualAmount)}}</span>
        </el-table-column>
        <el-table-column prop="settleNotifyTime" label="结算成功时间" width="160" v-if="columns[10].visible"></el-table-column>
      </el-table>
    </div>
    <div v-if="data" class="pagination-container">
      <el-pagination class="zshk-result-panel-pagination"
                     @current-change="loadData"
                     @size-change="handleSizeChange"
                     :current-page="data.page+1"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next"
                     :total="data.totalElements">
      </el-pagination>
    </div>
  </div>
</template>

<style scoped lang="scss">

</style>
