<template>
  <div class="main-container wrap">
    <div></div>
    <!--上部分-->
    <div class="header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/major/search' }">
          专业大全
        </el-breadcrumb-item>
        <el-breadcrumb-item v-if="state.majorInfo.zyl"><a>{{ state.majorInfo.zyl }}</a></el-breadcrumb-item>
      </el-breadcrumb>
      <div class="majorName">
        {{ state.majorInfo.majorName }}
      </div>
      <div class="flexWrap mt-10">
        <el-space spacer="|">
          <div>{{ state.majorInfo.educationalLevel === '1' ? '本科' : '专科' }}</div>
          <div>专业代码：{{ state.majorInfo.majorCode }}{{ state.majorInfo.majorCodeChar }}</div>
          <div>学制：{{ state.majorInfo.semester ? state.majorInfo.semester + '年' : '--' }}
          </div>
          <div>
            学位：{{ state.majorInfo.degree || '--' }}
          </div>
        </el-space>
      </div>
    </div>
    <div class="paneTypes flexWrap">
      <div class="panetype" :class="state.paneName === '专业概况' ? 'panetype-active' : ''" @click="switchPane('专业概况')">专业概况
      </div>
      <div class="panetype" :class="state.paneName === '开设院校' ? 'panetype-active' : ''" @click="switchPane('开设院校')">开设院校
      </div>
    </div>
    <div class="bodyr">
      <div v-show="state.paneName === '专业概况'">
        <Tip :title="'专业简介'" :size="'18px'" />
        <div class="text">
          {{ state.majorInfo.ssm || '--' }}
        </div>
        <Tip :title="'学什么'" :size="'18px'" />
        <div class="text">
          {{ state.majorInfo.xsm || '--' }}
        </div>
        <Tip :title="'干什么'" :size="'18px'" />
        <div class="text">
          {{ state.majorInfo.gsm || '--' }}
        </div>
        <el-row :gutter="20" class="mt-10">
          <!--男女比例-->
          <el-col :span="12">
            <div class="mt-15" ref="chartSexRef" :style="{ height: '400px' }"></div>
          </el-col>
          <!--就业岗位-->
          <el-col :span="12">
            <div class="mt-15" ref="chartJobDistributionRef" :style="{ height: '400px' }"></div>
          </el-col>
          <!--就业行业-->
          <el-col :span="12">
            <div class="mt-15" ref="chartIndustryDistributionRef" :style="{ height: '400px' }"></div>
          </el-col>
          <!--就业地区-->
          <el-col :span="12">
            <div class="mt-15" ref="chartRegionDistributionRef" :style="{ height: '400px' }"></div>
          </el-col>
        </el-row>
      </div>
      <div v-show="state.paneName === '开设院校'">
        <!--筛选项-->
        <div class="filterTable">
          <div class="filterTitle flexWrap">
            <div class="flex-item-75">
              <div class="searchSchool">
                <el-input v-model="state.selectForm.schoolName" maxlength="24" show-word-limit
                  style="max-width: 230px;height: 40px;line-height: 40px;" placeholder="请输入院校或专业名称"
                  class="input-with-select" />
                <el-button :icon="Search" @click="reloadSchoolList"
                  style="border-left: none;height: 40px;line-height: 40px;" />
              </div>
            </div>
          </div>
          <div class="filterBody">
            <div class="flexWrap">
              <div class="flex-item-1">就读地域</div>
              <div class="flex-item-9 tags">
                <span class="tag" :class="state.selectForm.addressList.length === 0 ? 'tag-active' : ''"
                  @click="checkboxAddress('')">不限</span>
                <span class="tag" :class="state.selectForm.addressList.includes(item.code) ? 'tag-active' : ''"
                  v-for="(item, index) in state.addressList" :key="index" @click="checkboxAddress(item.code)">
                  {{ item.name }}
                </span>
              </div>
            </div>
            <!-- <div class="flexWrap">
              <div class="flex-item-1">科研教学</div>
              <div class="flex-item-9 tags">
                <span class="tag" :class="state.selectForm.kyjxList.length === 0 ? 'tag-active' : ''"
                  @click="checkboxKyjx('')">不限</span>
                <span class="tag" :class="state.selectForm.kyjxList.includes(item) ? 'tag-active' : ''"
                  v-for="(item, index) in state.kyjxList" :key="index" @click="checkboxKyjx(item)">
                  {{ item }}
                </span>
              </div>
            </div> -->
            <div class="flexWrap">
              <div class="flex-item-1">院校标签</div>
              <div class="flex-item-9 tags">
                <span class="tag" :class="state.selectForm.tagsList.length === 0 ? 'tag-active' : ''"
                  @click="checkboxSchoolTags('')">不限</span>
                <span class="tag" :class="state.selectForm.tagsList.includes(item.code) ? 'tag-active' : ''"
                  v-for="(item, index) in state.tagsList" :key="index" @click="checkboxSchoolTags(item.code)">
                  {{ item.name }}
                </span>
              </div>
            </div>
            <div class="flexWrap">
              <div class="flex-item-1">办学类型</div>
              <div class="flex-item-9 tags">
                <span class="tag" :class="state.selectForm.schoolNatureList && state.selectForm.schoolNatureList.length === 0 ? 'tag-active' : ''"
                  @click="checkboxSchoolNature('')">不限</span>
                <span class="tag" :class="state.selectForm.schoolNatureList.includes(item.code) ? 'tag-active' : ''"
                  v-for="(item, index) in state.schoolNatureList" :key="index" @click="checkboxSchoolNature(item.code)">
                  {{ item.name }}
                </span>
              </div>
            </div>
            <div class="border-b"></div>
            <div class="flexWrap">
              <span class="clearFilterButton" @click="clearFilter">重置已选</span>
            </div>
          </div>
          <!--院校列表-->
          <div ref="scrollContainer" style="height: 800px; overflow-y: scroll;" @scroll="handleScroll" class="scroll-container schoolList" v-show="state.schoolResult.list">
            <div class="schoolItem" v-for="(item,index) in state.schoolResult.list" :key="index">
              <div class="flexWrap" @click="showSchoolInfo(item.schoolCode)">
                <div class="flex-item-13 left">
                    <img :src="item.schoolIcon" :alt="item.schoolName" style="width: 128px;border-radius: 50%"/>
                </div>
                <div class="flex-item-87 right">
                  <div class="flexWrap schoolName" style="">
                    {{ item.schoolName }}
                  </div>
                  <div class="flexWrap tags">
                    <span class="tag" v-for="(tag,i) in item.tagsList" :key="i">
                      {{ tag }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <!-- 加载更多提示 -->
            <p v-if="state.schoolResult.status==='loading'">加载中...</p>
            <p v-if="state.schoolResult.status==='noMore'">没有更多数据了</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { h, ref, onMounted, reactive } from 'vue';
import { useRoute } from 'vue-router';
import * as echarts from 'echarts';
import { Search } from '@element-plus/icons-vue';
import {ElMessage} from 'element-plus';
import ApiConstant from '@/utils/ApiConstant';
import StaticConstant from '@/utils/StaticConstant';
import axiosInstance from '@/utils/http';
const { query, params } = useRoute();
document.title = '专业介绍|' + import.meta.env.VITE_PROGRAM_TYPE;
//获取页面传参
let majorCode = params.majorCode
const state = reactive({
  paneName: '专业概况',
  addressList: [...StaticConstant.addressList] as any,//就读地域筛选项
  kyjxList: ['硕士点', '博士点', '保研'] as Array<string>,//科研教学筛选项
  rulesEnrollProbabilityList: [] as Array<any>,//录取方式
  tagsList: StaticConstant.tagsList as Array<any>,//院校标签
  schoolNatureList: [...StaticConstant.schoolTypeList] as Array<any>,//办学类型
  majorInfo: {
    majorName: '',
    majorTypeName: '',
    majorCode: '',
    majorCodeChar: "",
    educationalLevel: '',
    semester: '',
    degree: '',
    zyl:'未知',
    ssm: '',
    xsm: '',//学什么
    gsm: '',//干什么
    sexRatio: '',
    jobDistribution: '',//就业岗位分布
    industryDistribution: '',//就业行业分布
    regionDistribution: '',//就业地区分布
  },
  schoolList:[] as any,
  selectForm: {
    schoolName: '',
    current:1,
    size:10,
    addressList: [] as any,
    kyjxList: [] as any,
    tagsList: [] as any,
    schoolNatureList:[] as any,
  },
  schoolResult:{
    list:[] as any,
    status:'more',
  },
})
const chartSexRef = ref<HTMLDivElement | null>(null);
const chartJobDistributionRef = ref<HTMLDivElement | null>(null);
const chartIndustryDistributionRef = ref<HTMLDivElement | null>(null);
const chartRegionDistributionRef = ref<HTMLDivElement | null>(null);
const scrollContainer = ref<HTMLElement | null>(null);
onMounted(() => {
  reloadMajorInfo()
  getSchoolList()
})

const handleScroll = () => {
  console.log(111);
  const container = scrollContainer.value
  if (container) {
    const { scrollTop, scrollHeight, clientHeight } = container;
    if (scrollTop + clientHeight >= scrollHeight) {
      loadMore();
    }
  }
};

function loadMore(){
  if(state.paneName ==='开设院校' && state.schoolResult.status === 'more'){
    state.schoolResult.status = 'loading'
    state.selectForm.current++;
    getSchoolList();
  }
}

//选择pane
function switchPane(e: string) {
  if (state.paneName !== e) {
    state.paneName = e
  }
}

//写入男女比例图
function setPeople() {
  let sexRatio = state.majorInfo.sexRatio
  console.log(sexRatio)
  if (sexRatio) {
    try {
      let femaleRatio = ''
      let maleRatio = ''
      let ratios = sexRatio.replaceAll('%', '').split('、');
      if (ratios) {
        ratios.forEach(item => {
          if (item.split('：')[0] === '男生') {
            femaleRatio = item.split('：')[1]
          } else if (item.split('：')[0] === '女生') {
            maleRatio = item.split('：')[1]
          }
        })
        if (chartSexRef.value && echarts && (femaleRatio && maleRatio)) {
          const myChart = echarts.init(chartSexRef.value);
          const option = {
            title: {
              text: '男女比例',
              left: 'left'
            },
            tooltip: {
              trigger: 'item'
            },
            legend: {
              orient: 'vertical',
              left: 'right'
            },
            series: [
              {
                type: 'pie',
                radius: '60%',
                data: [
                  { value: femaleRatio, name: '男' },
                  { value: maleRatio, name: '女' }
                ],
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                },
                tooltip: {
                  trigger: 'item',
                  //formatter: '{a} <br/>{b}: {c} ({d}%)'
                  formatter: '{b}: {d}%'
                }
              }
            ]
          };
          // 设置实例参数
          myChart.setOption(option as any);
        }
      }
    } catch (error) {

    }
  }

}

//写入就业岗位
function setJobDistribution() {
  let jobDistribution = state.majorInfo.jobDistribution
  if (jobDistribution) {
    try {
      let ratios = jobDistribution.replaceAll('%', '').split('、');
      if (ratios) {
        let dataList = [] as any
        ratios.forEach(item => {
          dataList.push({ name: item.split('：')[0], value: item.split('：')[1] })
        })
        if (chartJobDistributionRef.value && echarts && dataList.length > 0) {
          const myChart = echarts.init(chartJobDistributionRef.value);
          const option = {
            title: {
              text: '就业岗位分布',
              left: 'left'
            },
            tooltip: {
              trigger: 'item'
            },
            legend: {
              orient: 'vertical',
              left: 'right'
            },
            series: [
              {
                type: 'pie',
                radius: '60%',
                data: dataList,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                },
                tooltip: {
                  trigger: 'item',
                  //formatter: '{a} <br/>{b}: {c} ({d}%)'
                  formatter: '{b}: {d}%'
                }
              }
            ]
          };
          // 设置实例参数
          myChart.setOption(option as any);
        }
      }
    } catch (error) {

    }
  }

}
//写入就业行业
function setIndustryDistribution() {
  let industryDistribution = state.majorInfo.industryDistribution
  if (industryDistribution) {
    try {
      let ratios = industryDistribution.replaceAll('%', '').split('、');
      if (ratios) {
        let dataList = [] as any
        ratios.forEach(item => {
          dataList.push({ name: item.split('：')[0], value: item.split('：')[1] })
        })
        if (chartIndustryDistributionRef.value && echarts && dataList.length > 0) {
          const myChart = echarts.init(chartIndustryDistributionRef.value);
          const option = {
            title: {
              text: '就业行业分布',
              left: 'left'
            },
            tooltip: {
              trigger: 'item'
            },
            legend: {
              orient: 'vertical',
              left: 'right'
            },
            series: [
              {
                type: 'pie',
                radius: '60%',
                data: dataList,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                },
                tooltip: {
                  trigger: 'item',
                  //formatter: '{a} <br/>{b}: {c} ({d}%)'
                  formatter: '{b}: {d}%'
                }
              }
            ]
          };
          // 设置实例参数
          myChart.setOption(option as any);
        }
      }
    } catch (error) {

    }
  }

}
//写入就业地区
function setRegionDistribution() {
  let regionDistribution = state.majorInfo.regionDistribution
  if (regionDistribution) {
    try {
      let ratios = regionDistribution.replaceAll('%', '').split('、');
      if (ratios) {
        let dataList = [] as any
        ratios.forEach(item => {
          dataList.push({ name: item.split('：')[0], value: item.split('：')[1] })
        })
        if (chartRegionDistributionRef.value && echarts && dataList.length > 0) {
          const myChart = echarts.init(chartRegionDistributionRef.value);
          const option = {
            title: {
              text: '就业地区分布',
              left: 'left'
            },
            tooltip: {
              trigger: 'item'
            },
            legend: {
              orient: 'vertical',
              left: 'right'
            },
            series: [
              {
                type: 'pie',
                radius: '60%',
                data: dataList,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                },
                tooltip: {
                  trigger: 'item',
                  //formatter: '{a} <br/>{b}: {c} ({d}%)'
                  formatter: '{b}: {d}%'
                }
              }
            ]
          };
          // 设置实例参数
          myChart.setOption(option as any);
        }
      }
    } catch (error) {

    }
  }

}

//获取专业详情信息
function reloadMajorInfo() {
  axiosInstance({
    url: ApiConstant.Major.majorInfo,
    method: 'get',
    params:{
      majorCode: majorCode,
    },
    showLoading: false,//是否显示加载图标
  }).then((response) => {
    return response.data
  }).then((data) => {
    if(!data.success){
      ElMessage.error(data.message);
      return false
    }
    if(data.result){
      state.majorInfo = data.result
      setPeople()
      setJobDistribution()
      setIndustryDistribution()
      setRegionDistribution()
    }
  }).catch((error: any) => {
    console.log(error);
  }).finally(() => {
  });
}

function reloadSchoolList(){
  state.selectForm.current = 1
  state.schoolResult.list = []
  getSchoolList()
}
//获取开设院校列表
function getSchoolList() {
  state.schoolResult.status === 'loading'
  axiosInstance({
    url: ApiConstant.School.searchSchoolList,
    method: 'get',
    params:{
      majorCode: majorCode,
      schoolName: state.selectForm.schoolName,
      pageNum: state.selectForm.current,
      pageSize: state.selectForm.size,
      addressList: state.selectForm.addressList,
      tagsList:state.selectForm.tagsList,
      schoolNatureList:state.selectForm.schoolNatureList
    },
    //showLoading: false,//是否显示加载图标
  }).then((response) => {
    return response.data
  }).then((data) => {
    if(!data.success){
      ElMessage.error(data.message);
      return false
    }
    if(data.result){
      state.schoolResult.list = [...state.schoolResult.list, ...data.result.records]
      if (data.result.current >= data.result.pages) {
        state.schoolResult.status = 'noMore'
      } else {
        state.schoolResult.status = 'more'
      }
    }
  }).catch((error: any) => {
    console.log(error);
  }).finally(() => {
  });
}

//清除筛选项
function clearFilter() {
  state.selectForm.schoolName = ''
  state.selectForm.addressList = []
  state.selectForm.kyjxList = []
  state.selectForm.tagsList = []
  state.selectForm.schoolNatureList = []
  reloadSchoolList()
}
//选择地区
function checkboxAddress(addressCode: string) {
  if (!addressCode) {
    state.selectForm.addressList = []
  } else if (state.selectForm.addressList.includes(addressCode)) {
    state.selectForm.addressList = state.selectForm.addressList.filter((element:any) => element !== addressCode)
  } else {
    state.selectForm.addressList.push(addressCode)
  }
  reloadSchoolList()
}
//选择院校标签
function checkboxSchoolTags(schoolTag: string) {
  if (!schoolTag) {
    state.selectForm.tagsList = []
  } else if (state.selectForm.tagsList.includes(schoolTag)) {
    state.selectForm.tagsList = state.selectForm.tagsList.filter((element:any) => element !== schoolTag)
  } else {
    state.selectForm.tagsList.push(schoolTag)
  }
  reloadSchoolList()
}
//选择办学类型
function checkboxSchoolNature(schoolNature: string) {
  if (!schoolNature) {
    state.selectForm.schoolNatureList = []
  } else if (state.selectForm.schoolNatureList.includes(schoolNature)) {
    state.selectForm.schoolNatureList = state.selectForm.schoolNatureList.filter((element:any) => element !== schoolNature)
  } else {
    state.selectForm.schoolNatureList.push(schoolNature)
  }
  reloadSchoolList()
}
const showSchoolInfo = (schoolCode: string) => {
  window.open('/school/'+schoolCode, '_self')
}
</script>

<style scoped lang="scss">
/* 上部分 start*/
.header {
  background-color: white;
  padding: 20px 30px;

  .majorName {
    width: 450px;
    line-height: 80px;
    font-size: 28px;
    border-bottom: 1px solid #e4e7ed;
  }
}

/* 上部分 end*/
/* 中间部分 start*/
.bodyr {
  background-color: white;
  padding: 20px 30px;

  .text {
    padding: 10px 0;
  }
}

/* 中间部分 end*/

.paneTypes {
  margin-top: 15px;

  .panetype {
    cursor: pointer;
    border: 1px solid #ebeef5;
    border-radius: 5px 5px 0 0;
    width: 100px;
    text-align: center;
    padding: 5px 15px;
    margin-right: 10px;
    background-color: white;
    color: $color-blue-60;
    transition: all 0.3s;
  }

  .panetype-active {
    background-color: $color-blue-60;
    color: white;
  }
}

</style>
