<template>
  <div>
    <div class="navBarTOP">
      <van-nav-bar class="navBar" left-arrow title="下属汇报率审批率统计" @click-left="onClickLeft"/>
    </div>
    <!--        主体内容-->
    <div class="lineGrey"></div>
    <div class="lineGrey"></div>
    <div class="lineGrey"></div>
    <div class="lineGrey"></div>
    <div class="lineGrey"></div>
    <div class="container contentpd16 containers">
      <van-row gutter="20">
        <van-col span="12">
          <van-cell :disabled="powerGrade<5" :title="companyName" arrow-direction="down" is-link @click="regionClick"/>
        </van-col>
        <van-col span="12">
          <van-cell :title="regionName" arrow-direction="down" is-link @click="SalesRegionClick"/>
        </van-col>
        <van-col span="12">
          <van-cell :title="seacherForm.startTime" is-link @click="StartTimeClick">
            <template #right-icon>
              <van-icon :name="timeico" class="search-icon"/>
            </template>
          </van-cell>
        </van-col>
        <van-col span="12">
          <van-cell :title="seacherForm.endTime" is-link @click="EndTimeClick">
            <template #right-icon>
              <van-icon :name="timeico" class="search-icon"/>
            </template>
          </van-cell>
        </van-col>
      </van-row>
    </div>
    <el-table :data="tableList" :load="load" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border class="elTreeTable" lazy row-key="id">
      <el-table-column class="firstName" label="组织名称/业务员(单位%)" prop="deptName" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.reportType==1">{{ scope.row.userName }}</span>
          <span v-if="scope.row.reportType!=1">{{ scope.row.deptName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="半月报" width="46">
        <el-table-column label="提交率%" prop="name" width="46">
          <template slot-scope="scope">
            <span v-if="scope.row.reportType!=3" class="spanNum">{{ scope.row.doubleWeekCommitRate }} </span>
            <div v-if="scope.row.reportType==3&&scope.row.doubleWeekCommitRate!=null">
              <span v-if="scope.row.doubleWeekCommitRate!='-'" class="linkSpan" @click="linKReportHistory(scope.row,3)">{{ scope.row.doubleWeekCommitRate }}</span>
              <span v-if="scope.row.doubleWeekCommitRate=='-'" style="text-align: center;display: block">{{ scope.row.doubleWeekCommitRate }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="周报" width="46">
        <el-table-column label="提交率%" prop="address" width="46">
          <template slot-scope="scope">
            <span v-if="scope.row.reportType!=2" class="spanNum">{{ scope.row.weekCommitRate }} </span>
            <div v-if="scope.row.reportType==2&&scope.row.weekCommitRate!=null">
              <span v-if="scope.row.weekCommitRate!='-'" class="linkSpan" @click="linKReportHistory(scope.row,2)">{{ scope.row.weekCommitRate }}</span>
              <span v-if="scope.row.weekCommitRate=='-'" style="text-align: right;display: block">{{ scope.row.weekCommitRate }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="审批率%" prop="weekApprovalRate" width="46">
          <template slot-scope="scope">
            <span v-if="scope.row.reportType!=2" class="spanNum">{{ scope.row.weekApprovalRate }} </span>
            <div v-if="scope.row.reportType==2&&scope.row.weekApprovalRate!==null">
              <span v-if="scope.row.weekApprovalRate!='-'" class="linkSpan" @click="linKReportHistory(scope.row,2)">{{ scope.row.weekApprovalRate }}</span>
              <span v-if="scope.row.weekApprovalRate=='-'" style="text-align: right;display: block">{{ scope.row.weekApprovalRate }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="日报" width="46">
        <el-table-column label="提交率%" prop="address" width="46">
          <template slot-scope="scope">
            <span v-if="scope.row.reportType!=1" class="spanNum">{{ scope.row.dayCommitRate }} </span>
            <div v-if="scope.row.reportType==1&&scope.row.dayCommitRate!=null">
              <span v-if="scope.row.dayCommitRate!='-'" class="linkSpan" @click="linKReportHistory(scope.row,1)">{{ scope.row.dayCommitRate }}</span>
              <span v-if="scope.row.dayCommitRate=='-'" style="text-align: right;display: block">{{ scope.row.dayCommitRate }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="审批率%" prop="address" width="46">
          <template slot-scope="scope">
            <span v-if="scope.row.reportType!=1" class="spanNum">{{ scope.row.dayApprovalRate }} </span>
            <div v-if="scope.row.reportType==1&&scope.row.dayApprovalRate!=null">
              <span v-if="scope.row.dayApprovalRate!='-'" class="linkSpan" @click="linKReportHistory(scope.row,1)">{{ scope.row.dayApprovalRate }}</span>
              <span v-if="scope.row.dayApprovalRate=='-'" style="text-align: right;display: block">{{ scope.row.dayApprovalRate }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>

    <van-popup v-model="RegionShow" capture position="bottom">
      <van-picker
          :columns="companyList"
          show-toolbar
          value-key="deptName"
          @cancel="RegionShow = false"
          @confirm="onregionConfirm"
      />
    </van-popup>
    <van-popup v-model="SalesRegionShow" capture position="bottom">
      <van-picker
          :columns="regionList"
          show-toolbar
          value-key="deptName"
          @cancel="SalesRegionShow = false"
          @confirm="onSalesRegionConfirm"
      />
    </van-popup>
    <van-popup v-model="SalesDepartmentShow" capture position="bottom">
      <van-picker
          :columns="deptList"
          show-toolbar
          value-key="deptName"
          @cancel="SalesDepartmentShow = false"
          @confirm="onSalesDepartmentConfirm"
      />
    </van-popup>
    <van-popup v-model="StaffShow" capture position="bottom">
      <van-picker
          :columns="userList"
          show-toolbar
          value-key="nickName"
          @cancel="StaffShow = false"
          @confirm="onStaffConfirm"
      />
    </van-popup>

    <van-popup v-model="StartTimeShow" capture position="bottom">
      <van-datetime-picker
          v-model="strtcurrentDate"
          :max-date="strtmaxDate"
          :min-date="strtminDate"
          title="选择查找开始时间"
          type="date"
          @cancel="StartTimeShow = false"
          @confirm="onStartTimeConfirm"
      />
    </van-popup>
    <van-popup v-model="EndTimeShow" capture position="bottom">
      <van-datetime-picker
          v-model="endcurrentDate"
          :max-date="endmaxDate"
          :min-date="endminDate"
          title="选择查找结束时间"
          type="date"
          @cancel="EndTimeShow = false"
          @confirm="onEndTimeConfirm"
      />
    </van-popup>
  </div>
</template>
<script>
import request from '@/utils/request'
import {queryRates, getDeptInfo} from "@/api/index";
import timeico from "@/assets/Icon/datatims.png";

export default {
  data() {
    return {
      timeico: timeico,
      RegionShow: false,
      SalesRegionShow: false,
      SalesDepartmentShow: false,
      StaffShow: false,
      StartTimeShow: false,
      EndTimeShow: false,
      PhotoTypeList: [{text: "009", value: "09"}],
      strtminDate: new Date(2022, 0, 1),
      endminDate: new Date(2022, 0, 1),
      strtmaxDate: new Date(),
      endmaxDate: new Date(),
      strtcurrentDate: new Date(),
      endcurrentDate: new Date(),
      companyName: "全部",
      deptName: "全部",
      regionName: "全部",
      userName: "全部",
      companyCode: "",
      deptCode: "",
      regionCode: "",
      userCode: "",
      companyList: [],
      deptList: [],
      regionList: [],
      userList: [],
      deptForm: {
        type: "",
        parentId: ""
      },
      list: [],
      tableList: [],
      seacherFormload: {
        companyId: "",
        regionId: "",
        parentId: "",
        startTime: "",
        endTime: ""
      },

      seacherForm: {
        companyId: "",
        regionId: "",
        parentId: "",
        startTime: "",
        endTime: ""
      }
    }
  },
  created() {
    this.seacherForm.startTime = this.parseTime(new Date(), '{y}-{m}-{d}')
    this.seacherFormload.startTime = this.parseTime(new Date(), '{y}-{m}-{d}')
    this.strtcurrentDate = new Date(this.parseTime(new Date(), '{y}-{m}-{d}'))
    this.seacherForm.endTime = this.parseTime(new Date(), '{y}-{m}-{d}') + ""
    this.seacherFormload.endTime = this.parseTime(new Date(), '{y}-{m}-{d}') + ""
    this.endminDate = new Date(this.GetPreMonthDay(this.parseTime(new Date(), '{y}-{m}-{d}'), 2))
    this.powerGrade = localStorage.getItem("powerGrade")
    this.getDeptInfo("dept")
    if (this.powerGrade > 3) {
      setTimeout(() => {
        this.getDeptInfo("dept", 1)
      }, 1000)
    }
  },
  watch: {
    $route(to, from) {
      if (to.path == "/reportingRate" && from.path == "/My/index") {
        this.seacherForm.startTime = this.parseTime(new Date(), '{y}-{m}-{d}')
        this.seacherFormload.startTime = this.parseTime(new Date(), '{y}-{m}-{d}')
        this.strtcurrentDate = new Date(this.parseTime(new Date(), '{y}-{m}-{d}'))
        this.seacherForm.endTime = this.parseTime(new Date(), '{y}-{m}-{d}') + ""
        this.seacherFormload.endTime = this.parseTime(new Date(), '{y}-{m}-{d}') + ""
        this.endminDate = new Date(this.GetPreMonthDay(this.parseTime(new Date(), '{y}-{m}-{d}'), 2))
        this.deptCode = "";
        this.userCode = "";
        this.regionCode = ""
        this.seacherForm.parentId = ""
        this.seacherFormload.parentId = ""
        this.regionName = "全部"
        this.powerGrade = localStorage.getItem("powerGrade")
        this.getDeptInfo("dept")
        if (this.powerGrade > 3) {
          setTimeout(() => {
            this.getDeptInfo("dept", 1)
          }, 1000)
        }
      }
    }
  },
  methods: {
    GetPreMonthDay(date, monthNum, type) {
      var dateArr = date.split('-');
      var year = dateArr[0]; //获取当前日期的年份
      var month = dateArr[1]; //获取当前日期的月份
      var day = dateArr[2]; //获取当前日期的日
      var days = new Date(year, month, 0);
      days = days.getDate(); //获取当前日期中月的天数
      var year2 = year;
      var month2 = parseInt(month) - monthNum;
      if (month2 <= 0) {
        var absM = Math.abs(month2);
        year2 = parseInt(year2) - Math.ceil(absM / 12 == 0 ? 1 : parseInt(absM) / 12);
        month2 = 12 - (absM % 12);
      }
      var day2 = day;
      var days2 = new Date(year2, month2, 0);
      days2 = days2.getDate();
      if (day2 > days2) {
        day2 = days2;
      }
      if (month2 < 10) {
        month2 = '0' + month2;
      }
      var t2 = ""
      if (monthNum > 0) {
        t2 = year2 + '-' + month2 + '-01';
      } else {
        if (type == "end") {
          var Months = new Date().getMonth() + 1
          var days111 = new Date().getDate()
          if (Months < 10) {
            Months = '0' + Months;
          }
          if (days111 < 10) {
            days111 = '0' + days111;
          }
          if (parseInt(month2) >= new Date().getMonth() + 1) {
            t2 = year2 + '-' + Months + '-' + days111;
          } else {
            var daysd = this.getMonthDays(year2, month2)
            t2 = year2 + '-' + month2 + '-' + daysd;
          }
        } else {
          t2 = year2 + '-' + month2 + '-' + day2;
        }
      }
      return t2;
    },
    getMonthDays(year, month) {
      var stratDate = new Date(year, month - 1, 1),
          endData = new Date(year, month, 1);
      var days = (endData - stratDate) / (1000 * 60 * 60 * 24);
      return days;
    },
    getDeptInfo(type, grade) {
      this.deptForm.type = type
      if (type == "dept") {
        if (grade == "1") {
          this.deptForm.parentId = this.companyCode
        } else if (grade == "2") {
          this.deptForm.parentId = this.regionCode
        } else {
          this.deptForm.type = ""
          this.deptForm.parentId = ""
        }
      } else if (type == "user") {
        this.deptForm.parentId = this.deptCode
      }
      getDeptInfo(this.deptForm).then(res => {
        if (type == "dept") {
          if (grade == "1") {
            if (res.data.region != null) {
              this.regionList = [{deptName: "全部", deptId: ""}].concat(res.data.region)
            }
          } else if (grade == "2") {
            if (res.data.dept != null) {
              this.deptList = [{deptName: "全部", deptId: ""}].concat(res.data.dept)
            }
          } else {
            this.companyList = res.data.company
            this.companyName = res.data.company[0].deptName
            this.companyCode = res.data.company[0].deptId
            if (res.data.region != null) {
              this.regionName = res.data.region[0].deptName
              this.regionCode = res.data.region[0].deptId
              this.regionList = res.data.region
            }
            if (res.data.user != null) {
              this.userList = res.data.user
              this.userCode = ""
            }
            this.queryRates()
          }
        } else if (type == "user") {
          if (res.data.user != null) {
            this.userList = [{nickName: "全部", userId: ""}].concat(res.data.user)
          }
        }
      })
    },
    dailyFn() {
      this.$router.push("/dailyDetails")
    },
    onClickLeft() {
      this.$router.go(-1)
    },
    regionClick() {
      this.RegionShow = true;
    },
    SalesRegionClick(val) {
      this.SalesRegionShow = true;
    },
    SalesDepartmentClick() {
      this.SalesDepartmentShow = true;
    },
    StaffClick() {
      this.StaffShow = true;
    },
    StartTimeClick() {
      this.StartTimeShow = true;
    },
    EndTimeClick() {
      this.EndTimeShow = true;
    },
    onregionConfirm(val) {
      this.tableList = []
      this.RegionShow = false;
      this.companyName = val.deptName;
      this.companyCode = val.deptId;
      this.regionName = "全部";
      this.regionCode = "";
      this.deptName = "全部";
      this.deptCode = "";
      this.userName = "全部";
      this.userCode = "";
      this.seacherForm.parentId = ""
      this.seacherFormload.parentId = ""
      this.getDeptInfo("dept", 1)
      this.queryRates()
    },
    onSalesRegionConfirm(val) {
      this.tableList = []
      this.SalesRegionShow = false;
      this.regionName = val.deptName;
      this.seacherForm.parentId = ""
      this.seacherFormload.parentId = ""

      if (val.deptId != "") {
        this.regionCode = val.deptId;
        this.getDeptInfo("dept", 2)
        this.deptName = "全部";
        this.deptCode = ""
      } else {
        this.regionCode = ""
        this.deptName = "全部";
        this.deptCode = "";
        this.userName = "全部";
        this.userCode = "";
      }
      this.queryRates()
    },
    onSalesDepartmentConfirm(val) {
      this.tableList = []
      this.SalesDepartmentShow = false;
      this.deptName = val.deptName;
      if (val.deptId != "") {
        this.deptCode = val.deptId;
        this.getDeptInfo("user")
      } else {
        this.userName = "全部";
        this.userCode = "";
      }
    },
    onStaffConfirm(val) {
      this.StaffShow = false;
      this.userName = val.nickName;
      this.userCode = val.userId;
    },
    onStartTimeConfirm(val) {
      this.seacherForm.startTime = this.parseTime(new Date(val), '{y}-{m}-{d}') + ""
      this.seacherForm.parentId = ""
      this.seacherFormload.startTime = this.parseTime(new Date(val), '{y}-{m}-{d}') + ""
      this.seacherFormload.parentId = ""
      this.tableList = []
      this.StartTimeShow = false;
      if(new Date(val).getTime()<new Date(this.GetPreMonthDay(this.formData.startTime,-2,"end")).getTime()){
        this.endminDate = new Date(this.GetPreMonthDay(this.formData.startTime,-2,"end"))
        this.endmaxDate=new Date(this.GetPreMonthDay(this.formData.startTime,-2,"end"))
      }else{
        this.endminDate = new Date(val)
        this.endmaxDate=new Date(this.GetPreMonthDay(this.formData.startTime,-2,"end"))
      }
      if ((new Date(this.seacherForm.startTime).getTime() > new Date(this.seacherForm.endTime).getTime()) || (new Date(this.endmaxDate).getTime() < new Date(this.seacherForm.endTime).getTime())) {
        this.seacherForm.endTime = this.parseTime(new Date(val), '{y}-{m}-{d}') + ""
        this.seacherFormload.endTime = this.parseTime(new Date(val), '{y}-{m}-{d}') + ""

        this.endcurrentDate = this.GetPreMonthDay(this.seacherForm.startTime, -2)
      }
      this.queryRates()
    },
    onEndTimeConfirm(val) {
      this.tableList = []
      this.seacherForm.endTime = this.parseTime(new Date(val), '{y}-{m}-{d}')
      this.seacherForm.parentId = ""
      this.seacherFormload.endTime = this.parseTime(new Date(val), '{y}-{m}-{d}')
      this.seacherFormload.parentId = ""
      this.strtmaxDate = new Date(val)
      if (new Date(this.seacherForm.startTime).getTime() > new Date(this.seacherForm.endTime).getTime()) {
        this.seacherForm.startTime = this.seacherForm.endTime
        this.seacherFormload.startTime = this.seacherForm.endTime

      }
      this.queryRates()
      this.EndTimeShow = false;
    },
    queryRates() {
      this.seacherForm.companyId = this.companyCode
      this.seacherFormload.companyId = this.companyCode
      this.seacherForm.regionId = this.regionCode
      this.seacherFormload.regionId = this.regionCode
      queryRates(this.seacherForm).then(res => {
        if (res.code == 200) {
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].reportType > 1) {
              res.data[i].hasChildren = true
            }
          }
          this.tableList = res.data
        } else {
          this.$toast.fail('数据获取失败');
        }
      })
    },
    linKReportHistory(row, type) {
      if (type == 1) {
        var userId = ""
        var userName = "全部"
        if (row.userId == "null") {
          userId = ""
          userName = "全部"
        } else {
          userId = row.userId
          userName = row.userName
        }
        this.$router.push({
          path: "/subordinateHistoricalDaily",
          query: {
            companyCode: this.companyCode,
            companyName: this.companyName,
            regionCode: row.regionId,
            regionName: row.regionName,
            deptCode: row.deptId,
            deptName: row.deptName + "销售部",
            userCode: userId,
            userName: userName,
            startTime: this.seacherForm.startTime,
            endTime: this.seacherForm.endTime
          }
        })
      } else if (type == 2) {
        this.$router.push({
          path: "/subordinateHistoricalWeekly",
          query: {
            companyCode: this.companyCode,
            companyName: this.companyName,
            regionCode: row.regionId,
            regionName: row.regionName,
            deptCode: row.deptId,
            deptName: row.deptName + "销售部",
            startTime: this.seacherForm.startTime,
            endTime: this.seacherForm.endTime
          }
        })
      } else {
        this.$router.push({
          path: "/doubleWeeklyHistorical",
          query: {
            companyCode: this.companyCode,
            companyName: this.companyName,
            regionCode: row.deptId,
            regionName: row.deptName + "销售大区",
            startTime: this.seacherForm.startTime,
            endTime: this.seacherForm.endTime
          }
        })
      }
    },
    load(tree, treeNode, resolve) {
      if (tree.reportType == 2) {
        this.seacherFormload.parentId = tree.deptId
      } else if (tree.reportType == 3) {
        // this.regionCode=tree.deptId
        // this.regionName=tree.deptName+"销售大区"
        this.seacherFormload.parentId = ""
        this.seacherFormload.regionId = tree.deptId
      } else {
        this.seacherFormload.parentId = ""
      }
      request({
        url: 'mobile/reportMobile/queryRates',
        method: 'get',
        params: this.seacherFormload
      }).then(res => {
        if (res.code == 200) {
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].reportType > 1) {
              res.data[i].hasChildren = true
            } else {
              res.data[i].hasChildren = false
            }
          }
          resolve(res.data)
        } else {
          this.$toast.fail('数据获取失败');
        }
      })
    }
  }
}
</script>
<style>
body {
  margin: 0;
}

.elTreeTable table {
  width: 100% !important;
}

.elTreeTable .el-table__cell:first-child .cell {
  padding-left: 2px !important;
}

.elTreeTable .el-table__cell {
  padding: 0px;
}

.elTreeTable .el-table__body td.el-table__cell {
  padding: 2px;
}

.elTreeTable table col {
  text-align: center;
}

.elTreeTable th.el-table__cell > .cell {
  padding: 1px !important;
}

.elTreeTable {
  font-size: 12px !important;
}

.elTreeTable th.el-table__cell {
  padding: 1px !important;
}

.elTreeTable th.el-table__cell > .cell {
  text-align: center;
}

.elTreeTable .el-table__header tr:first-child th.el-table__cell:first-child .cell {
  width: 98px;
}

.elTreeTable .linkSpan {
  text-decoration: underline;
  color: #0057ba;
  display: block;
  text-align: right;
  padding: 6px 10px;
}

.elTreeTable td.el-table__cell div {
  padding: 0px;
}

.elTreeTable .cell .spanNum {
  display: block;
  text-align: right;
  padding: 6px 10px;
}

.elTreeTable .el-table__expand-icon {
  float: right;
}
.search-icon {
  font-size: 16px;
  line-height: inherit;
  margin-top: 4px;
}
.contentpd16 {
  padding: 16px;
  background-color: white;
}
.contentpd16 .van-cell {
  background-color: #EBF4FF;
  margin: 8px 0;
  border-radius: 5px;
  padding: 4px 16px;
}
</style>
