<template>
  <div class="flex-row">
    <work-busy :is-busy="is_search"></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"
                   style="line-height: 20px;">&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" style="line-height: 20px;">统计年份</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 for="endDate" class="font_normal_body">统计类型</label>
            <v-select placeholder='统计类型' class="select select_list" style="width: 60%" :value.sync="type"
                      :value-single="true" :options='types' v-model="type" close-on-select clear-button>
            </v-select>
          </div>
          <div class="col-sm-3" style="width: 20%">
            <label for="endDate" class="font_normal_body">用户类型</label>
            <v-select placeholder='用户类型' class="select select_list" style="width: 60%" :value.sync="f_user_type"
                      :value-single="true" :options='usertypes' v-model="f_user_type" 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>
              <button class="button_search" @click="exportexcel()" v-el:cx>导出Excel</button>
            </div>
          </div>
        </div>
      </div>
      <div class="table-responsive" style="width:100%; height:92%; overflow:scroll;white-space: nowrap"
           id="planid">
        <table class="table table-bordered" style="width:2000px; height:100%; text-align:center">
          <thead>
          <tr>
            <th>公司</th>
            <th>应检数</th>
            <th>1月{{ type }}数</th>
            <th>1月{{ type }}率</th>
            <th>2月{{ type }}数</th>
            <th>2月{{ type }}率</th>
            <th>3月{{ type }}数</th>
            <th>3月{{ type }}率</th>
            <th>4月{{ type }}数</th>
            <th>4月{{ type }}率</th>
            <th>5月{{ type }}数</th>
            <th>5月{{ type }}率</th>
            <th>6月{{ type }}数</th>
            <th>6月{{ type }}率</th>
            <th>7月{{ type }}数</th>
            <th>7月{{ type }}率</th>
            <th>8月{{ type }}数</th>
            <th>8月{{ type }}率</th>
            <th>9月{{ type }}数</th>
            <th>9月{{ type }}率</th>
            <th>10月{{ type }}数</th>
            <th>10月{{ type }}率</th>
            <th>11月{{ type }}数</th>
            <th>11月{{ type }}率</th>
            <th>12月{{ type }}数</th>
            <th>12月{{ type }}率</th>
            <th>合计{{ type }}数</th>
            <th>合计{{ type }}率</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="(index, item) in resData">
            <td>{{ item.name }}</td>
            <td>{{ item.countnum }}</td>
            <td>{{ item.jan }}</td>
            <td>{{ item.jan_lv }}</td>
            <td>{{ item.feb }}</td>
            <td>{{ item.feb_lv }}</td>
            <td>{{ item.mar }}</td>
            <td>{{ item.mar_lv }}</td>
            <td>{{ item.apr }}</td>
            <td>{{ item.apr_lv }}</td>
            <td>{{ item.may }}</td>
            <td>{{ item.may_lv }}</td>
            <td>{{ item.jun }}</td>
            <td>{{ item.jun_lv }}</td>
            <td>{{ item.jul }}</td>
            <td>{{ item.jul_lv }}</td>
            <td>{{ item.aug }}</td>
            <td>{{ item.aug_lv }}</td>
            <td>{{ item.sep }}</td>
            <td>{{ item.sep_lv }}</td>
            <td>{{ item.oct }}</td>
            <td>{{ item.oct_lv }}</td>
            <td>{{ item.nov }}</td>
            <td>{{ item.nov_lv }}</td>
            <td>{{ item.dec }}</td>
            <td>{{ item.dec_lv }}</td>
            <td>{{ item.yearnum }}</td>
            <td>{{ item.yearnum_lv }}</td>
          </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import Datepicker from 'vue-client/src/vue-strap/src/Datepicker'
import XLSX from "xlsx";


export default {
  title: '安检率报表（公司）',
  data() {
    return {
      f_user_type:'',
      usertypes: [{ label: '民用', value: '民用' }, { label: '非民用', value: '非民用' }],
      type: '到户',
      types: [{ label: '到户', value: '到户' }, { label: '入户', value: '入户' }],
      userid: this.$login.f.id,
      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: '民用',
      is_search: false,
      resData: [],
      thisYear: 'XXX',//当前展示数据的年份
      f_orgname: '', //选择的分公司名称
      thisf_orgname: 'XXX公司',//当前展示数据的分公司名称
      thissafecheck_type: 'XXX',//当前展示数据的计划类型
      sumuserinfo: '', //截止到去年为止总用户数
      excelHeaders: {
        'mon': '月份',
        'checkcount': '完成数',
        'checkcompletion': '完成率',
        'sumcheckcount': '累计完成数',
        'sumcheckcompletion': '累计完成率',
        'novisit': '到访不遇数',
        'novisitcompletion': '到访不遇率'
      },
      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 : {

    exportexcel() {
      let tableData = [];
      this.resData.forEach(item => {
        let row = {
          "公司": item.name,
          "应检数": item.countnum,
          [`1月${this.type}数`]: item.jan,
          [`1月${this.type}率`]: `${((item.jan_lv || 0).replace('%', ''))}%`,
          [`2月${this.type}数`]: item.feb,
          [`2月${this.type}率`]: `${((item.feb_lv || 0).replace('%', ''))}%`,
          [`3月${this.type}数`]: item.mar,
          [`3月${this.type}率`]: `${((item.mar_lv || 0).replace('%', ''))}%`,
          [`4月${this.type}数`]: item.apr,
          [`4月${this.type}率`]: `${((item.apr_lv || 0).replace('%', ''))}%`,
          [`5月${this.type}数`]: item.may,
          [`5月${this.type}率`]: `${((item.may_lv || 0).replace('%', ''))}%`,
          [`6月${this.type}数`]: item.jun,
          [`6月${this.type}率`]: `${((item.jun_lv || 0).replace('%', ''))}%`,
          [`7月${this.type}数`]: item.jul,
          [`7月${this.type}率`]: `${((item.jul_lv || 0).replace('%', ''))}%`,
          [`8月${this.type}数`]: item.aug,
          [`8月${this.type}率`]: `${((item.aug_lv || 0).replace('%', ''))}%`,
          [`9月${this.type}数`]: item.sep,
          [`9月${this.type}率`]: `${((item.sep_lv || 0).replace('%', ''))}%`,
          [`10月${this.type}数`]: item.oct,
          [`10月${this.type}率`]: `${((item.oct_lv || 0).replace('%', ''))}%`,
          [`11月${this.type}数`]: item.nov,
          [`11月${this.type}率`]: `${((item.nov_lv || 0).replace('%', ''))}%`,
          [`12月${this.type}数`]: item.dec,
          [`12月${this.type}率`]: `${((item.dec_lv || 0).replace('%', ''))}%`,
          [`合计${this.type}数`]: item.yearnum,
          [`合计${this.type}率`]: `${((item.yearnum_lv || 0).replace('%', ''))}%`
        };
        tableData.push(row);
      });
      // 使用 XLSX 写入自定义数据
      let ws = XLSX.utils.json_to_sheet(tableData);
      let wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
      XLSX.writeFile(wb, '安检率报表（公司）.xlsx');
    },
    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);
    },
    // 执行查询
    async search() {
      this.is_search = true
      setTimeout(()=>{
        this.is_search = false
      },5000)
      let usertype = this.f_user_type ?` and f_check_type = '${this.f_user_type}'`:''
      let newdate = {
        f_filialeid_id: this.f_filialeid_id,
        yearDate: this.yearDate,
        condition: this.type === '入户' ? `f_entry_status = '入户' AND f_safecheck_type in ('年度普检','专项计划') ${usertype}` : `1 = 1 AND f_safecheck_type in ('年度普检','专项计划') ${usertype}`
      }
      this.searchData = newdate;//导出
      let res = await this.$resetpost("/api/af-safecheck/sql/ReportSql1?pageNo=1&pageSize=999999",
        {"data": newdate},
        {resolveMsg : '查询汇总成功！', rejectMsg : '查询汇总失败！'})
      let sum = {
        "jul": 0,
        "oct": 0,
        "feb": 0,
        "apr": 0,
        "jun": 0,
        "dec": 0,
        "may": 0,
        "countnum": 0,
        "aug": 0,
        "nov": 0,
        "jan": 0,
        "name": "合计",
        "yearnum": 0,
        "mar": 0,
        "sep": 0
      }
       if (res.data) {
         for (let i = 0; i < res.data.length; i++) {
           for (let datumKey in res.data[i]) {
             switch (datumKey) {
               case 'jul':
                 sum.jul += res.data[i][datumKey]
                 break;
               case 'oct':
                 sum.oct += res.data[i][datumKey]
                 break;
               case 'feb':
                 sum.feb += res.data[i][datumKey]
                 break;
               case 'apr':
                 sum.apr += res.data[i][datumKey]
                 break;
               case 'jun':
                 sum.jun += res.data[i][datumKey]
                 break;
                 case 'dec':
                 sum.dec += res.data[i][datumKey]
                 break;
               case 'may':
                 sum.may += res.data[i][datumKey]
                 break;
               case 'countnum':
                 sum.countnum += res.data[i][datumKey]
                 break;
               case 'aug':
                 sum.aug += res.data[i][datumKey]
                 break;
               case 'nov':
                 sum.nov += res.data[i][datumKey]
                 break;
               case 'jan':
                 sum.jan += res.data[i][datumKey]
                 break;
               case 'mar':
                 sum.mar += res.data[i][datumKey]
                 break;
               case 'sep':
                 sum.sep += res.data[i][datumKey]
                 break;
               case 'yearnum':
                 sum.yearnum += res.data[i][datumKey]
                 break;
             }
           }
         }
         res.data.push(sum)
         this.resData = this.calculateMonthlyRates(res.data)
         console.log(this.resData)
       }
      this.is_search = false
    },
    calculateMonthlyRates(data) {
      data.forEach(item => {
        const months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", "yearnum"];
        months.forEach(month => {
          if (item.hasOwnProperty(month)) {
            let rate = (item[month] / item.countnum) * 100; // 计算率（百分比）
            item[`${month}_lv`] = `${rate.toFixed(2)}%`; // 保留两位小数并添加到对象中
          }
        });
      });
      return data;
    }
  },
  computed: {
    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 scoped>
.tableinfo {
  text-align: center;
  background-color: #00A3F0;
  color: #0c2e4d;
}
</style>
