<template>
  <div class="item-list-wrap">
    <bread-crumb :curmbFirst="curmbFirst" :curmbSecond="curmbSecond" :curmbThird="curmbThird" :jumPathThird="jumPathThird"></bread-crumb>
    <div class="component-content screenSet" id="screenSet">
      <el-form class="item-form" ref="formInline" :model="formInline" label-width="80px">
        <div class="form-title">查询条件</div>
        <el-form-item label="选择地区：">
          <!-- :props="props" -->
          <el-col :span="12">
          <el-cascader
            size="small"
            ref="cascaderRegion"
            :options="optionsRegion"
            :props="props"
            v-model="formInline.region"
            @change="handleChange"
            filterable
            change-on-select
            placeholder="请先选择地区后再进行查询"
            style="width:330px"
          ></el-cascader>
          </el-col>
          <el-col :span="6">
            <el-checkbox v-if="showOriginal !== 1" size="small" v-model="formInline.checked">查看原始数据</el-checkbox>
          </el-col>
        </el-form-item>
        <el-form-item label="选择机构：">
          <el-select
            size="small"
            v-model="formInline.organization"
            :placeholder="organizationNotice"
            @change="changeOrganization"
            multiple
            collapse-tags
            :disabled="areaLen < 3"
            style="width:330px"
          >
            <el-option
              v-for="item in organizationList"
              :key="item.index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <div class="tag-group">
          <el-tag
            v-for="tag in tags"
            :key="tag.value"
            type="info"
            closable
            @close="handleTagClose(tag)"
          >{{ tag.label }}</el-tag>
        </div>
        <el-form-item label="选择时间：">
          <el-col :span="8">
            <el-select 
              size="small"
              v-model="formInline.timeFlag" 
              placeholder="请选择"
              style="width:330px;"
              >
              <el-option
                v-for="item in timeFlagList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="8" v-show="formInline.timeFlag == 2">
            <el-date-picker
              size="small"
              v-model="formInline.during"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-col>
        </el-form-item>
        <!-- <el-form-item label v-if="showOriginal !== 1">
          <el-checkbox size="small" v-model="formInline.checked">查看原始数据</el-checkbox>
        </el-form-item> -->
        <div class="form-button">
          <el-button size="small" @click="search()" type="primary">查询</el-button>
          <el-button size="small" @click="resetForm()">重置</el-button>
        </div>
      </el-form>
      <div class="button-group">
        <el-button v-if="roleType == 1 || roleType == 2" type="default" size="small" @click="changeDate">数据修改</el-button>
        <!-- <el-button type="default" size="small" @click="update" v-else>修改范围</el-button> -->
        <el-button type="default" size="small" :disabled="exportStatus" @click="exportPDF">导出PDF</el-button>
        <el-button type="default" size="small" :disabled="exportStatus" @click="exportExcel">导出明细</el-button>
      </div>
      <div class="item-tab"></div>
      <el-tabs class="item-list-tabs" ref="tabs" id="item-list-tabs" v-model="activeName" @tab-click="handleClick" :before-leave="beforeLeave">
        <el-tab-pane label="数据总览" name="zero" >
          <data-all
            ref="childDataAll"
            :formInline="formInline"
            :activeName="activeName"
            :organizationNum="organizationNum"
            :organizationList="organizationList"
          ></data-all>
        </el-tab-pane>
        <!-- <el-tab-pane label="参与情况" name="first">
          <part-in
            ref="childPart"
            :formInline="formInline"
            :activeName="activeName"
            :organizationNum="organizationNum"
            :organizationList="organizationList"
          ></part-in>
        </el-tab-pane> -->
        <el-tab-pane label="人群分析" name="second">
          <crowd-analysis
            ref="childCrowd"
            :formInline="formInline"
            :activeName="activeName"
            :organizationList="organizationList"
          ></crowd-analysis>
        </el-tab-pane>
        <el-tab-pane label="课程分析" name="third" v-if="displayCourse == 1">
          <course-analysis
            ref="childCourse"
            :formInline="formInline"
            :activeName="activeName"
            :dialogData="dialogData"
            :organizationList="organizationList"
          ></course-analysis>
        </el-tab-pane>
        <el-tab-pane label="考试分析" name="fourth" v-if="displayExam == 1">
          <examination-analysisfrom
            ref="childExam"
            :formInline="formInline"
            :activeName="activeName"
            :dialogData="dialogData"
            :organizationList="organizationList"
          ></examination-analysisfrom>
        </el-tab-pane>
        <el-tab-pane label="学习效果分析" name="fifth" v-if="displayEffect == 1">
          <learning-effect 
            ref="childEffect"
            :formInline="formInline"
            :activeName="activeName"
          ></learning-effect>
        </el-tab-pane>
      </el-tabs>
      <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" center>
        <p style="text-align:center">文件正在生成，你可以去“我的导出下载”页，下载文件</p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">留在当前页</el-button>
          <el-button type="primary" @click="toDownload()">去下载</el-button>
        </span>
      </el-dialog>
      <el-dialog title :visible.sync="dialogUpdate" width="80%" center>
        <!-- <el-button @click="dialogUpdate = false">取 消</el-button> -->
        <data-alignment
          ref="childAlignment"
          @closeDialog="dialogUpdate = false"
          @closeSearch="closeSearch"
          :formInline="formInline"
          :dialogData="dialogData"
          :organizationList="organizationList"
        ></data-alignment>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import BreadCrumb from "../../components/breadcrumb.vue";
import CourseAnalysis from "./item-course-analysis.vue";
import CrowdAnalysis from "./item-crowd-analysis.vue";
import PartIn from "./item-part-in.vue";
import ExaminationAnalysisfrom from "./item-examination-analysis.vue";
import LearningEffect from "./item-learning-effect.vue";
import DataAlignment from "./data-alignment.vue";
import DataAll from "./item-data-all.vue";
import { create } from "domain";
import { mapGetters } from "vuex";
import { openLoading, closeLoading } from "../../utils/utils";
import * as commonUtil from "../../utils/utils";
import * as operationData from "../../utils/operation";
import { log } from "util";
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'

let vm = null;
export default {
  components: {
    BreadCrumb,
    CourseAnalysis,
    CrowdAnalysis,
    PartIn,
    ExaminationAnalysisfrom,
    LearningEffect,
    DataAlignment,
    DataAll,
  },
  data() {
    return {
      curmbFirst: "学情报告",
      curmbSecond: "项目列表",
      curmbThird: "",
      jumPathThird: "/report-list",
      projectId: "",
      projectName: "",
      exportStatus: false,
      organizationList: [],
      optionsRegion: [],
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node;
          if (node.level >= 1) {
            console.log("node", node);
            let req = {
              projectId: vm.projectId,
              regionId: node.data.value
            };
            vm.GET("stats/region", req).then(res => {
              let newData = vm.setRegionOptionMore(res.data.list);
              console.log("newData", newData);
              resolve(newData);
            });
          }
        }
      },
      showOriginal: 2,
      roleType: '',
      formInline: {
        region: [],
        date: "",
        organization: [],
        checked: false,
        timeFlag: 1,
        during: null,
        pageNo: 1,
        pageSize: 20,
      },
      organizationNotice: '选择地区筛选到区才能选择机构',
      dialogData: {
        region: "",
        // regionData: "",
        organization: ""
        // organizationData: "",
      },
      tags: [],
      activeName: "zero",
      organizationNum: 0,
      dialogVisible: false,
      dialogUpdate: false,
      displayExam: 1,
      flag: 1,
      //v2.0更新data部分
      timeFlagList: [
        {
          value: 1,
          label: '截至昨日',
        },
        {
          value: 2,
          label: '开始时间结束时间',
        }
      ],
      areaLen: 1,
      hospitalCnt: 0,
      hospitalId: [],
      certFlag: 0,
      displayCourse: 1,
      displayEffect: 1,
    };
  },
  computed: {
    ...mapGetters(["_token"])
  },
  watch: {
    tags: function(val) {
      this.setDialogData();
    }
  },
  created() {
    vm = this;
    this.projectId = vm.getUrlSearch(window.location.href, "id");
    this.projectName = vm.getUrlSearch(window.location.href, "projectName");
    this.curmbThird = vm.getUrlSearch(window.location.href, "projectName");
    this.getDisplay();
    // this.search();
    // this.getRegionOption();
  },
  mounted: function() {
    commonUtil.resizeHeight();
  },
  methods: {
    getDisplay(type) {
      let reqInfo = {
        projectId: vm.projectId,
      };
      openLoading(vm);
      vm.GET("stats/region/info", reqInfo).then(res => {
        closeLoading(vm);
        if (res.code == "000000") {
          vm.showOriginal = res.data.status;
          vm.roleType = res.data.roleType;
          vm.displayCourse = res.data.existCourse;
          vm.displayExam = res.data.existExam;
          vm.displayEffect = res.data.existEffect;
          vm.certFlag = res.data.certFlag;
          vm.getRegionOption();
        }
      });
    },
    beforeLeave(activeName, oldActiveName) {
      // console.log('action',activeName,'oldActive',oldActiveName)
    },
    handleClick(tab, event) {
      // console.log("activeName", this.activeName, tab.name);
      // if (tab.name == "first") {
      //   this.$refs.childPart.$emit("init");
      // } else if (tab.name == "second") {
      //   this.$refs.childCrowd.$emit("init");
      // } else if (tab.name == "third") {
      //   this.$refs.childCourse.$emit("init");
      // } else if (tab.name == "fourth") {
      //   this.$refs.childExam.$emit("init");
      // }
    },
    handleChange(value) {
      this.formInline.organization = [];
      this.tags = [];
      setTimeout(function() {
        // console.log(vm.$refs["cascaderRegion"].inputValue);
        vm.dialogData.region = vm.$refs["cascaderRegion"].inputValue;
        // vm.dialogData.regionData = value[value.length-1];
        // console.log('vm.dialogData.region',vm.dialogData.region)
      }, 20);
      // console.log('region',value,vm.formInline);
      let areaArr = value[value.length -1].split('_');
      vm.areaLen = areaArr.length;
      console.log('areaArr!!',areaArr);
      if (areaArr.length >= 3) {
        this.getOrganizationList();
        this.organizationNotice = "请选择机构";
      } else {
        this.organizationNotice = "选择地区筛选到区才能选择机构";
      }
    },
    setRegionOptionMore(data) {
      let option = [];
      for (let i = 0; i < data.length; i++) {
        let obj = data[i];
        obj.label = data[i].label;
        obj.value = data[i].id;
        if(obj.degree == 4) {
          obj.leaf = true;
        }
        option.push(obj);
      }
      return option;
    },
    changeOrganization(value) {
      // console.log('formInline',this.formInline.organization);
      this.tags = [];
      //选了全部的情况下
      for (let a = 0; a < this.formInline.organization.length; a++) {
        if (this.formInline.organization[a] == 0) {
          //选了全部
          let tagItem = {
            label: "全部",
            value: 0
          };
          this.tags.push(tagItem);
          return;
        }
      }
      //没选全部
      for (let i = 0; i < this.organizationList.length; i++) {
        for (let j = 0; j < value.length; j++) {
          if (value[j] == this.organizationList[i].value) {
            // console.log('value[j]',j,value[j],this.organizationList[i].label )
            let tagItem = {
              label: this.organizationList[i].label,
              value: this.organizationList[i].value
            };
            this.tags.push(tagItem);
          }
        }
      }
    },
    handleTagClose(tag) {
      // console.log(tag);
      //选了全部的情况下
      if (this.tags.length > 0 && this.tags[0].value == 0) {
        this.tags.splice(0, 1);
        this.formInline.organization = [];
        return;
      }
      //没全部的情况下
      for (let i = 0; i < this.tags.length; i++) {
        if (tag.value == this.tags[i].value) {
          this.tags.splice(i, 1);
          this.formInline.organization.splice(
            this.formInline.organization.indexOf(tag.value),
            1
          );
          break;
        }
      }
    },
    getMoreRegion() {
      let http = new Promise((resolve, reject) => {
        let req = {
          provinceId: 350
        };
        vm.GET("basic-data/position/cities", req).then(res => {
          resolve(res);
        });
      });
      console.log("http值", http);
      return http;
    },
    //获取地区
    getRegionOption() {
      let req = {
        projectId: vm.projectId,
      };
      openLoading(vm);
      vm.GET("stats/region", req).then(res => {
        closeLoading(vm);
        if (res.code == "000000") {
          vm.formInline.region[0] = res.data.list[0].id;
          vm.optionsRegion = operationData.setRegionOptionNew(
            res.data.list
          );
          vm.search();
        }
      });
    },
    //获取机构列表
    getOrganizationList() {
      vm.organizationList = [];
      let regionId = vm.formInline.region[vm.formInline.region.length - 1];
      let req = {
        projectId: vm.projectId,
        regionId : regionId
      };
      openLoading(vm);
      vm.GET("stats/region/hospital", req).then(res => {
        closeLoading(vm);
        if (res.code == "000000") {
          this.organizationList = operationData.getLearnOrganization(
            res.data.list
          );
        }
      });
    },
    getOrganizationNum() {
      //选择全部
      let num = 0;
      if (this.tags.length == 0) {
        return;
      }
      if (this.tags[0].value == 0) {
        num = this.organizationList.length - 1;
        return num;
      }
      //没有选择全部
      num = this.tags.length;
      return num;
    },
    closeSearch() {
      vm.dialogUpdate = false;
      vm.getDisplay(2);
      vm.search();
    },
    search() {
      // console.log(vm.formInline.during);
      this.$refs.childDataAll.$emit("search");
      this.$refs.childCrowd.$emit("search");
      this.$refs.childCourse.$emit("search");
      this.$refs.childExam.$emit("search");
      this.$refs.childEffect.$emit("search");

      // if (this.activeName == "first") {
      //   this.organizationNum = this.getOrganizationNum();
      //   // console.log('this.organizationNum',this.organizationNum)
      //   this.$nextTick(function() {
      //     this.$refs.childPart.$emit("search");
      //   });
      // } else if (this.activeName == "second") {
      //   this.$refs.childCrowd.$emit("search");
      // } else if (this.activeName == "third") {
      //   this.$refs.childCourse.$emit("search");
      // } else if (this.activeName == "fourth") {
      //   this.$refs.childExam.$emit("search");
      // }
    },
    //重置
    resetForm() {
      vm.formInline = Object.assign(
        {},
        {
          region: [],
          date: "",
          organization: [],
          checked: false,
          pageNo: 1,
          pageSize: 20,
        }
      );
      vm.tags = [];
      if (this.activeName == "first") {
        this.$refs.childPart.$emit("reset");
      } else if (this.activeName == "second") {
        this.$refs.childCrowd.$emit("reset");
      } else if (this.activeName == "third") {
        this.$refs.childCourse.$emit("reset");
      } else if (this.activeName == "fourth") {
        this.$refs.childExam.$emit("reset");
      }
    },
    exportExcel() {
      if (vm.formInline.region.length == 0) {
        const h = this.$createElement;
        vm.$message({
          message: h('p', { style: 'color: #FF3399' }, '请先选择地区后再进行导出 ')
        });
        return;
      }
      //按钮置灰三秒
      vm.exportStatus = true;
      setTimeout(function() {
        vm.exportStatus = false;
      },3000);
      this.dialogVisible = true;
      //download接口
      let checkAll = operationData.hasAll(vm.formInline.organization)
      let req = {
        projectId : vm.projectId,
        ids: operationData.getIds(vm.formInline,vm.organizationList,checkAll),
        type: operationData.getSearchType(vm.formInline,checkAll),
        originalFlag: vm.formInline.checked == false ? 0 : 1,
        projectName: vm.$route.query.projectName,
        cityName: vm.getCityName(),
      };
      openLoading(vm);
      vm.reportGET("report/downLoad/downLoad", req).then(res => {
        closeLoading(vm);
        // console
        if (res.code == "000000") {
        }
      });
    },
    getCityName() {
      let city = '';
      let region = vm.dialogData.region;
      console.log('region',region,typeof region,region == '');
      if(region != '') {
        city = region.split(' / ').join('');
        console.log('city',city);
      }
      return city;
    },
    toDownload() {
      let checkAll = operationData.hasAll(vm.formInline.organization)
      let routerData = {
        // projectId : vm.projectId,
        projectId : '',
      };
      vm.$router.push({ path: "export-download", query: routerData });
    },
    update() {},
    release() {},
    setDialogData() {
      //传递给dialog数据
      this.dialogData.organization = "";
      for (let x = 0; x < this.tags.length; x++) {
        this.dialogData.organization += this.tags[x].label + "、";
      }
      let len = this.dialogData.organization.length;
      this.dialogData.organization = this.dialogData.organization.substring(
        0,
        len - 1
      );
    },
    changeDate() {
      if (vm.formInline.region.length == 0) {
        const h = this.$createElement;
        vm.$message({
          message: h('p', { style: 'color: #FF3399' }, '请先选择地区后再进行修改 ')
        });
        return;
      }
      this.setDialogData();
      this.dialogUpdate = true;
      this.$nextTick(function() {
        this.$refs.childAlignment.$emit("search");
      });
    },
    exportPDF() {
      openLoading(vm);
      let tabsList = vm.$refs.tabs.$children;
      for(let i= 1;i<tabsList.length;i++) {
        tabsList[i].$el.style.display = 'block';
      }

      let element = '';
      element = document.querySelector('.item-list-tabs .el-tabs__content');
      console.log(element);
      if(element == null) {
        return
      }
      setTimeout(() => {
        html2Canvas(element).then(function(canvas) {
          let contentWidth = canvas.width;
          let contentHeight = canvas.height;

          //一页pdf显示html页面生成的canvas高度;
          let pageHeight = contentWidth / 592.28 * 841.89;
          //未生成pdf的html页面高度
          let leftHeight = contentHeight;
          //页面偏移
          let position = 0;
          //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
          let imgWidth = 595.28;
          let imgHeight = 592.28 / contentWidth * contentHeight;

          let pageData = canvas.toDataURL('image/jpeg', 1.0);

          let pdf = new JsPDF('', 'pt', [contentWidth*0.7,contentHeight*0.7]);
          
          pdf.addImage(pageData, 'JPEG', 0, position, contentWidth*0.7, contentHeight*0.7)
          let title = "导出学情报告";
          pdf.save(title + '.pdf');

          for(let i= 1;i<tabsList.length;i++) {
            let idStr = tabsList[i].$el.id;
            console.log(idStr,vm.activeName);
            if(idStr.indexOf(vm.activeName) == -1) {
              tabsList[i].$el.style.display = 'none';
            }
          }
          closeLoading(vm);
        });
      }, 0);
    },
  }
};
</script>
<style lang="scss">
.item-list-wrap {
  .component-content {
    // position: relative;
    // background: #fff;
    padding: 10px;
    .header-title {
      padding: 10px 12px;
      font-size: 12px;
      color: #449284;
      border-bottom: 1px solid #efefef;
    }
    .item-form {
      position: relative;
      // margin-bottom: 20px;
      padding: 10px 0 10px 0;
      background: #fff;
      width: 100%;
      border-radius: 4px 4px 0 0;
      .form-title {
        position: relative;
        margin: 20px 0 24px 30px;
        height: 25px;
        font-size:18px;
        font-weight:600;
        line-height: 25px;
        color: #000000;
      }
      .el-form-item {
        margin-left: 25px;
      }
      .is-checked {
        .el-checkbox__inner {
          background-color: #449284;
          border-color: #449284;
        }
        .el-checkbox__label {
          color: #449284;
        }
      }
      .form-button {
        position: absolute;
        width: 140px;
        top: 78px;
        right: 10px;
        .el-button--default{
          border:1px solid #449284;
          color: #449284;
        }
      }
      .col-text {
        font-size: 12px;
      }
    }
    .button-group {
      position: relative;
      // right: 100px;
      float: right;
      margin-right: 20px;
      z-index: 999;
      .el-button {
        border:1px solid #449284;
        color: #449284;
      }
    }
    .choose {
      font-size: 12px;
      margin-bottom: 20px;
    }
    .item-tab {
      width: 100%;
      height: 46px;
      background: #F0F2F5;
      position: absolute;
    }
    .el-tabs__item.is-active {
      color: #409eff;
    }
    .el-tabs__header {
      width: 100%;
      background: #fff;
      margin-bottom: 20px;
      .el-tabs__nav-scroll {
        margin-left: 30px;
      }
    }
    .el-tabs__nav-wrap::after {
      height: 0px;
    }
    .tag-group {
      margin-left: 78px;
      margin-bottom: 20px;
      .el-tag {
        margin-right: 20px;
      }
    }
    .el-tabs__active-bar {
      background-color: #449284;
    }
  }
}
</style>