<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-width="68px">
      <el-row>
        <el-col :span="8">
          <el-form-item class="treeselectForm treeselectForm2" label="组织架构" prop="deptIds">
            <tree @treeselectFn="treeselectFn" :treeval="queryParams.deptIds" :ismultiple="true" style="width: 193px;"></tree>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售员" prop="userId">
            <user :userId="queryParams.userId" :orgIds="queryParams.deptIds" @userIdFn="userIdFn"></user>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="门店名称" prop="storeName">
            <el-input
              v-model="queryParams.storeName"
              placeholder="请输入门店名称"
              clearable
              @input="onInput"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="门店类型" prop="storeCategorys">
            <el-select size="mini" multiple collapse-tags v-model="queryParams.storeCategorys" clearable placeholder="请选择门店类型" @change="onInput">
              <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-form-item label="拜访类型" prop="visitEntry">
            <el-select size="mini" v-model="queryParams.visitEntry" clearable placeholder="请选择拜访类型" @change="onInput">
              <el-option
                v-for="item in visitTypeOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="拜访来源" prop="visitSource">
            <el-select size="mini" v-model="queryParams.visitSource" placeholder="请选择拜访来源" @change="visitSourceChange">
              <el-option
                v-for="item in visitSourceOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="拜访模式" prop="visitModel">
            <el-select size="mini" v-model="queryParams.visitModel" placeholder="请选择拜访模式" @change="onInput">
              <el-option
                v-for="item in visitModelOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
                :disabled="item.isDisabled">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="流程类型" prop="processKey">
            <el-select size="mini"  v-model="queryParams.processKey" clearable placeholder="流程类型"  @change="onInput()">
              <el-option
                v-for="item in listModeler"
                :key="item.id"
                :label="item.name"
                :value="item.key">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="异常信息" prop="timeAbnormals">
            <el-select size="mini" multiple collapse-tags  v-model="queryParams.timeAbnormals" clearable placeholder="异常信息"  @change="onInput()">
              <el-option label="正常" value="0"></el-option>
              <el-option label="非上班期间异常" value="1"></el-option>
              <el-option label="进店时间过短异常" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="起止时间" prop="datetimerange">
            <el-date-picker
              style="width: 193px;"
              v-model="datetimerange"
              type="daterange"
              align="right"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              @change="datetimeRangeChange">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</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-table v-loading="loading" :data="visitResultsList">
      <el-table-column label="公司" align="center" prop="company"  width="180" :show-overflow-tooltip="true"/>
      <el-table-column label="大区" align="center" prop="parentDeptName" width="180"/>
      <el-table-column label="销售部" align="center" prop="deptName" width="150" />
      <el-table-column label="门店编号" align="center" prop="storeCode" width="106" />
      <el-table-column label="门店名称" align="center" prop="storeName" width="300" />
      <el-table-column label="门店类型" align="center" prop="storeCategory" width="120" >
<!--        <template slot-scope="scope">-->
<!--          {{storeCategoryFormat(scope.row)}}-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="经销商编号" align="center" prop="chainCode" width="120" />
      <el-table-column label="经销商名称" align="center" prop="chainName" width="300" />
      <el-table-column label="销售员工号" align="center" prop="workCode" width="140" />
      <el-table-column label="销售员" align="center" prop="nickName" width="300" :show-overflow-tooltip="true"/>
      <el-table-column label="审批进度" align="center" prop="status" width="180" :show-overflow-tooltip="true">
<!--        <template slot-scope="scope">-->
<!--          <span v-if="scope.row.status == 1">审批中</span>-->
<!--          <span v-if="scope.row.status == 2">审批完成</span>-->
<!--          <span v-if="scope.row.status == 3">拒绝</span>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="拜访类型" align="center" prop="visitEntry" width="90" >
        <template slot-scope="scope">
          <span v-if="scope.row.visitEntry == 0">线内</span>
          <span v-else>线外</span>
        </template>
      </el-table-column>
      <el-table-column label="拜访来源" align="center" prop="nickName" width="90" >
        <template slot-scope="scope">
          <span>{{visitSourceFormat(scope.row,scope.column)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="拜访模式" align="center"  width="90">
        <template slot-scope="scope">
          <span>{{visitModelFormat(scope.row,scope.column)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="签到距离（米）" align="center" prop="locationAccuracy" width="130">
        <template slot-scope="scope">
          <span v-if="scope.row.locationAccuracy != null && scope.row.locationAccuracy !== ''">{{scope.row.locationAccuracy}}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="进店时间" align="center" prop="startTime"width="160" />
      <el-table-column label="离店时间" align="center" prop="stopTime" width="160" />
      <el-table-column label="停留时间" align="center" prop="dwellTime" width="90" :show-overflow-tooltip="true"/>
      <el-table-column label="异常信息" align="center" prop="timeAbnormal" width="150" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.timeAbnormal == 0">正常</span>
          <span v-if="scope.row.timeAbnormal == 1">非上班期间异常</span>
          <span v-if="scope.row.timeAbnormal == 2">进店时间过短异常</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleDetail(scope.row)"
          >详情</el-button>
        </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 { getVisitResultsList } from "@/api/sfa/visitResults";
    import user from "@/views/components/sfa/user";
    import tree from "@/views/components/sfa/treeselectParent";
    import {listModeler} from "@/api/activiti/modeler";
    export default {
        name: "VisitResults",
        components: { user,tree },
        data() {
            return {
              selectDate:"",
              pickerOptions: {
                shortcuts: [{
                  text: '本周',
                  onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setDate(start.getDate() - 6);
                    picker.$emit('pick', [start, end]);
                  }
                }],
                //
                // disabledDate:(time)=> {
                //   if (this.pickerMinDate) {
                //     const day1 =  366 * 24 * 3600 * 1000
                //     let maxTime = this.pickerMinDate + day1
                //     let minTime = this.pickerMinDate - day1
                //     return time.getTime() > maxTime || time.getTime()<minTime || time.getTime() > Date.now()-1 * 24 * 3600 * 1000
                //   }else{
                //     return time.getTime() > Date.now()-1 * 24 * 3600 * 1000
                //   }
                //
                // }
              },
                // 遮罩层
                loading: false,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 线路表格数据
                visitResultsList: [],
                // 弹出层标题
                title: "",

                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    visitModel:'',
                    visitSource:'',
                    deptIds:null
                },
                datetimerange:[],
                // 表单参数
                form: {},
                visitModelOptions:[
                    {
                        dictValue:'',
                        dictLabel:'全部',
                        isDisabled:false
                    },
                ],
                visitSourceOptions:[
                    {
                        dictValue:'',
                        dictLabel:'全部'
                    },
                ],
                personNameOptions:[],
                personLoading:false,
                personList:[],
                // 门店类型
                storeCategoryOptions:[],
                visitTypeOptions:[
                    {
                        dictValue:0,
                        dictLabel:'线内'
                    },
                    {
                        dictValue:1,
                        dictLabel:'线外'
                    },
                ],
              listModeler:[]
            };
        },
        created() {
            this.getDicts("sfa_visit_model").then(response => {
                this.visitModelOptions = [...this.visitModelOptions,...response.data];
                this.visitModelOptions.forEach((item)=>{
                    item.isDisabled=true;
                })
            });
            this.getDicts("visit_source").then(response => {
                this.visitSourceOptions = [...this.visitSourceOptions,...response.data];
            });
            if(this.$store.state.user.type == '2'){
                this.getDicts("ysl_store_type").then(response => {
                    this.storeCategoryOptions = response.data;
                });
            }else{
                this.getDicts("sfa_store_type").then(response => {
                    this.storeCategoryOptions = response.data;
                });
            }
          this.datetimerange[1] = this.parseTime(new Date(),'{yy}-{mm}-{dd}');
          this.datetimerange[0] = this.queryMonth();
          this.queryParams.startTime = this.datetimerange[0]+" 00:00:00";
          this.queryParams.stopTime = this.datetimerange[1]+" 00:00:00";
            // this.getList();
            // this.getSelectUserRouteListData();
          this.getListModeler()
        },
        methods: {
          getListModeler(){
            listModeler().then(response=>{
              this.listModeler=response.rows
            })
          },
            treeselectFn(val){
                this.queryParams.deptIds = val;
                // this.$refs['queryParams'].validate((valid) => {
                //     console.log(valid)
                // })
            },
            visitSourceChange(val){
                this.$forceUpdate();
                this.queryParams.visitModel = null;
                this.visitModelOptions.forEach((item)=>{
                    if(this.queryParams.visitSource == '' && item.dictValue == ''){
                        item.isDisabled =  false;
                    }else if(this.queryParams.visitSource == '1' && (item.dictValue == '1'||item.dictValue == '5')){
                        item.isDisabled =  false;
                    }else if(this.queryParams.visitSource == '2' && (item.dictValue == '3'||item.dictValue == '5')){
                        item.isDisabled =  false;
                    }else{
                        item.isDisabled =  true;
                    }
                })

            },
            onInput(){
                this.$forceUpdate();
            },
            /** 查询线路列表 */
            getList() {
                this.loading = true;
                getVisitResultsList(this.queryParams).then(response => {
                    this.visitResultsList = response.rows;
                    this.total = response.total;
                    this.loading = false;
                });
            },
            userIdFn(val){
                console.log(val)
                this.queryParams.userId = val;
            },
            storeCategoryFormat(row){
                return this.selectDictLabel(this.storeCategoryOptions, row.storeCategory);
            },
            visitSourceFormat(row, column) {
                return this.selectDictLabel(this.visitSourceOptions, row.visitSource);
            },
            // 拜访行为字典翻译
            visitModelFormat(row, column) {
                return this.selectDictLabel(this.visitModelOptions, row.visitModel);
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.datetimerange = [];
                this.queryParams.startTime = '';
                this.queryParams.stopTime = '';
                this.resetForm("queryForm");
              this.datetimerange[1] = this.parseTime(new Date(),'{yy}-{mm}-{dd}');
              this.datetimerange[0] = this.queryMonth();
              this.queryParams.startTime = this.datetimerange[0]+" 00:00:00";
              this.queryParams.stopTime = this.datetimerange[1]+" 00:00:00";
              this.queryParams.deptIds=[]
                this.handleQuery();
            },
          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;
          },
            datetimeRangeChange(val){
                this.$forceUpdate()
                if(val == undefined || val == null){
                    this.datetimerange = [];
                    this.queryParams.startTime = '';
                    this.queryParams.stopTime = '';
                }else{
                    this.queryParams.startTime = val[0]+" 00:00:00";
                    this.queryParams.stopTime = val[1]+" 00:00:00";
                }
            },
            handleDetail(row){
                this.$router.push({path:'/route/visitResultsDetail',query:{id:row.id}});
            },
            /** 导出按钮操作 */
            handleExport() {
                this.download('sfa/visits/export', {
                    ...this.queryParams
                }, `拜访结果查询_${new Date().getTime()}.xlsx`)
            },
        }
    };
</script>

<style lang="scss" scoped>

</style>
