<template>
  <div class="page-style">
    <div class="section-header" @click="goBack">
      <div class="screen-title">
        {{ cityName }}科技大脑智慧服务平台
      </div>
      <div class="back-button">返回省级</div>
    </div>
    <div class="section-container">
      <div class="section-top">
        <div class="section-top-left">
          <MapCity class="map-card" :geojson="cityGeoJson" v-if="cityGeoJson" @district-hover="onDistrictHover" @district-click="onDistrictClick"></MapCity>
        </div>
        <div class="section-top-right">
          <card title="专利转化潜力值排行" :heightPercentage="100">
            <div class="patent-ranking">
              <div class="ranking-header">
                <div class="ranking-city">{{cityName}}</div>
                <div class="ranking-count">145个</div>
              </div>
              <div class="ranking-chart" ref="potentialChartContainer">
                <div ref="potentialChart" style="width: 100%; height:350px;"></div>
              </div>
            </div>
          </card>
        </div>
      </div>
      <div class="section-bottom">
        <div class="chart-container">
          <card title="各类科技成果占比" :heightPercentage="100">
            <div ref="achievementChart" class="chart" style="height: 240px;"></div>
          </card>
        </div>
        <div class="chart-container">
          <card :title="`${cityName}地区专利数量`" :heightPercentage="100">
            <div ref="patentChart" class="chart" style="height: 240px;"></div>
          </card>
        </div>
        <div class="chart-container">
          <card title="地区科研单位占比" :heightPercentage="100">
            <div ref="institutionChart" class="chart" style="height: 240px;"></div>
          </card>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import card from '../components/card/index'
import barChart from '../components/bar/3DIndex.vue'
import lineChart from '../components/line/index.vue'
import pieChart from '../components/pie/index.vue'
import rank from '../components/scroll/index.vue'
import rank2 from '../components/scroll/index2.vue'
import WordCloud from '../components/wordCloud/index.vue'
import MapCity from '../components/map/mapCity.vue'
import * as echarts from 'echarts'

export default {
  name: 'CityPage',
  components: {
    card,
    barChart,
    lineChart,
    pieChart,
    rank,
    rank2,
    WordCloud,
    MapCity
  },
  props: {
    cityName: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      containerHeight: '220px',
      cityGeoJson: null,
      hoveredDistrict: null,
      selectedDistrict: null,
      districtData: {
        // 模拟各区县数据
        '朝阳区': { patents: 256, research: 18, conversion: 145 },
        '南关区': { patents: 189, research: 12, conversion: 98 },
        '宽城区': { patents: 210, research: 15, conversion: 120 },
        '二道区': { patents: 178, research: 10, conversion: 85 },
        '绿园区': { patents: 195, research: 14, conversion: 110 },
        '双阳区': { patents: 120, research: 8, conversion: 65 },
        '九台区': { patents: 145, research: 9, conversion: 78 },
        '农安县': { patents: 132, research: 7, conversion: 70 }
      },
      pieList: [
        {id: 1, value: 72.49, name: '数据名称', color: '#37FFC9'},
        {id: 2, value: 32.55, name: '数据名称', color: '#0084FF'},
        {id: 3, value: 28.6, name: '数据名称', color: '#19D6FF'},
        {id: 4, value: 10.91, name: '数据名称', color: '#FFE777'}
      ],
      peopleList: [
        {id: 1, label: '行业应用'},
        {id: 2, label: '工作性质'}
      ],
      keywords: [
        'Digital Humans', 'Deep Learning', 'VR', 'AR', 'IoT',
        'Decentralization', 'Sustainability', 'Data Mining',
        'Autonomous Driving', 'MR'
      ],
      achievementChart: null,
      patentChart: null,
      institutionChart: null,
      potentialChart: null,
      cityLineData: {
        '长春市': [150, 160, 150, 140, 160, 150, 140, 155, 160, 140, 135, 150],
        '延边州': [120, 130, 110, 120, 125, 115, 120, 125, 115, 120, 125, 115],
        '吉林市': [80, 75, 70, 85, 95, 85, 75, 80, 95, 85, 60, 90]
      }
    }
  },
  watch: {
    windowHeight(newValue) {
      if (newValue >= 1000) {
        this.containerHeight = '240px'
      } else {
        this.containerHeight = '190px'
      }
    }
  },
  computed: {
    windowHeight() {
      return this.$store.state.windowHeight
    }
  },
  async created() {
    try {
      // Load city GeoJSON data based on city name
      this.cityGeoJson = await this.loadCityGeoJson(this.cityName)
      console.log('this.cityGeoJson', this.cityGeoJson)
    } catch (error) {
      console.error('Failed to load city GeoJSON:', error)
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initAchievementChart();
      this.initPatentChart();
      this.initInstitutionChart();
      this.initPotentialChart();
      
      // 监听窗口大小变化
      window.addEventListener('resize', this.handleResize);
    });
  },
  updated() {
    this.$nextTick(() => {
      this.handleResize();
    });
  },
  beforeDestroy() {
    // 销毁图表实例
    this.achievementChart?.dispose()
    this.patentChart?.dispose()
    this.institutionChart?.dispose()
    this.potentialChart?.dispose()
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    async loadCityGeoJson(cityName) {
      try {
        const geoJson = await import(`@/components/map/geojson/${cityName}.json`)
        return geoJson.default
      } catch (error) {
        console.error(`Failed to load GeoJSON for ${cityName}:`, error)
        return null
      }
    },
    onDistrictHover(districtName) {
      this.hoveredDistrict = districtName
      // 更新UI显示，高亮显示当前悬停的区县数据
      // 可以在这里添加临时的UI反馈
    },
    onDistrictClick(districtName) {
      // 设置选中的区县
      this.selectedDistrict = districtName

      // 如果有区县数据，更新相关图表
      if (districtName && this.districtData[districtName]) {
        const data = this.districtData[districtName]

        // 这里可以触发图表组件的更新
        // 例如，可以通过事件总线或者直接更新数据
        console.log(`区县 ${districtName} 被选中，专利数量: ${data.patents}, 研究机构: ${data.research}, 转化数量: ${data.conversion}`)

        // 更新页面标题或其他UI元素，显示选中的区县
        document.title = `${this.cityName} - ${districtName} - 科技大脑智慧服务平台`
      }
    },
    goBack() {
      this.$router.push('/')
    },
    handleResize() {
      this.$nextTick(() => {
        if (this.achievementChart) this.achievementChart.resize();
        if (this.patentChart) this.patentChart.resize();
        if (this.institutionChart) this.institutionChart.resize();
        if (this.potentialChart) this.potentialChart.resize();
      });
    },
    initAchievementChart() {
      this.achievementChart = echarts.init(this.$refs.achievementChart)
      const option = {
        backgroundColor: '#031845',
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b}: {c} ({d}%)"
        },
        graphic: {
          elements: [{
            type: 'text',
            left: '33%',
            top: '42%',
            style: {
              text: '43.56%',
              textAlign: 'center',
              fill: '#fff',
              fontSize: 24,
              fontWeight: 'bold'
            },
            z: 3
          }, {
            type: 'text',
            left: '38%',
            top: '52%',
            style: {
              text: '专利',
              textAlign: 'center',
              fill: '#00FFFF',
              fontSize: 16
            },
            z: 3
          }]
        },
        legend: {
          orient: 'vertical',
          right: '5%',
          top: 'middle',
          itemWidth: 12,
          itemHeight: 12,
          itemGap: 20,
          data: ['论文', '专利', '报告', '文献'],
          textStyle: {
            color: '#fff',
            fontSize: 14,
            padding: [0, 0, 0, 8]
          },
          formatter: function(name) {
            const data = option.series[0].data;
            let value, percent;
            for (let i = 0; i < data.length; i++) {
              if (data[i].name === name) {
                value = data[i].value;
                percent = Math.round(value / data.reduce((sum, item) => sum + item.value, 0) * 100) + '%';
                break;
              }
            }
            return `${name} ${value} ${percent}`;
          }
        },
        series: [{
          name: '科技成果',
          type: 'pie',
          hoverAnimation: false,
          legendHoverLink: false,
          radius: ['45%', '55%'],
          center: ['40%', '50%'],
          color: ['#00FFFF', '#4B85E2', '#F0CA00', '#41D195'],
          label: {
            normal: {
              show: false
            }
          },
          labelLine: {
            normal: {
              show: false
            }
          },
          tooltip: {
            show: false
          },
          data: [{
            value: 2560,
            name: '论文'
          }, {
            value: 1980,
            name: '专利'
          }, {
            value: 1466,
            name: '报告'
          }, {
            value: 1203,
            name: '文献'
          }]
        }, {
          name: '科技成果',
          type: 'pie',
          radius: ['55%', '70%'],
          center: ['40%', '50%'],
          color: ['#00FFFF', '#4B85E2', '#F0CA00', '#41D195'],
          itemStyle: {
            normal: {
              shadowBlur: 20,
              shadowColor: 'rgba(0, 255, 255, 0.3)',
              opacity: 0.9
            }
          },
          labelLine: {
            normal: {
              show: false
            }
          },
          label: {
            normal: {
              show: false
            }
          },
          data: [{
            value: 2560,
            name: '论文'
          }, {
            value: 1980,
            name: '专利'
          }, {
            value: 1466,
            name: '报告'
          }, {
            value: 1203,
            name: '文献'
          }]
        }]
      }

      this.achievementChart.setOption(option)
    },
    initPatentChart() {
      this.patentChart = echarts.init(this.$refs.patentChart)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: false
          },
          axisLabel: {
            color: '#fff'
          }
        },
        yAxis: {
          type: 'category',
          data: ['长春', '吉林', '四平', '白城', '四平'],
          axisLine: {
            lineStyle: {
              color: '#0A2E5D'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#fff'
          }
        },
        series: [{
          type: 'bar',
          data: [320, 450, 280, 380, 220],
          barWidth: 10,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{
              offset: 0,
              color: '#0074D9'
            }, {
              offset: 1,
              color: '#00FFFF'
            }])
          }
        }]
      }
      this.patentChart.setOption(option)
    },
    initInstitutionChart() {
      this.institutionChart = echarts.init(this.$refs.institutionChart)
      const option = {
        backgroundColor: '#031845',
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}m² ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: '5%',
          top: 'middle',
          itemWidth: 12,
          itemHeight: 12,
          itemGap: 20,
          textStyle: {
            color: '#fff',
            fontSize: 14,
            padding: [0, 0, 0, 8]
          },
          formatter: function(name) {
            const data = option.series[0].data;
            let value, percent;
            for (let i = 0; i < data.length; i++) {
              if (data[i].name === name) {
                value = data[i].value;
                percent = Math.round(value / data.reduce((sum, item) => sum + item.value, 0) * 100) + '%';
                break;
              }
            }
            return `${name} ${value}m² ${percent}`;
          }
        },
        series: [{
          name: '科研单位',
          type: 'pie',
          radius: ['20%', '65%'],
          center: ['40%', '50%'],
          roseType: 'radius',
          itemStyle: {
            borderRadius: 0,
            borderColor: '#031845',
            borderWidth: 2
          },
          label: {
            show: false
          },
          labelLine: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 14,
              fontWeight: 'bold'
            }
          },
          color: ['#00FFFF', '#4B85E2', '#F0CA00', '#41D195'],
          data: [{
            value: 72.49,
            name: '数据名称1',
            itemStyle: {
              shadowBlur: 20,
              shadowColor: 'rgba(0, 255, 255, 0.3)'
            }
          }, {
            value: 32.55,
            name: '数据名称2',
            itemStyle: {
              shadowBlur: 20,
              shadowColor: 'rgba(75, 133, 226, 0.3)'
            }
          }, {
            value: 28.6,
            name: '数据名称3',
            itemStyle: {
              shadowBlur: 20,
              shadowColor: 'rgba(240, 202, 0, 0.3)'
            }
          }, {
            value: 10.91,
            name: '数据名称4',
            itemStyle: {
              shadowBlur: 20,
              shadowColor: 'rgba(65, 209, 149, 0.3)'
            }
          }]
        }]
      }
      this.institutionChart.setOption(option)
    },
    initPotentialChart() {
      // 确保DOM已经渲染
      this.$nextTick(() => {
        if (!this.$refs.potentialChart) {
          console.error('potentialChart ref not found');
          return;
        }

        // 如果已经初始化过，先销毁
        if (this.potentialChart) {
          this.potentialChart.dispose();
        }

        // 初始化图表
        this.potentialChart = echarts.init(this.$refs.potentialChart);

        const option = {
          backgroundColor: 'transparent',
          tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(0,0,0,0.7)',
            borderColor: 'rgba(0,147,233,0.2)',
            textStyle: {
              color: '#fff'
            }
          },
          legend: {
            data: ['朝阳区', '南关区', '宽城区', '二道区', '绿园区'],
            textStyle: {
              color: '#8CAFE0'
            },
            top: 0,
            itemWidth: 15,
            itemHeight: 10,
            itemGap: 15
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '8%',
            top: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['2020年', '2021年', '2022年', '2023年', '2024年'],
            axisLine: {
              lineStyle: {
                color: '#1E3F66'
              }
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              color: '#8CAFE0',
              fontSize: 12
            }
          },
          yAxis: {
            type: 'value',
            splitLine: {
              lineStyle: {
                color: '#1E3F66',
                type: 'dashed'
              }
            },
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              color: '#8CAFE0',
              fontSize: 12
            }
          },
          series: [
            {
              name: '朝阳区',
              type: 'line',
              smooth: true,
              symbol: 'circle',
              symbolSize: 6,
              data: [256, 245, 260, 255, 270],
              itemStyle: {
                color: '#00FFFF'
              },
              lineStyle: {
                color: '#00FFFF',
                width: 2
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: 'rgba(0, 255, 255, 0.3)'
                  },
                  {
                    offset: 1,
                    color: 'rgba(0, 255, 255, 0)'
                  }
                ])
              }
            },
            {
              name: '南关区',
              type: 'line',
              smooth: true,
              symbol: 'circle',
              symbolSize: 6,
              data: [189, 195, 185, 192, 198],
              itemStyle: {
                color: '#19D6FF'
              },
              lineStyle: {
                color: '#19D6FF',
                width: 2
              }
            },
            {
              name: '宽城区',
              type: 'line',
              smooth: true,
              symbol: 'circle',
              symbolSize: 6,
              data: [210, 205, 215, 208, 220],
              itemStyle: {
                color: '#FFC900'
              },
              lineStyle: {
                color: '#FFC900',
                width: 2
              }
            },
            {
              name: '二道区',
              type: 'line',
              smooth: true,
              symbol: 'circle',
              symbolSize: 6,
              data: [178, 182, 175, 180, 185],
              itemStyle: {
                color: '#FF7A45'
              },
              lineStyle: {
                color: '#FF7A45',
                width: 2
              }
            },
            {
              name: '绿园区',
              type: 'line',
              smooth: true,
              symbol: 'circle',
              symbolSize: 6,
              data: [195, 190, 200, 193, 205],
              itemStyle: {
                color: '#41D195'
              },
              lineStyle: {
                color: '#41D195',
                width: 2
              }
            }
          ]
        };

        try {
          this.potentialChart.setOption(option);
          console.log('Potential chart initialized successfully');
        } catch (error) {
          console.error('Failed to initialize potential chart:', error);
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.page-style {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
  margin: 0 auto;
  background: linear-gradient(270deg,
          #081B34 0%,   /* 深海军蓝 */
          #0D2A50 35%,  /* 略亮一点，增加层次 */
          #113667 54%,  /* 主"亮点" */
          #0D2A50 70%,  /* 对称回落 */
          #081B34 100%  /* 与首色呼应 */
  );
}

.section-header {
  position: relative;
  width: 100%;
  height: 80px;
  background: url("./../assets/images/screen1/blockTop/header_bg3.png") no-repeat;
  background-size: 100% 100%;
  overflow: hidden;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.screen-title {
  position: relative;
  height: 80px;
  line-height: 65px;
  text-align: center;
  margin-left: 20px;
  font-family: YouSheBiaoTiHei;
  font-size: 40px;
  color: white;
  text-shadow: 0px 2px 3px #1E736C, 0px 0px 15px rgba(228, 239, 255, 0.1);
  font-style: normal;
  text-transform: none;
}

.back-button {
  background: rgba(24, 144, 255, 0.1);
  color: #fff;
  margin-right: 20px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: background 0.3s;

  &:hover {
    background: rgba(24, 144, 255, 0.2);
  }
}

.section-container {
  position: relative;
  width: 100%;
  height: calc(100% - 80px);
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  padding: 10px 10px 30px 10px;
  box-sizing: border-box;
}

.section-top{
  position: relative;
  width: 100%;
  flex: 6;
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.section-top-left{
  height: 100%;
  flex: 2;
}

.section-top-right{
  height: 100%;
  flex: 1;
  margin-left: 120px;
}

.section-bottom {
  position: relative;
  width: 100%;
  flex: 4;
  display: flex;
  justify-content: center;
  gap: 20px;
  min-height: 260px;
  
  .chart-container {
    flex: 1;
    background: rgba(3, 20, 47, 0.7);
    border: 1px solid rgba(0, 147, 233, 0.2);
    border-radius: 4px;
    height: 100%;
    display: flex;
    flex-direction: column;

    .chart-title {
      color: #fff;
      font-size: 16px;
      display: flex;
      align-items: center;

      .icon-arrow {
        display: inline-block;
        width: 4px;
        height: 16px;
        background: #00FFFF;
        margin-right: 8px;
      }
    }

    .chart {
      flex: 1;
      width: 100%;
      min-height: 0;
    }
  }
}

.patent-ranking {
  width: 100%;
  height: 100%;
  padding: 15px;
  display: flex;
  flex-direction: column;

  .ranking-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 15px;
    height: 40px;

    .ranking-city {
      font-size: 16px;
      color: #fff;
      background-color: rgba(0, 147, 233, 0.2);
      padding: 4px 15px;
      border-radius: 4px;
    }

    .ranking-count {
      margin-right: 40px;
      font-size: 14px;
      color: #8CAFE0;
    }
  }

  .ranking-chart {
    width: 100%;
    overflow: visible;
  }
}

.map-card {
  width: 100%;
  height: 100%;
}
</style>


