<template>
  <div>
    <el-dialog
      :visible.sync="isOpenDetail"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :append-to-body="false"
      @close="close"
      custom-class="chart-detail-container"
      top="4vh"
      center
      width="80%"
      v-dialogDrag
    >
      <div slot="title" style="display: flex; align-items: center;padding-right: 40px;">
        <span style="font-size: 16px;cursor:pointer" class="my-chart-title" @dblclick.stop="copyTitleText" 
        :data-clipboard-text="chartInfo.ChartName">{{
          isNoChart ? '暂无' : (currentLang==='en'?chartInfo.ChartNameEn||chartInfo.ChartName : chartInfo.ChartName)
        }}</span>
      </div>
      <div class="nodata" v-if="isNoChart">
        <tableNoData text="暂无图表"/>
      </div>
      <template v-else>
        <div class="header">
          <div class="top-left">
            <!-- 默认曲线图 -->
            <template v-if="sameOptionType.includes(chartInfo.ChartType) && chartInfo.Source===1">
              <el-button
                type="primary"
                v-for="item in yearSelector"
                :key="item.value"
                size="medium"
                :plain="item.value !== year_select"
                class="year-btn"
                @click.native="changeYear(item)"
                >{{ item.name }}</el-button
              >
              <el-button type="text" class="btn-sty" @click="openDateDia">{{
                dateTip
              }}</el-button>
            </template>
            <!-- 季节性图选择年份区间 -->
            <date-picker
              v-else-if="chartInfo.ChartType === 2"
              v-model="season_year"
              type="month"
              value-type="format"
              range
              placeholder="年份日期选择"
              @change="seasonYearChange"
            />
          </div>
          <div class="top-right" v-if="chartInfo.Button">
            <span class="collected" @click="removeMychart(chartInfo)" v-if="classifyUserId === roleId">
              <i class="el-icon-remove-outline"></i>移出
            </span>
            <el-popover
              v-if="!chartInfo.Disabled"
              placement="top"
              width="200"
              trigger="manual"
             
              v-model="showPopConfirmMap['url']">
              <p>{{hintText}}</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="closePop('url')">取消</el-button>
                <el-button type="primary" size="mini" @click="copyChart('url')">确定</el-button>
              </div>
              <span class="span-item shareLink" style="margin-left: 7px;" slot="reference"
                @click="copyChartConfirm('url')" :data-clipboard-text="linkUrl"  v-if="!chartInfo.Disabled">
                <i class="el-icon-share"/>&nbsp;分享
              </span>
            </el-popover>
            <span class="span-item" @click="$parent.moveMychart(chartInfo.ChartInfoId)" v-if="classifyUserId === roleId">
              <img
                :src="$icons.chart_move_ico"
                alt=""
                style="
                  width: 12px;
                  height: 12px;
                  margin-left: 7px;
                  vertical-align: middle;
                "
              />
              复制到
            </span>
            <span class="span-item" @click="refreshHandle" style="margin-left: 7px;">
              <span><i class="el-icon-refresh" style="font-size: 15px;"/>&nbsp;刷新 </span>
            </span>
            <span
                class="span-item"
                style="margin-left: 7px"
                @click="$parent.addMychartHandle(chartInfo)"
                v-if="['/database'].includes($route.path)"
            >
                <img
                    :src="$icons.chart_join_ico"
                    alt=""
                    style="width: 13px; height: 12px; vertical-align: middle"
                />
                加入我的图库
            </span>
            <span
              class="span-item"
              style="margin-left: 7px"
              v-if="chartInfo.Button.IsEdit"
              @click="editChartHandle"
            >
              <span> <i class="el-icon-edit" />&nbsp;编辑 </span>
            </span>
            <span
              class="span-item"
              style="margin-left: 7px"
              @click="saveChartMapHandle"
              v-if="![3,6,7,8,9].includes(chartInfo.Source)"
            >
              <span> <i class="el-icon-collection" />&nbsp;保存 </span>
            </span>
            <span
              class="span-item"
              style="margin-left: 7px"
              v-if="chartInfo.Button.IsCopy"
              @click="saveChartOtherHandle"
            >
              <span> <i class="el-icon-document-add" />&nbsp;另存为 </span>
            </span>
            <el-popover
              v-if="!chartInfo.Disabled"
              placement="top"
              width="200"
              trigger="manual"
              v-click-outside="resetShowPopConfirmMap"
              v-model="showPopConfirmMap['office']">
              <p>{{hintText}}</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="closePop('office')">取消</el-button>
                <el-button type="primary" size="mini" @click="copyChart('office')">确定</el-button>
              </div>
              <span
              slot="reference"
              class="span-item copy"
              style="margin-left: 7px"
              @click="copyChartConfirm('office')"
              v-if="!chartInfo.Disabled"
            >
              <i class="el-icon-document-copy" />&nbsp;复制至office
            </span>
            </el-popover>
            <el-popover
              v-if="!chartInfo.Disabled"
              placement="top"
              width="200"
              trigger="manual"
              v-click-outside="resetShowPopConfirmMap"
              v-model="showPopConfirmMap['微信']">
              <p>{{hintText}}</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="closePop('微信')">取消</el-button>
                <el-button type="primary" size="mini" @click="copyChart('微信')">确定</el-button>
              </div>
              <span
                slot="reference"
                class="span-item copy"
                style="margin: 0 7px"
                @click="copyChartConfirm('微信')"
                v-if="!chartInfo.Disabled"
              >
                <img style="width: 13px; height: 12px;vertical-align: middle" src="~@/assets/img/chart_m/WeChat.jpg" />&nbsp;复制至微信
              </span>
            </el-popover>
            <span
              class="span-item"
              style="margin-left: 7px"
              @click="openEnNameDia"
            >
              <span> <img style="width: 16px;vertical-align: middle" :src="$icons.to_en" />&nbsp;设置英文名称 </span>
            </span>
            <el-popconfirm
              title="删除后该图表将不能再引用，确认删除吗？"
              icon="el-icon-info"
              @onConfirm="delChartHandle"
              v-if="chartInfo.Button.IsEdit"
            >
              <span
                slot="reference"
                class="span-item"
                style="color: #ff4040"
              >
                <i class="el-icon-delete" style="color: #ff4040" />&nbsp;删除
              </span>
            </el-popconfirm>
          </div>
        </div>
        <div class="cont-bottom" v-loading="refreshLoading">

          <div class="chartEn-mark" v-show="chartInfo.IsEnChart" style="top: unset;left:unset;">En</div>
          <div class="chart-show-cont">
            <div class="chartWrapper" id="chartWrapper">
              <template v-if="!chartInfo.WarnMsg">
                <Chart :options="options" ref="chartRef"/>
                <!-- 上下限 -->
                <div class="range-cont left" v-if="leftIndex != -1">
                  <el-input
                    style="width: 60px; display: block"
                    size="mini"
                    type="number"
                    placeholder="上限"
                    v-model="tableData[leftIndex].MaxData"
                  />
                  <el-input
                    class="min-data-input"
                    size="mini"
                    type="number"
                    placeholder="下限"
                    v-model="tableData[leftIndex].MinData"
                  />
                </div>
                <div class="range-cont right" v-if="rightIndex != -1">
                  <el-input
                    style="width: 60px; display: block"
                    size="mini"
                    type="number"
                    placeholder="上限"
                    v-model="tableData[rightIndex].MaxData"
                  />
                  <el-input
                    class="min-data-input"
                    size="mini"
                    type="number"
                    placeholder="下限"
                    v-model="tableData[rightIndex].MinData"
                  />
                </div>

                <!-- 右2上下限设置 -->
                <div class="range-cont rightTwo" v-if="rightTwoIndex != -1">
                  <el-input
                    style="width: 60px; display: block"
                    size="mini"
                    type="number"
                    placeholder="上限"
                    v-model="tableData[rightTwoIndex].MaxData"
                  />
                  <el-input
                    class="min-data-input"
                    size="mini"
                    type="number"
                    placeholder="下限"
                    v-model="tableData[rightTwoIndex].MinData"
                  />
                </div>

                  <!-- 后续新图专用上下限 和其他数据依赖不公用 柱形图 截面散点-->
                <template v-if="[7,10].includes(chartInfo.ChartType)">	
                  <div class="range-cont left">
                    <el-input
                      style="width: 60px; display: block"
                      size="mini"
                      type="number"
                      placeholder="上限"
                      v-model="chartLimit.max"
                      @change="changeLimit"
                    />
                    <el-input
                      class="min-data-input"
                      size="mini"
                      type="number"
                      placeholder="下限"
                      v-model="chartLimit.min"
                      @change="changeLimit"
                    />
                  </div>
                  <!-- x轴上下限 -->
                  <div class="range-cont bottom" v-if="chartLimit.x_min||chartLimit.x_max">
                    <el-input
                      class="left"
                      size="mini"
                      type="number"
                      placeholder="下限"
                      v-model="chartLimit.x_min"
                      @change="changeLimit"
                    />
                    <el-input
                      class="left"
                      size="mini"
                      type="number"
                      placeholder="上限"
                      v-model="chartLimit.x_max"
                      @change="changeLimit"
                    />
                  </div>
                </template>
              </template>

              <!-- 异常显示 -->
              <p class="error-tip" v-if="chartInfo.WarnMsg">{{chartInfo.WarnMsg}}</p>

              <!-- 左右切换按钮 -->
              <template v-if="allChart.length > 1">
                <img :src="$icons.chart_left_arrow" alt="" class="arrow left" @click="switchChart('prev')">  
                <img :src="$icons.chart_right_arrow" alt="" class="arrow right"  @click="switchChart('next')">
              </template>
            </div>
            <!-- 公历农历切换 只用于季节性图 -->
            <el-radio-group
              v-if="chartInfo.ChartType === 2 && !chartInfo.WarnMsg"
              v-model="calendar_type"
              class="calendar-cont"
              @change="getPreviewChartInfo"
            >
              <el-radio-button label="公历" />
              <el-radio-button label="农历" />
            </el-radio-group>
          </div>
          <el-table
            :data="tableData"
            ref="tableRef"
            @row-click="rowClickHandle"
            @expand-change="expandChangeHandle"
            :row-key="getRowKey"
            :expand-row-keys="expandKey"
            highlight-current-row
            border
          >
            <!-- 可配置展开 只用于默认图 季节性隐藏-->
            <el-table-column type="expand" v-if="sameOptionType.includes(chartInfo.ChartType) && chartInfo.ChartType!==5 && chartInfo.Source===1">
              <template slot-scope="props">
                <div class="options-cont">
                  <!-- 堆叠图 或组合图中的堆叠类型 非第一项隐藏配置 -->
                  <template v-if="showYOptionsHandle(props.row,props.$index)">
                      <el-checkbox v-model="props.row.IsOrder">逆序</el-checkbox>
                      <el-radio-group v-model="props.row.IsAxis" size="mini">
                        <el-radio-button :label="1">左轴</el-radio-button>
                        <el-radio-button :label="0">右轴</el-radio-button>
                        <!-- 指标有右轴时才可以选右2轴 不然没有右2这个概念的意义 -->
                        <el-radio-button 
                          v-if="[1,6].includes(chartInfo.ChartType)"
                          :label="2" 
                          :disabled="(tableData.findIndex(_ => _.IsAxis===0) === -1) 
                          || (tableData.findIndex(_ => _.IsAxis===0) === props.$index 
                              && tableData.filter(_ => _.IsAxis===0).length === 1)"
                        >右2轴</el-radio-button>
                      </el-radio-group>
                  </template>
                  <div style="min-width: 250px">
                    <el-radio
                      v-model="props.row.EdbInfoType"
                      :label="1"
                      @change="getPreviewChartInfo"
                      >标准指标</el-radio
                    >
                    <div style="margin-top: 22px">
                      <el-radio
                        v-model="props.row.EdbInfoType"
                        :label="0"
                        style="margin-right: 10px"
                        @change="getPreviewChartInfo"
                        >领先指标</el-radio
                      >
                      <template v-if="props.row.EdbInfoType === 0">
                        领先
                        <el-input
                          style="width: 60px"
                          size="mini"
                          type="number"
                          min="0"
                          v-model="props.row.LeadValue"
                          @change="getPreviewChartInfo"
                          @keyup.native="filterCode(props.row)"
                        ></el-input>
                        <el-select
                          v-model="props.row.LeadUnit"
                          placeholder=""
                          style="width: 60px"
                          size="mini"
                          @change="getPreviewChartInfo"
                        >
                          <el-option
                            v-for="item in fre_options"
                            :key="item"
                            :label="item"
                            :value="item"
                          >
                          </el-option>
                        </el-select>
                      </template>
                    </div>
                  </div>
                  <div>
                    <div style="display: flex">
                      <span style="margin-right: 3px">线条颜色：</span>
                      <el-color-picker
                        v-model="props.row.ChartColor"
                        size="mini"
                        show-alpha
                        :predefine="predefineColors"
                      ></el-color-picker>
                    </div>
                    <div 
                      style="margin-top: 12px"
                      v-if="chartInfo.ChartType === 1 
                      || (chartInfo.ChartType === 6 && props.row.ChartStyle==='spline')"
                    >
                      线条粗细：
                      <el-input
                        style="width: 60px"
                        size="mini"
                        type="number"
                        :min="1"
                        v-model="props.row.ChartWidth"
                      />
                    </div>
                  </div>
                  <div v-if="chartInfo.ChartType === 6">
                    <span style="margin-right: 3px">生成样式：</span>
                    <el-select
                      v-model="props.row.ChartStyle"
                      placeholder="请选择生成样式"
                      style="width: 50%"
                      class="edb-item-style"
                    >
                      <el-option
                        v-for="item in chartItemStyleArr"
                        :key="item.key"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </div>
                  <div class="copy-excel">
                    <span class="editsty" @click="copyCode(props.row)">
                      <i class="el-icon-document-copy" />&nbsp;复制数据</span
                    >
                    <span 
                      class="editsty" 
                      @click="viewTarget(props.row)"
                      style="display:block;margin-top:15px;"
                    >&nbsp;查看数据</span>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              v-for="item in tableColums"
              :key="item.label"
              :label="item.label"
              :width="item.widthsty"
              :min-width="item.minwidthsty"
              align="center"
            >
              <template slot-scope="scope">
                <span v-if="item.key==='SourceName'">
                  {{scope.row[item.key]}}
                  <i 
                    class="el-icon-tickets" 
                    style="color:#409EFF;font-size:18px" 
                    @click="isLookHistory=true;lookEdbId=scope.row.EdbInfoId"
                    v-if="scope.row.EdbType===2"
                  />
                </span>
                <span v-else>{{ currentLang==='en' ? (scope.row[item.enKey]||scope.row[item.key]) : scope.row[item.key] }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              key="Copy"
              align="center"
              v-if="[2,5,7].includes(chartInfo.ChartType)"
              width="110"
            >
              <template slot-scope="scope">
                <span class="editsty" @click="copyCode(scope.row)">
                  <i class="el-icon-document-copy" />&nbsp;复制数据</span
                >
                <span 
                  class="editsty"
                  @click="viewTarget(scope.row)"
                >查看数据</span>
              </template>
            </el-table-column>
            <div slot="empty">
              <tableNoData text="暂无指标" size="mini"/>
            </div>
          </el-table>
        </div>
      </template>  
      <img :src="drawImg" alt="" class="drawImg" />
    </el-dialog>

    <!-- 自定义时间段选择弹窗 -->
    <DateChooseDia
      :isDateDia="isDateDia"
      :dateForm="dateForm"
      @cancel="isDateDia = false"
      @dateBack="dataChangeBack"
    />

    <!-- 图表另存 -->
    <SaveChartOther 
      :show.sync="isShowSaveOther" 
      :data="chartInfo"
			:source="chartInfo.Source"
    />

    <!-- 输入英文指标弹窗 -->
    <set-en-name-dia 
      :isOpenDialog="setEnName" 
      @cancel="setEnName=false" 
      @updateEnName="updateEnName" 
      :formData="formItemArray"
      :chartType="chartInfo.ChartType"
      :datainfo="chartInfo.ChartType===10?JSON.parse(chartInfo.ExtraConfig):null"
      :edblist="chartInfo.ChartType===10?tableData:[]"
    />

    <!-- 指标历史记录 -->
    <edbHistoryDialog
      :isOpenDialog.sync="isLookHistory"
      :edbId="lookEdbId"
    />
  </div>
</template>

<script>
import { dataBaseInterface,mychartInterface } from '@/api/api.js';
import futuresInterface from '@/api/modules/futuresBaseApi';
import chartRelevanceApi from '@/api/modules/chartRelevanceApi';
import { fittingEquationInterface,statisticFeatureInterface } from '@/api/modules/chartRelevanceApi';
import {
  seasonOptions,
  copyOtherOptions
} from '@/utils/defaultOptions';
import Chart from '@/views/dataEntry_manage/components/chart';
import SaveChartOther from '@/views/dataEntry_manage/components/SaveChartOther';
import DateChooseDia from '@/views/dataEntry_manage/components/DateChooseDia';
import changeLang from "@/views/dataEntry_manage/components/changeLang"
import setEnNameDia from "@/views/dataEntry_manage/components/setEnNameDia"
import { chartSetMixin } from '@/views/dataEntry_manage/mixins/chartPublic'

export default {
  components: { Chart, DateChooseDia,SaveChartOther,changeLang,setEnNameDia },
  mixins: [ chartSetMixin ],
  directives: {
    'click-outside':{
      bind(el, binding) {
        const clickHandle = (e)=>{
          //console.log(e.target.className)
          const isCurrentTarget = el.contains(e.target)||e.target.className==='el-popover el-popper'||['shareLink','copy'].some(str => e.target.className.includes(str))
          if(isCurrentTarget){
            return false
          }
          if(binding.value && typeof binding.value === 'function'){
            //console.log('binding')
            binding.value(e)
          }
        }
        el.__click__outside = clickHandle
        document.addEventListener('click',clickHandle)
      },
      unbind(el,binding,vnode){
        document.removeEventListener('click',el.__click__outside)
      }
    },
  },
  props: {
    isOpenDetail: {
      type: Boolean,
    },
    chart_code: {
      type: String,
    },
    allChart: {
      type: Array,
    },
    select_classify: {
      type: Number
    },
    classifyUserId: {
      type: Number
    }
  },
  computed: {
    role() {
      let role = localStorage.getItem('Role') || '';
      if (['rai_researcher', 'ficc_researcher', 'researcher','ficc_seller','rai_seller','seller'].includes(role)) {
        return 'researcher';
      } else if (['rai_admin', 'ficc_admin'].includes(role)) {
        return 'admin';
      } else {
        return role;
      }
    },
    /* 登录角色id */
    roleId() {
      let id = parseInt(localStorage.getItem('AdminId'));
      return id;
    },
    /* 分享地址 */
    linkUrl() {
      const LINK_CHART_URL = process.env.CHART_LINK;
      return `${LINK_CHART_URL}?code=${this.chartInfo.UniqueCode}&fromType=share?&lang=${this.currentLang}`
    }
  },
  watch: {
    isOpenDetail(newval) {
      this.isNoChart = false;
      this.currentLang=this.$parent.chart_lang;
      this.formItemArray=[]
      newval && this.getChartDetail();
      this.resetShowPopConfirmMap()
    },
    tableData: {
      handler(newval) {
        newval.length && !this.chartInfo.WarnMsg && this.chartInfo.Source===1&& this.setChartOptionHandle(newval);
      },
      deep: true,
    },
  },
  data() {
    return {
      isNoChart: false, //删完最后一张图展示缺省
			refreshLoading: false,//loading

      showChart: false,
      chartInfo: {},

      dateTip: '请选择时间段',
      season_year: [], //季节图时间段
      calendar_type: '', //公历农历选择项
      drawImg: '', //用于复制后的图标图片存储

      expandKey: [], //展开数组
      showPopConfirmMap:{
        '微信':false,
        'office':false,
        'url':false
      },
      hintText:'英文名称未输入完整，分享图表上可能出现空名称的情况，确定继续分享吗？',

      /* 查看历史弹窗 */
			isLookHistory: false,
			lookEdbId: 0,
    };
  },
  methods: {
    // 配合修改英文信息 chartPublic.js ，防止没有getChartInfo()这个方法
    getChartInfo(){
      this.getChartDetail(this.chartInfo.UniqueCode)
    },
    /* 获取详情 */
    getChartDetail(code = '') {
      this.refreshLoading = true;
      dataBaseInterface
        .getChartByCode({
          UniqueCode: code || this.chart_code,
        })
        .then((res) => {
          this.refreshLoading = false;
          if (res.Ret !== 200) return;
          this.chartInfo = res.Data.ChartInfo;
          

          if(this.chartInfo.Source===1) {
            this.tableData = res.Data.EdbInfoList;
            //eta图
            this.setDefaultDateSelect(); //设置默认的日期选中
            this.chartInfo.ChartType === 7 && this.initBarData(res.Data);

            this.chartInfo.ChartType === 10 && this.initSectionScatterData(res.Data);
          }else if([2,5].includes(this.chartInfo.Source)) {
            this.tableData = [res.Data.EdbInfoList[0]];
            this.chartInfo = res.Data.ChartInfo.Source===5 ? {
              ...res.Data.ChartInfo,
              ProfitNameEn: res.Data.DataResp.ProfitNameEn,
              ProfitName: res.Data.DataResp.ProfitName,
            } : res.Data.ChartInfo;
            //商品价格图
            this.initCommodityData(res.Data);
          }else if([3,4].includes(this.chartInfo.Source)){//相关性 滚动相关性

            this.relevanceChartData={
                ChartInfo:res.Data.ChartInfo,
                EdbInfoList:res.Data.EdbInfoList,
                XEdbIdValue:this.chartInfo.Source === 3 ? res.Data.XEdbIdValue : res.Data.DataResp.XDateTimeValue,
                CorrelationChartInfo:res.Data.CorrelationChartInfo,
                YDataList:[
                  {
                    Value: this.chartInfo.Source === 3 ? res.Data.YDataList[0].Value : res.Data.DataResp.YDataList[0].Value,
                    Color:'#00f',
                    Name:res.Data.ChartInfo.ChartName,
                    NameEn:res.Data.ChartInfo.ChartNameEn
                  }
                ]
            }
            
            this.initRelevanceChartData()
            this.tableData = res.Data.EdbInfoList
          }else if([6,7,8].includes(this.chartInfo.Source)){//拟合方程 标准差 百分比
            this.tableData = res.Data.EdbInfoList;
            
            this.setDefaultChart([res.Data.DataResp]);
          }else if(this.chartInfo.Source===9) { //统计频率
            this.tableData = res.Data.EdbInfoList;
            this.statisticFrequencyData = res.Data.DataResp;
            this.setStatisticFrequency();
          }
        });
    },

    /* 设置默认时间选中项 */
    setDefaultDateSelect() {
      this.year_select = this.chartInfo.DateType;
      this.select_date = [this.chartInfo.StartDate, this.chartInfo.EndDate];
      this.calendar_type = this.chartInfo.Calendar; //日历类型
      this.season_year = [
        this.chartInfo.SeasonStartDate,
        this.chartInfo.SeasonEndDate,
      ];
      this.dateTip =
        this.chartInfo.DateType === 5
          ? `${this.chartInfo.StartDate}~${this.chartInfo.EndDate}`
          : this.chartInfo.DateType === 6
          ? `${this.chartInfo.StartDate}~至今`
          : '请选择时间段';
    },

    /* 曲线图筛选项发生变化时 非配置项 获取新的图表数据 */
   async getPreviewChartInfo() {

      let params = {
        ChartType: this.chartInfo.ChartType,
        DateType: this.year_select,
        StartDate: [5, 6].includes(this.year_select)
          ? this.select_date[0]
          : '',
        EndDate: this.year_select === 5 ? this.select_date[1] : '',
        Calendar: this.calendar_type,
        SeasonStartDate: this.season_year ? this.season_year[0] : '',
        SeasonEndDate: this.season_year ? this.season_year[1] : '',
        ChartEdbInfoList: this.tableData.map(_ => ({
          EdbInfoId: _.EdbInfoId,
          EdbInfoType: _.EdbInfoType,
          LeadValue: _.EdbInfoType ? 0 : Number(_.LeadValue),
          LeadUnit: _.EdbInfoType ? '' : _.LeadUnit,
        }))
      }

      const res = await dataBaseInterface.getSplinePreviewData(params)

      if(res.Ret !== 200) return

      const { EdbInfoList } = res.Data;

      this.tableData.forEach((item) => {
        let edbData = EdbInfoList.find(_ => _.EdbInfoId===item.EdbInfoId);
        item.DataList = edbData.DataList;
        if(edbData.EdbInfoCategoryType===1) item.MoveLatestDate = edbData.MoveLatestDate;
      });
    },

    /* 打开时间段弹窗 */
    openDateDia() {
      // 自定义时间段回显
      this.dateForm = {
        date_type: this.year_select,
        start_date:
          this.year_select === 5 || this.year_select === 6
            ? this.select_date[0]
            : '',
        end_date: this.year_select === 5 ? this.select_date[1] : '',
      };
      this.isDateDia = true;
    },

    /* 保存完自定义日期 刷新数据 保存当前的图表配置和上下限 只改变图表*/
    dataChangeBack(data) {
      this.year_select = data.dateType;
      this.isDateDia = false;
      this.select_date = [data.start_date, data.end_date];

      this.dateTip =
        data.dateType === 5
          ? `${data.start_date}~${data.end_date}`
          : `${data.start_date}~至今`;

      this.saveNowOptions();
      this.getPreviewChartInfo();
    },

    /* 季节图切换年份  保持当前配置 */
    seasonYearChange() {
      this.saveNowOptions();
      this.getPreviewChartInfo();
    },

    /* 年份改变 重新刷新图表接口  保存当前的图表配置和上下限 只改变图表 */
    changeYear(item) {
      this.year_select = item.value;
      this.select_date = '';
      this.dateTip = '请选择时间段';
  
      //保存表格配置和上下限 曲线图需要保存表格配置
      this.saveNowOptions();
      this.getPreviewChartInfo();
    },

    /* 保存图表当前配置项 上下限 */
    saveNowOptions() {
      // const dataArr = _.cloneDeep(this.tableData);
      // dataArr.forEach((item) => {
      //   item.MaxData = Number(item.MaxData);
      //   item.MinData = Number(item.MinData);
      //   delete item.DataList;
      // });
      // sessionStorage.setItem('myChartbeforeOptions', JSON.stringify(dataArr));
    },

    /* 一键刷新 超长等待..*/
    async refreshHandle() {
      // 清除缓存配置项
      this.refreshLoading = true;
      const { Source,ChartInfoId,UniqueCode } = this.chartInfo;

      let res=null
      if(Source===1){
        res= await dataBaseInterface.chartRefresh({ ChartInfoId })
      }else if([2,5].includes(Source)){
        res=await futuresInterface.refreshChart({ ChartInfoId })
      }else if([3,4].includes(Source)){
        res=await chartRelevanceApi.refreshChart({ ChartInfoId })
      }else if(Source===6){
        res=await fittingEquationInterface.refreshChart({ ChartInfoId })
      }else if([7,8,9].includes(Source)) {
        res=await statisticFeatureInterface.refreshChart({ ChartInfoId })
      }
     
        this.refreshLoading = false;
        if (res.Ret !== 200) return
        this.$message.success(res.Msg);
        Source === 1 ? this.getPreviewChartInfo() : this.getChartDetail(UniqueCode);
    },
    // 英文面板时候的判断
    copyChartConfirm(type){
        if(this.currentLang=='en'){
          // 是否所有数据都填写完
          let flag=true
          // 是否有英文表格名称
          if(!this.chartInfo.ChartNameEn) flag = false
          if(flag&&this.chartInfo.Source!=3){
            for (const data of this.tableData) {
              if(data.EdbNameEn=="" ||data.UnitEn==""){
                flag = false
                break
              }
            }
          }
          if(!flag){
            //用Popconfirm替代confirm confirm嵌套:append-to-body="false"的弹窗会有遮罩问题
            this.resetShowPopConfirmMap()
            this.$set(this.showPopConfirmMap,type,true)
            /* this.$confirm('英文名称未输入完整，分享图表上可能出现空名称的情况，确定继续分享吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
            .then(() => {
              if(type==='url'){
                // this.shareUrl()
                const input = document.createElement('input')
                input.setAttribute('readonly','readonly')
                input.value = this.linkUrl
                document.body.appendChild(input)
                input.select();
                document.execCommand('copy');
                document.body.removeChild(input);
                this.$message.success('复制链接成功')
              }else{
                this.copyChartHandle(type)
              }
              $('body .v-modal').remove()
              $('#right > div > div:nth-child(4)').append('<div class="v-modal" tabindex="0"></div>')
            })
            .catch(() => {
              $('body .v-modal').remove()
              $('#right > div > div:nth-child(4)').append('<div class="v-modal" tabindex="0"></div>')
            }); */
          }else{
            this.$set(this.showPopConfirmMap,type,false)
            if(type=='url'){
              this.shareUrl()
            }else{
              this.copyChartHandle(type)
            }
          }
        }else{
          if(type=='url'){
            this.shareUrl()
          }else{
            this.copyChartHandle(type)
          }
        }
    },
    copyChart(type){
      console.log('复制的是：',type)
      if(type==='url'){
        const input = document.createElement('input')
        input.setAttribute('readonly','readonly')
        input.value = this.linkUrl
        document.body.appendChild(input)
        input.select();
        document.execCommand('copy');
        document.body.removeChild(input);
        this.$message.success('复制链接成功')
      }else{
        this.copyChartHandle(type)
      }
      this.closePop(type)
    },
    closePop(type){
      this.$set(this.showPopConfirmMap,type,false)
    },
    resetShowPopConfirmMap(){
      this.showPopConfirmMap={
        '微信':false,
        'office':false,
        'url':false
      }
    },
    /* 点击复制先用canvas画出 转成图片在放到粘贴板中 */
    copyChartHandle:_.debounce(function(type){
      let chartsName = this.currentLang=='ch'?this.chartInfo.ChartName:this.chartInfo.ChartNameEn
      let { heightNum, widthNum , newTitle , dynamic_copyOptions} = this.dynamicWidthAndHeight(type,this.chartInfo.ChartType,chartsName, this.chartInfo.Source === 1?this.tableData.length:this.commodityChartData.length)
      const chartType = this.sameOptionType.includes(this.chartInfo.ChartType) ? 'legend' : 'seasonLegend';
      // 英文转SVG设置变动
      if(this.currentLang == 'en'){
        // 散点图 如果横轴单位为'英文单位'，表示客户没填，转成svg时置为空
        if(this.chartInfo.ChartType == 5){
          this.$refs.chartRef.chart.options.xAxis.forEach(it => {
            if(it.title.text == '英文单位') it.title.text='' 
          });
        }
        // 如果竖轴坐标单位为'英文单位'，表示客户没填，转成svg时置为空
        this.$refs.chartRef.chart.options.yAxis.forEach(it => {
          if(it.title.text == '英文单位') it.title.text='' 
        });
      }
      let svgObj={
        chart:{
          width:widthNum,
          height:heightNum,
          backgroundColor:"rgba(255, 255, 255, 0)",
        },
        title: {
          text: newTitle,
          margin: 10,
          style: {
            fontSize: '18px'
          }
        },
        legend:{
          ...copyOtherOptions[chartType],
          ...dynamic_copyOptions[chartType]
        },
      }
      if(this.options.isRelevanceChart){
        svgObj={
          ...svgObj,
          xAxis:[{
            ...this.options.xAxis,
            offset:-(heightNum-136)/2
          }],
        }
      }
      let svg = this.$refs.chartRef.chart.getSVG(svgObj);
      this.copyBlobItem(widthNum,heightNum,svg,type);
    },500),
    // 选择
    getSelect(targetNode) {
      if (window.getSelection) {
        //chrome等主流浏览器
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNode(targetNode);
        selection.removeAllRanges();
        selection.addRange(range);
      } else if (document.body.createTextRange) {
        //ie
        var range = document.body.createTextRange();
        range.moveToElementText(targetNode);
        range.select();
      }
    },

    /* 图表保存 分配 */
    saveChartMapHandle() {
      const sourceMap = {
        1: this.saveChartHandle,
        2: this.saveCommodityChart
      }
      sourceMap[this.chartInfo.Source]();
    },

    /* 商品价格图保存 */
    saveCommodityChart: _.debounce(async function() {
			const { Ret } = await futuresInterface.chartSave({
				ChartInfoId: this.chartInfo.ChartInfoId,
				LeftMin: String(this.chartLimit.min),
				LeftMax: String(this.chartLimit.max),
			})

			if(Ret!==200) return
			this.$message.success('保存成功');
			//关联图表和图片
			this.setChartImage();
		},300),

    /* 保存当前图表配置 */
    saveChartHandle: _.debounce(function () {
      //遍历每条线的指标配置
      let arr = this.tableData.map((item) => {
        return {
          ChartColor: item.ChartColor,
          ChartStyle: item.ChartStyle,
          ChartWidth: Number(item.ChartWidth),
          EdbInfoId: item.EdbInfoId,
          EdbInfoType: item.EdbInfoType,
          IsAxis: item.IsAxis,
          IsOrder: item.IsOrder,
          LeadUnit: item.EdbInfoType ? '' : item.LeadUnit,
          LeadValue: item.EdbInfoType ? 0 : Number(item.LeadValue),
          MaxData: Number(item.MaxData),
          MinData: Number(item.MinData),
        };
      });

      let public_param = {
        ChartInfoId: this.chartInfo.ChartInfoId || 0,
        ChartEdbInfoList: arr,
      }

      let typeChartParam = {};
      switch(this.chartInfo.ChartType) {
        case 2:
          typeChartParam = {
            ...public_param,
            Calendar: this.calendar_type,
            SeasonStartDate: this.season_year ? this.season_year[0] : '',
            SeasonEndDate: this.season_year ? this.season_year[1] : '',
          }
          break
        case 7:
          typeChartParam = {
            ...public_param,
            DateType: 6,
            LeftMin: String(this.chartLimit.min),
            LeftMax: String(this.chartLimit.max),
          }
        case 10: 
          typeChartParam = {
            ...public_param,
            DateType: 6,
            Calendar: "公历",
            ExtraConfig: JSON.stringify({
              ...JSON.parse(this.chartInfo.ExtraConfig),
              XMinValue: String(this.chartLimit.x_min),
              XMaxValue: String(this.chartLimit.x_max),
              YMinValue: String(this.chartLimit.min),
              YMaxValue: String(this.chartLimit.max),
            })
          } 
      }

      let params = this.sameOptionType.includes(this.chartInfo.ChartType)
        ? {
            ...public_param,
            DateType: this.year_select,
            StartDate:
              this.year_select === 5 || this.year_select === 6
                ? this.select_date[0]
                : '',
            EndDate: this.year_select === 5 ? this.select_date[1] : '',
          }
        : typeChartParam;

      dataBaseInterface.chartSave(params).then((res) => {
        if (res.Ret === 200) {
          this.$message.success('保存成功');
          sessionStorage.removeItem('myChartbeforeOptions');
          //关联图表和图片
          this.setChartImage();
        }
      });
    }, 500),

    /* 删除图表 */
    delChartHandle() {
      this.delHandle(this.chartInfo.ChartInfoId);
    },

    /* 删除方法 */
    delHandle(ChartInfoId) {
      dataBaseInterface
        .delChartClassify({
          ChartInfoId,
        })
        .then((res) => {
          if (res.Ret !== 200) return;
          this.$message.success(res.Msg);
          sessionStorage.removeItem('myChartbeforeOptions');

          let index = this.allChart.findIndex(
            (item) => item === this.chartInfo.UniqueCode
          );
          this.$emit('remove',this.chartInfo.UniqueCode);
          const newId = index > this.allChart.length - 1 ? this.allChart[0] : this.allChart[index];

          if(this.allChart.length >= 1) this.getChartDetail(newId);

          // //只有一个图表且删除了 则展示缺省
          this.isNoChart = !this.allChart.length ? true : false;
        });
    },

    /* 转base64 */
    svgToBase64(svg) {
      const base64img = `data:image/svg+xml;base64,${window.btoa(
        unescape(encodeURI(svg))
      )}`;
      // console.log(base64img)
      return base64img;
    },
    /* 点击保存时关联图表和截取的图片 */
    setChartImage() {
      let svg = this.$refs.chartRef.chart.getSVG({
          chart:{
            width: 340,
            height: 230,
          }
        });
        let form = new FormData();
        form.append('Img', svg);
        this.setImageHandle(form);
    },
    async setImageHandle(form) {
      let { Data } = await dataBaseInterface.uploadImgSvg(form);
      // let { Data } = await dataBaseInterface.uploadImg(form);
      await dataBaseInterface.setChartImage({
        ChartInfoId: this.chartInfo.ChartInfoId,
        ImageUrl: Data.ResourceUrl,
      });
    },

    /* 点击表格行展开配置项 */
    rowClickHandle(row) {
      this.expandKey =
        this.expandKey.length && this.expandKey[0] === row.EdbCode
          ? []
          : [row.EdbCode];
      // this.$refs.tableRef.toggleRowExpansion(row);
      //曲线图点击行 自动置底
      if (this.sameOptionType.includes(this.chartInfo.ChartType)) {
        this.$nextTick(() => {
          $('.cont-bottom')[0].scrollTop = 10000;
        });
      }
    },
    /* 设置row-key */
    getRowKey(row) {
      return row.EdbCode;
    },
    /* 控制展开一行收起其他行并高亮 */
    expandChangeHandle(row, expandedRows) {
      this.expandKey =
        this.expandKey.length && this.expandKey[0] === row.EdbCode
          ? []
          : [row.EdbCode];
      //曲线图点击行 自动置底
      if (this.selected_chartType === 1) {
        this.$nextTick(() => {
          $('.cont-bottom')[0].scrollTop = 10000;
        });
      }
      this.$refs.tableRef.setCurrentRow(row);
    },

		/* 移出我的图库 */
    removeMychart(item) {
      if (!this.select_classify)
        return this.$message.warning(
          '当前图表所属多个分类，请选中具体分类移出'
        );
      mychartInterface.del({ MyChartId: item.MyChartId,MyChartClassifyId: this.select_classify }).then((res) => {
        if (res.Ret !== 200) return;
        this.$message.success('移出成功');
        item.IsAdd = false;
				sessionStorage.removeItem('myChartbeforeOptions');

        let index = this.allChart.findIndex(
          (item) => item === this.chartInfo.UniqueCode
        );
        this.$emit('remove',item.UniqueCode);
        const newId = index > this.allChart.length - 1 ? this.allChart[0] : this.allChart[index];

				if(this.allChart.length >= 1) this.getChartDetail(newId);

        // //只有一个图表且删除了 则展示缺省
        this.isNoChart = !this.allChart.length ? true : false;
      });
    },

    /* 上下切换图表  同一分类内 */
    switchChart(type) {
      //判断当前图表在列表中的index pre时为0去最后一个 next时为最后一个取0
      this.formItemArray=[]
      let index = this.allChart.findIndex(
        (item) => item === this.chartInfo.UniqueCode
      );
      let newCode = '';
      if (type === 'prev') {
        newCode =
          index === 0
            ? this.allChart[this.allChart.length - 1]
            : this.allChart[index - 1];
      } else {
        newCode =
          index === this.allChart.length - 1
            ? this.allChart[0]
            : this.allChart[index + 1];
      }
			sessionStorage.removeItem('myChartbeforeOptions');
      this.getChartDetail(newCode);
      this.resetShowPopConfirmMap()
    },

    /* 编辑图表 */
    editChartHandle() {
      
      let path = '';
      if(this.chartInfo.Source === 1){
        path='/editchart'
      }else if([2,5].includes(this.chartInfo.Source)){
        path='/addCommodityChart'
      }else if([3,4].includes(this.chartInfo.Source)){
        path='/relevancechartEditor'
      }else if(this.chartInfo.Source===6){
        path='/fittingEquationChartEditor'
      }else if([7,8,9].includes(this.chartInfo.Source)) {
        path='/statisticFeatureChartEditor'
      }


      let { href } = this.$router.resolve({
        path,
        query: {
          code: this.chartInfo.UniqueCode,
          from: 'mychart'
        }
      })
      window.open(href,'_blank');
    },

    /* 分享图表链接 */
    shareUrl() {
      var clipboard = new this.Clipboard('.shareLink')
      clipboard.on('success', e => {
        this.$message.success('复制链接成功')
        e.clearSelection() // 释放内存
        clipboard.destroy()
      })
      // // 浏览器不支持
      clipboard.on('error', e => {
        this.$message.warning('浏览器暂不支持')
        // 释放内存
        clipboard.destroy()
      })
    },

    copyTitleText() {
      let clipboard = new this.Clipboard('.my-chart-title')
      clipboard.on('success', e => {
        this.$message.success('复制标题成功')
        e.clearSelection() // 释放内存
        clipboard.destroy()
      })
      // // 浏览器不支持
      clipboard.on('error', e => {
        this.$message.warning('浏览器暂不支持')
        // 释放内存
        clipboard.destroy()
      })
    },

    init() {
      this.dateTip = '请选择时间段';
			sessionStorage.removeItem('myChartbeforeOptions');
    },

    close() {
      this.init();
      this.$emit('close');
      $('#right > div > div:nth-child(4) .v-modal').remove()
    },
  },
  created() {},
  mounted() {},
};
</script>
<style lang="scss">
.chart-detail-container {
  min-width: 1200px;
  $font_normal: 14px;
  $font_mini: 12px;

  $normal_height: 650px;
  $mini_height: 550px;

  @media screen and (max-width: 1710px) {

    /* transform: scale(0.8);
    left: 10%;
    top: 5%; */
    .year-btn {
      padding: 8px 20px;
    }
    .year-btn,.btn-sty,.top-right {
      font-size: $font_mini;
    }
    .el-icon-refresh {
      font-size: 14px;
    }
    .el-table {
      font-size: $font_mini;
      td,th {
        padding: 8px 0;
      }
      .el-table__expanded-cell {
        padding: 10px 15px;
      }
    }
    .cont-bottom,.nodata {
      height: $mini_height;
    }
    .min-data-input {
      margin-top: 220px;
    }
    .btn-sty {
      padding: 8px;
    }
  }
  @media screen and (min-width: 1711px) {
    .year-btn,.btn-sty,.top-right {
      font-size: $font_normal;
    }
    .cont-bottom,.nodata {
      height: $normal_height;
    }
    .min-data-input {
      margin-top: 308px;
    }
    .btn-sty {
      padding: 10px;
    }
    .el-table__expanded-cell {
      padding: 20px 26px;
    }
  }
  
  .el-dialog__body {
    padding: 10px 0 20px;
  }
  .nodata {
    text-align: center;
    padding: 40px 0;
    color: #999;
  }

  .my-chart-title:hover {
    text-decoration: underline;
  }
  .header {
    padding: 0 30px 0;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .close {
      font-size: 26px;
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      cursor: pointer;
    }
    .top-left {
      .year-btn {
        min-width: 98px;
        margin-right: 5px;
        margin-bottom: 5px;
      }
      .btn-sty {
        border: 1px solid #409eff;
      }
    }
    .top-right {
      .join_txt {
        color: #409eff;
        cursor: pointer;
        &:hover {
          text-decoration: underline;
        }
      }
      .collected {
        color: #f00;
        cursor: pointer;
        &:hover {
          text-decoration: underline;
        }
      }
      .span-item {
        color: #409eff;
        cursor: pointer;
        &:hover {
          text-decoration: underline;
        }
        .el-icon-collection,
        .el-icon-document-copy {
          color: #409eff;
        }
      }
    }
  }
  .cont-bottom {
    padding: 10px 30px 30px;
    overflow: auto;
    .error-tip{ color: #D03F28; font-size: 16px;padding: 25px 0 0 25px; }
    .el-input__inner {
      height: 27px;
      line-height: 27px;
      padding: 0 4px;
    }
    .el-input-number .el-input__inner {
      padding: 0 34px 0 4px;
    }
    .el-color-picker--mini .el-color-picker__trigger {
      width: 60px;
      height: 25px;
      padding: 0;
    }
    .el-color-picker--mini .el-color-picker__mask {
      width: 60px;
      height: 25px;
    }
    .highcharts-range-selector-group {
      display: none;
      .highcharts-input-group {
        display: none;
      }
    }
    .highcharts-axis-title {
      display: block;
    }
    .calendar-cont {
      display: block;
      margin: 10px auto 0;
      text-align: center;
    }
    /* =================== */
    .chart-show-cont {
      /* margin-bottom: 15px; */
      padding: 0 180px 10px 150px;
      position: relative;
      .chart-title {
        font-size: 16px;
        font-weight: normal;
        text-align: center;
        margin-bottom: 10px;
      }
      .chart-author {
        color: #333;
        position: absolute;
        bottom: 20px;
        right: 38px;
      }
      .chartWrapper {
        position: relative;
        min-height: 300px;
        .range-cont {
          position: absolute;
          top: 10%;
          .min-data-input {
            width: 60px;
            display: block;
          }
          &.left {
            left: -80px;
          }
          &.right {
            right: -65px;
          }
          &.rightTwo {
            right: -140px;
          }
          &.bottom {
            width: 100%;
            display: flex;
            justify-content: space-between;
            top: auto;
            right: 0;
            bottom: -1%;
            .left {
              width: 60px;
              display: block;
              flex-shrink: 0;
            }
          }
        }
        .arrow {
          width: 38px;
          height: 38px;
          position: absolute;
          color: #999;
          top: 50%;
          transform: translateY(-50%);
          cursor: pointer;
          &:hover {
            opacity: 0.7;
          }
          &.left {
            left: -150px;
          }
          &.right {
            right: -180px;
          }
        }
      }
    }
    .options-cont {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
    }
  }
  .drawImg {
    position: absolute;
    top: -999px;
    z-index: -100;
  }
}
</style>

<style lang="scss">
.el-dialog .el-dialog__header {
  padding: 15px 40px 15px 25px;
}
.edb-item-style .el-input__icon {
	line-height: 27px;
}
</style>