<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryParams" size="mini" :inline="true" :rules="queryRules" v-show="showSearch" label-width="78px">
      <el-form-item :class="['treeselectForm',{borderRed:!validTree}]" label="组织架构" prop="orgIds">
        <tree @treeselectFn="treeselectFn" :treeval="queryParams.orgIds" :ismultiple="true"></tree>
      </el-form-item>
      <el-form-item label="销售员" prop="userId">
        <user :userId="queryParams.userId" :orgIds="queryParams.orgIds" @userIdFn="userIdFn"></user>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery('queryParams')">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="24">
        <div class="tips">
          <div>注意：1、根据线路规则重新生成后会覆盖原来的每日线路！</div>
          <div style="padding-left: 50px;">2、自动生成范围：从明天至下周日。<el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQueryData('queryParams')">生成</el-button></div>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-row :gutter="10" class="mb8">
      <el-calendar class="myCalendar" v-model="calendarValue" style="width:60%;margin-left: 20%;">
        <div
          slot="dateCell"
          slot-scope="{ data }"
          class="dateCell"
          @click="calendarClick(data)"
        >
            <div class="calendarDay" :class="data.isSelected ? 'is-selected' : ''">
              {{ data.day.split("-").slice(2).join("-") }}
            </div>
            <div class="calendarNum">({{visitCountFn(data.day)}})</div>
        </div>
      </el-calendar>
    </el-row>
    <el-table v-loading="loading" :data="visitPlanList">
      <el-table-column label="计划拜访日期" align="center" prop="genDate" width="120" />
      <el-table-column label="门店名称" align="center" prop="storeName" />
      <el-table-column label="门店编号" align="center" prop="storeCode" width="100" />
      <el-table-column label="门店地址" align="center" prop="addressLine" />
      <el-table-column label="拜访顺序" align="center" prop="sort" width="90"/>
      <el-table-column label="联系人" align="center" prop="contactName" width="90"/>
      <el-table-column label="电话" align="center" prop="telephone" width="120" />
    </el-table>

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

<script>
    import tree from "@/views/components/sfa/treeselectParent";
    import user from "@/views/components/sfa/user";
    import { getSelectRouteDetailList,getSelectRouteDetailStoreList,createRouteDetails } from "@/api/sfa/visitPlan";

    export default {
        name: "VisitPlan",
        components: { tree,user },
        data() {
            // var checkUserId = (rule, value, callback) => {
            //     console.log(this.queryParams.orgIds)
            //     if (!value) {
            //         return callback(new Error('请输入姓名'));
            //     }
            //     setTimeout(() => {
            //       if(this.queryParams.orgIds.length == 0){
            //           this.queryParams.userId = '';
            //           callback(new Error('请先选择组织架构'));
            //       }else{
            //           callback();
            //       }
            //     }, 1000);
            // };
            return {
                // 遮罩层
                loading: false,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 线路表格数据
                visitPlanList: [],
                // 弹出层标题
                title: "",

                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    orgIds:[],
                    userId:null
                },
                queryRules:{
                    // orgIds: [ { required: true, message: '请选择组织架构', trigger: 'change' }],
                    // userId: [ { required: true, validator: checkUserId, trigger: 'change' }],
                    userId: [ { required: true, message: '请选择姓名', trigger: 'change' }],
                },
                personNameOptions:[],
                personLoading:false,
                personList:[],
                // 表单参数
                form: {},
                // 菜单树选项
                menuOptions: [],

                calendarValue:new Date(),
                currentDay:'',
                calendarData:[],
                validTree:true
            };
        },
      watch:{
        "queryParams.orgIds": {
          handler:function(newValue, oldValue) {
            // if(newValue.length > 0){
            //     // this.getSelectUserRouteListData();、
            // }
            // this.userIdFocus();
          },
          immediate: true,
          deep: true
        },
      },
        created() {
            this.$nextTick(() => {
                // 点击前一个月
                let prevBtn = document.querySelector(
                    ".el-calendar__button-group .el-button-group>button:nth-child(1)"
                );
                prevBtn.addEventListener("click", e => {
                    this.getList();
                });

            //     //点击下一个月
                let nextBtn = document.querySelector(
                    ".el-calendar__button-group .el-button-group>button:nth-child(3)"
                );
                nextBtn.addEventListener("click", () => {
                    this.getList();
                });

                //点击今天
                let todayBtn = document.querySelector(
                    ".el-calendar__button-group .el-button-group>button:nth-child(2)"
                );
                todayBtn.addEventListener("click", () => {
                    this.getList();
                });
            });
            // this.getSelectUserRouteListData();
            // this.getList();
        },
        methods: {
            treeselectFn(val){
                this.queryParams.orgIds = val;
            },
            userIdFn(val){
                console.log(val)
                this.queryParams.userId = val;
            },
            // userIdFocus(){
            //     if(this.queryParams.orgIds.length == 0){
            //         this.$refs['queryParams'].validate((valid) => {
            //             if (valid) {
            //                 this.validTree = true;
            //             }else{
            //                 if(this.queryParams.orgIds.length==0){
            //                     this.validTree = false;
            //                 }else{
            //                     this.validTree = true;
            //                 }
            //             }
            //         })
            //     }
            // },
            /** 查询日历数据及拜访门店列表 */
            getList() {
                this.currentDay = this.parseTime(this.calendarValue,'{yy}-{mm}-{dd}');
                console.log(this.calendarValue)
                let obj = {
                    userId:this.queryParams.userId,
                    genDate:this.currentDay
                }
                getSelectRouteDetailList(obj).then(response => {
                    console.log(response)
                    this.calendarData = response.data;
                });
                this.visitPlanListData();
            },
            visitCountFn(day){
                let visitCount = 0;
                if(this.calendarData !== undefined &&this.calendarData !== null && this.calendarData.length > 0){
                    this.calendarData.forEach((item,index)=>{
                        if(item.genDate == day){
                            visitCount = item.visitCount;
                        }
                    })
                }else{
                    visitCount = 0;
                }
                return visitCount;
            },
            visitPlanListData(){
                this.loading = true;
                this.visitPlanList = [];
                let obj = {
                    genDate:this.currentDay,
                    userId:this.queryParams.userId,
                    pageNum:this.queryParams.pageNum,
                    pageSize: this.queryParams.pageSize
                };
                getSelectRouteDetailStoreList(obj).then(response => {
                    console.log(response)
                    this.visitPlanList = response.rows;
                    this.total = response.total;
                    this.loading = false;
                });
            },
            calendarClick(data){
                console.log(data)
                // this.calendarValue = data.day;
                setTimeout(() => {
                    this.calendarValue = data.day;
                    this.$refs['queryParams'].validate((valid) => {
                        if (valid) {
                            this.queryParams.pageNum = 1;
                            this.getList();
                        }
                    })
                }, 500);
            },

            /** 搜索按钮操作 */
            handleQuery(formName) {
                console.log(this.$refs[formName])
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.validTree = true;
                        this.queryParams.pageNum = 1;
                        this.calendarValue = new Date();
                        this.getList();
                    }
                    // else{
                    //     if(this.queryParams.orgIds.length==0){
                    //         this.validTree = false;
                    //     }else{
                    //         this.validTree = true;
                    //     }
                    // }
                })
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.resetForm("queryParams");
                this.handleQuery();
            },
            // 根据拜访规则生成人员门店拜访详细记录
            createRouteDetailsFn(){
              const loading = this.$loading({
                lock: true,
                body: true,
                text: 'Loading正在生成中...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
              });
                let obj = {
                    userId : this.queryParams.userId
                }
                createRouteDetails(obj).then(response => {
                  loading.close();
                    this.$modal.msgSuccess("生成成功");
                    this.getList();
                });
            },
            resetQueryData(formName){

                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.createRouteDetailsFn();
                    }
                })
            },
        }
    };
</script>

<style lang="scss" scoped>
  .calendarNum{
    position: absolute;
    top: 6px;
    right: 6px;
  }
  .calendarDay{
    font-size: 16px;
    /*color: #0072C6;*/
    font-weight: bold;
    position: absolute;
    left: 8px;
    bottom: 8px;
  }
  .tips{
    color: #666;
  }
</style>
<style lang="scss">
  .dateCell{
    height: 50px;
    padding: 8px;
    box-sizing: border-box;
  }
  .el-calendar-table td.is-selected{
    background: rgb(64 158 255);
    color: #FFF;
  }
  .el-calendar-table td.is-today{
    /*color: #FFF;*/
  }
  .el-calendar-table .el-calendar-day{
    padding: 0;
  }
  .el-calendar-table .el-calendar-day:hover {
    cursor: pointer;
    background-color: rgb(64 158 255);
    color: #FFF;
  }
</style>
