<template>
  <div class="trial-analysis">
    <div ref="listContainer" v-loading="listLoading" class="list-container">
      <el-table
        height="99%"
        border
        size="small"
        :data="list"
        show-summary
        :summary-method="getSummaries"
        :span-method="objectSpanMethod"
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="Type" label="Type" min-width="130" show-overflow-tooltip />
        <el-table-column prop="TrialCode" label="Trial ID" min-width="100" show-overflow-tooltip />
        <el-table-column
          prop="Expedited"
          min-width="110"
          label="Expedited"
          show-overflow-tooltip
        >
          <template
            slot-scope="scope"
          >{{ scope.row.Expedited==0?'No':scope.row.Expedited==1?'24H':'48H' }}</template>
        </el-table-column>
        <el-table-column prop="Indication" label="Indication" min-width="120" show-overflow-tooltip />
        <el-table-column prop="Cro" label="CRO" min-width="120" show-overflow-tooltip />
        <el-table-column prop="PaymentUSD" label="Payment($)" min-width="120" show-overflow-tooltip>
          <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
        >
          <template slot-scope="scope">
            <div v-if="scope.row.PaymentUSD>0&&scope.row.RevenusUSD==0&&scope.row.TrialCode">
              <span style="color: red">Missing 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
        >
          <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"
        />
      </el-table>
    </div>
  </div>
</template>
<script>
import { getTrialAnalysisList } 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,
      spanArr: [],
      pos: 0
    }
  },
  watch: {
    param: {
      handler(newValue, oldValue) {
        this.listQuery.CroId = newValue.CroId
        this.listQuery.TrialCode = newValue.TrialCode
        this.listQuery.BeginDate = newValue.BeginDate
        this.listQuery.EndDate = newValue.EndDate
        this.listQuery.AttendedReviewerType = newValue.AttendedReviewerType ? newValue.AttendedReviewerType * 1 : ''
      },
      deep: true
    }
  },
  mounted() {
    this.listQuery.CroId = this.param.CroId
    this.listQuery.TrialCode = this.param.TrialCode
    this.listQuery.BeginDate = this.param.BeginDate
    this.listQuery.EndDate = this.param.EndDate
    this.listQuery.AttendedReviewerType = this.param.AttendedReviewerType ? this.param.AttendedReviewerType * 1 : ''
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getTrialAnalysisList(this.listQuery)
        .then(res => {
          this.listLoading = false
          this.list = res.Result
          this.total = res.Result.TotalCount
          this.getSpanArr(this.list)
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    resetList() {
      this.getList()
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      // const scope = this
      columns.forEach((column, index) => {
        if (index === 1) {
          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 floatObj.add(prev, curr)
              } else {
                return prev
              }
            }, 0)
            if (column.property === 'GrossProfitMargin') {
              sums[index] = Number(sums[8]) !== 0 ? ((Number(sums[8]) / Number(sums[7])) * 100).toFixed(2) + '%' : '0.00%'
            } 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) + '%'
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    getSpanArr(data) {
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1)
          this.pos = 0
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].Type === data[i - 1].Type) {
            this.spanArr[this.pos] += 1
            this.spanArr.push(0)
          } else {
            this.spanArr.push(1)
            this.pos = i
          }
        }
      }
    },
    export() {
      const sheetName = `${this.listQuery.BeginDate}--${this.listQuery.EndDate}`
      const columns = [
        { key: 'Index', width: 5 },
        { key: 'Type', width: 15 },
        { key: 'TrialCode', width: 15 },
        { key: 'Expedited', width: 15 },
        { key: 'Indication', width: 15 },
        { key: 'Cro', width: 15 },
        { key: 'PaymentUSD', width: 15 },
        { key: 'RevenusUSD', width: 15 },

        { key: 'GrossProfit', width: 20 },
        { key: 'GrossProfitMargin', width: 25 }
      ]
      let conditional = ''
      if (this.listQuery.CroId) {
        conditional = `Type:Trial CRO:${this.listQuery.CroId}  Beginning Month:${this.listQuery.BeginDate}  End Month:${this.listQuery.EndDate}`
      } else {
        conditional = `Type:Trial  Beginning Month:${this.listQuery.BeginDate}  End Month:${this.listQuery.EndDate}`
      }
      const headerArr = ['', 'Type', 'Trial ID', 'Expedited', 'Indication', 'Cro', 'Payment($)', 'Revenus($)', 'Gross profit($)', 'Gross Profit Margin']
      const numFmts = [
        { colIndex: 7, format: '#,##0.00' },
        { colIndex: 8, format: '#,##0.00' },
        { colIndex: 9, format: '#,##0.00' },
        { colIndex: 10, format: '0.00%' }
      ]
      let payment = 0
      let revenus = 0
      let profit = 0
      var exportExcelData = this.list
      let mergeCount = 0
      let index = 1
      exportExcelData.forEach(element => {
        element.Index = index++
        element.Expedited = element.Expedited === 0 ? 'No' : element.Expedited === 0 ? '24-Hour' : '48-Hour'
        payment += element.PaymentUSD
        revenus += element.RevenusUSD
        profit += element.GrossProfit
        if (element.Type === 'Trial') {
          mergeCount++
        }
      })
      let merge = ''
      if (mergeCount > 1) {
        merge = `B5:B${mergeCount + 4}`
      }
      const totalRow = ['', 'Total', '', '', '', '', payment, revenus, profit, profit / revenus]

      exportExcelWithTotal(sheetName, columns, 'Analysis', conditional, headerArr, exportExcelData, totalRow, numFmts, merge)
    }
  }
}
</script>
<style lang="scss" scoped>
.trial-analysis {
  height: 100%;
  .list-container {
    height: 100%;
    padding: 5px;
    .el-table {
      overflow: visible !important;
    }
  }
}
</style>
