<!--  -->
<template>
  <div class="chart-show">
    <header class="chart-header" @click="openNew">
      <span 
        class="chart-title" 
        @click.stop 
        @dblclick="copyText"
        :style="chartInfo.ChartThemeStyle?`
          text-align:${JSON.parse(chartInfo.ChartThemeStyle).titleOptions.align};
          font-size:${JSON.parse(chartInfo.ChartThemeStyle).titleOptions.style.fontSize}px;
          color:${JSON.parse(chartInfo.ChartThemeStyle).titleOptions.style.color}
        `:''"
      >
        {{ language === 'en'?(chartInfo.ChartNameEn||chartInfo.ChartName): chartInfo.ChartName}}
      </span>

    </header>
    <template v-if="haveData">
      <div
        class="chart-wrapper"
        id="chart-wrapper"
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <chart 
          :options="options" 
          :chartId="chartInfo.ChartInfoId || 0" :chartInfo="chartInfo"
        />

        <div class="mark"></div>
      </div>
    </template>
    <div class="chart-wrapper notfound" v-else>
      <i class="el-icon-warning"></i>哎吆，你的图飞了，赶快去找管理员救命吧~
    </div>

    <!-- 图表来源说明 -->
    <div 
      class="chart-bottom-info bootom-source"
      v-if="chartInfo.Instructions&&JSON.parse(chartInfo.Instructions).isShow
    ">

      <!-- 图表说明 -->
      <div 
        class="chart-instruction text_oneLine" 
        v-text="JSON.parse(chartInfo.Instructions).text"
        :style="`
          color: ${JSON.parse(chartInfo.Instructions).color};
          font-size: ${ JSON.parse(chartInfo.Instructions).fontSize }px
        `"
      ></div>
    </div>

    <div class="bootom-source">

      <!-- 自定义来源 -->
      <div>
        <div class="chart-source text_oneLine" 
          v-if="chartInfo.SourcesFrom&&JSON.parse(chartInfo.SourcesFrom).isShow"
          :style="`
              color: ${ JSON.parse(chartInfo.SourcesFrom).color };
              font-size: ${ JSON.parse(chartInfo.SourcesFrom).fontSize }px;
          `"
        >
            source：<em>{{ JSON.parse(chartInfo.SourcesFrom).text}}</em>
        </div>
      </div>


      <ul class="right-action" @click.stop>
        <li v-if="$route.query.source==='ybxcx'"><collectBtn/></li>
        <!-- eta小程序报告详情中的有收藏 -->
        <li v-if="$route.query.source==='etamini'" @click="handleChangeChartCollect">{{IsCollect?'取消收藏':'收藏'}}</li>
        <li @click="copyUrl" class="copy" v-if="isShare"><i class="el-icon-share"/>分享</li>
        <li @click="refreshChart" v-if="chartInfo.UniqueCode&&$route.query.source!=='smartReportGetImg'"><i class="el-icon-refresh"/>刷新</li>
      </ul>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, onMounted, ref, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import _ from 'lodash';
import { useRoute } from 'vue-router';
import chart from '@/components/chart.vue';
import { IState } from './typing';
import { ChartApi } from '@/request/api';
import collectBtn from './components/collectBtn.vue'
import { useChartRender } from '@/hooks/chart/useChartRender';


export default defineComponent({
  components: {
    chart,
    collectBtn
  },
  setup() {
    const route = useRoute();
    const state = reactive<IState>({
      options: {},
      chartInfo: {},
      dataList: [],
      sourceName: ''
    });

    onMounted(() => {
      getChartInfo();
    });

    // 打开新窗口
    const openNew = (): void => {
			window.open(window.location.href,'_blank');
    }

    /* 获取图表数据信息 */
    const loading = ref(false);
    const haveData = ref(false);
    const code = ref(route.query.code);
    const isShare = ref(route.query.fromType === 'share');
    // 语言 中英文 ch en  默认中文
    const language = ref(route.query.fromPage || route.query.lang || 'zh');
    const IsCollect=ref(false)//图表是否收藏
    const getChartInfo = async (type='') => {

      if(!code.value) {
        haveData.value = false; 
        return
      } 

      loading.value = true;
      try {
        let params={
          UniqueCode: code.value || '',
        }
        // 如果是来自etamini 也就是eta小程序的报告详情
        if(route.query.source==='etamini'){
          params.Source=1
          params.Token=route.query.token
        }
        const { Data } = await ChartApi.getChart(params);
        loading.value = false;
        state.chartInfo = Data.ChartInfo;
        IsCollect.value=Data.IsCollect
        state.dataList = Data.ChartInfo.Source === 1 ? Data.EdbInfoList : [Data.EdbInfoList[0]];

        //处理英文研报英文设置不全就展示中文
        // setLangFromEnReport();
        document.title = language.value==='zh'?Data.ChartInfo.ChartName:Data.ChartInfo.ChartNameEn;

        state.options = useChartRender(Data,language.value)
        
        haveData.value = true;
        type === 'refresh' && ElMessage.success('刷新成功');

        //水印配置
        nextTick(()=>{
          const markDom = document.querySelector('.mark')
          Data.WaterMark&&(markDom.style.backgroundImage = `url(${Data.WaterMark})`)
        })
      }catch (e) {
        loading.value = false;
        haveData.value = false; 
      }

    };

    /* 复制标题 */
    const copyText = () => {
      const { chartInfo } = state;
      let input = document.createElement("input");
      input.value = chartInfo.ChartName;
      document.body.appendChild(input)
      input.select();
      document.execCommand('copy');
      document.body.removeChild(input);
      ElMessage.success('复制标题成功')
    }

    /* 分享链接 */
    const copyUrl = () => {
      let input = document.createElement("input");
      input.value = location.href;
      document.body.appendChild(input)
      input.select();
      document.execCommand('copy');
      document.body.removeChild(input);
      ElMessage.success('复制链接成功')
    }

    const refreshChart = _.debounce(async () => {
      loading.value = true;
      let res: any=null
      if([1,6,7,8,9,10].includes(state.chartInfo.Source)){
        res=await ChartApi.refreshChart({UniqueCode: state.chartInfo.UniqueCode})
      }else if([2,5].includes(state.chartInfo.Source)){
        res=await ChartApi.refreshCommordityChart({UniqueCode: state.chartInfo.UniqueCode});
      }else if([3,4].includes(state.chartInfo.Source)){
        res=await ChartApi.refreshRelevanceChart({UniqueCode: state.chartInfo.UniqueCode});
      }
      
      loading.value = false;
      res.Ret === 200 && getChartInfo('refresh');
    },400)


    // 点击收藏\取消收藏
    const handleChangeChartCollect=async ()=>{
      const params={
        UniqueCode:code.value || '',
        Token:route.query.token,
      }
      const res=IsCollect.value?await ChartApi.chartCollectCancel(params):await ChartApi.chartCollect(params)
      if(res.Ret===200){
        ElMessage.success(IsCollect.value?'取消收藏成功':'收藏成功')
        IsCollect.value=!IsCollect.value
      }
      
    }

    return {
      ...toRefs(state),
      loading,
      haveData,
      getChartInfo,
      openNew,
      copyUrl,
      isShare,
      language,
      refreshChart,
      copyText,
      handleChangeChartCollect
    };
  },
});
</script>
<style scoped lang="less">
@import './index.less';
</style>
