<template>
  <div style="background: #ececec; padding: 15px">
    <a-card title="按批次对比分析" :loading="loading" :bordered="false">
      <template #extra>
        <!-- <a-select v-model:value="college" style="width: 300px" :options="collegeOptions"></a-select> -->
        <a-cascader v-model:value="collegeMajor" :options="collegeMajorOptions" change-on-select />
        <a-button style="margin-left: 10px" type="primary" @click="query">查询</a-button>
      </template>

      <a-row :gutter="12">
        <a-col :xl="16" :style="{ marginBottom: '24px' }">
          <!-- 根据需求 删除 或 更改-->
          <a-card class="tip">
            <div style="display: flex">
              <div v-if="topCollege != null">
                <span style="font-size: 15px; padding-left: 100px">该数据为 </span>
                <span style="color: red; font-size: 18px">{{ topCollege }}</span>
                <span v-if="topMajor != null && topMajor != ''" style="color: red; font-size: 18px"> / {{ topMajor }}</span>
                <span style="font-size: 15px"> 的四级通过率变化趋势 </span>
              </div>
            </div>
          </a-card>

          <a-card>
            <div>
              <div id="map1" style="width: 100%; height: 400px"></div>
            </div>
          </a-card>
        </a-col>

        <a-col :xl="8">
          <a-card :loading="participate_Piechartloading" style="margin-bottom: 10px">
            <div style="width: 100%; height: 210px; padding: 10px" class="participate_Piechart" id="participate_Piechart"></div>
          </a-card>

          <a-card :loading="pass_Piechartloading">
            <div style="width: 100%; height: 210px; padding: 10px" class="pass_Piechart" id="pass_Piechart"></div>
          </a-card>
        </a-col>
      </a-row>
    </a-card>
  </div>
</template>

<script>
  import { defHttp } from '/@/utils/http/axios';
  import * as echarts from 'echarts';

  export default {
    data() {
      return {
        Url: {
          getBatch: '/cet/getBatch',
          getCollege: '/cet/getCollege',
          getRate: '/cet/getRateByAllBatch',
          getCollegeMajor: '/cet/getCollegeMajor',
          getRateByMajor: '/cet/getgetRateByMajor',
          getRateByMajorAndLastestBatch: '/cet/getRateByMajorAndLastestBatch',
          getRateByEntryDate: '/cet/getRateByEntryDate',
        },
        loading: false,
        participate_Piechartloading: false,
        pass_Piechartloading: false,
        collegeOptions: [],
        collegeMajorOptions: [],
        batchOptions: [],
        levelOptions: [
          { value: 'cet4', label: '英语四级' },
          { value: 'cet6', label: '英语六级' },
        ],
        level: null,
        college: null,
        batch: null,
        collegeMajor: null,
        topCollege: null, //顶部解释行
        topMajor: null, //顶部解释行
      };
    },
    mounted() {
      this.getCollegeMajorData();
      this.getBatch();
      this.query();
    },
    methods: {
      dataChart(data) {
        let xData = [];
        let yData = [];
        for (let key in data) {
          xData.push(key);
          // 将数据转换为百分比（加上%）
          yData.push(data[key].toFixed(1));
        }
        let myChart = echarts.init(document.getElementById('map1'));
        // 指定图表的配置项和数据
        let option = {
          title: {
            // text: '学院 / 专业四级通过率变化',
          },
          xAxis: {
            type: 'category',
            data: xData,
            axisLabel: {
              interval: 1, //代表显示所有x轴标签显示
              rotate: -10, //代表倾斜30度显示
            },
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow',
            },
            formatter: function (params) {
              return (
                params[0].name +
                '<br/>' +
                '<table>' +
                '<tr><td>' +
                params[0].marker +
                '</td><td style="font-weight: bold;">' +
                '&nbsp;&nbsp;&nbsp;&nbsp;' +
                params[0].value +
                '%' +
                '</td></tr>' +
                '<tr>' +
                '</table>'
              );
            },
          },
          yAxis: {
            type: 'value',
            name: '通过率',
            axisLabel: {
              formatter: '{value} %',
            },
          },
          series: [
            {
              data: yData,
              type: 'line',
              itemStyle: {
                normal: {
                  label: {
                    show: true, //开启显示
                    position: 'top', //在上方显示
                    textStyle: {
                      //数值样式
                      color: 'black',
                      fontSize: 12,
                    },
                    formatter: '{c}%',
                  },
                },
              },
            },
          ],
        };
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
      },

      //绘画饼图--最新批次每一年级的通过率饼图
      async draPieChart_Participate() {
        console.log(this.collegeMajor, 'collegeMajor');
        let college = this.collegeMajor[0];
        let major = this.collegeMajor[1];
        console.log(college, major, 'college major');

        let queryParams = {
          college: college,
          major: major,
          level: 'cet4',
        };
        let url = this.Url.getRateByMajorAndLastestBatch;
        this.participate_Piechartloading = true;
        console.log(queryParams, 'queryParams');

        let result = await defHttp.post({ url: url, data: queryParams });

        if (!result) {
          return;
        }
        console.log(result.data, 'result');

        let titleText = major ? `${college} / ${major}专业 最新批次通过人数` : `${college} 最新批次通过人数`;

        // 使用 API 返回的数据填充饼图
        let chartData = [];

        for (let key in result.data) {
          chartData.push({
            name: key + '级',
            value: result.data[key].passRate,
          });
        }
        console.log(chartData, '123');
        let xData = chartData.map((item) => item.name); // 提取类别数据
        let yData = chartData.map((item) => item.value); // 提取值数据
        let option = {
          grid: {
            left: '20%', // 增加左边距，可以根据需要调整
            right: '5%', // 右边距
            top: '20%', // 上边距
            bottom: '10%', // 下边距
          },
          title: {
            text: '最新批次每一年级的通过率',
            left: 'top',
            top: '0%',
            textStyle: {
              fontSize: 14,
            },
          },
          tooltip: {
            trigger: 'item',
          },
          xAxis: {
            type: 'category',
            data: xData,
            //data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: '{value}%',
            },
          },
          series: [
            {
              name: titleText,
              data: yData,
              //data: [150, 230, 224, 218, 135, 147, 260],
              type: 'line',
              itemStyle: {
                normal: {
                  label: {
                    show: true, //开启显示
                    position: 'top', //在上方显示
                    textStyle: {
                      //数值样式
                      color: 'black',
                      fontSize: 12,
                    },
                    formatter: '{c}%',
                  },
                },
              },
            },
          ],
          animationDurationUpdate: 500,
        };
        this.participate_Piechartloading = false;
        this.$nextTick(() => {
          var myChart = echarts.init(document.getElementById('participate_Piechart'));
          myChart.setOption(option);
        });
      },

      //绘画饼图--学院/专业每个年级的通过率柱状图
      async draPieChart_Pass() {
        //console.log(this.passRatePie);
        //console.log('piedata', piedata);
        let college = this.collegeMajor[0];
        let major = this.collegeMajor[1];
        let queryParams = {
          college: college,
          major: major,
          level: 'cet4',
        };
        let url = this.Url.getRateByEntryDate;
        this.pass_Piechartloading = true;
        console.log(queryParams, 'queryParams');
        let result = await defHttp.post({ url: url, data: queryParams });
        if (!result) {
          return;
        }
        console.log(result, 'result');
        // 从 result 提取数据
        let xData = result.data.map((item) => item.entryDate); // 用于 X 轴
        let values = result.data.map((item) => item.passRate); // 用于柱状图的数据
        console.log(xData, values, 'xData values');
        let titleText = major ? `${college} / ${major}专业 每个年级的通过率柱状图` : `${college} 每个年级的通过率柱状图`;
        let option = {
          grid: {
            left: '15%', // 调整左边距，向右移动
            top: '20%', // 调整上边距，向下移动
            right: '10%', // 可根据需要调整右边距
            bottom: '10%', // 可根据需要调整底边距
          },
          tooltip: {
            trigger: 'item',
            formatter: function (params) {
              // 在默认格式基础上添加 %
              return `${params.marker}${params.name}  ${params.value}%`;
            },
          },
          title: {
            text: titleText,
            left: 'left',
            top: '0%',
            textStyle: {
              fontSize: 14,
            },
          },
          xAxis: {
            type: 'category',
            data: xData,
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: '{value}%', // Y 轴显示百分比符号
            },
          },
          series: [
            {
              data: values,
              type: 'bar',
              showBackground: true,
              backgroundStyle: {
                color: 'rgba(180, 180, 180, 0.2)',
              },
              label: {
                show: true, // 显示数据标签
                position: 'top', // 标签位置在柱体顶部
                formatter: '{c}%', // 标签内容为百分比
                fontSize: '10px',
              },
            },
          ],
          animationDurationUpdate: 500,
        };
        this.pass_Piechartloading = false;
        this.$nextTick(() => {
          var myChart = echarts.init(document.getElementById('pass_Piechart'));
          myChart.setOption(option);
        });
      },
      // 获取批次数据
      async getBatch() {
        const getBatch = await defHttp.get({ url: this.Url.getBatch });
        // const getCollege = await defHttp.get({ url: this.Url.getCollege });

        // this.collegeOptions = getCollege.colleges;
        // this.college = this.collegeOptions[0].value;

        this.level = this.levelOptions[0].value;

        // this.query();
      },
      //获取学院专业级联数据
      async getCollegeMajorData() {
        const res = await defHttp.get({ url: this.Url.getCollegeMajor });
        //通过map方法将数据转换为级联选择器需要的数据格式
        this.collegeMajorOptions = res.collegeMajor.map((item) => {
          return {
            value: item.college,
            label: item.college,
            children: item.major.map((major) => {
              return {
                value: major,
                label: major,
              };
            }),
          };
        });
        this.collegeMajor = ['东语学院', '日语'];
      },
      // 查询数据
      async query() {
        let data = null;
        console.log(this.collegeMajor, 'collegeMajor');
        try {
          //如果this.collegeMajor为null则先赋个值
          if (!this.collegeMajor) {
            this.collegeMajor = ['东语学院', '日语'];
          }
          let major = null;
          let college = null;
          //如果this.collegeMajor[1]不存在则设为null
          college = this.collegeMajor[0];
          major = this.collegeMajor.length > 1 ? this.collegeMajor[1] : '';
          this.topCollege = college;
          this.topMajor = major;
          this.loading = true;
          console.log(college, major, 'college,major');
          let params = {
            college: college,
            major: major,
            level: 'cet4',
          };
          data = await defHttp.get({ url: this.Url.getRate, params });
          console.log(data, 'data');
        } finally {
          this.loading = false;
          this.$nextTick(() => {
            this.dataChart(data);
            this.draPieChart_Pass();
            this.draPieChart_Participate();
          });
        }
      },
    },
  };
</script>

<style lang="less" scoped>
  .container {
    // display: flex;
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
  }

  .title {
    font-size: 20px;
    color: rgb(8, 8, 8);
    font-weight: bold;
  }
  .tip {
    margin-bottom: 10px;
    background-color: #d0e5fe;
    opacity: 0.9;
  }
</style>
