<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="GetEFFinanceBillGroup()">查看</el-button>
            </el-form-item>
            <el-form-item>
              <el-button @click="OutEFFinanceBillDatail()">导出</el-button>
            </el-form-item></el-form>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="n-row">
      <el-col :span="12">
        <el-card>
          <highcharts :options="grossProfitOptions" />
        </el-card></el-col>
      <el-col :span="12">
        <el-card>
          <highcharts :options="grossProfitRateOptions" />
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="n-row">
      <el-col :span="12">
        <el-card>
          <div slot="header" class="clearfix">
            <span><i class="el-icon-s-data" />客户毛利</span>
            <div class="listSearch">
              <el-form inline>
                <el-form-item>
                  <el-date-picker
                    v-model="searchDto.customerSerachDate"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    value-format="yyyy-MM-dd"
                    end-placeholder="结束日期"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button size="mini" @click="GetEFFinanceBillGroupAsCustomer()">修改</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <ul class="esList">
            <el-table :data="customerData">
              <el-table-column prop="所属客户" label="客户" />
              <el-table-column prop="GrossProfit" label="趋势">
                <template slot-scope="r">
                  <svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="height:30px;widht:120px;cursor: pointer;" @click="getRowdialogCustomerAnalysis(r.row)">
                    <line x1="0" :y1="getY2(r.row)" x2="100" :y2="getY1(r.row)" style="stroke:rgb(124, 181, 236);stroke-width:2" />
                  </svg>
                </template>
              </el-table-column>
              <el-table-column prop="收货重量" label="收货重量" />
              <el-table-column prop="收货单量" label="收货单量" />
              <el-table-column prop="预计收入" label="预计收入" />
              <el-table-column prop="毛利" label="毛利" />
              <el-table-column prop="单件毛利" label="单件毛利" />
              <el-table-column prop="毛利占比" label="毛利率" />
              <el-table-column>
                <template slot-scope="r">
                  <el-button type="text" @click="outEFFinanceBillAsCustomer(r.row)">
                    导出
                  </el-button>
                </template>
              </el-table-column> </el-table></ul>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div slot="header" class="clearfix">
            <span><i class="el-icon-s-data" />渠道毛利</span>
            <div class="listSearch">
              <el-form inline>
                <el-form-item>
                  <el-date-picker
                    v-model="searchDto.channelSearchDate"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    value-format="yyyy-MM-dd"
                    end-placeholder="结束日期"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button size="mini" @click="GetEFFinanceBillGroupAsChannel()">修改</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <ul class="esList">
            <el-table :data="channelData">
              <el-table-column prop="渠道名称" label="渠道" />
              <el-table-column prop="GrossProfit" label="趋势">
                <template slot-scope="r">
                  <svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="height:30px;widht:120px;cursor: pointer;" @click="getRowdialogCustomerAnalysis(r.row)">
                    <line x1="0" :y1="getY2(r.row)" x2="100" :y2="getY1(r.row)" style="stroke:rgb(124, 181, 236);stroke-width:2" />
                  </svg>
                </template>
              </el-table-column>
              <el-table-column prop="收货重量" label="收货重量" />
              <el-table-column prop="收货单量" label="收货单量" />
              <el-table-column prop="预计收入" label="预计收入" />
              <el-table-column prop="毛利" label="毛利" />
              <el-table-column prop="单件毛利" label="单件毛利" />
              <el-table-column prop="毛利占比" label="毛利率" />
              <el-table-column>
                <template slot-scope="r">
                  <el-button type="text" @click="outEFFinanceBillAsChannel(r.row)">
                    导出
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </ul>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog :visible.sync="dialogAnalysisCustomer">
      <highcharts :options="dialogAnalysisCustomerConfig" />
    </el-dialog>
  </div>
</template>
<script>
import { Chart } from 'highcharts-vue'
import { _getCustomers, _getChannel } from '@/api/baseInfo'
import { _getEFFinanceBillGroup, _getEFFinanceBillGroupAsCustomer, _getEFFinanceBillGroupAsChannel, _outEFFinanceBillDatail } from '@/api/estimated'
export default {
  name: 'Estimated',
  components: {
    highcharts: Chart
  },
  data: function() {
    return {
      dialogAnalysisCustomer: false,
      Channels: [],
      FinanceCompanys: [],
      searchDto: {
        DelvieryDate: [], ChannelId: '', SettlementCompany: '', customerSerachDate: [], channelSearchDate: []
      },
      dialogAnalysisCustomerConfig: {
        title: {
          text: '毛利变化'
        },
        yAxis: {
          title: {
            text: '毛利'
          },
          labels: {
            formatter() {
              return this.value / 10000 + '万'
            }
          }
        },
        tooltip: {
          formatter() {
            return this.y / 10000 + '万'
          }
        },
        series: [
          {
            name: '毛利',
            data: []
          },
          {
            name: '趋势',
            data: []
          }],
        xAxis: {
          categories: []
        }

      },
      grossProfitOptions: {
        title: {
          text: '毛利变化'
        },
        yAxis: {
          title: {
            text: '毛利'
          },
          labels: {
            formatter() {
              return this.value / 10000 + '万'
            }
          }
        },
        tooltip: {
          formatter() {
            return this.y / 10000 + '万'
          }
        },
        series: [
          {
            name: '毛利',
            data: []
          },
          {
            name: '趋势',
            data: []
          }],
        xAxis: {
          categories: []
        }

      },
      grossProfitRateOptions: {
        title: {
          text: '毛利率变化'
        },
        yAxis: {
          title: {
            text: '毛利率'
          },
          labels: {
            formatter() {
              return this.value + '%'
            }
          }
        },
        tooltip: {
          formatter() {
            return this.y + '%'
          }
        },
        series: [
          {
            name: '毛利率',
            data: []
          }, {
            name: '趋势',
            data: [] }],
        xAxis: {
          categories: []
        }

      },
      customerData: [

      ],
      channelData: [

      ]
    }
  },
  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.GetEFFinanceBillGroup()
    this.GetEFFinanceBillGroupAsChannel()
    this.GetEFFinanceBillGroupAsCustomer()
    _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
    },
    OutEFFinanceBillDatail() {
      _outEFFinanceBillDatail({
        StartDate: this.searchDto.DelvieryDate[0],
        EndDate: this.searchDto.DelvieryDate[1],
        channelId: this.searchDto.CreateOrderChannelId,
        customerId: this.searchDto.CustomerId })
    },
    GetEFFinanceBillGroup() {
      _getEFFinanceBillGroup({
        StartDate: this.searchDto.DelvieryDate[0],
        EndDate: this.searchDto.DelvieryDate[1],
        channelId: this.searchDto.CreateOrderChannelId,
        customerId: this.searchDto.CustomerId
      }).then(res => {
        var tempArray = []
        var tempFeeArray = []
        var tempRateArray = []
        var tempIndex = []
        for (var i = 0; i < res.length; i++) {
          tempArray[i] = res[i].称重时间
          tempFeeArray[i] = res[i].毛利
          tempRateArray[i] = res[i].毛利占比 * 100
          tempIndex[i] = i + 1
        }
        this.grossProfitOptions.xAxis.categories = tempArray
        this.grossProfitRateOptions.xAxis.categories = tempArray
        this.grossProfitOptions.series[0].data = tempFeeArray
        this.grossProfitOptions.series[1].data = this.findLineByLeastSquares(tempIndex, tempFeeArray)
        this.grossProfitRateOptions.series[0].data = tempRateArray
        this.grossProfitRateOptions.series[1].data = this.findLineByLeastSquares(tempIndex, tempRateArray)
      })
    },
    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
      }
    },
    getRowdialogCustomerAnalysis(row) {
      this.dialogAnalysisCustomer = true
      var tempArray = []
      var tempFeeArray = []
      var tempIndex = []
      var res = row.EveryDayBill
      for (var i = 0; i < res.length; i++) {
        tempArray[i] = res[i].称重时间
        tempFeeArray[i] = res[i].毛利
        tempIndex[i] = i + 1
      }
      this.dialogAnalysisCustomerConfig.xAxis.categories = tempArray
      this.dialogAnalysisCustomerConfig.series[0].data = tempFeeArray
      this.dialogAnalysisCustomerConfig.series[1].data = this.findLineByLeastSquares(tempIndex, tempFeeArray)
    },
    GetEFFinanceBillGroupAsCustomer() {
      _getEFFinanceBillGroupAsCustomer({
        StartDate: this.searchDto.customerSerachDate[0],
        EndDate: this.searchDto.customerSerachDate[1]
      }).then(res => {
        for (var i = 0; i < res.length; i++) {
          var item = res[i]
          for (var j in item) {
            var isKg = false
            var isOri = false
            if (j == '收货重量') { isKg = true }
            if (j == '单件毛利') { isOri = true }
            item[j] = this.getFormat(item[j], isKg, isOri)
          }
        }
        this.customerData = res
      })
    },
    GetEFFinanceBillGroupAsChannel() {
      _getEFFinanceBillGroupAsChannel({
        StartDate: this.searchDto.channelSearchDate[0],
        EndDate: this.searchDto.channelSearchDate[1]
      }).then(res => {
        for (var i = 0; i < res.length; i++) {
          var item = res[i]
          for (var j in item) {
            var isKg = false
            var isOri = false
            if (j == '收货重量') { isKg = true }
            if (j == '单件毛利') { isOri = true }
            item[j] = this.getFormat(item[j], isKg, isOri)
          }
        }
        this.channelData = res
      })
    },
    outEFFinanceBillAsCustomer(row) {
      _outEFFinanceBillDatail({
        StartDate: this.searchDto.customerSerachDate[0],
        EndDate: this.searchDto.customerSerachDate[1],
        channelId: 0,
        customerId: row.CustomerId })
    },
    outEFFinanceBillAsChannel(row) {
      _outEFFinanceBillDatail({
        StartDate: this.searchDto.channelSearchDate[0],
        EndDate: this.searchDto.channelSearchDate[1],
        channelId: row.CreateOrderChannelId,
        customerId: 0 })
    },
    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>
