<template>
  <div class="container" v-loading="loading">
    <PageHeader :title="`${$t('field.auditNum')}${datekey}`">
      <el-select v-model="site" :placeholder="$t('field.pleaseChoose')" style="width: 120px" @change="getShowData">
        <el-option v-for="item in siteList" :key="item.code" :label="item.localName" :value="item.code">
        </el-option>
      </el-select>
      <template #icon>
        <i class="el-icon-refresh-right refresh-icon" @click="handleRefresh"></i>
      </template>
    </PageHeader>

    <div class="chartsBox" >
      <div v-if="chartData" :ref="`pieCharts${this.datekey}`" class="pieCharts" :id="`pieCharts${this.datekey}`"></div>
      <Empty v-else />
      <div class="scheduleCharts" :ref="`scheduleCharts${this.datekey}`" :id="`scheduleCharts${this.datekey}`"></div>
    </div>
  </div>
</template>

<script>
import PageHeader from './PageHeader.vue';
import { themeChangeMixin } from '@/mixins/themeChangeMixin'
import { chartThemeMap } from '../common/chartTheme'
import Empty from './Empty/index.vue'
export default {
  name: 'AuditNum',
  mixins: [themeChangeMixin],
  components: {
    PageHeader,
    Empty
  },
  props: {
    datekey: {
      type: String,
      default: 'T'
    }
  },
  data() {
    return {
      siteList: [],
      site: '',

      loading: true,
      date: '',
      chart: null,
      chartData: null,
      rightChart: null
    };
  },

  async mounted() {
    await this.getSiteList()
    await this.getCurrentDate()
    this.getShowData()

    window.addEventListener('resize', () => {
      // 调用图表实例的resize方法，使图表自适应
      this.rightChart?.resize();
      this.chart?.resize();
    });
  },

  watch: {
    theme(val) {
      this.chart?.clear()
      this.rightChart?.clear()
      this.buildCharts()
    }
  },

  methods: {
    async handleRefresh() {
      await this.getSiteList()
      await this.getCurrentDate()
      this.getShowData()
    },
    // 获取机构列表
    async getSiteList() {
      this.loading = true;
      const res = await this.$apis.querySiteList({ codifierGrpCodes: 'site' });
      this.loading = false;
      if (res.success) {
        this.siteList = res.data.result;
        this.site = this.siteList[0].code;
      }
    },

    async getCurrentDate() {
      this.loading = true
      const res = await this.$apis.getSystemDate()
      if (res.success) {
        this.loading = false
        this.date = res.data.result.date + ''
      }
    },

    async getShowData() {
      this.loading = true;
      const queryParam = {
        'queryParam.sysDate': this.date,
        'queryParam.sql': `and E.CANDIDATE4_ in('1')and E.CANDIDATE1_ = '${this.site}'`
      }
      const res = await this.$apis.queryDealAuditNum(queryParam);
      this.loading = false;
      this.chartData = null
      if (res.success) {
        this.chartData = res.data.result;
        this.chart?.clear()
        this.rightChart?.clear()
        this.chart = null
        this.rightChart = null
        this.buildCharts();
      }
    },

    // 构建图表
    buildCharts() {
      if (!this.chartData) return
      this.$nextTick(() => {
        if (!this.chart) {
          const pieChartEl = this.$refs[`pieCharts${this.datekey}`]
          this.chart = this.$echarts.init(pieChartEl);
        }
        const option = {
          legend: {
            orient: 'vertical',
            right: '0%', // 将图例放在右边
            top: 'center', // 使图例在垂直方向上居中
            icon: 'circle',
            itemWidth: 10, // 设置图例图标的宽度
            itemHeight: 10, // 设置图例图标的高度
            textStyle: {
              color: chartThemeMap[this.theme]['legendText']
            }
          },
          tooltip: {
            // 提示tip
            trigger: 'item',
            axisPointer: {
              show: false // 禁用 axisPointer
            }
          },
          color: [
            chartThemeMap[this.theme]['serie_1'],
            chartThemeMap[this.theme]['serie_2'],
            chartThemeMap[this.theme]['serie_3'],
            chartThemeMap[this.theme]['serie_4']],
          series: [
            {
              type: 'pie',
              radius: '50%',
              center: ['50%', '50%'],
              data: [],
              // emphasis: {
              //   itemStyle: {
              //     shadowBlur: 10,
              //     shadowOffsetX: 0,
              //     shadowColor: chartThemeMap[this.theme]['color']
              //   }
              // },
              labelLine: {
                show: false // 禁用引导线
              },
              label: {
                show: false // 禁用标签文本
              }
            }
          ]
        };

        option.series[0].data.push({
          value: this.chartData['initNum'],
          name: 'init'
        });
        option.series[0].data.push({
          value: this.chartData['validNum'],
          name: 'valid'
        });
        option.series[0].data.push({
          value: this.chartData['pendingNum'],
          name: 'pending'
        });
        option.series[0].data.push({
          value: this.chartData['openNum'],
          name: 'open'
        });

        this.chart.setOption(option);
        const front = (this.chartData['validNum'] / (this.chartData['initNum'] + this.chartData['validNum']) * 100).toFixed(0);
        const back = (this.chartData['openNum'] / (this.chartData['openNum'] + this.chartData['pendingNum']) * 100).toFixed(0);
        this.buildRightCharts(Number(back), Number(front));
      })
    },

    buildRightCharts(front, back) {
      const scheduleChartEl = this.$refs[`scheduleCharts${this.datekey}`]
      if (!this.rightChart) {
        this.rightChart = this.$echarts.init(scheduleChartEl);
      }
      const option = {
        tooltip: {
          // 提示tip
          show: true
        },

        grid: {
          left: 60, // 调整左侧边距，给纵坐标添加额外空间
          top: 30,
          right: 30,
          bottom: 0 // 调整底部边距，给横坐标添加额外空间
        },
        xAxis: {
          // 横坐标设置
          type: 'value',
          min: 0, // 设置横坐标最小值
          max: 100, // 设置横坐标最大值
          interval: 25, // 设置刻度间隔
          axisLabel: {
            // label格式化
            formatter: function (value) {
              if (value === 0) {
                return '0';
              }
              return value + ' %';
            },
            color: chartThemeMap[this.theme]['axisColor']
          },
          axisLine: {
            show: false,
          },
          splitLine: {
            lineStyle: {
              color: chartThemeMap[this.theme]['splitLine'],
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          // 纵坐标设置
          type: 'category',
          data: ['后台进度', '前台进度'],
          axisLabel: {
            interval: 0, // 设置坐标文字全部显示
            color: chartThemeMap[this.theme]['axisColor']
          },
          axisTick: {
            alignWithLabel: true,
          },
          axisLine: {
            lineStyle: {
              color: chartThemeMap[this.theme]['axisColor']
            }
          },
        },
        series: [
          // 具体数据以及图表形状
          {
            data: [],
            type: 'bar',
            color: '#3389FF',
            barWidth: 10 // 调整柱状图宽度
          }
        ]
      };
      const xArr = [front, back];
      option.series[0].data = xArr;
      this.rightChart.setOption(option);
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  overflow-y: scroll;
  padding: 8px 9px;
}

.chartsBox {
  display: flex;
  width: 100%;
  flex: 1;
  overflow-y: hidden;
  margin-left: auto;
  margin-right: auto;
  position: relative;

  .pieCharts {
    position: absolute;
    width: 40%;
    height: 10vw;
    top: -10%;
    left: -10%;
  }

  .scheduleCharts {
    width: 60%;
    flex: 1;
    height: 9vw;
    position: absolute;
    top: -8%;
    right: 0%;
  }
}
</style>
