<template>
  <div class="app-container">
    <el-form :model="queryParams" size="mini" ref="queryForm" :inline="true" :rules="queryRules" v-show="showSearch" label-width="78px">
      <el-row>
        <el-col :span="8">
          <el-form-item class="treeselectForm treeselectForm2" label="组织架构" prop="deptIds">
            <tree @treeselectFn="treeselectFn" :treeval="queryParams.deptIds" style="width: 200px;"></tree>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售员" prop="userId">
            <user :userId="queryParams.userId" :orgIds="queryParams.orgIds" @userIdFn="userIdFn" style="width: 200px;"></user>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="起止时间" prop="datetimerange">
            <el-date-picker
              style="width: 200px;"
              v-model="datetimerange"
              type="daterange"
              align="right"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="门店编号" prop="storeCode">
            <el-input
              style="width: 200px;"
              v-model="queryParams.storeCode"
              placeholder="请输入门店编号"
              clearable
              @input="onInput"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="门店名称" prop="storeName">
            <el-input
              style="width: 200px;"
              v-model="queryParams.storeName"
              placeholder="请输入门店名称"
              clearable
              @input="onInput"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="门店类型" prop="storeTypes">
            <el-select v-model="queryParams.storeTypes" multiple collapse-tags clearable placeholder="请选择门店类型" @change="onInput" style="width: 200px;">
              <el-option
                v-for="item in storeCategoryOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">

        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery('queryForm')">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
    <div style="margin: 15px 0;"></div>
    <el-checkbox-group v-model="checkList" @change="checkboxChange">
      <el-checkbox :label="item.label" v-for="(item,index) in checkboxList" :key="index" :disabled="item.disabled"></el-checkbox>
    </el-checkbox-group>
<!--    :span-method="arraySpanMethod"-->
    <el-table v-loading="loading" :data="routeList">
      <el-table-column :label="item.label" :prop="item.prop" v-for="(item,index) in tableHead" :key="item.prop+index" align="center" :min-width="item.width"  >
          <template slot-scope="scope">
<!--            <span>{{scope.row.visitRate}}</span>-->
            <span v-if="item.label == '线内拜访比例'">{{scope.row[item.prop]+'%'}}</span>
            <span v-else>{{scope.row[item.prop]}}</span>
          </template>
      </el-table-column>
    </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />


  </div>
</template>

<script>
    import tree from "@/views/components/sfa/treeselectParent";
    import user from "@/views/components/sfa/user";
    import { analysisList } from "@/api/sfa/visitAnalysis";
    import mymap from '@/views/components/sfa/map'
    export default {
        name: "VisitAnalysis",
        components: { tree,user,mymap },
        data() {
            return {
                // 遮罩层
                loading: false,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                routeList:[],
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    showGsName:false,
                    showDqName:false,
                    showDeptName:false,
                    showUserName:false,
                    showStoreName:false,
                    showStoreType:false,
                    showDate:false,
                },
                queryRules:{},
                checkList: ['公司','销售大区','销售部','账号','姓名','门店编号','门店名称','门店类型','日期'],
                checkboxList:[
                    {
                        label:'公司',
                        prop:'gsDeptName',
                        id:1,
                        width:100
                    },
                    {
                        label:'销售大区',
                        prop:'dqDeptName',
                        id:2,
                        width:120
                    },
                    {
                        label:'销售部',
                        prop:'deptName',
                        id:3,
                        width:120
                    },
                    {
                        label:'账号',
                        prop:'userName',
                        id:4,
                        width:200
                    },
                    {
                        label:'姓名',
                        prop:'nickName',
                        id:5,
                        width:90
                    },
                    {
                        label:'门店编号',
                        prop:'storeCode',
                        id:6,
                        width:120
                    },
                    {
                        label:'门店名称',
                        prop:'storeName',
                        id:7,
                        width:160
                    },
                    {
                        label:'门店类型',
                        prop:'storeTypeName',
                        id:8,
                        width:120
                    },
                    {
                        label:'日期',
                        prop:'date',
                        id:9,
                        width:120
                    },
                ],
                tableHead:[
                    {
                        label:'线内拜访数量',
                        prop:'planInVisitNum',
                        width:100
                    },
                    {
                        label:'线内计划数量',
                        prop:'planInNum',
                        width:100
                    },
                    {
                        label:'线内拜访比例',
                        prop:'visitRate',
                        width:100
                    },
                    {
                        label:'拜访终端数量',
                        prop:'visitNum',
                        width:100
                    },
                    {
                        label:'线外拜访数量',
                        prop:'outVisitNum',
                        width:100
                    },
                    {
                        label:'在线时间',
                        prop:'onlineTimeStr',
                        width:200
                    },
                    {
                        label:'在店工作时间',
                        prop:'inStoreTimeStr',
                        width:200
                    },
                    {
                        label:'在途时间',
                        prop:'onWayTimeStr',
                        width:200
                    },
                ],
                checkAll: true,
                isIndeterminate: true,
                // 门店类型
                storeCategoryOptions:[],
                datetimerange:[],
                spanGS: [], //合并公司
                GSIndex: 0, //合并公司索引
                spanDQ: [], //合并大区
                DQIndex: 0, //合并大区索引
                spanXSB: [], //合并销售部
                XSBIndex: 0, //合并销售部索引
                spanZH: [], //合并账号
                ZHIndex: 0, //合并账号索引
                spanXM: [], //合并姓名
                XMIndex: 0, //合并姓名索引
                spanStoreCode: [], //合并门店编号
                StoreCodeIndex: 0, //合并门店编号索引
                spanStoreName: [], //合并门店名称
                StoreNameIndex: 0, //合并门店名称索引
                spanStoreType: [], //合并门店类型
                StoreTypeIndex: 0, //合并门店类型索引
                spanDate: [], //合并日期
                DateIndex: 0, //合并日期索引
                pickerOptions: {
                  onPick: ({ maxDate, minDate }) => {
                    this.selectDate = minDate.getTime()
                    if (maxDate) {
                      this.selectDate = ''
                    }
                  },
                  disabledDate: time => {
                    const choiceDateTime = new Date(this.selectDate).getTime()
                    const minTime = new Date(choiceDateTime).setMonth(new Date(choiceDateTime).getMonth() - 1)
                    const maxTime = new Date(choiceDateTime).setMonth(new Date(choiceDateTime).getMonth() + 1)
                    const min = minTime
                    const newDate = new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1
                    const max = newDate < maxTime ? newDate : maxTime
                    return time.getTime() < min || time.getTime() > max

                  }
                    // disabledDate(time) {
                    //     return time.getTime() > Date.now();
                    // }
                },
            };
        },
        watch:{

        },
        created() {
            if(this.$store.state.user.type == '2'){
                this.getDicts("ysl_store_type").then(response => {
                    this.storeCategoryOptions = response.data;
                });
                this.isYSL = true;
            }else{
                this.getDicts("sfa_store_type").then(response => {
                    this.storeCategoryOptions = response.data;
                });
                this.isYSL = false;
            }
          this.datetimerange[1] = this.parseTime(new Date(),'{yy}-{mm}-{dd}');
          this.selectDate =new Date().getTime();
          this.datetimerange[0] = this.queryMonth();
            this.handleCheckAllChange(this.checkAll);
            // this.getList();
        },
        methods: {
          queryMonth () {
            //先获取当前日期
            let data = new Date()
            let year = data.getFullYear()
            //当前月份需要加一
            let mon = data.getMonth() + 1
            let day = data.getDate()
            //一月的时候年份要减一
            if(mon == 1){
              year--
              mon = 12
            }else if(mon == 3 && day > 28){
              //三月要考虑是否为闰年
              mon--
              if(year%4==0&&year%100!=0||year%400==0){
                day = 29
              }else{
                day = 28
              }
            }else if(mon != 12 || mon != 8 && day == 31){
              //31号的月份要考虑上个月是否有31号
              mon--
              day == 30
            } else {
              mon--
            }
            mon < 10 ? mon = '0'+mon: mon;
            day < 10 ? day = '0'+day: day;

            //最后拼接年月日
            let date = year + "-" + mon + "-" + day
            return date;
          },
            onInput(){
                this.$forceUpdate();
            },
            treeselectFn(val){
                this.queryParams.deptIds = val;
                this.$forceUpdate();
            },
            userIdFn(val){
                this.queryParams.userId = val;
            },
            /** 查询线路列表 */
            getList() {
                if(this.checkList.length>0){
                    this.checkList.indexOf('公司') == -1 ? this.queryParams.showGsName = false:this.queryParams.showGsName = true;
                    this.checkList.indexOf('销售大区') == -1 ? this.queryParams.showDqName = false:this.queryParams.showDqName = true;
                    this.checkList.indexOf('销售部') == -1 ? this.queryParams.showDeptName = false:this.queryParams.showDeptName = true;
                    if(this.checkList.indexOf('账号') != -1 || this.checkList.indexOf('姓名') != -1){
                        this.queryParams.showUserName = true;
                    }else{
                        this.queryParams.showUserName = false;
                    }
                    if(this.checkList.indexOf('门店编号') != -1 || this.checkList.indexOf('门店名称') != -1){
                        this.queryParams.showStoreName = true;
                    }else{
                        this.queryParams.showStoreName = false;
                    }
                    this.checkList.indexOf('门店类型') == -1 ? this.queryParams.showStoreType = false:this.queryParams.showStoreType = true;
                    this.checkList.indexOf('日期') == -1 ? this.queryParams.showDate = false:this.queryParams.showDate = true;
                    if(this.datetimerange == null || this.datetimerange == []){
                        this.queryParams.startDate = '';
                        this.queryParams.endDate = '';
                    }else{
                        this.queryParams.startDate = this.datetimerange[0];
                        this.queryParams.endDate = this.datetimerange[1];
                    }
                    this.loading = true;
                    analysisList(this.queryParams).then(response => {
                        this.routeList = response.rows;
                        this.total = response.total;
                        this.loading = false;
                    }).catch((err)=>{
                        this.loading = false;
                    });
                }else{
                    this.routeList = [];
                    this.$modal.msgError('请勾选复选框中选项！');
                }

            },
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.queryParams.userId = '';
                this.datetimerange= [];
                this.resetForm("queryForm");
                this.handleQuery();
            },
            checkboxChange(val){
                let checkedCount = val.length;
                this.checkAll = checkedCount === this.checkboxList.length;
                this.isIndeterminate = checkedCount > 0 && checkedCount < this.checkboxList.length;
                let tableHead = [];
                this.tableHead = [
                    {
                        label:'线内拜访数量',
                        prop:'planInVisitNum',
                        width:100
                    },
                    {
                        label:'线内计划数量',
                        prop:'planInNum',
                        width:100
                    },
                    {
                        label:'线内拜访比例',
                        prop:'visitRate',
                        width:100
                    },
                    {
                        label:'拜访终端数量',
                        prop:'visitNum',
                        width:100
                    },
                    {
                        label:'线外拜访数量',
                        prop:'outVisitNum',
                        width:100
                    },
                    {
                        label:'在线时间',
                        prop:'onlineTimeStr',
                        width:200
                    },
                    {
                        label:'在店工作时间',
                        prop:'inStoreTimeStr',
                        width:200
                    },
                    {
                        label:'在途时间',
                        prop:'onWayTimeStr',
                        width:200
                    },
                ];
                val.forEach((da,i)=>{
                    this.checkboxList.forEach((item,index)=>{
                        if(item.label == da ){
                            tableHead.push(item);
                        }
                    })
                })
                this.tableHead = [...this.sortFn(tableHead),...this.tableHead];
                this.handleQuery();
            },
            handleCheckAllChange(val) {
                let checkedAll = [];
                let checkedHead = [];
                this.tableHead = [
                    {
                        label:'线内拜访数量',
                        prop:'planInVisitNum',
                        width:100
                    },
                    {
                        label:'线内计划数量',
                        prop:'planInNum',
                        width:100
                    },
                    {
                        label:'线内拜访比例',
                        prop:'visitRate',
                        width:100
                    },
                    {
                        label:'拜访终端数量',
                        prop:'visitNum',
                        width:100
                    },
                    {
                        label:'线外拜访数量',
                        prop:'outVisitNum',
                        width:100
                    },
                    {
                        label:'在线时间',
                        prop:'onlineTimeStr',
                        width:200
                    },
                    {
                        label:'在店工作时间',
                        prop:'inStoreTimeStr',
                        width:200
                    },
                    {
                        label:'在途时间',
                        prop:'onWayTimeStr',
                        width:200
                    },
                ];
                this.checkboxList.forEach((item,index)=>{
                    checkedAll.push(item.label);
                    checkedHead.push(item)
                })
                this.checkList = val ? checkedAll : [];
                this.tableHead = val ? [...checkedHead,...this.tableHead] : this.tableHead;
                this.isIndeterminate = false;
            },
            sortFn(arr){
                for(var i=0;i<arr.length;i++){
                    for(var j=i+1;j<arr.length;j++){
                        //如果第一个比第二个大，就交换他们两个位置
                        if(arr[i].id>arr[j].id){
                            var temp = arr[i];
                            arr[i] = arr[j];
                            arr[j] = temp;
                        }
                    }
                }
                return arr;
            },
            /** 导出按钮操作 */
            handleExport() {
                this.download('sfa/analysis/export', {
                    ...this.queryParams
                }, `拜访分析_${new Date().getTime()}.xlsx`)
            },
            mergeInit(){

            },
            arraySpanMethod(){

            },
        }
    };
</script>

<style lang="scss">
  .el-input--suffix .el-input__inner{
    padding-right: 15px;
  }
  .map-marker {
    position: absolute;
    font-size: 16px;
    color: dodgerblue;
    font-weight: 500;
      div {
      position: absolute;//改变定位
      img {
        height: 10px;
        width: 10px;
      }
    }
  }
</style>
