<template>
  <div v-loading="loading">
    <div class="white-box">
      <div class="filter-box">
        <filter-user :filter-types.sync="filterTypes" filter-btn-name="screen"
                     @select-value="handleFilterUser"></filter-user><!-- Select -->
      </div>
      <el-table :data="tableData" stripe style="width: 100%;" @selection-change="handleSelectionChange"
                :height="tool.getTableHeight()">
        <el-table-column prop="PERIOD_NUM" label="Number of periods"><!-- 期数 -->
          <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="Bonus Month" 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="time frame" width="260"><!-- 时间范围 -->
          <template slot-scope="scope">
            <!-- 应开始于 -->Should start on：{{getWatTime(scope.row.START_TIME)}}<br/>
            <!-- 应结束于 -->Should end on：{{getWatTime(scope.row.END_TIME)}}
          </template>
        </el-table-column>
        <el-table-column label="Closing time" width="180"><!-- 封期时间 -->
          <template slot-scope="scope">
            {{getWatTime(scope.row.CLOSED_AT)}}
          </template>
        </el-table-column>
        <el-table-column label="Performance sheet progress" 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="Time of generating performance sheet" width="210"><!-- 生成业绩单时间 -->
          <template slot-scope="scope">
            <!-- 开始 -->start：{{getWatTime(scope.row.PERF_STARTED_AT)}}<br>
            <!-- 完成 -->complete：{{getWatTime(scope.row.PERFED_AT)}}
          </template>
        </el-table-column>
        <el-table-column label="Settlement progress" 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="Date" width="210"><!-- 结算时间 -->
          <template slot-scope="scope">
            <!-- 开始 -->start：{{getWatTime(scope.row.CALCULATE_STARTED_AT)}}<br>
            <!-- 完成 -->complete：{{getWatTime(scope.row.CALCULATED_AT)}}
          </template>
        </el-table-column>
        <el-table-column label="Network connection progress" 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="Network connection time" width="210"><!-- 挂网时间 -->
          <template slot-scope="scope">
            <!-- 开始 -->start：{{getWatTime(scope.row.SEND_STARTED_AT)}}<br/>
            <!-- 完成 -->complete：{{getWatTime(scope.row.SENT_AT)}}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="Action" width="180"><!-- 操作 -->
          <template slot-scope="scope">
            <el-button v-if="scope.row.IS_CAN_CLOSE && permission.hasPermission(`bonus/close-period`)" class="button" type="primary"
                       @click.native="autoPerfHandle(scope.row.PERIOD_NUM)" >
              预计算
            </el-button>
            <el-button v-if="scope.row.IS_CAN_CLOSE && permission.hasPermission(`bonus/close-period`)" type="primary" class="button"
                       @click.native="closeHandle(scope.row)">
              Closure period<!-- 封期 -->
            </el-button>
            <el-button v-if="scope.row.IS_CAN_PERF" type="primary" class="button"
                       @click="dialogTableVisible = true;currentPeriod = scope.row.PERIOD_NUM;getDialogData();">
              操作</el-button>
            <el-button @click.native="sentHandle(scope.row)" type="primary" class="button"
                              v-if="scope.row.IS_CAN_SENT && permission.hasPermission(`bonus/send-period`)">
              <!-- 挂网 -->spread a net
            </el-button>

            <el-dialog :title="`第${currentPeriod}期计算任务日志`" :visible.sync="dialogTableVisible" append-to-body width="60%">
              <el-row><el-button class="button" type="primary" @click.native="getDialogData();dialogLoading=true;" >日志刷新</el-button></el-row>
              <div class="flex">
                <div>
                  <el-table :data="dialogData" height="550" v-loading="dialogLoading">
                    <el-table-column prop="CREATED_AT" label="操作时间" width="180">
                      <template slot-scope="scope">
                        {{tool.formatDate(scope.row.CREATED_AT)}}
                      </template>
                    </el-table-column>
                    <el-table-column prop="TEXT" label="日志内容" width="650"></el-table-column>
                  </el-table>
                </div>
                <div style="margin-left: 15px">
                  <el-row>
                    <el-button class="button" type="success" @click.native="autoCalcHandle(currentPeriod)"
                     v-if="permission.hasPermission(`bonus/calc-period`)"
                    >自动计算</el-button>
                  </el-row>
                  <el-row><el-button class="button" type="primary" @click.native="perfOrderHandle(currentPeriod)" >生成业绩单</el-button></el-row>
                  <el-row><el-button class="button" type="primary" @click.native="initDataHandle(currentPeriod)" >初始化基础数据</el-button></el-row>
                  <el-row><el-button class="button" type="primary" @click.native="perfPeriodHandle(currentPeriod)" >生成期业绩</el-button></el-row>
                  <el-row><el-button class="button" type="primary" @click.native="pullPerfPeriodHandle(currentPeriod)" >拉取期业绩</el-button></el-row>
                  <el-row><el-button class="button" type="primary" @click.native="calcBonusHandle(currentPeriod)" >计算奖金</el-button></el-row>
                  <el-row><el-button class="button" type="primary" @click.native="pullBonusHandle(currentPeriod)" >拉取奖金数据</el-button></el-row>
<!--                  <el-row><el-button class="button" type="primary" @click.native="autoPerfHandle(currentPeriod)" >计算和拉取期业绩</el-button></el-row>-->
                </div>
              </div>
            </el-dialog>

<!--            <el-dropdown size="small" trigger="click" v-if=false>-->
<!--            <el-dropdown size="small" trigger="click" v-if="scope.row.BUTTON_IS_CAN">-->
<!--              <el-button type="primary" size="small" @click.stop="">-->
<!--                &lt;!&ndash; 操作该数据 &ndash;&gt;Action<i class="el-icon-arrow-down el-icon&#45;&#45;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`)">Closure period&lt;!&ndash; 封期 &ndash;&gt;-->
<!--                </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`)">-->
<!--                  &lt;!&ndash; 生成业绩单 &ndash;&gt;Generate performance sheet-->
<!--                </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`)">-->
<!--                  &lt;!&ndash; 强制生成业绩单 &ndash;&gt;Forced generation of performance sheet-->
<!--                </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`)">-->
<!--                  &lt;!&ndash; 结算 &ndash;&gt;settlement-->
<!--                </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`)">-->
<!--                  &lt;!&ndash; 强制结算 &ndash;&gt;Forced settlement-->
<!--                </el-dropdown-item>-->
<!--                <el-dropdown-item @click.native="sentHandle(scope.row)"-->
<!--                                  v-if="scope.row.IS_CAN_SENT && permission.hasPermission(`bonus/send-period`)">-->
<!--                  &lt;!&ndash; 挂网 &ndash;&gt;spread a net-->
<!--                </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>
        <el-button type="primary" size="small" @click="doAutoWithdraw()">
          批量提现
        </el-button>
      </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 {
      currentPeriod: 0,
      tableData: null,
      loading: true,
      multipleSelection: [],
      currentPage: 1,
      totalPages: 1,
      totalCount: 1,
      pageSize: 10,
      tool: tool,
      permission: permission,
      filterTypes: {
        'periodNum': {isUserTable: false, name: 'Number of periods'}, // 期数
        'year': {isUserTable: false, name: 'Bonus Year'}, // 所在结算年
        'month': {isUserTable: false, name: 'Bonus Month'}, // 所在结算月
        'startTime': {isUserTable: false, name: 'Period start time', other: 'date'}, // 期数开始时间
        'endTime': {isUserTable: false, name: 'Period end time', other: 'date'}, // 期数结束时间
        'closedAt': {isUserTable: false, name: 'Closing time', other: 'date'}, // 封期时间
        'perfStartedAt': {isUserTable: false, name: 'Start time of generating performance sheet', other: 'date'}, // 生成业绩单开始时间
        'perfedAt': {isUserTable: false, name: 'End time of generating performance sheet', other: 'date'}, // 生成业绩单结束时间
        'calStartedAt': {isUserTable: false, name: 'Settlement start time', other: 'date'}, // 结算开始时间
        'calculatedAt': {isUserTable: false, name: 'Settlement end time', other: 'date'}, // 结算结束时间
        'sendStartedAt': {isUserTable: false, name: 'Network connection start time', other: 'date'}, // 挂网开始时间
        'sentAt': {isUserTable: false, name: 'End time of network connection', other: 'date'} // 挂网结束时间
      },
      filterModel: {},
      percentList: {
        'PERF_PERCENT': {},
        'CALC_PERCENT': {},
        'SENT_PERCENT': {}
      },
      dialogTableVisible: false,
      dialogData: null,
      currentDialogPage: 1,
      dialogPageSize: 100,
      dialogLoading: true,
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      formLabelWidth: '120px'
    };

  },
  methods: {
    autoCalcHandle(currentPeriod) {
      this.$confirm('Confirm to perform settlement operation for the auto current period？', 'Hint', { // '确定对当前期进行结算操作？', '提示'
        confirmButtonText: 'confirm', // 确定
        cancelButtonText: 'cancel', // 取消
        type: 'warning'
      }).then(() => {
        return network.getData(`calc/auto-calc/${currentPeriod}`)
      }).then(response => {
        this.$message({
          message: response,
          type: 'success'
        })
        this.getDialogData(this.currentPage, this.pageSize)
      }).catch(response => {
      })
    },
    perfOrderHandle(currentPeriod) {
      this.$confirm('Confirm to generate performance order for the current period？', 'Hint', { // '确定对当前期进行生成业绩单操作？', '提示'
        confirmButtonText: 'confirm', // 确定
        cancelButtonText: 'cancel', // 取消
        type: 'warning'
      }).then(() => {
        return network.getData(`calc/perf-order/${currentPeriod}`)
      }).then(response => {
        this.$message({
          message: response,
          type: 'success'
        })
        this.getDialogData(this.currentPage, this.pageSize)
      }).catch(response => {
      })
    },
    initDataHandle(currentPeriod) {
      this.$confirm('Confirm to generate performance sheet for the current period？', 'Hint', { // '确定对当前期进行生成业绩单操作？', '提示'
        confirmButtonText: 'confirm', // 确定
        cancelButtonText: 'cancel', // 取消
        type: 'warning'
      }).then(() => {
        return network.getData(`calc/init-data/${currentPeriod}`)
      }).then(response => {
        this.$message({
          message: response,
          type: 'success'
        })
        this.getDialogData(this.currentPage, this.pageSize)
      }).catch(response => {
      })
    },
    perfPeriodHandle(currentPeriod) {
      this.$confirm('Confirm to generate performance sheet for the current period？', 'Hint', { // '确定对当前期进行生成业绩单操作？', '提示'
        confirmButtonText: 'confirm', // 确定
        cancelButtonText: 'cancel', // 取消
        type: 'warning'
      }).then(() => {
        return network.getData(`calc/calc-perf-period/${currentPeriod}`)
      }).then(response => {
        this.$message({
          message: response,
          type: 'success'
        })
        this.getDialogData(this.currentPage, this.pageSize)
      }).catch(response => {
      })
    },
    pullPerfPeriodHandle(currentPeriod) {
      this.$confirm('Confirm to pull performance sheet for the current period？', 'Hint', { // '确定对当前期进行生成业绩单操作？', '提示'
        confirmButtonText: 'confirm', // 确定
        cancelButtonText: 'cancel', // 取消
        type: 'warning'
      }).then(() => {
        return network.getData(`calc/pull-perf-period/${currentPeriod}`)
      }).then(response => {
        this.$message({
          message: response,
          type: 'success'
        })
        this.getDialogData(this.currentPage, this.pageSize)
      }).catch(response => {
      })
    },
    calcBonusHandle(currentPeriod) {
      this.$confirm('Confirm to calculate bonus data for the current period？', 'Hint', { // '确定对当前期进行生成业绩单操作？', '提示'
        confirmButtonText: 'confirm', // 确定
        cancelButtonText: 'cancel', // 取消
        type: 'warning'
      }).then(() => {
        return network.getData(`calc/calc-bonus/${currentPeriod}`)
      }).then(response => {
        this.$message({
          message: response,
          type: 'success'
        })
        this.getDialogData(this.currentPage, this.pageSize)
      }).catch(response => {
      })
    },
    calcBonusRecordHandle(currentPeriod) {
      this.$confirm('Confirm to sync calculate bonus record for the current period？', 'Hint', { // '确定对当前期进行生成业绩单操作？', '提示'
        confirmButtonText: 'confirm', // 确定
        cancelButtonText: 'cancel', // 取消
        type: 'warning'
      }).then(() => {
        return network.getData(`calc/sync-calc-record/${currentPeriod}`)
      }).then(response => {
        this.$message({
          message: response,
          type: 'success'
        })
        this.getDialogData(this.currentPage, this.pageSize)
      }).catch(response => {
      })
    },
    pullBonusHandle(currentPeriod) {
      this.$confirm('Confirm to calculate bonus data for the current period？', 'Hint', { // '确定对当前期进行生成业绩单操作？', '提示'
        confirmButtonText: 'confirm', // 确定
        cancelButtonText: 'cancel', // 取消
        type: 'warning'
      }).then(() => {
        return network.getData(`calc/pull-bonus/${currentPeriod}`)
      }).then(response => {
        this.$message({
          message: response,
          type: 'success'
        })
        this.getDialogData(this.currentPage, this.pageSize)
      }).catch(response => {
      })
    },
    autoPerfHandle (currentPeriod) {
      this.$confirm('Confirm to calculate bonus data for the current period？', 'Hint', { // '确定对当前期进行生成业绩单操作？', '提示'
        confirmButtonText: 'confirm', // 确定
        cancelButtonText: 'cancel', // 取消
        type: 'warning'
      }).then(() => {
        return network.getData(`calc/auto-perf/${currentPeriod}`)
      }).then(response => {
        this.$message({
          message: response,
          type: 'success'
        })
        this.getDialogData(this.currentPage, this.pageSize)
      }).catch(response => {
      })
    },

    getDialogData () {
      let vueObj = this
      let paramsData = {
        page: this.currentDialogPage,
        pageSize: this.dialogPageSize,
      }
      network.getData('calc/record-list/' + this.currentPeriod, paramsData)
        .then(response => {
          vueObj.dialogData = response.list
          vueObj.dialogLoading = false;
        }).catch(response => {
          this.$message({
            message: response,
            type: 'fail'
          })
        })
    },

    closeHandle (row) {
      this.$confirm('Confirm to manually seal the current period？', 'Hint', { // '确定对当前期进行手动封期操作？', '提示'
        confirmButtonText: 'confirm', // 确定
        cancelButtonText: 'cancel', // 取消
        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('Confirm to perform settlement operation for the current period？', 'Hint', { // '确定对当前期进行结算操作？', '提示'
        confirmButtonText: 'confirm', // 确定
        cancelButtonText: 'cancel', // 取消
        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('Confirm to generate performance sheet for the current period？', 'Hint', { // '确定对当前期进行生成业绩单操作？', '提示'
        confirmButtonText: 'confirm', // 确定
        cancelButtonText: 'cancel', // 取消
        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('Are you sure to connect the current period? Performance sheet and settlement cannot be generated after network connection', 'Hint', { // '确定对当前期进行挂网操作？挂网后无法生成业绩单和结算', '提示'
        confirmButtonText: 'confirm', // 确定
        cancelButtonText: 'cancel', // 取消
        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 => {
      })
    },
    doAutoWithdraw () {
      this.$confirm('全部提现？', 'Hint', {
        confirmButtonText: 'confirm', // 确定
        cancelButtonText: 'cancel', // 取消
        type: 'warning'
      }).then(() => {
        return network.getData(`bonus/auto-withdraw`)
      }).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)
        }
      }
    },
    getWatTime (ts) {
      ts = parseInt(ts)
      if (ts) {
        return this.$moment(ts * 1000).utcOffset('+0100' ).format('YYYY-MM-DD HH:mm:ss')
      } else {
        return ''
      }
    }
  }
}
</script>
<style>
.flex{
  display: flex;
}
.button{
  margin-bottom: 10px;
}
.el-table__body {
-webkit-border-horizontal-spacing: -30px;
-webkit-border-vertical-spacing: -30px;
}
</style>
