<template>
  <div class="flex-row">
    <work-busy :is-busy="seaching" v-show="seaching"></work-busy>
    <div class="basic-main">
        <div  class="form-horizontal select-overspread container-fluid auto" >
          <div class="row">
            <div class="col-sm-3" style="width: 20%">
              <label class="font_normal_body">&nbsp;大&nbsp;&nbsp;&nbsp;&nbsp;区&nbsp;</label>
              <right-tree :userid.sync='userid' style="width: 60%;"
                          :source.sync='source' @re-res="getRes" ></right-tree>
            </div>
            <div class="col-sm-3" style="width: 20%">
              <label class="font_normal_body">统计年份</label>
              <datepicker  placeholder="结束日期" style="width:60%"
                           v-model="yearDate"
                           :value.sync="yearDate"
                           :format="'yyyy'"
                           :show-reset-button="true"
                           :select-year="true">
              </datepicker>
            </div>
            <div class="col-sm-3" style="width: 20%">
              <label class="font_normal_body">安检类型</label>
              <v-select id="f_approved"
                        class="select_list select"
                        placeholder='安检类型' style="width: 60%"
                        v-model='f_safecheck_type'
                        :value.sync="f_safecheck_type"
                        :options='f_safecheck_types'
                        :value-single="true"
                        close-on-select clear-button></v-select>
            </div>


            <div class="col-sm-3" style="width: 20%">
              <label class="font_normal_body" style="line-height: 20px;">用户类型</label>
              <v-select id="f_check_type"
                        class="select_list select"
                        placeholder='用户类型' style="width: 60%"
                        v-model='f_check_type'
                        :value.sync="f_check_type"
                        :options='f_check_types'
                        :value-single="true"
                        close-on-select clear-button></v-select>
            </div>


            <div class="col-sm-3" style="width: 20%">
              <div class="span" style="text-align: center;">
                <button class="button_search" @click="search()">查询</button>
                <export-excel   :data="searchData"
                                :field="excelHeaders"
                                sqlurl="api/af-safecheck/logic/exportfile" sql-name="SearchLargeAreaCheckSummaryTabTS"
                                :template-name='excelTitle'></export-excel>
              </div>
            </div>
          </div>
        </div>

        <div class="table-responsive" style="width:100%; height:92%; overflow:scroll;">
          <table class="table table-bordered diy-table" style="width:2000px; height:100%; text-align:center">
            <thead>
                <tr >
                  <th colspan="32" class="tableinfo">{{thisf_orgname}}{{thisYear}}年度各公司年度{{thissafecheck_type}}完成情况统计表</th>
                </tr>
              <tr>
                <th>序号</th>
                <th>公司名称</th>
                <th>全年应完成总数</th>
                <template v-for="index of 12">
                  <th>{{index+1}}月完成数</th>
                  <th>{{index+1}}月完成率</th>
                </template>
                <th>累计完成数</th>
                <th>累计完成率</th>
                <th>累计到访不遇数</th>
                <th>累计到访不遇率</th>
              </tr>
            </thead>

            <tbody>
                <tr v-for="(index,item) in resData">
                    <td>{{$index+1}}</td>
                    <td>{{item[0].orgname}}</td>
                    <td>{{item[0].useinfosum}}</td>
                  <template v-for="idx of 12">
                    <template v-for="it of item">
                      <td v-if="(idx+1)===it.mon" >
                        {{it.checkcount}}
                      </td>
                      <td v-if="(idx+1)===it.mon ">
                        {{it.checkcompletion}}
                      </td>
                    </template>
                  </template>
                    <td>{{item[0].checksumcount}}</td>
                    <td>{{item[0].checksumcompletion}}</td>
                    <td>{{item[0].novisitsum}}</td>
                    <td>{{item[0].novisitsumcompletion}}</td>
                </tr>
            <tr>
              <td>合计</td>
              <td>{{thisf_orgname}}</td>
              <td>{{numberOfSecurityChecksInTheYear}}</td>
              <template v-for="idx of 12">
                <td>{{numberOfSecurityChecksPerMonth(idx+1,false)}}</td>
                <td>{{numberOfSecurityChecksPerMonth(idx+1,true)}}</td>
              </template>
              <td>{{cumulativeCompletion(false)}}</td>
              <td>{{cumulativeCompletion(true)}}</td>
              <td>{{unexpectedVisits(false)}}</td>
              <td>{{unexpectedVisits(true)}}</td>
            </tr>
            </tbody>
          </table>
        </div>
    </div>
  </div>
</template>

<script>
import {HttpResetClass, PagedList} from "vue-client";
import Datepicker from 'vue-client/src/vue-strap/src/Datepicker'
import * as Util from '../../../Util'
import Vue from "vue";


export default {
  title:'安检率报表（大区）(未整合)',
  data() {
    return {
      seaching: false,
      userid: this.$login.f.id,
      // source: `tool.getFullTree(this.getRights().where(row.getType() != $zone$).where(row.getType() == $organization$))`,
      source: `tool.getFullTree(this.getRights().where(row.getType() != $zone$).where(row.getType() == $organization$))`,
      f_filialeid_id:`('${this.$login.f.orgid}')`, //分公司id
      yearDate: (new Date()).getFullYear().toString(), //统计年份
      f_safecheck_types: [{label:'年度普检',value:'年度普检'},{label:'专项计划',value:'专项计划'}],//安检类型
      f_safecheck_type: '年度普检',//安检类型
      f_check_types: [{label:'所有用户类型',value:''},{label:'民用',value:'民用'},{label:'非民用',value:'非民用'}],
      f_check_type: '民用',
      resData: [],
      thisYear: 'XXX',//当前展示数据的年份
      f_orgname: '', //选择的分公司名称
      thisf_orgname: 'XXX大区',//当前展示数据的分公司名称
      thissafecheck_type: 'XXX',//当前展示数据的计划类型
      sumuserinfo: '', //截止到去年为止总用户数
      excelHeaders:{
        'mon': '月份',
        'orgname': '公司名称',
        'useinfosum': '全年应完成总数',
        'checkcount': '完成数',
        'checkcompletion': '完成率',
        'checksumcount': '累计完成数',
        'checksumcompletion': '累计完成率',
        'novisitsum': '累计到访不遇数',
        'novisitsumcompletion': '累计到访不遇率',
      },
      searchData: {
        f_filialeid_id: this.f_filialeid_id,
        f_safecheck_type: this.f_safecheck_type,
        yearDate: this.yearDate,
        f_check_type: this.f_check_type
      }
    }
  },
  components:{
    Datepicker
  },
  methods : {
    getRes(obj) {
      console.log(obj)
      this.f_filialeid_id = this.$login.convertToIn(obj.resids);
      this.f_orgname = obj.res[0]
      // this.model.f_filialeid_id = this.$login.convertToIn(obj.resids);
    },
    // 执行查询
    search() {
      this.seaching = true;
      let  http = new HttpResetClass()
      if (this.f_safecheck_type === '年度普检' && this.f_check_type !== '民用') {
        this.$showMessage("年度普检只能选择民用用户类型，已为您自动切换为民用类型")
        this.f_check_type = '民用'
      }
      let newdate = {
        f_filialeid_id: this.f_filialeid_id,
        f_safecheck_type: this.f_safecheck_type,
        yearDate: this.yearDate,
        f_check_type: this.f_check_type
      }
      this.searchData = newdate;//导出

      http.load('POST',`/api/af-safecheck/sql/SearchLargeAreaCheckSummaryTabTS?pageNo=1&pageSize=999999`, {"data": newdate},
        {resolveMsg: '查询汇总成功！', rejectMsg: '查询汇总失败!'}).then((ress) => {
        this.seaching = false;
        if (ress.data) {
          this.thisYear = this.yearDate
          this.thisf_orgname = this.f_orgname
          this.thissafecheck_type = this.f_safecheck_type
          this.sumuserinfo = ress.data[0].sumuserinfo
          // this.resData = ress.data
          this.organizeData(ress.data)
        }
      })
    },
    organizeData(data) {
      console.log(data)
      let itemdata = data
      let enddata = []
      let i = 0;
      while (i < itemdata.length) {
         let thisFgsId  = itemdata[i].f_filialeid
         let thisFgsName  = itemdata[i].orgname
         let returendata = []
          let j = 0;
          while ( j < itemdata.length) {
            let itmdat = itemdata[j]
            let resdata = {}
            if (thisFgsId===itmdat.f_filialeid && thisFgsName===itmdat.orgname ){
              resdata=itemdata[j]
              itemdata.splice(j,1)
              j = 0
            }else {
              j++
            }
            returendata.push(resdata)
          }
          i=0
        enddata.push(returendata)
      }
     this.resData = enddata
    },
    //isRate为true 则是安检率
    numberOfSecurityChecksPerMonth(mon,isRate) {
      let monSunCount = 0
      for (let item of this.resData) {
        for (let itemElement of item) {
          if (itemElement.mon == mon) {
            monSunCount+= itemElement.checkcount
          }
        }
      }
      if (isRate) {
        let checkCpmple = ( monSunCount / this.numberOfSecurityChecksInTheYear) * 100
        return (checkCpmple?checkCpmple:0).toFixed(3) + '%'
      }else {
        return  monSunCount
      }
    },
    cumulativeCompletion(isRate){
      let sumdata = 0;
      for (let item of this.resData) {
        sumdata += item[0].checksumcount
      }
      if (isRate) {
        let checkCpmple = ( sumdata / this.numberOfSecurityChecksInTheYear) * 100
        return (checkCpmple?checkCpmple:0).toFixed(3) + '%'
      }else {
        return sumdata
      }
    },
    unexpectedVisits(isRate) {
      let sumdata = 0;
      for (let item of this.resData) {
        sumdata += item[0].novisitsum
      }
      if (isRate) {
        let checkCpmple = ( sumdata / this.numberOfSecurityChecksInTheYear) * 100
        return (checkCpmple?checkCpmple:0).toFixed(3) + '%'
      }else {
        return sumdata
      }
    }


  },
  computed: {
    numberOfSecurityChecksInTheYear() {
      let sumdata = 0;
      for (let item of this.resData) {
        sumdata += item[0].useinfosum
      }
      return sumdata
    },
    excelTitle() {
      return `${this.thisf_orgname + this.thisYear+'年度各公司年度'+this.thissafecheck_type}完成情况统计表`
    },
  },
  ready() {
    this.searchData = {
      f_filialeid_id: this.f_filialeid_id,
      f_safecheck_type: this.f_safecheck_type,
      yearDate: this.yearDate,
      f_check_type: this.f_check_type
    }
  },
  watch: {
    'f_filialeid_id': function (val) {
      this.searchData.f_filialeid_id = val
    },
    'f_safecheck_type': function (val) {
      this.searchData.f_safecheck_type = val
      if (this.f_safecheck_type === '年度普检' && this.f_check_type !== '民用') {
        this.$showMessage("年度普检只能选择民用用户类型，已为您自动切换为民用类型")
        this.f_check_type = '民用'
      }
    },
    'yearDate': function (val) {
      this.searchData.yearDate = val
    },
    'f_check_type' : function (val) {
      if (this.f_safecheck_type === '年度普检' && this.f_check_type !== '民用') {
        this.$showMessage("年度普检只能选择民用用户类型，已为您自动切换为民用类型")
        this.f_check_type = '民用'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.tableinfo {
  text-align: center;
  background-color: #00A3F0;
  color: #0c2e4d;
}
.diy-table {
  tr{
    min-width: 240px;
    max-height: 50px;
    td{
      max-height: 50px;
      min-width: 100px;
      text-align: center;
    }
  }
}
</style>
