<template>
  <div v-loading="loading">
    <div class="white-box">
      <div class="filter-box">
        <filter-user :filter-types.sync="filterTypes" filter-btn-name="筛选"
                     @select-value="handleFilterUser"></filter-user>
      </div>
      <el-table :data="tableData" stripe style="width: 100%;" @selection-change="handleSelectionChange"
                :height="tool.getTableHeight()">
        <el-table-column prop="PERIOD_NUM" label="期数">
          <template slot-scope="scope">
            <el-tag type="" size="small" class="no-border">{{scope.row.PERIOD_NUM}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="所在结算月" width="100">
          <template slot-scope="scope">
            <el-tag type="warning" size="small" class="no-border">{{scope.row.CALC_YEAR}}-{{scope.row.CALC_MONTH}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="时间范围" width="260">
          <template slot-scope="scope">
            应开始于：{{tool.formatDate(scope.row.START_TIME)}}<br/>
            应结束于：{{tool.formatDate(scope.row.END_TIME)}}
          </template>
        </el-table-column>
        <el-table-column label="封期时间" width="180">
          <template slot-scope="scope">
            {{tool.formatDate(scope.row.CLOSED_AT)}}
          </template>
        </el-table-column>
        <el-table-column label="业绩单进度" width="90">
          <template slot-scope="scope">
            <el-progress type="circle" :percentage="Number.parseInt(percentList['PERF_PERCENT'][scope.row.ID])"
                         :width="50" :stroke-width="3"></el-progress>
          </template>
        </el-table-column>
        <el-table-column label="生成业绩单时间" width="210">
          <template slot-scope="scope">
            开始：{{tool.formatDate(scope.row.PERF_STARTED_AT)}}<br>
            完成：{{tool.formatDate(scope.row.PERFED_AT)}}
          </template>
        </el-table-column>
        <el-table-column label="结算进度" width="80">
          <template slot-scope="scope">
            <el-progress type="circle" :percentage="Number.parseInt(percentList['CALC_PERCENT'][scope.row.ID])"
                         :width="50" :stroke-width="3"></el-progress>
          </template>
        </el-table-column>
        <el-table-column label="结算时间" width="210">
          <template slot-scope="scope">
            开始：{{tool.formatDate(scope.row.CALCULATE_STARTED_AT)}}<br>
            完成：{{tool.formatDate(scope.row.CALCULATED_AT)}}
          </template>
        </el-table-column>
        <el-table-column label="挂网进度" width="80">
          <template slot-scope="scope">
            <el-progress type="circle" :percentage="Number.parseInt(percentList['SENT_PERCENT'][scope.row.ID])"
                         :width="50" :stroke-width="3"></el-progress>
          </template>
        </el-table-column>
        <el-table-column label="挂网时间" width="210">
          <template slot-scope="scope">
            开始：{{tool.formatDate(scope.row.SEND_STARTED_AT)}}<br/>
            完成：{{tool.formatDate(scope.row.SENT_AT)}}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template slot-scope="scope">
            <el-dropdown size="small" trigger="click" v-if="scope.row.BUTTON_IS_CAN">
              <el-button type="primary" size="small" @click.stop="">
                操作该数据<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="closeHandle(scope.row)"
                                  v-if="scope.row.IS_CAN_CLOSE && permission.hasPermission(`bonus/close-period`)">封期
                </el-dropdown-item>
                <el-dropdown-item @click.native="perfHandle(scope.row)"
                                  v-if="scope.row.IS_PERFING === '0' && scope.row.IS_CAN_PERF && permission.hasPermission(`bonus/perf-period`)">
                  生成业绩单
                </el-dropdown-item>
                <el-dropdown-item @click.native="perfHandle(scope.row)"
                                  v-if="scope.row.IS_PERFING === '1' && scope.row.IS_CAN_PERF && permission.hasPermission(`bonus/perf-period`)">
                  强制生成业绩单
                </el-dropdown-item>
                <el-dropdown-item @click.native="calcHandle(scope.row)"
                                  v-if="scope.row.IS_CALCING === '0' && scope.row.IS_CAN_CALC && permission.hasPermission(`bonus/calc-period`)">
                  结算
                </el-dropdown-item>
                <el-dropdown-item @click.native="calcHandle(scope.row)"
                                  v-if="scope.row.IS_CALCING === '1' && scope.row.IS_CAN_CALC && permission.hasPermission(`bonus/calc-period`)">
                  强制结算
                </el-dropdown-item>
                <el-dropdown-item @click.native="sentHandle(scope.row)"
                                  v-if="scope.row.IS_CAN_SENT && permission.hasPermission(`bonus/send-period`)">
                  挂网
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="white-box-footer">
        <pagination :total="totalCount" :page_size="pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange"></pagination>
      </div>
    </div>
  </div>
</template>

<script>
  import Vue from 'vue'
  import {BONUS_WEBSOCKET_HOST} from '@/utils/config'
  import userInfo from '@/utils/userInfo'
  import network from './../../utils/network'
  import tool from './../../utils/tool'
  import store from '@/utils/vuexStore'
  import FilterUser from '@/components/FilterUser'
  import permission from '@/utils/permission'
  import Pagination from '@/components/Pagination'
  import filterHelper from '../../utils/filterHelper'

  export default {
    name: 'bonus-period',
    components: {FilterUser,Pagination},
    created() {
      let wsServer = BONUS_WEBSOCKET_HOST
      let webSocket = new WebSocket(wsServer)
      webSocket.onopen = function (evt) {
        let userId = userInfo.userId()
        let sendData = {app: 'admin', userId: userId}
        webSocket.send(JSON.stringify(sendData))
      }
      webSocket.onmessage = (env) => {
        let data = JSON.parse(env.data)
        if (data.handle === 'adminAsyncPercent') {
          this.onMessageCallback(data)
        }
      }
    },
    mounted() {
      this.getData(this.currentPage, this.pageSize)
      store.state.socket.onMessageCallback = this.onMessageCallback
    },
    data() {
      return {
        tableData: null,
        loading: true,
        multipleSelection: [],
        currentPage: 1,
        totalPages: 1,
        totalCount: 1,
        pageSize: 10,
        tool: tool,
        permission: permission,
        filterTypes: {
          'periodNum': {isUserTable: false, name: '期数'},
          'year': {isUserTable: false, name: '所在结算年'},
          'month': {isUserTable: false, name: '所在结算月'},
          'startTime': {isUserTable: false, name: '期数开始时间', other: 'date'},
          'endTime': {isUserTable: false, name: '期数结束时间', other: 'date'},
          'closedAt': {isUserTable: false, name: '封期时间', other: 'date'},
          'perfStartedAt': {isUserTable: false, name: '生成业绩单开始时间', other: 'date'},
          'perfedAt': {isUserTable: false, name: '生成业绩单结束时间', other: 'date'},
          'calStartedAt': {isUserTable: false, name: '结算开始时间', other: 'date'},
          'calculatedAt': {isUserTable: false, name: '结算结束时间', other: 'date'},
          'sendStartedAt': {isUserTable: false, name: '挂网开始时间', other: 'date'},
          'sentAt': {isUserTable: false, name: '挂网结束时间', other: 'date'},
        },
        filterModel: {},
        percentList: {
          'PERF_PERCENT': {},
          'CALC_PERCENT': {},
          'SENT_PERCENT': {},
        },
      }
    },
    methods: {
      closeHandle(row) {
        this.$confirm('确定对当前期进行手动封期操作？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return network.getData(`bonus/close-period/${row.PERIOD_NUM}`)
        }).then(response => {
          this.$message({
            message: response,
            type: 'success'
          })
          this.getData(this.currentPage, this.pageSize)
        }).catch(response => {
        })
      },
      calcHandle(row) {
        this.$confirm('确定对当前期进行结算操作？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return network.getData(`bonus/calc-period/${row.PERIOD_NUM}`)
        }).then(response => {
          this.$message({
            message: response,
            type: 'success'
          })
          this.getData(this.currentPage, this.pageSize)
        }).catch(response => {
        })
      },
      perfHandle(row) {
        this.$confirm('确定对当前期进行生成业绩单操作？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return network.getData(`bonus/perf-period/${row.PERIOD_NUM}`)
        }).then(response => {
          this.$message({
            message: response,
            type: 'success'
          })
          this.getData(this.currentPage, this.pageSize)
        }).catch(response => {
        })
      },
      sentHandle(row) {
        this.$confirm('确定对当前期进行挂网操作？挂网后无法生成业绩单和结算', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return network.getData(`bonus/send-period/${row.PERIOD_NUM}`)
        }).then(response => {
          this.$message({
            message: response,
            type: 'success'
          })
          this.getData(this.currentPage, this.pageSize)
        }).catch(response => {
        })
      },
      viewHandle(row) {
        this.$router.push({path: `/bonus/period-detail/${row.PERIOD_NUM}`})
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      handleCurrentChange(page) {
        this.getData(page, this.pageSize)
      },
      handleSizeChange(pageSize) {
        this.getData(this.currentPage, pageSize)
      },
      handleFilterUser(filterData) {
        filterHelper.handleFilterUser(this, filterData)
      },
      handleFilter() {
        this.getData()
      },
      getData(page, pageSize) {
        let filterData = this.filterModel
        let vueObj = this
        network.getPageData(this, 'bonus/period', page, pageSize, filterData, function (response) {
          vueObj.allData = response
        }, null, ['PERF_PERCENT', 'CALC_PERCENT', 'SENT_PERCENT'])
      },
      onMessageCallback(data) {
        if (data) {
          if (data.other && data.other.MODEL === 'PERIOD' && data.other.ID) {
            this.$set(this.percentList[data.other.FIELD], data.other.ID, data.percent)
          }
          if (data.other && data.other.MODEL === 'PERIOD' && data.percent === 100) {
            this.getData(this.currentPage, this.pageSize)
          }
        }
      },
    }
  }
</script>
