<template>
  <div class="reviewer-analysis">
    <div ref="listContainer" v-loading="listLoading" class="list-container">
      <el-table
        size="small"
        stripe
        :data="list"
        show-summary
        :summary-method="getSummaries"
        height="99%"
        @selection-change="handleSelectChange"
      >
        <el-table-column type="selection" />
        <el-table-column type="index" width="50" />

        <el-table-column
          prop="LastName"
          label="Name"
          min-width="120"
          show-overflow-tooltip
          sortable
        >
          <template slot-scope="scope">{{ scope.row.LastName }} / {{ scope.row.FirstName }}</template>
        </el-table-column>
        <el-table-column prop="ChineseName" label="Name CN" min-width="100" show-overflow-tooltip sortable />
        <el-table-column
          prop="ReviewerCode"
          label="Reviewer ID"
          min-width="110"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          prop="PaymentUSD"
          label="Payment($)"
          min-width="120"
          show-overflow-tooltip
          sortable
        >
          <template slot-scope="scope">
            <span>{{ scope.row.PaymentUSD | rounding }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="RevenusUSD" label="Revenus($)" min-width="120" show-overflow-tooltip sortable>
          <template slot-scope="scope">
            <div
              v-if="scope.row.MissingTrialCodes && scope.row.MissingTrialCodes.length>0"
            >
              <span>{{ scope.row.RevenusUSD | rounding }}</span>
              <span
                style="color: red"
              > ({{ scope.row.MissingTrialCodes.join(',') }} need setting trial unit price)</span>
            </div>
            <div v-else>{{ scope.row.RevenusUSD | rounding }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="GrossProfit"
          label="Gross profit($)"
          min-width="120"
          show-overflow-tooltip
          sortable
        >
          <template slot-scope="scope">
            <span>{{ scope.row.GrossProfit | rounding }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="GrossProfitMargin"
          label="Gross Profit Margin"
          min-width="140"
          show-overflow-tooltip
          :formatter="grossProfitMarginFormatter"
          sortable
        />
      </el-table>
    </div>
  </div>
</template>
<script>
import { getReviewerAnalysisList } from '@/api/financials'
import { exportExcelWithTotal } from '@/utils/export'
import floatObj from '@/utils/float-operation'
export default {
  filters: {
    rounding(value) {
      return value ? Number(value).toFixed(2) : value
    }
  },
  props: {
    param: {
      type: Object,
      default() { return {} }
    }
  },
  data() {
    return {
      list: [],
      listQuery: {},
      listLoading: false,
      arrID: []
    }
  },
  watch: {
    param: {
      deep: true,
      handler(newValue, oldValue) {
        console.log(newValue)
        this.listQuery.Reviewer = newValue.Reviewer
        this.listQuery.BeginDate = newValue.BeginDate
        this.listQuery.EndDate = newValue.EndDate
        this.listQuery.Nation = newValue.Nation ? newValue.Nation * 1 : ''
      }
    }
  },
  mounted() {
    this.listQuery.Reviewer = this.param.Reviewer
    this.listQuery.BeginDate = this.param.BeginDate
    this.listQuery.EndDate = this.param.EndDate
    this.listQuery.Nation = this.param.Nation ? this.param.Nation * 1 : ''
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getReviewerAnalysisList(this.listQuery).then(res => {
        this.listLoading = false
        this.list = res.Result
        this.total = res.Result.TotalCount
      }).catch(() => { this.listLoading = false })
    },
    resetList() {
      this.getList()
    },
    getSummaries(param) {
      window.setTimeout(() => {
        if (this.theight === this.height) {
          this.theight -= 0.5
        } else {
          this.theight = this.height
        }
      }, 1000)
      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 === 'PaymentUSD' ||
          column.property === 'RevenusUSD' ||
          column.property === 'GrossProfit' ||
          column.property === 'GrossProfitMargin'
        ) {
          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 prev + curr
                return floatObj.add(prev, curr)
              } else {
                return prev
              }
            }, 0)

            if (column.property === 'GrossProfitMargin') {
              sums[index] = sums[6] === 0 ? '0.00%' : ((Number(sums[7]) / Number(sums[6])) * 100).toFixed(2) + '%'
            } else if (column.property === 'PaymentUSD' || column.property === 'RevenusUSD' || column.property === 'GrossProfit') {
              // sums[index] = Number(sums[index]).toFixed(2)
              sums[index] = Number(sums[index])
            }
          } else {
            sums[index] = ''
          }
        }
      })
      return sums
    },
    grossProfitMarginFormatter(row) {
      return Number(row.GrossProfitMargin * 100).toFixed(2) + '%'
    },
    handleSelectChange(val) {
      const arr = []
      for (let index = 0; index < val.length; index++) {
        arr.push(val[index].ReviewerId)
      }
      this.arrID = arr
      if (this.arrID.length > 0) {
        this.$emit('selectMore', false)
      } else {
        this.$emit('selectMore', true)
      }
    },
    export() {
      const sheetName = `${this.listQuery.BeginDate}--${this.listQuery.EndDate}`
      const columns = [
        { key: 'Index', width: 5 },
        { key: 'LastName', width: 15 },
        { key: 'FirstName', width: 15 },
        { key: 'ChineseName', width: 15 },
        { key: 'ReviewerCode', width: 20 },

        { key: 'PaymentUSD', width: 15 },
        { key: 'RevenusUSD', width: 15 },
        { key: 'GrossProfit', width: 20 },
        { key: 'GrossProfitMargin', width: 25 }
      ]
      const conditional = `Type:Reviewer  Beginning Month:${this.listQuery.BeginDate}  End Month:${this.listQuery.EndDate}`
      const headerArr = [
        '',
        'Surname',
        'Given Name',
        'Name CN',
        'Reviewer ID',
        'Payment($)',
        'Revenus($)',
        'Gross profit($)',
        'Gross Profit Margin'
      ]
      const numFmts = [
        { colIndex: 6, format: '#,##0.00' },
        { colIndex: 7, format: '#,##0.00' },
        { colIndex: 8, format: '#,##0.00' },
        { colIndex: 9, format: '0.00%' }
      ]
      let payment = 0
      let revenus = 0
      let profit = 0
      let index = 1
      var exportExcelData = this.list.filter(item => this.arrID.indexOf(item.ReviewerId) > -1)
      exportExcelData.forEach(element => {
        element.Index = index++
        payment += element.PaymentUSD
        revenus += element.RevenusUSD
        profit += element.GrossProfit
      })
      const totalRow = ['', 'Total', '', '', '', payment, revenus, profit, revenus === 0 ? 0 : profit / revenus]
      exportExcelWithTotal(sheetName, columns, 'Analysis', conditional, headerArr, exportExcelData, totalRow, numFmts)
    }
  }
}
</script>
<style lang="scss" scoped>
.reviewer-analysis{
  height: 100%;
  .list-container{
    height: 100%;
    .el-table{
      overflow:visible !important;
    }
  }
}
</style>
