<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"
      >
        <el-form-item label="选择地区：">
          <!-- :props="props" -->
          <el-cascader
            size="small"
            ref="cascaderRegion"
            :options="optionsRegion"
            :props="props"
            v-model:value="formInline.region"
            @change="handleChange"
            filterable
            change-on-select
            placeholder="请先选择地区后再进行查询"
            style="width: 330px"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="选择机构：">
          <el-select
            size="small"
            v-model:value="formInline.organization"
            :placeholder="organizationNotice"
            @change="changeOrganization"
            multiple
            collapse-tags
            :disabled="formInline.region.length < 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 v-if="showOriginal == 1">
          <el-checkbox size="small" v-model:value="formInline.checked"
            >查看原始数据</el-checkbox
          >
        </el-form-item>
      </el-form>
      <div class="form-button">
        <el-button @click="search()" type="primary">查询</el-button>
        <el-button @click="resetForm()">重置</el-button>
      </div>

      <div class="button-group">
        <el-button
          v-if="roleType == 'L1' || roleType == 'L2'"
          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="exportExcel"
          >导出明细</el-button
        >
      </div>
      <!-- <div class="item-tab"></div> -->
      <el-tabs
        v-model:value="activeName"
        @tab-click="handleClick"
        :before-leave="beforeLeave"
      >
        <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">
          <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" lazy>
              <learning-effect></learning-effect>
            </el-tab-pane>-->
      </el-tabs>
      <el-dialog
        title="提示"
        v-model:visible="dialogVisible"
        width="30%"
        center
      >
        <p style="text-align: center">
          文件正在生成，你可以去“我的导出下载”页，下载文件
        </p>
        <template v-slot:footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">留在当前页</el-button>
            <el-button type="primary" @click="toDownload()">去下载</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog title v-model:visible="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 { $on, $off, $once, $emit } from '../../../utils/gogocodeTransfer'
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 { create } from 'domain'
import { mapGetters } from 'vuex'
import { openLoading, closeLoading } from '../../utils-o/utils'
import * as commonUtil from '../../utils-o/utils'
import * as operationData from '../../utils-o/operation'
import { log } from 'util'

let vm = null
export default {
  components: {
    BreadCrumb,
    CourseAnalysis,
    CrowdAnalysis,
    PartIn,
    ExaminationAnalysisfrom,
    LearningEffect,
    DataAlignment,
  },
  data() {
    return {
      curmbFirst: '学情报告',
      curmbSecond: '项目列表',
      curmbThird: '',
      jumPathThird: '/item-manager',
      projectId: '',
      projectName: '',
      exportStatus: false,
      organizationList: [],
      optionsRegion: [],
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node
          console.log('node', node)
          if (node.level == 1) {
            let req = {
              provinceId: node.data.value,
            }
            vm.GET('basic-data/position/cities', req).then((res) => {
              let newData = vm.setMoreOption(res.data.cityList, 'cities')
              console.log('newData', newData)
              resolve(newData)
            })
          } else if (node.level == 2) {
            let req = {
              cityId: node.data.value,
            }
            vm.GET('basic-data/position/counties', req).then((res) => {
              let newData = vm.setMoreOption(res.data.countyList, 'counties')
              console.log('newData', newData)
              resolve(newData)
            })
          } else if (node.level == 3) {
            let req = {
              countyId: node.data.value,
            }
            vm.GET('basic-data/position/towns', req).then((res) => {
              let newData = vm.setMoreOption(res.data.townList, 'towns')
              console.log('newData', newData)
              resolve(newData)
            })
          }
        },
      },
      showOriginal: 2,
      roleType: '',
      formInline: {
        region: [0],
        date: '',
        organization: [],
        checked: false,
        pageNo: 1,
        pageSize: 20,
      },
      organizationNotice: '选择地区筛选到区才能选择机构',
      dialogData: {
        region: '',
        // regionData: "",
        organization: '',
        // organizationData: "",
      },
      tags: [],
      activeName: 'first',
      organizationNum: 0,
      dialogVisible: false,
      dialogUpdate: false,
      displayExam: 2,
      flag: 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 req = {
        projectId: vm.projectId,
        projectName: vm.projectName,
      }
      openLoading(vm)
      vm.reportGET('report/portal/display', req).then((res) => {
        closeLoading(vm)
        if (res.code == '000000') {
          console.log('vm.showOriginal', res.data)
          vm.showOriginal = res.data.status
          vm.roleType = res.data.roleType
          vm.displayExam = res.data.existExam
          vm.flag = res.data.flag
        }
        if (type != 2) {
          vm.getRegionOption()
        }
      })
    },
    beforeLeave(activeName, oldActiveName) {
      console.log('action', activeName, 'oldActive', oldActiveName)
    },
    handleClick(tab, event) {
      //console.log(tab, event);
      // if(tab.name == this.activeName) {
      //   return;
      // }
      console.log('activeName', this.activeName, tab.name)
      if (tab.name == 'first') {
        $emit(this.$refs.childPart, 'init')
      } else if (tab.name == 'second') {
        $emit(this.$refs.childCrowd, 'init')
      } else if (tab.name == 'third') {
        $emit(this.$refs.childCourse, 'init')
      } else if (tab.name == 'fourth') {
        $emit(this.$refs.childExam, '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);
      if (value.length >= 3) {
        this.getOrganizationList()
        this.organizationNotice = '请选择机构'
      } else {
        this.organizationNotice = '选择地区筛选到区才能选择机构'
      }
    },
    setMoreOption(data, type) {
      let option = []
      for (let i = 0; i < data.length; i++) {
        let obj = data[i]
        if (type == 'cities') {
          obj.label = data[i].cityName
          obj.value = data[i].cityId
        } else if (type == 'counties') {
          obj.label = data[i].countyName
          obj.value = data[i].countyId
          // obj.leaf = true;
        } else if (type == 'towns') {
          obj.label = data[i].townName
          obj.value = data[i].townId
          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() {
      if (vm.flag == 2 && vm.roleType == 'L2') {
        this.optionsRegion = [
          {
            id: 11,
            provinceId: 330,
            provinceName: '浙江省',
            value: 330,
            label: '浙江省',
          },
        ]
      } else {
        let req = {}
        openLoading(vm)
        vm.GET('basic-data/position/provinces', req).then((res) => {
          closeLoading(vm)
          if (res.code == '000000') {
            this.optionsRegion = operationData.setRegionOption(
              res.data.provinceList
            )
            // console.log("this.optionsRegion", this.optionsRegion);
          }
        })
      }
    },
    getOrganizationList() {
      this.organizationList = []
      let countyId = vm.formInline.region[vm.formInline.region.length - 1]
      let type = 3
      if (vm.formInline.region.length == 4) {
        type = 5
      }
      let req = {
        projectId: vm.projectId,
        type: type,
        id: countyId,
      }
      openLoading(vm)
      vm.reportGET('report/portal/getOrganizationList', req).then((res) => {
        closeLoading(vm)
        if (res.code == '000000') {
          this.organizationList = operationData.getLearnOrganization(
            res.data.hospitalList
          )
        }
      })
    },
    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(this.formInline,this.activeName);
      if (this.activeName == 'first') {
        this.organizationNum = this.getOrganizationNum()
        // console.log('this.organizationNum',this.organizationNum)
        this.$nextTick(function () {
          $emit(this.$refs.childPart, 'search')
        })
      } else if (this.activeName == 'second') {
        $emit(this.$refs.childCrowd, 'search')
      } else if (this.activeName == 'third') {
        $emit(this.$refs.childCourse, 'search')
      } else if (this.activeName == 'fourth') {
        $emit(this.$refs.childExam, 'search')
      }
    },
    //重置
    resetForm() {
      vm.formInline = Object.assign(
        {},
        {
          region: [],
          date: '',
          organization: [],
          checked: false,
          pageNo: 1,
          pageSize: 20,
        }
      )
      vm.tags = []
      if (this.activeName == 'first') {
        $emit(this.$refs.childPart, 'reset')
      } else if (this.activeName == 'second') {
        $emit(this.$refs.childCrowd, 'reset')
      } else if (this.activeName == 'third') {
        $emit(this.$refs.childCourse, 'reset')
      } else if (this.activeName == 'fourth') {
        $emit(this.$refs.childExam, '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-old', 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 () {
        $emit(this.$refs.childAlignment, 'search')
      })
    },
  },
  emits: ['init', 'search', 'reset'],
}
</script>

<style lang="scss">
.item-list-wrap {
  .component-content {
    // background: #fff;
    padding: 10px;
    .header-title {
      padding: 10px 12px;
      font-size: 12px;
      color: #449284;
      border-bottom: 1px solid #efefef;
    }
    .item-form {
      padding: 10px;
      background: #fff;
      width: 100%;
      border-radius: 4px;
    }
    .form-button {
      width: 45%;
      top: -120px;
      position: relative;
      left: 50%;
    }
    .button-group {
      position: relative;
      // right: 100px;
      float: right;
      margin-right: 20px;
    }
    .choose {
      font-size: 12px;
      margin-bottom: 20px;
    }
    .item-tab {
      width: 95%;
      height: 46px;
      background: #f0f2f5;
      position: absolute;
    }
    .el-tabs__item.is-active {
      color: #409eff;
    }
    .el-tabs__header {
      width: 65%;
    }
    .el-tabs__nav-wrap::after {
      height: 0px;
    }
    .tag-group {
      margin-left: 78px;
      .el-tag {
        margin-right: 20px;
      }
    }
  }
}
</style>
