<template>
  <div class="main-div" style="position: relative;background: #f5f5f5;min-width: 1300px;">
    <Modal
      v-model="btDataShow"
      title="自定义时间区间">
      <DatePicker type="daterange" v-model="btDate" placeholder="请选择" style="width: 100%" confirm @on-ok="btOk"></DatePicker>
      <div slot="footer"></div>
    </Modal>
    <div style="z-index: 10;box-shadow: 0px 2px 5px #c5c5c575;display: flex;height: 50px;width: 100%;align-items: center;padding: 0 20px;position: fixed;top: 40px;background: #fff;">
      <DatePicker ref="date-picker" @on-change="onChangeDate" :editable="false" v-model="date" :clearable="false" placement="bottom-start" type="month" :format="format" :options="options2" placeholder="Select date" style="width: 200px"></DatePicker>

      <SelectPop v-model="orgIds" ref="orgIds" :multiple="true" style="width:250px;margin-left: 10px"
                 @on-change="changeSearch"
                 :options="orgList"
                 :title="$t('orgId')"
                 labelKey="name"
                 valueKey=id>
      </SelectPop>
      <Button style="margin-left: 5px;" type="success" @click="getReport()">{{$t('refreshReport')}}</Button>
      <Button style="margin-left: 5px;" type="success" @click="exportAll()">导出报表</Button>
<!--      v-if="$libaray.checkButtonHasRight('report-sales-kit-export')"-->

    </div>
    <div style="height: 50px;"></div>
    <!--  浮窗可能不明显先注释掉吧 然后没做完全 只做个大概  -->
<!--    <div :class="(searchModalFlag?'search-modal-true':'search-modal-false') + ' search-modal'">-->
<!--      <div v-show="!searchModalFlag" style="width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;" @click="searchModalFlag = true">-->
<!--        <Icon type="ios-search" color="#fff" size="24"/>-->
<!--      </div>-->
<!--      <div v-show="searchModalFlag" style="width: 100%;height: 100%;display: flex;position: relative;" >-->
<!--        <div style="position:absolute;top: 5px;right: 5px;" @click="searchModalFlag = false">-->
<!--          <Icon type="ios-close" color="#7f7f7f" size="24"/>-->
<!--        </div>-->
<!--        <DatePicker type="month" v-model="date" format="yyyy年MM月" :clearable="false" placeholder="Select date" style="width: 200px"></DatePicker>-->
<!--      </div>-->
<!--    </div>-->

    <div class="line">
      <!--   销售分析   -->
      <div class="line-item">

        <div class="line-item-inner">
          <Spin size="large" v-if="loading" fix ></Spin>

          <div class="title">
            <div class="left">
              <img :src="icon" style="width: 30px;height: 30px"/>
              <div>销售分析</div>
              <a class="single-export" @click="exportSingle('sale')">导出</a>
            </div>
            <div class="right" @click="clickDetail('order-analysis')">
              <div>详情</div>
              <Icon type="ios-arrow-forward"/>
            </div>
          </div>
          <div class="content">
            <div class="top">
              <div class="left">
                <span class="amount">
                  <span class="cny">￥</span>
                  <span class="number">{{ toFixAndToLocaleString(orderAnalysis.sumAmount/10000) }}</span>
                </span>
                <span class="text">成交额(万)</span>
                <span class="yay-mam">
                  同比<span class="yy">{{orderAnalysis.mmRate}}%</span>环比<span class="mm">{{orderAnalysis.yyRate}}%</span>
                </span>
              </div>
            </div>
            <div class="bottom">
              <div class="bottom-line">
                <div class="bottom-line-item bottom-line-item2">
                  <span class="top"><span class="cny">￥</span>{{toFixAndToLocaleString(orderAnalysis.rejectAmount/10000)}}</span>
                  <span class="bottom">退货额(万)</span>
                </div>
                <div class="bottom-line-item bottom-line-item2">
                  <span class="top"><span class="cny">￥</span>{{ toFixAndToLocaleString(orderAnalysis.outAmount/10000) }}</span>
                  <span class="bottom">出库额(万)</span>
                </div>
              </div>
              <div class="bottom-line">
                <div class="bottom-line-item bottom-line-item2">
                  <span class="top">{{ orderAnalysis.csmCount }}</span>
                  <span class="bottom">成交户数</span>
                </div>
                <div class="bottom-line-item bottom-line-item2">
                  <span class="top"><span class="cny">￥</span>{{ toFixAndToLocaleString(orderAnalysis.csmUnitPrice/10000) }}</span>
                  <span class="bottom">客单价(万)</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--   收款分析   -->
      <div class="line-item">
        <div class="line-item-inner">
          <Spin size="large" v-if="loading" fix ></Spin>
          <div class="title">
            <div class="left">
              <img :src="icon" style="width: 30px;height: 30px"/>
              <div>收款分析</div>
              <a class="single-export" @click="exportSingle('received')">导出</a>
            </div>
            <div class="right" @click="clickDetail('collection-analysis')">
              <div>详情</div>
              <Icon type="ios-arrow-forward"/>
            </div>
          </div>
          <div class="content">
            <div class="top">
              <div class="left">
                <span class="amount">
                  <span class="cny">￥</span>
                  <span class="number">{{toFixAndToLocaleString(repayAnalysis.repayAmount/10000)}}</span>
                </span>
                <span class="text">收款额(万)</span>
              </div>
            </div>
            <div class="bottom">
              <div class="bottom-line" style="height: 100%">
                <div class="bottom-line-item" style="width: calc(50% - 5px);padding: 26px 0;">
                  <span class="top"><span class="cny">￥</span>{{toFixAndToLocaleString(repayAnalysis.debtAmount/10000)}}</span>
                  <span class="bottom">欠款额(万)</span>
                </div>
                <div class="bottom-line-item" style="width: calc(50% - 5px);padding: 26px 0;">
                  <span class="top">{{repayAnalysis.debtCount}}</span>
                  <span class="bottom">欠款户数</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--   客户分析   -->
      <div class="line-item">
        <div class="line-item-inner">
          <Spin size="large" v-if="loading" fix ></Spin>
          <div class="title">
            <div class="left">
              <img :src="icon" style="width: 30px;height: 30px"/>
              <div>客户分析</div>
              <a class="single-export" @click="exportSingle('customerAnalysis')">导出</a>
            </div>
            <div class="right" @click="clickDetail('customer-analysis')">
              <div>详情</div>
              <Icon type="ios-arrow-forward"/>
            </div>
          </div>
          <div class="content">
            <div class="bottom" style="height: calc(100% - 20px); padding-top: 10px">
              <div class="bottom-line">
                <div class="bottom-line-item bottom-line-item1">
                  <span class="top">{{csmAnalysisHome.csmCount}}</span>
                  <span class="bottom">新增潜客数</span>
                </div>
              </div>
              <div class="bottom-line">
                <div class="bottom-line-item bottom-line-item2">
                  <span class="top">{{csmAnalysisHome.agreedMmeasureCount}}</span>
                  <span class="bottom">约尺客户数</span>
                </div>
                <div class="bottom-line-item bottom-line-item2">
                  <span class="top">{{csmAnalysisHome.completeMmeasureCount}}</span>
                  <span class="bottom">量尺客户数</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="line">
      <div class="line-item">
        <div class="line-item-inner">
          <Spin size="large" v-if="loading" fix ></Spin>

          <div class="title">
            <div class="left">
              <img :src="icon" style="width: 30px;height: 30px"/>
              <div>客户来源分布</div>
              <a class="single-export" @click="exportSingle('customerFrom')">导出</a>
            </div>
            <div class="right" @click="clickDetail('customer-from-analysis')">
              <div>详情</div>
              <Icon type="ios-arrow-forward"/>
            </div>
          </div>
          <div class="content">
            <div class="top" style="height: 30%;">
              <div class="left">
                <span class="amount" style="display: inline;">
                  <span class="cny">￥</span>
                  <span class="number">{{toFixAndToLocaleString(csmFromOrder.sumAmount/10000)}}</span>
                </span>
                <span class="text" style="display: inline;">成交额(万)</span>
              </div>
            </div>
            <div class="bottom" style="height: calc(70% - 10px);">
              <div id="echarts-khlyfb" style="height: 100%;width: 100%"></div>
            </div>
          </div>
        </div>
      </div>

      <div class="line-item">
        <div class="line-item-inner">
          <Spin size="large" v-if="loading" fix ></Spin>

          <div class="title">
            <div class="left">
              <img :src="icon" style="width: 30px;height: 30px"/>
              <div>产品分布</div>
              <a class="single-export" @click="exportSingle('product')">导出</a>

            </div>
            <div class="right" @click="clickDetail('product-analysis')">
              <div>详情</div>
              <Icon type="ios-arrow-forward"/>
            </div>
          </div>
          <div class="content">
            <div class="top" style="height: 30%;">
              <div class="left">
                <span class="amount" style="display: inline;">
                  <span class="cny">￥</span>
                  <span class="number">{{toFixAndToLocaleString(spuAnalysis.sumAmount/10000)}}</span>
                </span>
                <span class="text" style="display: inline;">成交额(万)</span>
              </div>
            </div>
            <div class="bottom" style="height: calc(70% - 10px);">
              <div id="echarts-cpfb" style="height: 100%;width: 100%"></div>
            </div>
          </div>
        </div>
      </div>

      <div class="line-item">
        <div class="line-item-inner">
          <Spin size="large" v-if="loading" fix ></Spin>

          <div class="title">
            <div class="left">
              <img :src="icon" style="width: 30px;height: 30px"/>
              <div>部门成交排行</div>
              <a class="single-export" @click="exportSingle('departmentTransactionRanking')">导出</a>
            </div>
            <div class="right"  @click="clickDetail('org-order-rank')">
              <div>详情</div>
              <Icon type="ios-arrow-forward"/>
            </div>
          </div>
          <div class="content">
            <div class="top" style="height: 30%;">
              <div class="left">
                <span class="amount" style="display: inline;">
                  <span class="cny">￥</span>
                  <span class="number">{{toFixAndToLocaleString(indexOrgOrder.sumAmount/10000)}}</span>
                </span>
                <span class="text" style="display: inline;">成交额(万)</span>
              </div>
            </div>
            <div class="bottom" style="height: calc(70% - 10px);">
              <div id="echarts-bmcjph" style="height: 100%;width: 100%"></div>
            </div>
          </div>
        </div>
      </div>

    </div>

    <div class="line">
      <div class="line-item">
        <div class="line-item-inner">
          <Spin size="large" v-if="loading" fix ></Spin>
          <div class="title">
            <div class="left">
              <img :src="icon" style="width: 30px;height: 30px"/>
              <div>部门收款排行</div>
              <a class="single-export" @click="exportSingle('departmentCollectionRanking')">导出</a>

            </div>
            <div class="right"  @click="clickDetail('org-repay-rank')">
              <div>详情</div>
              <Icon type="ios-arrow-forward"/>
            </div>
          </div>
          <div class="content">
            <div class="top" style="height: 30%;">
              <div class="left">
                <span class="amount" style="display: inline;">
                  <span class="cny">￥</span>
                  <span class="number">{{toFixAndToLocaleString(indexOrgRepay.sumAmount/10000)}}</span>
                </span>
                <span class="text" style="display: inline;">收款额(万)</span>
              </div>
            </div>
            <div class="bottom" style="height: calc(70% - 10px);">
              <div id="echarts-bmskph" style="height: 100%;width: 100%"></div>
            </div>
          </div>
        </div>
      </div>

      <div class="line-item">
        <div class="line-item-inner">
          <Spin size="large" v-if="loading" fix ></Spin>

          <div class="title">
            <div class="left">
              <img :src="icon" style="width: 30px;height: 30px"/>
              <div>业务员成交排行</div>
              <a class="single-export" @click="exportSingle('staffTransactionRanking')">导出</a>

            </div>
            <div class="right"  @click="clickDetail('staff-order-rank')">
              <div>详情</div>
              <Icon type="ios-arrow-forward"/>
            </div>
          </div>
          <div class="content">
            <div class="top" style="height: 30%;">
              <div class="left">
                <span class="amount" style="display: inline;">
                  <span class="cny">￥</span>
                  <span class="number">{{toFixAndToLocaleString(indexStaffOrder.sumAmount/10000)}}</span>
                </span>
                <span class="text" style="display: inline;">成交额(万)</span>
              </div>
            </div>
            <div class="bottom" style="height: calc(70% - 10px);">
              <div id="echarts-ywycjph" style="height: 100%;width: 100%"></div>
            </div>
          </div>
        </div>
      </div>

      <div class="line-item">
        <div class="line-item-inner">
          <Spin size="large" v-if="loading" fix ></Spin>

          <div class="title">
            <div class="left">
              <img :src="icon" style="width: 30px;height: 30px"/>
              <div>业务员收款排行</div>
              <a class="single-export" @click="exportSingle('staffCollectionRanking')">导出</a>

            </div>
            <div class="right"  @click="clickDetail('staff-repay-rank')">
              <div>详情</div>
              <Icon type="ios-arrow-forward"/>
            </div>
          </div>
          <div class="content">
            <div class="top" style="height: 30%;">
              <div class="left">
                <span class="amount" style="display: inline;">
                  <span class="cny">￥</span>
                  <span class="number">{{toFixAndToLocaleString(indexStaffRepay.sumAmount/10000)}}</span>
                </span>
                <span class="text" style="display: inline;">收款额(万)</span>
              </div>
            </div>
            <div class="bottom" style="height: calc(70% - 10px);">
              <div id="echarts-ywyskph" style="height: 100%;width: 100%"></div>
            </div>
          </div>
        </div>
      </div>
    </div>


    <Drawer title="报表明细" width="520" :closable="false" v-model="detailFlag">
      <div style="padding: 10px;width: 500px;">
        <OrderAnalysis v-show="type === 'order-analysis'" ref="order-analysis"></OrderAnalysis>
        <CollectionAnalysis v-show="type === 'collection-analysis'" ref="collection-analysis"></CollectionAnalysis>
        <CustomerAnalysis v-show="type === 'customer-analysis'" ref="customer-analysis"></CustomerAnalysis>
        <CustomerFromAnalysis v-show="type === 'customer-from-analysis'" ref="customer-from-analysis"></CustomerFromAnalysis>
        <ProductAnalysis v-show="type === 'product-analysis'" ref="product-analysis"></ProductAnalysis>
        <OrgOrderRank v-show="type === 'org-order-rank'" ref="org-order-rank"></OrgOrderRank>
        <OrgRepayRank v-show="type === 'org-repay-rank'" ref="org-repay-rank"></OrgRepayRank>
        <StaffOrderRank v-show="type === 'staff-order-rank'" ref="staff-order-rank"></StaffOrderRank>
        <StaffRepayRank v-show="type === 'staff-repay-rank'" ref="staff-repay-rank"></StaffRepayRank>
      </div>
    </Drawer>
  </div>
</template>

<script>
import './index.less'
import icon from '@/assets/images/func-icon.png'
import echartsJs from './echarts.js'
import wxProcess from '@/components/process/index.vue'
import { OrderAnalysis,CollectionAnalysis,CustomerAnalysis,CustomerFromAnalysis,ProductAnalysis,OrgOrderRank,OrgRepayRank,StaffOrderRank,StaffRepayRank } from './details'
import util from "@/view/report/sales-kit/details/util";
import store from '@/store'


export default {
  name: "sales-kit",
  components:{
    OrderAnalysis,CollectionAnalysis,CustomerAnalysis,CustomerFromAnalysis,ProductAnalysis,OrgOrderRank,OrgRepayRank,StaffOrderRank,StaffRepayRank,wxProcess
  },
  data() {
    let _self = this
    return {
      dateType:3,
      format:'本月',
      options2: {
        shortcuts: [
          {
            text: '本日',
            onClick(){
              _self.$refs['date-picker'].visible = false
              _self.format = '本日'
              _self.dateType = 1
              _self.getReport()
            }
          },
          {
            text: '本周',
            onClick(){
              _self.$refs['date-picker'].visible = false
              _self.format = '本周'
              _self.dateType = 2
              _self.getReport()
            }
          },
          {
            text: '本月',
            onClick(){
              _self.$refs['date-picker'].visible = false
              _self.format = '本月'
              _self.dateType = 3
              _self.getReport()

            }
          },
          {
            text: '本年',
            onClick(){
              _self.$refs['date-picker'].visible = false
              _self.format = '本年'
              _self.dateType = 5
              _self.getReport()
            }
          },
          {
            text: '区间',
            onClick(){
              _self.$refs['date-picker'].visible = false
              // _self.format = '区间'
              _self.dateType = 6
              _self.btDataShow = true
              // _self.getReport()
            }
          }
        ]
      },
      date:new Date(),
      type:null,
      icon,
      tabs:[],
      loading:false,
      detailFlag:false,
      dateRange:[],
      orgIds:[],
      orgList:[],
      staffIds:[],
      staffList:[],
      searchModalFlag:false,
      orderAnalysis :{},
      repayAnalysis :{},
      csmAnalysisHome:{},
      csmFromOrder :{},
      spuAnalysis :{},
      indexOrgOrder :{},
      indexOrgRepay:{},
      indexStaffOrder:{},
      indexStaffRepay:{},
      btDate:[],
      btDataShow:false
    }
  },
  methods: {
    btOk(){
      this.format = '区间：'+this.btDate[0].format('yyyy-MM-dd') + '-' + this.btDate[1].format('yyyy-MM-dd')
      this.btDataShow = false
      this.getReport()
    },
    /* 单独导出方法 */
    exportSingle(type){
      const enumType = {
        sale:"销售简报-销售分析",
        received:"销售简报-收款分析",
        customerAnalysis:"销售简报-客户分析",
        customerFrom:"销售简报-客户来源分布",
        product:"销售简报-产品分布",
        departmentTransactionRanking:"销售简报-部门成交排行",
        departmentCollectionRanking:"销售简报-部门收款排行",
        staffTransactionRanking:"销售简报-业务员成交排行",
        staffCollectionRanking:"销售简报-业务员收款排行"
      }
      this.doExport([type],enumType[type])
    },
    onChangeDate(){
      this.format = 'yyyy年MM月'
      this.dateType = 0
      // this.getReport()
    },
    getDateStr(now) {
      let year = now.getFullYear(); // 年
      let month = now.getMonth() + 1; // 月
      let day = now.getDate(); // 日
      if(day < 10) {
        day = '0' + day;
      }

      if(month < 10) {
        month = '0' + month;
      }
      return year + "-" + month + "-" + day;
    },
    echarts(id,data) {
      let echarts = require('echarts')
      let echarts_div = echarts.init(document.getElementById(id))
      echarts_div.setOption(
        data
      )
    },
    getDateSingle(date){
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      return [year, month, day].map(n => {
        n = n.toString()
        return n[1] ? n : '0' + n
      }).join('-')
    },
    getDateBetween(date){
      if(this.dateType === 6){
        return {beginDate: this.btDate[0].format('yyyy-MM-dd'),endDate: this.btDate[1].format('yyyy-MM-dd')}
      }
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let yearAndMonth = year + '-' + (month>=10?month:'0'+month);
      return { beginDate:yearAndMonth+'-01',endDate:yearAndMonth +'-'+ new Date(year,month,0).getDate()}
    },
    clickDetail(type){
      this.type = type
      this.$refs[type].init(this.date,this.dateType,this.format,this.staffIds,this.staffList,this.orgIds,this.orgList,this.btDate)
      this.detailFlag = true
    },
    toFixAndToLocaleString(number){
      if(!number){
        return '0.00'
      }
      let arr = number.toString().split('.')
      if(arr.length>1){
        return parseInt(arr[0]).toLocaleString()+(parseFloat('.'+arr[1]).toFixed(2).slice(1,4))
      }else{
        return parseInt(arr[0]).toLocaleString()+'.00'
      }
    },
    changeSearch(){
      // this.getReport();
    },
    getOrgList(){
      let params = {
        cpId: this.$store.state.user.cpId,
        ascpId:this.$store.state.user.cpId,
        dataSourceCode: "org",
        docName: "客户资料",
        orgId: this.$store.state.user.orgId,
        sysId: this.$store.state.user.sysId,
        userId:this.$store.state.user.id,
      }
      this.excute(this.$service.wxCommonService, this.$service.wxCommonService.wxStoreList, params).then(res=>{
        if (res.code === 200) {
          this.orgList = res.data
        } else {
          this.$Message.error(res.message)
        }
      })
    },
    getStoreList(){
      let params = {
        cpId: this.$store.state.user.cpId,
        ascpId:this.$store.state.user.cpId,
        dataSourceCode: "staff",
        docName: "客户资料",
        orgId: this.$store.state.user.orgId,
        sysId: this.$store.state.user.sysId,
        userId:this.$store.state.user.id,
      }
      this.excute(this.$service.wxCommonService, this.$service.wxCommonService.wxStoreList, params).then(res=>{
        if (res.code === 200) {
          this.staffList = res.data
        } else {
          this.$Message.error(res.message)
        }
      })
    },
    getQjDate(){
      return {beginDate: this.btDate[0].format('yyyy-MM-dd'),endDate: this.btDate[1].format('yyyy-MM-dd')}
    },

    getExportParams(exportTypes){
      console.log("exportTypes",exportTypes)
      let p = {
        /*
        * secondTitle:合计行字符串，
        * calc10000：需要除以一万的字段
        * items：items对应的字段
        * */
        sale:{
          saleTask:Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date),{ "items":"items","calc10000":["sumAmount","avgAmount"],"secondTitle":"成交额（总额:万）${sumAmount}，成交额（均值:万）${avgAmount}",userId:this.$store.state.user.id,type: 'f_report_s001_index_org_order', cpId: this.$store.state.user.cpId, orgIds: this.orgIds,dateType:this.dateType }),
          returnSituation:Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date), { "items":"items","calc10000":["sumAmount","avgAmount"],"secondTitle":"退货额（总额:万）${sumAmount}，退货额（均值:万）${avgAmount}",userId:this.$store.state.user.id,type: 'f_report_s001_order_analysis_reject', cpId: this.$store.state.user.cpId, orgIds: this.orgIds,dateType:this.dateType }),
          customerUnitPrice:Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date), { "items":"items","calc10000":["avgAmount"],"secondTitle":"客户单价（均值:万）${avgAmount}，成交户数 ${csmCount}",userId:this.$store.state.user.id,type: 'f_report_s001_order_analysis_csm', cpId: this.$store.state.user.cpId, orgIds: this.orgIds ,dateType:this.dateType}),
          // activityEffect1:Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date), { "items":"comItems","calc10000":["comAmount","sumAmount"],"secondTitle":"活动成交（万）${sumAmount}，促销成交（万）${comAmount}",userId:this.$store.state.user.id,type: 'f_report_s001_order_analysis_activity', cpId: this.$store.state.user.cpId, orgIds: this.orgIds,dateType:this.dateType }),
          // activityEffect2:Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date), { "items":"pomItems","calc10000":["pomAmount","sumAmount"],"secondTitle":"活动成交（万）${sumAmount}，单品促销（万）${pomAmount}",userId:this.$store.state.user.id,type: 'f_report_s001_order_analysis_activity', cpId: this.$store.state.user.cpId, orgIds: this.orgIds,dateType:this.dateType }),
          // customizedWisdom1:Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date), {"items":"items","calc10000":["sumAmount","dzAmount","znAmount"],"secondTitle":"定+智品类(万)${sumAmount}，定制品(万）${dzAmount}，智能单品(万）${znAmount}",userId:this.$store.state.user.id,type: 'f_report_s001_order_analysis_specs', cpId: this.$store.state.user.cpId, orgIds: this.orgIds,dateType:this.dateType }),
          // customizedWisdom2:Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date), {"items":"dzItems","calc10000":['cabinetAmount', 'glassAmount', 'dzAmount'],"secondTitle":"定制品(万) ${dzAmount}，定制柜(万) ${cabinetAmount}，订制玻璃(万) ${glassAmount}",userId:this.$store.state.user.id,type: 'f_report_s001_order_analysis_specs', cpId: this.$store.state.user.cpId, orgIds: this.orgIds,dateType:this.dateType }),
        },
        received:{
          receivedTask: Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date),{ "items":"items","calc10000":["avgAmount","sumAmount"],"secondTitle":"收款额（总额:万）${sumAmount}，收款额（均值:万）${avgAmount}",userId:this.$store.state.user.id,type: 'f_report_s001_index_org_repay',cpId:this.$store.state.user.cpId,orgIds:this.orgIds,dateType:this.dateType}),
          arrearsInfo: Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date),{ "items":"items","calc10000":["avgAmount","receivable"],"secondTitle":"欠款额（总额:万）${receivable}，欠款额（均值:万）${avgAmount}",userId:this.$store.state.user.id,type: 'f_report_s001_repay_debt',cpId:this.$store.state.user.cpId,orgIds:this.orgIds,dateType:this.dateType})
        },
        customerAnalysis:{
          // budgetQuotation: Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date), { "items":"items","calc10000":["avgAmount","offerAmount"],"secondTitle":"报价（总额:万）${offerAmount}，报价额（均值:万）${avgAmount}",userId:this.$store.state.user.id,type: 'f_report_s001_csm_analysis_offer', cpId: this.$store.state.user.cpId, orgIds: this.orgIds ,dateType:this.dateType}),
          potentialCustomerAnalysis: Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date), { "items":"items","calc10000":[],"secondTitle":"新增潜客${csmCount}，新增成交${orderCsmCount}，新增量尺${measureCsmCount}，新增制图${designCsmCount}",userId:this.$store.state.user.id,type: 'f_report_s001_csm_analysis_order', cpId: this.$store.state.user.cpId, orgIds: this.orgIds ,dateType:this.dateType}),
        },
        customerFrom:{
          transaction: Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date), { "items":"items","calc10000":["sumAmount","avgAmount"],"secondTitle":"成交额(总额:万)${sumAmount}，成交额(均值:万)${avgAmount}",userId:this.$store.state.user.id,type: 'f_report_s001_csm_from_order', cpId: this.$store.state.user.cpId, orgIds: this.orgIds,staffIds:this.staffIds, dateType:this.dateType }),
          // offer: Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date), { "items":"items","calc10000":["sumAmount","avgAmount"],"secondTitle":"报价(总额:万)${sumAmount}，报价额(均值:万)${avgAmount}",userId:this.$store.state.user.id,type: 'f_report_s001_csm_from_offer', cpId: this.$store.state.user.cpId, orgIds: this.orgIds,staffIds:this.staffIds, dateType:this.dateType }),
          potentialCustomerAnalysisFrom: Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date), { "items":"items","calc10000":[],"secondTitle":"新增潜客${csmCount}，新增成交${orderCsmCount}，新增制图${designCsmCount}",userId:this.$store.state.user.id,type: 'f_report_s001_csm_from_filing', cpId: this.$store.state.user.cpId, orgIds: this.orgIds,staffIds:this.staffIds,dateType:this.dateType }),
        },
        product:{
          productDistribution: Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date), { "items":"items","calc10000":["sumAmount"],"secondTitle":"成交额(万)${sumAmount}",userId:this.$store.state.user.id,type: 'f_report_s001_spu_analysis', cpId: this.$store.state.user.cpId, orgIds: this.orgIds,staffIds:this.staffIds,dateType:this.dateType }),
        },
        departmentTransactionRanking:{
          departmentTransactionRanking:Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date),
            { "items":"items","calc10000":["sumAmount","avgAmount"],"secondTitle":"成交额(总额：万)${sumAmount}，成交额(均值：万)${avgAmount}", userId:this.$store.state.user.id,type: 'f_report_s001_index_org_order', cpId: this.$store.state.user.cpId, orgIds: this.orgIds,dateType:this.dateType })
        },
        departmentCollectionRanking:{
          departmentCollectionRanking:Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date),
            { "items":"items","calc10000":["sumAmount","avgAmount"],"secondTitle":"收款额(总额：万)${sumAmount}，收款额(均值：万)${avgAmount}", userId:this.$store.state.user.id,type: 'f_report_s001_index_org_repay', cpId: this.$store.state.user.cpId, orgIds: this.orgIds,dateType:this.dateType }),
        },
        staffTransactionRanking:{
          staffTransactionRanking:Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date),
            { "items":"items","calc10000":["sumAmount","avgAmount"],"secondTitle":"成交额(总额：万)${sumAmount}，成交额(均值：万)${avgAmount}",userId:this.$store.state.user.id, type: 'f_report_s001_index_staff_order', cpId: this.$store.state.user.cpId,orgIds:[], staffIds: this.staffIds,dateType:this.dateType }),
        },
        staffCollectionRanking:{
          staffCollectionRanking:Object.assign(this.dateType===6?this.getQjDate():util.getBeginDateAndEndDate(this.date),
            { "items":"items","calc10000":["sumAmount","avgAmount"],"secondTitle":"收款额(总额：万)${sumAmount}，收款额(均值：万)${avgAmount}", userId:this.$store.state.user.id,type: 'f_report_s001_index_staff_repay', cpId: this.$store.state.user.cpId,orgIds:[],staffIds: this.staffIds,dateType:this.dateType }),
        }
      }
      let params = {};
      for (let i = 0; i < exportTypes.length; i++) {
        console.log(exportTypes[i])
        params = Object.assign(params,p[exportTypes[i]])
      }
      return params;
    },
    exportAll(){
      this.doExport(["sale","received","customerAnalysis","customerFrom","product","departmentTransactionRanking","departmentCollectionRanking","staffTransactionRanking","staffCollectionRanking"],"销售简报-全部")
    },
    doExport(exportTypes,fileName){
      let p  = this.getExportParams(exportTypes)
      let searchCond = p[Object.keys(p)[0]]
      let orgNameList = (searchCond.orgIds.length>0?this.orgList.filter(it=>searchCond.orgIds.indexOf(it.id)>-1):[]).map(it=>it.name)
      // let staffList = (searchCond.orgIds.length>0?this.staffList.filter(it=>searchCond.staffIds.indexOf(it.id)>-1):this.staffList).map(it=>it.name)

      let reportDate = util.getDateByDateType(this.dateType);
      if(!reportDate){
        reportDate = [searchCond.beginDate,searchCond.endDate]
      }

      let p2 = {
        params:p,
        searchCond:"开始时间："+reportDate[0] + "，结束时间：" + reportDate[1]
          + (orgNameList.length>0?"，门店："+orgNameList.toString():''),
        fileName:fileName,
        filePath: "销售管理/销售分析/",
      }
      // console.log(p2)
      this.excute(this.$service.detailReportService, this.$service.detailReportService.exportPushParams, p2).then(res=>{
        if(res.code === 200){
          //拼接业务服务编码
          window.location.href = this.$config.serviceUrl + '/mdm-server'+ '-' + this.$store.state.user.svcCode.replace('_', '-') +'/mst/report/export?uuid='+res.data
        }
      })
    },
    getReport() {
      this.loading = true
      console.log('user',this.$store.state.user)
      let params = {
        orderAnalysis: Object.assign(this.getDateBetween(this.date),{
          userId: this.$store.state.user.id,
          cpId: this.$store.state.user.cpId,
          orgIds: this.orgIds,
          type: 'f_report_s001_order_analysis_home',
          dateType:this.dateType
        }),
        repayAnalysis: Object.assign(this.getDateBetween(this.date),{
          userId: this.$store.state.user.id,
          cpId: this.$store.state.user.cpId,
          orgIds: this.orgIds,
          type: 'f_report_s001_repay_analysis',
          dateType:this.dateType
        }),
        csmAnalysisHome: Object.assign(this.getDateBetween(this.date), {
          userId: this.$store.state.user.id,
          cpId: this.$store.state.user.cpId,
          orgIds: this.orgIds,
          type: 'f_report_s001_csm_analysis_home',
          dateType:this.dateType
        }),
        csmFromOrder: Object.assign(this.getDateBetween(this.date), {
          userId: this.$store.state.user.id,
          cpId: this.$store.state.user.cpId,
          orgIds: this.orgIds,
          type: 'f_report_s001_csm_from_order',
          dateType:this.dateType
        }),
        spuAnalysis: Object.assign(this.getDateBetween(this.date), {
          userId: this.$store.state.user.id,
          cpId: this.$store.state.user.cpId,
          orgIds: this.orgIds,
          type: 'f_report_s001_spu_analysis',
          dateType:this.dateType
        }),
        indexOrgOrder: Object.assign(this.getDateBetween(this.date),{
          userId: this.$store.state.user.id,
          cpId: this.$store.state.user.cpId,
          orgIds: this.orgIds,
          type: 'f_report_s001_index_org_order',
          dateType:this.dateType
        }),
        indexOrgRepay: Object.assign(this.getDateBetween(this.date),{
          userId: this.$store.state.user.id,
          cpId: this.$store.state.user.cpId,
          orgIds: this.orgIds,
          type: 'f_report_s001_index_org_repay',
          dateType:this.dateType
        }),
        indexStaffOrder: Object.assign(this.getDateBetween(this.date),{
          userId: this.$store.state.user.id,
          cpId: this.$store.state.user.cpId,
          orgIds: this.orgIds,
          staffIds: [],
          type: 'f_report_s001_index_staff_order',
          dateType:this.dateType
        }),
        indexStaffRepay: Object.assign(this.getDateBetween(this.date),{
          userId: this.$store.state.user.id,
          cpId: this.$store.state.user.cpId,
          orgIds: this.orgIds,
          staffIds: [],
          type: 'f_report_s001_index_staff_repay',
          dateType:this.dateType
        }),
      }
      this.excute(this.$service.detailReportService, this.$service.detailReportService.getReportBatch, params).then(res => {
        this.loading = false
        if (res.code === 200) {
            this.orderAnalysis = res.data.orderAnalysis
            this.repayAnalysis = res.data.repayAnalysis
            this.csmAnalysisHome = res.data.csmAnalysisHome
            this.csmFromOrder = Object.assign(res.data.csmFromOrder,{items:res.data.csmFromOrder.items.slice(0,8)})
            this.spuAnalysis = Object.assign(res.data.spuAnalysis,{items:res.data.spuAnalysis.items.slice(0,8)})
            this.indexOrgOrder = Object.assign(res.data.indexOrgOrder,{items:res.data.indexOrgOrder.items.slice(0,5)})
            this.indexOrgRepay = Object.assign(res.data.indexOrgRepay,{items:res.data.indexOrgRepay.items.slice(0,5)})
            this.indexStaffOrder = Object.assign(res.data.indexStaffOrder,{items:res.data.indexStaffOrder.items.slice(0,5)})
            this.indexStaffRepay = Object.assign(res.data.indexStaffRepay,{items:res.data.indexStaffRepay.items.slice(0,5)})
            this.$nextTick(() => {
              this.echarts('echarts-khlyfb',echartsJs.getOpData({ data: res.data.csmFromOrder.items, labelKey: 'fromName', valueKey: 'orderAmount', optionType: 1 }))
              this.echarts('echarts-cpfb', echartsJs.getOpData({ data: res.data.spuAnalysis.items, labelKey: 'specsName', valueKey: 'sumAmount', optionType: 1 }))
              this.echarts('echarts-bmcjph', echartsJs.getOpData({ data: res.data.indexOrgOrder.items, labelKey: 'orgName', valueKey: 'orderAmount', optionType: 3 }))
              this.echarts('echarts-bmskph', echartsJs.getOpData({ data: res.data.indexOrgRepay.items, labelKey: 'orgName', valueKey: 'repayAmount', optionType: 3 }))
              this.echarts('echarts-ywycjph', echartsJs.getOpData({ data: res.data.indexStaffOrder.items, labelKey: 'staffName', valueKey: 'orderAmount', optionType: 2 }))
              this.echarts('echarts-ywyskph', echartsJs.getOpData({ data: res.data.indexStaffRepay.items, labelKey: 'staffName', valueKey: 'repayAmount', optionType: 2 }))
             })
        } else {
          this.$Message.error(res.message)
        }
      })
    },
  },
  created() {
    this.getReport()
    this.getStoreList()
    this.getOrgList()
  }
}
</script>

<style scoped>

/deep/.ivu-picker-confirm>.ivu-btn-default{
  display: none !important;
}
.bottom-line-item4  {
  width: calc(25% - 5px) !important;
}
.bottom-line-item2  {
  width: calc(50% - 5px) !important;
}
.bottom-line-item1  {
  width: calc(100% - 5px) !important;
}
.single-export{
  font-size: 14px;margin-left: 10px;
}
</style>
