<template>
  <div class="n-app-container">
    <el-row :gutter="20" class="n-row">
      <el-col :span="24">
        <el-card>
          <el-form inline>
            <el-form-item label="发货时间">
              <el-date-picker
                v-model="searchDto.DelvieryDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                value-format="yyyy-MM-dd"
                end-placeholder="结束日期"
              />
            </el-form-item>

            <el-form-item label="下单渠道">
              <el-select v-model="searchDto.CreateOrderChannelId" placeholder="请选择" clearable filterable>
                <el-option
                  v-for="item in Channels"
                  :key="item.Id"
                  :label="item.Name"
                  :value="item.Id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="所属公司">
              <el-select v-model="searchDto.CustomerId" placeholder="请选择" clearable filterable>
                <el-option
                  v-for="item in FinanceCompanys"
                  :key="item.Id"
                  :label="item.CompanyName"
                  :value="item.Id"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="GetFinanceBillDetailWeightDifferenceGroup()">查看</el-button>
            </el-form-item>
            <el-form-item>
              <el-button @click="OutFinanceBillDetailWeightDifferenceDetails()">导出</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <el-row class="n-row" :gutter="30">
      <el-col :span="8">
        <el-card>
          <div slot="header" class="clearfix">
            录入完成率
          </div>
          <el-table :data="differenceTableDto">
            <el-row>
              <el-table-column label="费项" prop="费项" />
              <el-table-column label="差异平均/件" prop="差异平均/件" />
              <el-table-column label="差异平均/KG" prop="差异平均/KG" />
              <el-table-column label="差异率" prop="差异率" />
            </el-row>
          </el-table>
        </el-card>
      </el-col>

      <el-col :span="8">
        <highcharts :options="difference" />
      </el-col>

      <el-col :span="8">
        <highcharts :options="differenceRate" />
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { Chart } from 'highcharts-vue'
import { _getCustomers, _getChannel } from '@/api/baseInfo'
import { _getFinanceBillDetailWeightDifferenceGroup, _outFinanceBillDetailWeightDifferenceDetails } from '@/api/estimated'
import { Loading } from 'element-ui'
export default {
  name: 'Difference',
  components: {
    highcharts: Chart
  },
  data: function() {
    return {
      loading: true,
      dialogAnalysisCustomer: false,
      Channels: [],
      FinanceCompanys: [],
      searchDto: {
        DelvieryDate: [], ChannelId: '', SettlementCompany: '', customerSerachDate: [], channelSearchDate: []
      },
      differenceTableDto: [],
      difference: {
        chart: {
          type: 'column'
        },
        title: {
          text: '成本差异'
        },
        yAxis: {
          title: {
            text: '差异'
          },
          labels: {
            formatter() {
              return this.value
            }
          }
        },
        tooltip: {
          formatter() {
            return this.y
          }
        },
        series: [
          {
            name: '差异平均/件',
            data: []
          },
          {
            name: '差异平均/KG',
            data: []
          }],
        xAxis: {
          categories: []
        }

      },
      differenceRate: {
        chart: {
          type: 'column'
        },
        title: {
          text: '差异率'
        },
        yAxis: {
          title: {
            text: '差异'
          },
          labels: {
            formatter() {
              return this.value * 100 + '%'
            }
          }
        },
        tooltip: {
          formatter() {
            return this.y * 100 + '%'
          }
        },
        series: [
          {
            name: '差异率',
            data: []
          }],
        xAxis: {
          categories: []
        }

      }
    }
  },
  mounted() {
    var end = this.addDays(new Date(), -1)
    var start = this.addDays(end, -6)
    this.searchDto.DelvieryDate = [this.DateFormat(start, 'yyyy-MM-dd'), this.DateFormat(end, 'yyyy-MM-dd')]
    this.searchDto.customerSerachDate = [this.DateFormat(start, 'yyyy-MM-dd'), this.DateFormat(end, 'yyyy-MM-dd')]
    this.searchDto.channelSearchDate = [this.DateFormat(start, 'yyyy-MM-dd'), this.DateFormat(end, 'yyyy-MM-dd')]
    this.GetFinanceBillDetailWeightDifferenceGroup()
    _getCustomers().then(res => {
      this.FinanceCompanys = res
    })
    _getChannel().then(res => {
      this.Channels = res
    })
  },
  methods: {
    addDays(d, days) {
      var adjustDate = new Date(d.getTime() + 24 * 60 * 60 * 1000 * days)
      return adjustDate
    },
    DateFormat(d, format) {
      var date = {
        'M+': d.getMonth() + 1,
        'd+': d.getDate(),
        'h+': d.getHours(),
        'm+': d.getMinutes(),
        's+': d.getSeconds(),
        'q+': Math.floor((d.getMonth() + 3) / 3),
        'S+': d.getMilliseconds()
      }
      if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length))
      }
      for (var k in date) {
        if (new RegExp('(' + k + ')').test(format)) {
          format = format.replace(RegExp.$1, RegExp.$1.length == 1
            ? date[k] : ('00' + date[k]).substr(('' + date[k]).length))
        }
      }
      return format
    },
    OutFinanceBillDetailWeightDifferenceDetails() {
      _outFinanceBillDetailWeightDifferenceDetails({
        StartDate: this.searchDto.DelvieryDate[0],
        EndDate: this.searchDto.DelvieryDate[1],
        channelId: this.searchDto.CreateOrderChannelId,
        customerId: this.searchDto.CustomerId })
    },
    GetFinanceBillDetailWeightDifferenceGroup() {
      var that = this
      var loading = Loading.service()
      _getFinanceBillDetailWeightDifferenceGroup({
        StartDate: this.searchDto.DelvieryDate[0],
        EndDate: this.searchDto.DelvieryDate[1],
        channelId: this.searchDto.CreateOrderChannelId,
        customerId: this.searchDto.CustomerId
      }).then(res => {
        that.difference.xAxis.categories = ['末端派送差异', '营运成本差异', '一级中转差异', '二级中转差异', '出口报关差异', '空运成本差异', '海外清关差异', '关税差异', '海外中转差异', '补贴差异']
        that.difference.series[0].data = [res.末端派送差异_票 * 1, res.营运成本差异_票 * 1, res.一级中转差异_票 * 1, res.二级中转差异_票 * 1,
          res.出口报关差异_票 * 1, res.空运成本差异_票 * 1, res.海外清关差异_票 * 1, res.关税差异_票 * 1, res.海外中转差异_票 * 1, res.补贴差异_票 * 1]
        that.difference.series[1].data = [res.末端派送差异_KG * 1, res.营运成本差异_KG * 1, res.一级中转差异_KG * 1, res.二级中转差异_KG * 1,
          res.出口报关差异_KG * 1, res.空运成本差异_KG * 1, res.海外清关差异_KG * 1, res.关税差异_KG * 1, res.海外中转差异_KG * 1, res.补贴差异_KG * 1]

        that.differenceRate.xAxis.categories = ['末端派送差异', '营运成本差异', '一级中转差异', '二级中转差异', '出口报关差异', '空运成本差异', '海外清关差异', '关税差异', '海外中转差异', '补贴差异']
        that.differenceRate.series[0].data = [res.末端派送差异_比例 * 1, res.营运成本差异_比例 * 1, res.一级中转差异_比例 * 1, res.二级中转差异_比例 * 1,
          res.出口报关差异_比例 * 1, res.空运成本差异_比例 * 1, res.海外清关差异_比例 * 1, res.关税差异_比例 * 1, res.海外中转差异_比例 * 1, res.补贴差异_比例 * 1]

        that.differenceTableDto = [
          { '费项': '末端派送差异', '差异平均/件': res.末端派送差异_票, '差异平均/KG': res.末端派送差异_KG, '差异率': res.末端派送差异_比例 },
          { '费项': '营运成本差异', '差异平均/件': res.营运成本差异_票, '差异平均/KG': res.营运成本差异_KG, '差异率': res.营运成本差异_比例 },
          { '费项': '一级中转差异', '差异平均/件': res.一级中转差异_票, '差异平均/KG': res.一级中转差异_KG, '差异率': res.一级中转差异_比例 },
          { '费项': '二级中转差异', '差异平均/件': res.二级中转差异_票, '差异平均/KG': res.二级中转差异_KG, '差异率': res.二级中转差异_比例 },
          { '费项': '出口报关差异', '差异平均/件': res.出口报关差异_票, '差异平均/KG': res.出口报关差异_KG, '差异率': res.出口报关差异_比例 },
          { '费项': '空运成本差异', '差异平均/件': res.空运成本差异_票, '差异平均/KG': res.空运成本差异_KG, '差异率': res.空运成本差异_比例 },
          { '费项': '海外清关差异', '差异平均/件': res.海外清关差异_票, '差异平均/KG': res.海外清关差异_KG, '差异率': res.海外清关差异_比例 },
          { '费项': '关税差异', '差异平均/件': res.关税差异_票, '差异平均/KG': res.关税差异_KG, '差异率': res.关税差异_比例 },
          { '费项': '海外中转差异', '差异平均/件': res.海外中转差异_票, '差异平均/KG': res.海外中转差异_KG, '差异率': res.海外中转差异_比例 },
          { '费项': '补贴差异', '差异平均/件': res.补贴差异_票, '差异平均/KG': res.补贴差异_KG, '差异率': res.补贴差异_比例 }
        ]
      }).finally(r => {
        loading.close()
      })
    },
    isNumber(obj) {
      return obj === +obj
    },
    getFormat(obj, isKg, isOri) {
      if (isOri) {
        return (Math.round(obj * 100.0)) / 100
      } else if (isKg) {
        if (Math.abs(obj) > 1000) {
          return Math.round(obj / 1.0) * 1 / 1000 + 'T'
        } else {
          return (Math.round(obj * 100.0)) / 100 + 'KG'
        }
      } else if (this.isNumber(obj)) {
        if (Math.abs(obj) > 1000) {
          return (Math.round(obj / 100.0) * 100 / 10000) + '万'
        } else
        if (Math.abs(obj) < 1) {
          if (obj != 0) {
            return (Math.round(obj * 10000.0) / 100) + '%'
          }
        } else {
          if ((obj + '').indexOf('.')) {
            return (Math.round(obj * 100.0)) / 100
          }
          return obj
        }
      } else {
        return obj
      }
    },

    getY(row, start) {
      var tempArray = []
      var tempFee = []
      for (var i = 0; i < row.EveryDayBill.length; i++) {
        tempArray[i] = i + 1
        tempFee[i] = row.EveryDayBill[i].毛利
      }

      var o = this.findLineByLeastSquares(tempArray, tempFee)
      var min = Math.min.apply(null, o)
      if (min < 0) {
      // 存在负坐标时平移坐标
        for (var j = 0; j < o.length; j++) {
          o[j] += Math.abs(min)
        }
      }

      var max = Math.max(o[0], o[o.length - 1])
      var d = max / 20
      if (start == true) {
        return o[0] / d
      } else {
        return o[o.length - 1] / d
      }
    },
    getY1(row) {
      return this.getY(row, true)
    },
    getY2(row) {
      return this.getY(row, false)
    },
    findLineByLeastSquares(values_x, values_y) {
      var sum_x = 0
      var sum_y = 0
      var sum_xy = 0
      var sum_xx = 0
      var count = 0

      /*
     * We'll use those variables for faster read/write access.
     */
      var x = 0
      var y = 0
      var values_length = values_x.length

      if (values_length != values_y.length) {
        throw new Error('The parameters values_x and values_y need to have same size!')
      }

      /*
     * Nothing to do.
     */
      if (values_length === 0) {
        return [[], []]
      }

      /*
     * Calculate the sum for each of the parts necessary.
     */
      for (var v = 0; v < values_length; v++) {
        x = values_x[v]
        y = values_y[v]
        sum_x += x
        sum_y += y
        sum_xx += x * x
        sum_xy += x * y
        count++
      }

      /*
     * Calculate m and b for the formular:
     * y = x * m + b
     */
      var m = (count * sum_xy - sum_x * sum_y) / (count * sum_xx - sum_x * sum_x)
      var b = (sum_y / count) - (m * sum_x) / count

      /*
     * We will make the x and y result line now
     */
      var result_values_x = []
      var result_values_y = []

      for (var v = 0; v < values_length; v++) {
        x = values_x[v]
        y = x * m + b
        result_values_x.push(x)
        result_values_y.push(y)
      }
      return result_values_y
    }
  }
}
</script>
<style scoped>

    .el-card{
        border:none;
        box-shadow: var(--p-card-shadow,0 0 0 1px rgba(63,63,68,.05),0 1px 3px 0 rgba(63,63,68,.15));
        border-radius: var(--p-border-radius-wide,3px);}
 .n-row{margin-bottom:20px;}
 .esList{font-size: 14px;list-style: none;padding:0;margin: 0;}
 .esList li{line-height: 36px;border-bottom: 1px solid #f7f7f7;}
.esList .pull-right{color:#dd4b39;float: right;}
.clearfix span{ color: #4383b4;font-size:16px;line-height: 36px; }
.listSearch{float: right;}
.el-form-item{margin-bottom: 0;}
</style>
