<template>
  <div class="adjustment-list">
    <div class="list-container clearfix">
      <el-table
        ref="adjustList"
        v-loading="listLoading"
        size="small"
        stripe
        :data="list"
        height="99%"
        show-summary
        :summary-method="getSummaries"
        @sort-change="sortByColumn"
        @selection-change="selectMore"
      >
        <el-table-column type="selection" />
        <el-table-column type="index" width="50" />

        <el-table-column
          prop="LastName"
          label="Name"
          min-width="100"
          sortable="custom"
          show-overflow-tooltip
        >
          <template slot-scope="scope">{{ scope.row.LastName + ' / ' + scope.row.FirstName }}</template>
        </el-table-column>
        <el-table-column
          prop="ChineseName"
          label="Name CN"
          min-width="120"
          sortable="custom"
          show-overflow-tooltip
        />
        <el-table-column
          prop="ReviewerCode"
          label="Reviewer ID"
          min-width="110"
          sortable="custom"
          show-overflow-tooltip
        />
        <el-table-column
          prop="AdjustPaymentUSD"
          label="Amount($)"
          min-width="120"
          sortable="custom"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.AdjustPaymentUSD | rounding }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="AdjustPaymentCNY"
          label="Amount(￥)"
          min-width="120"
          sortable="custom"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.AdjustPaymentCNY }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="Note" label="Note" min-width="120" show-overflow-tooltip />
        <el-table-column
          prop="YearMonth"
          label="Adjust Month"
          min-width="120"
          sortable="custom"
          show-overflow-tooltip
        />
      </el-table>
    </div>
    <div class="pagination">
      <pagination :total="total" :page.sync="listQuery.PageIndex" :limit.sync="listQuery.PageSize" @pagination="getList" />
    </div>
  </div>
</template>
<script>
import { FormatTime } from 'utils/formatter.js'
import { getPaymentAdjustmentList } from '@/api/financials'
import { exportExcelWithTotal } from 'utils/export'
import Pagination from '@/components/Pagination'
import floatObj from '@/utils/float-operation'
export default {
  components: { Pagination },
  filters: {
    rounding(value) {
      return value ? Number(value).toFixed(2) : value
    }
  },
  props: {
    param: {
      type: Object,
      default() { return {} }
    }
  },
  data() {
    return {
      listQuery: { PageIndex: 1, PageSize: 20 },
      list: [],
      total: 0,
      arrID: [],
      listLoading: false
    }
  },
  watch: {
    param: {
      handler(newValue, oldValue) {
        this.listQuery.PageIndex = newValue.PageIndex
        this.listQuery.Reviewer = newValue.Reviewer
        this.listQuery.BeginMonth = newValue.BeginMonth
        this.listQuery.EndMonth = newValue.EndMonth
      },
      deep: true
    }
  },
  mounted() {
    this.listQuery.Reviewer = this.param.Reviewer
    this.listQuery.BeginMonth = this.param.BeginMonth
    this.listQuery.EndMonth = this.param.EndMonth
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getPaymentAdjustmentList(this.listQuery).then(res => {
        this.listLoading = false
        this.list = res.Result.CurrentPageData
        this.total = res.Result.TotalCount
      }).catch(() => { this.listLoading = false })
    },
    resetList() {
      this.listQuery.PageIndex = 1
      this.getList()
    },
    selectMore(val) {
      const arr = []
      for (let index = 0; index < val.length; index++) {
        arr.push(val[index].Id)
      }
      this.arrID = arr
    },
    sortByColumn(column) {
      if (column.order === 'ascending') {
        this.listQuery.Asc = true
      } else {
        this.listQuery.Asc = false
      }
      this.listQuery.SortField = column.prop
      this.listQuery.PageIndex = 1
      this.getList()
    },
    errorMonthFormatter(row) {
      return row.ErrorYearMonth ? FormatTime(new Date(row.ErrorYearMonth), 'yyyy-MM') : ''
    },
    adjustMonthFormatter(row) {
      return row.AdjustedYearMonth ? FormatTime(new Date(row.AdjustedYearMonth), 'yyyy-MM') : ''
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      // const scope = this
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = 'Total (Current Page)'
          return
        }
        if (column.property === 'AdjustPaymentUSD') {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values
              .reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return floatObj.add(prev, curr)
                } else {
                  return prev
                }
              }, 0)
          }
        }
        if (column.property === 'AdjustPaymentCNY') {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values
              .reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return floatObj.add(prev, curr)
                } else {
                  return prev
                }
              }, 0)
          }
        }
      })

      return sums
    },
    export() {
      const sheetName = `${this.listQuery.BeginMonth}--${this.listQuery.EndMonth}`
      const columns = [
        { key: 'Index', width: 5 },
        { key: 'LastName', width: 15 },
        { key: 'FirstName', width: 15 },
        { key: 'ChineseName', width: 15 },
        { key: 'ReviewerCode', width: 20 },
        { key: 'AdjustPaymentUSD', width: 15 },
        { key: 'AdjustPaymentCNY', width: 15 },
        { key: 'Note', width: 15 },
        { key: 'AdjustedYearMonth', width: 15 }
      ]
      const conditional = `Type:Adjustment  Beginning Month:${this.listQuery.BeginMonth}  End Month:${this.listQuery.EndMonth}`
      const headerArr = ['', 'Surname', 'Given Name', 'Name CN', 'Reviewer ID', 'Amount($)', 'Amount(¥)', 'Note', 'Adjust Month']
      const numFmts = [
        { colIndex: 6, format: '#,##0.00' },
        { colIndex: 7, format: '#,##0.00' }
      ]
      let totalCNY = 0
      let totalUSD = 0
      let index = 1
      var exportExcelData = this.list.filter(item => this.arrID.indexOf(item.Id) > -1)
      exportExcelData.forEach(element => {
        totalCNY += element.AdjustPaymentCNY
        totalUSD += element.AdjustPaymentUSD
        if (element.AdjustedYearMonth) {
          const date = new Date(element.AdjustedYearMonth)
          element.AdjustedYearMonth = FormatTime(date, 'yyyy-MM')
        }
        element.Index = index++
      })
      const totalRow = ['', 'Total', '', '', '', totalUSD, totalCNY, '', '']
      exportExcelWithTotal(sheetName, columns, 'Payment History', conditional, headerArr, exportExcelData, totalRow, numFmts)
    }
  }
}
</script>
<style lang="scss">
.adjustment-list{
  height: 100%;
  display: flex;
  flex-direction: column;
  .list-container{
    padding: 5px 0px;
    flex: 1;
    .el-table{
      overflow:visible !important;
    }
  }
  .pagination{
    text-align: right;
  }
}
</style>
