<template>
  <div v-loading="loading">
    <div class="white-box">
      <div class="filter-box">
        <filter-user :filter-types="filterTypes" @select-value="handleFilterUser"></filter-user>
      </div>
      <el-table class="table-box" ref="multipleTable" :data="tableData" stripe style="width: 100%;"
                @selection-change="handleSelectionChange" :summary-method="getSummaries" show-summary
                :height="tool.getTableHeight()">
        <el-table-column type="selection" width="70" v-if="tableHeaders"></el-table-column>
        <el-table-column v-for="(tableHeader, key) in tableHeaders" :key="key" :label="tableHeader.header" :width="tableHeader.other.width ? tableHeader.other.width : ''" :prop="tableHeader.other.prop ? tableHeader.other.prop : null">
          <template slot-scope="scope">
            <template v-if="scope.row[tableHeader.index].other.tag" >
              <el-tag :type="scope.row[tableHeader.index].other.tag.type ? scope.row[tableHeader.index].other.tag.type : null" :size="scope.row[tableHeader.index].other.tag.size ? scope.row[tableHeader.index].other.tag.size : null" :class="scope.row[tableHeader.index].other.tag.class ? scope.row[tableHeader.index].other.tag.class : null" >{{scope.row[tableHeader.index].value}}</el-tag>
            </template>
            <template v-else>
              <div v-html="scope.row[tableHeader.index].value"></div>
            </template>
          </template>
        </el-table-column>


      </el-table>
      <div class="white-box-footer">
        <!--<el-button type="primary" size="small" @click="handleSendShow" icon="el-icon-plus"-->
                   <!--v-show="permission.hasPermission(`bonus/cf-lx-apply`)">年度奖申请发放-->
        <!--</el-button>-->
        <el-button type="success" size="small" @click="handleExport" v-show="permission.hasPermission(`bonus/balance-export`)"><!-- 导出Excel -->Export Excel</el-button>
        <pagination :total="totalCount" :page_size="pageSize" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"></pagination>
      </div>
    </div>
    <el-dialog title="Annual award distribution" :visible.sync="dialogVisible" v-loading="dialogLoading"><!-- 年度奖发放 -->
      <el-form :model="form" label-width="250px" class="form-dialog">
        <el-form-item label="Distribution type"><!-- 发放类型 -->
          <el-select v-model="form.sendType" placeholder="Please select the distribution type"><!-- 请选择发放类型 -->
            <el-option v-for="(item,index) in applyTypes" :key="index" :label="item.NAME"
                       :value="item.ID"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Include member status"><!-- 包含会员状态 -->
          <el-select v-model="form.statusValue" placeholder="Please select a status" multiple><!-- 请选择状态 -->
            <el-option v-for="(item,key) in statuses" :label="item.label" :value="item.value" :key="key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Remark"><!-- 备注 -->
          <el-input type="textarea" :row="2" placeholder="Please enter the content" v-model="form.remark"><!-- 请输入内容 --></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false"><!-- 取消 -->cancel</el-button>
        <el-button type="primary" @click.native="handleSend"><!-- 发放 -->grant</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import network from '@/utils/network'
  import tool from '@/utils/tool'
  import baseInfo from '@/utils/baseInfo'
  import FilterUser from '@/components/FilterUser'
  import permission from '@/utils/permission'
  import Pagination from '@/components/Pagination'
  import filterHelper from '@/utils/filterHelper'

  export default {
    name: 'bonus_balance-list',
    components: {FilterUser, Pagination},
    mounted() {
      network.getData('user/status-audit-get-statuses').then(response => {
        this.statuses = response.statuses
        return this.getData()
      })
    },
    data() {
      return {
        tableHeaders: null,
        tableData: null,
        tableHeight: window.innerHeight - 310,
        loading: true,
        multipleSelection: [],
        currentPage: 1,
        totalPages: 1,
        totalCount: 1,
        pageSize: 20,
        tool: tool,
        permission: permission,
        baseDecLevels: baseInfo.decLevels(),
        baseEmpLevels: baseInfo.empLevels(),
        filterTypes: null,
        filterModel: {},
        dialogVisible: false,
        dialogLoading: false,
        statuses: null,
        applyTypes: [
          {'ID': 'all', 'NAME': 'All'},//全部
          {'ID': 'cf', 'NAME': 'Garage endowment'},//车房养老
          {'ID': 'lx', 'NAME': 'Leader bonus'}//领袖分红
        ],
        form: {
          selectedIds: [],
          statusValue: [],
          sendType: null,
          remark: null,
        },
      }
    },
    methods: {
      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)
      },
      getData(page, pageSize) {
        let filterData = this.filterModel
        network.getPageData(this, 'bonus/balance-list', page, pageSize, filterData, response => {
          this.filterTypes = response.filterTypes
          this.allData = response
          this.sumData = response.sumData
        })
      },
      handleSendShow() {
        if (this.multipleSelection.length < 1) {
          this.$message({
            message: 'Please check the member to apply for distribution',//请勾选要申请发放的会员
            type: 'warning'
          })
          return false
        }
        this.dialogVisible = true
      },
      handleSend() {
        this.dialogLoading = true
        this.$message({
          message: 'Applying for distribution, please wait',//正在申请发放请稍后
          type: 'info'
        })
        for (let val of this.multipleSelection) {
          this.form.selectedIds.push(val.USER_ID)
        }
        network.postData(`bonus/cf-lx-apply`,
          this.form
        ).then(response => {
          this.$message({
            message: response,
            type: 'success'
          })
          this.dialogVisible = false
          this.dialogLoading = false
          this.form = {
            selectedIds: [],
            year: null,
            sendType: null,
            remark: null,
          }
          this.getData()
        }).catch(response => {
          this.dialogLoading = false
        })
      },
      getSummaries(param) {
        const {columns, data} = param
        const sums = []
        if (columns && data && columns.length > 0 && data.length > 0) {
          columns.forEach((column, index) => {
            if (index === 0) {
              sums[index] = 'sub-total' + "\n" + 'Total' // '小计' + "\n" + '合计'
              return
            }
            const values = data.map(item => {
              if(typeof item[column.property] === 'object'){
                return Number(item[column.property].value)
              } else {
                return Number(undefined)
              }
            });
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0);
              const field = 'SUM_' + column.property;
              if (typeof this.sumData[field] !== 'undefined') {
                sums[index] = tool.formatPrice(sums[index]) + "\n" + tool.formatPrice(this.sumData[field])
              } else {
                sums[index] = tool.formatPrice(sums[index])
              }
            } else {
              sums[index] = '-'
            }
          })
        }
        return sums
      },
      handleExport(){
        this.$confirm(`Are you sure you want to export the current data？`, 'Hint', {//`确定要导出当前数据吗？`, '提示',
          confirmButtonText: 'confirm',//确定
          cancelButtonText: 'cancel',//取消
          type: 'warning'
        }).then(() => {
          return network.getData(`bonus/balance-export`, this.filterModel)
        }).then(response => {
          this.$message({
            message: response,
            type: 'success'
          })
        }).catch(response => {

        })
      },
    }
  }

</script>

<style scoped>
</style>
