<template>
  <div class="chartSetting_container">
    <div class="chartSetting_main box" id="box" v-if="showData">
      <span
        class="slide-icon slide-right"
        @click="slideHandle"
        v-show="isSlideLeft"
      >
        <i class="el-icon-d-arrow-right"></i>
      </span>
      <div class="chartSetting-main">
        <div class="main-left left" id="left" v-show="!isSlideLeft">
          
          <div class="add-chart-cont">
            <el-button 
              v-permission="permissionBtn.chartLibPermission.chartLib_add"
              @click="$router.push({path: '/addchart'})" type="primary"
            ><!-- 添加图表 -->{{$t('Chart.add_chart_btn')}}</el-button>

          </div>
          
          <div class="left-main">
            <div class="chartSetting_main_top">
              <el-radio-group 
                v-model="classifyShowType" 
                @input="handleChangeClassifyType"
              >
                <el-radio-button :label="item.key" v-for="item in classifyTabs" :key="item.key">
                  {{item.label}}
                </el-radio-button>
              </el-radio-group>

              <el-select
                v-if="classifyShowType!=='shared'"
                v-model="search_txt"
                v-loadMore="searchLoad"
                :filterable="!search_txt"
                remote
                clearable
                :placeholder="$t('Chart.search_chart_placeholder')"
                style="width: 100%; margin-top: 20px"
                :remote-method="searchHandle"
                @click.native="inputFocusHandle"
              >
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
                <el-option
                  v-for="item in searchOptions"
                  :key="item.ChartInfoId"
                  :label="currentLang==='en'?(item.ChartNameEn||item.ChartName):item.ChartName"
                  :value="item.ChartInfoId"
                >
                  <div>
                    <img 
                      :src="$icons.lock_ico2" 
                      width="18" 
                      height="18" 
                      style="vertical-align:middle" 
                      v-if="!item.HaveOperaAuth"
                    />
                    {{currentLang==='en'?(item.ChartNameEn||item.ChartName):item.ChartName}}
                  </div>
                </el-option>
              </el-select>
            </div>
            
            <!-- 公共目录，我的目录 -->
            <div 
              class="tree-cont" 
              v-if="['public','own'].includes(classifyShowType)"
            >
              <div 
                class="own-tree" 
                :style="`height:${classifyShowType==='own'?'60%':'100%'}`
              ">
                <!-- <div class="tree-title">目录</div> -->
                <div class="tree-wrapper">
                    <el-tree
                      ref="treeRef"
                      class="target_tree"
                      :data="treeData"
                      node-key="UniqueCode"
                      :props="defaultProp"
                      :allow-drag="canDragHandle"
                      :allow-drop="canDropHandle"
                      :current-node-key="select_node"
                      :default-expanded-keys="defaultShowNodes"
                      draggable
                      :expand-on-click-node="false"
                      check-strictly
                      :empty-text="$t('Common.no_classify_msg')"
                      lazy
                      :load="getLazyTreeData"
                      @node-expand="handleNodeExpand"
                      @node-collapse="handleNodeCollapse"
                      @current-change="nodeChange"
                      @node-drop="dropOverHandle"
                      @node-drag-end="dropMouseLeave"
                      @node-drag-leave="dropMouseLeave"
                      @node-drag-enter="dropMouseOver"
                    >
                      <span class="custom-tree-node" slot-scope="{ node, data }">
                        <span
                          class="text_oneLine node_label"
                          :style="`width:${select_node === data.UniqueCode?'60%':'auto'}`"
                          :id="`node${data.UniqueCode}`"
                        >
                          <img 
                            :src="$icons.lock_ico2" 
                            width="18" 
                            height="18" 
                            style="vertical-align:middle" 
                            v-if="!data.HaveOperaAuth&&data.ChartInfoId"
                          />
                          <span>{{ currentLang==='en' ? (data.ChartClassifyNameEn||data.ChartClassifyName) : data.ChartClassifyName }}</span>
                        </span>
                        <span
                          style="display: flex; align-items: center"
                          v-if="select_node === data.UniqueCode"
                        >
                          <img
                            src="~@/assets/img/data_m/move_ico.png"
                            alt=""
                            style="width: 14px; height: 14px; margin-right: 8px"
                            v-if="data.Button.MoveButton"
                          />
                          <!-- 添加子项 -->
                          <img
                            src="~@/assets/img/set_m/add.png"
                            alt=""
                            style="width: 14px; height: 14px; margin-right: 8px"
                            @click.stop="addNode(node, data)"
                            v-if="data.Button.AddButton&&permissionBtn.isShowBtn('chartLibPermission','chartLib_classifyOpt_add')"
                          />
                          <!-- 编辑子项 -->
                          <img
                            src="~@/assets/img/set_m/edit.png"
                            alt=""
                            style="width: 15px; height: 14px; margin-right: 8px"
                            @click.stop="editNode(node, data)"
                            v-if="data.Button.OpButton&&permissionBtn.isShowBtn('chartLibPermission','chartLib_classifyOpt_add')"
                          />
                          <!-- 删除子项 -->
                          <img
                            slot="reference"
                            src="~@/assets/img/set_m/del.png"
                            alt=""
                            style="width: 14px; height: 14px"
                            @click.stop="removeNode(node, data)"
                            v-if="data.Button.DeleteButton&&permissionBtn.isShowBtn('chartLibPermission','chartLib_classifyOpt_delete')"
                          />
                        </span>
                      </span>
                    </el-tree>
                </div>

                <div class="opt-wrapper">
									<!-- 新增分类 -->
									<div 
                    class="opt-item" 
                    @click="addLevelOneHandle"
                    v-if="CanOpClassify&&permissionBtn.isShowBtn('chartLibPermission','chartLib_classifyOpt_add')"
                  >
										<img
											src="~@/assets/img/set_m/add_ico.png"
											alt=""
											style="width: 16px; height: 16px; margin-right: 5px"
										/>
										<span>添加图表分类</span>
									</div>
									<!-- 移动图表 -->
									<div class="opt-item">
										<img
											src="~@/assets/img/set_m/move_batch_ico.png"
											alt=""
											style="width: 16px; height: 16px; margin-right: 5px"
										/>
										<span>批量移动图表</span>
									</div>
									<template v-if="classifyShowType==='own'">
										<!-- 共享图表 -->
										<div class="opt-item" @click="handleOpenSetShared('shared')">
											<img
												src="~@/assets/img/set_m/shared_ico.png"
												alt=""
												style="width: 16px; height: 16px; margin-right: 5px"
											/>
											<span>设置图表共享</span>
										</div>
										<!-- 公开图表 -->
										<div class="opt-item" @click="handleOpenSetShared('public')">
											<img
												src="~@/assets/img/set_m/public_ico.png"
												alt=""
												style="width: 16px; height: 16px; margin-right: 5px"
											/>
											<span>设置图表公开</span>
										</div>
									</template>
							  </div>
              </div>

              <!-- 收藏目录 拼接我的指标tab-->
              <div class="collect-tree" v-if="classifyShowType==='own'">
                  <div class="tree-title">收藏图表</div>
                  <div class="tree-wrapper">
                    <collectEdbMenu
                      :data="collectClassifys"
                      @change="getCollectClassifys"
                      ref="collectEdbMenuRef"
                    />
                  </div>

                  <div class="opt-wrapper">
                      <div class="opt-item" @click="handleOpenCollectClassify">
                        <img
                          src="~@/assets/img/set_m/add_ico.png"
                          alt=""
                          style="width: 16px; height: 16px; margin-right: 5px"
                        />
                        <span>新增收藏分类</span>
                      </div>
                  </div>
              </div>
            </div>

            <!-- 共享指标目录 -->
            <div class="tree-cont"
              v-else-if="classifyShowType==='shared'"
            >
                <sharedMenu/>
            </div>
          </div>
          
          <span
            class="move-btn resize"
            v-drag
            id="resize"
          ></span>
          <span class="slide-icon slide-left" @click="slideHandle">
            <i class="el-icon-d-arrow-left"></i>
          </span>
        </div>

        <div
          class="main-right right"
          id="right"
          :style="isSlideLeft ? 'width:100%' : `width:${dynamicWidth}`"
        >
          <!-- =============具体图表区域============== -->
          <div class="chart-min-cont" v-if="tableData.length">

            <template v-if="chartInfo.HaveOperaAuth">
              <div class="cont-top">
                <div class="top-left">
                  <!-- 默认曲线图 -->
                  <template v-if="sameOptionType.includes(chartInfo.ChartType)">
                    <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>

                  <div v-else-if="chartInfo.ChartType === 2" @click="openDateDia" class="date-setting">
                    {{ season_year && season_year.length>0 ? season_year[0]+'~'+season_year[1]:"年份日期选择" }}
                  </div>
                </div>
              </div>
              <div class="cont-bottom">
                <el-row class="bottom-min">
                  <el-col
                    :span="21"
                    style="padding-bottom: 30px;"
                  >
                  
                    <div class="chart-show-cont"  v-if="!chartInfo.WarnMsg">
                      <div class="chartWrapper" id="chartWrapper">
                        <h2 
                          class="chart-title"
                          :style="`
                            textAlign:${JSON.parse(chartInfo.ChartThemeStyle).titleOptions.align};
                            fontSize:${JSON.parse(chartInfo.ChartThemeStyle).titleOptions.style.fontSize}px;
                            color:${JSON.parse(chartInfo.ChartThemeStyle).titleOptions.style.color}
                          `"
                        >
                          {{ currentLang==='en'?chartInfo.ChartNameEn:chartInfo.ChartName }}
                        </h2>

                        <Chart :options="options" :chartInfo="chartInfo" ref="chartRef"/>


                        <template v-if="![7,10,11].includes(chartInfo.ChartType)">
                            <div class="range-cont left" v-if="leftIndex != -1">
                                <el-input
                                    style="width: 60px; display: block"
                                    size="mini"
                                    type="number"
                                    placeholder="上限"
                                    :disabled="!permissionBtn.isShowBtn('chartLibPermission','chartLib_editLimit')"
                                    v-model="chartLimit.max"
                                    @change="changeLimit"
                                />
                                <el-input
                                    class="min-data-input"
                                    size="mini"
                                    type="number"
                                    placeholder="下限"
                                    :disabled="!permissionBtn.isShowBtn('chartLibPermission','chartLib_editLimit')"
                                    v-model="chartLimit.min"
                                    @change="changeLimit"
                                />
                            </div>
                        <div 
                          class="range-cont right" 
                          v-if="rightIndex != -1"
                        >
                          <el-input
                            style="width: 60px; display: block"
                            size="mini"
                            type="number"
                            placeholder="上限"
                            :disabled="!permissionBtn.isShowBtn('chartLibPermission','chartLib_editLimit')"
                            v-model="chartLimit.rightMax"
                            @change="changeLimit"
                          />
                          <el-input
                            class="min-data-input"
                            size="mini"
                            type="number"
                            placeholder="下限"
                            :disabled="!permissionBtn.isShowBtn('chartLibPermission','chartLib_editLimit')"
                            v-model="chartLimit.rightMin"
                            @change="changeLimit"
                          />
                        </div>
                        <div class="range-cont rightTwo" v-if="rightTwoIndex != -1">
                          <el-input
                            style="width: 60px; display: block"
                            size="mini"
                            type="number"
                            placeholder="上限"
                            :disabled="!permissionBtn.isShowBtn('chartLibPermission','chartLib_editLimit')"
                            v-model="chartLimit.rightTwoMax"
                            @change="changeLimit"
                          />
                          <el-input
                            class="min-data-input"
                            size="mini"
                            type="number"
                            placeholder="下限"
                            :disabled="!permissionBtn.isShowBtn('chartLibPermission','chartLib_editLimit')"
                            v-model="chartLimit.rightTwoMin"
                            @change="changeLimit"
                          />
                        </div>
                        </template>

                        <!-- 后续新图专用上下限 和其他数据依赖不公用 柱形图 截面散点-->
                        <template v-if="[7,10,11].includes(chartInfo.ChartType)">	
                          <div class="range-cont left">
                            <el-input
                              style="width: 60px; display: block"
                              size="mini"
                              type="number"
                              :placeholder="$t('Chart.up_limit')"
                              :disabled="!permissionBtn.isShowBtn('chartLibPermission','chartLib_editLimit')"
                              v-model="chartLimit.max"
                              @change="changeLimit"
                            />
                            <el-input
                              class="min-data-input"
                              size="mini"
                              type="number"
                              :placeholder="$t('Chart.low_limit')"
                              :disabled="!permissionBtn.isShowBtn('chartLibPermission','chartLib_editLimit')"
                              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="$t('Chart.low_limit')"
                              :disabled="!permissionBtn.isShowBtn('chartLibPermission','chartLib_editLimit')"
                              v-model="chartLimit.x_min"
                              @change="changeLimit"
                            />
                            <el-input
                              class="left"
                              size="mini"
                              type="number"
                              :placeholder="$t('Chart.up_limit')"
                              :disabled="!permissionBtn.isShowBtn('chartLibPermission','chartLib_editLimit')"
                              v-model="chartLimit.x_max"
                              @change="changeLimit"
                            />
                          </div>
                        </template>
                      </div>
                      <span class="chart-author"
                        ><!-- 作者 -->{{$t('Chart.Detail.author')}}:{{ chartInfo.SysUserRealName || '' }}</span
                      >

                      <div class="chart-bottom-insruction-info">

                        <div class="chart-source" >
                            <span
                              v-if="chartInfo.SourcesFrom&&JSON.parse(chartInfo.SourcesFrom).isShow"
                              :style="`
                              color: ${JSON.parse(chartInfo.SourcesFrom).color};
                              fontSize: ${ JSON.parse(chartInfo.SourcesFrom).fontSize }px;
                            `"
                            ><!-- 来源 -->{{$t('Chart.Detail.source')}}:{{ JSON.parse(chartInfo.SourcesFrom).text}}</span>
                        </div>

                        <!-- 公历农历切换 只用于季节性图 -->
                        <el-radio-group
                          v-model="calendar_type"
                          :class="chartInfo.SourcesFrom&&JSON.parse(chartInfo.SourcesFrom).isShow ? 'calendar-cont' : 'calendar-cont clear-margin'"
                          v-if="chartInfo.ChartType === 2"
                          @change="getPreviewChartInfo"
                        >
                          <el-radio-button label="公历">{{$t('Chart.calendar_gre')}}</el-radio-button>
                          <el-radio-button label="农历">{{$t('Chart.calendar_lunar_text')}}</el-radio-button>
                        </el-radio-group>

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

                    <!-- 异常显示 -->
                    <p class="error-tip" style="min-height: 400px;" v-if="chartInfo.WarnMsg">{{chartInfo.WarnMsg}}</p>
                  </el-col>
                  <el-col :span="3" style="position: absolute;height: 100%;right: 0;min-width: 115px;">
                    <ul class="right-actions">
                        <li><!-- 操作 -->{{$t('Table.column_operations')}}</li>
                        <li
                          v-permission="permissionBtn.chartLibPermission.chartLib_share"
                          class="span-item shareLink"
                          @click="copyChartConfirm('url')"
                          :data-clipboard-text="linkUrl"
                          v-if="!chartInfo.Disabled"
                        >
                          <i class="el-icon-share"/>&nbsp;<!-- 分享 -->
                          {{$t('Chart.chart_share_btn')}}
                        </li>
                    
                        <li 
                          v-permission="permissionBtn.chartLibPermission.chartLib_refresh"
                          class="span-item" 
                          @click="refreshHandle"
                        >
                          <span>
                            <i class="el-icon-refresh" style="margin-left:0"/>&nbsp;<!-- 刷新 -->{{$t('Edb.detail_refresh_btn')}} 
                          </span>
                        </li>
                        <li 
                          v-permission="permissionBtn.chartLibPermission.chartLib_save"
                          class="span-item"
                        >
                          <span @click="saveChartHandle('')">
                            <i class="el-icon-collection" />&nbsp;<!-- 保存 -->{{$t('Chart.chart_save_btn')}}
                          </span>
                        </li>
                        <li 
                          v-permission="permissionBtn.chartLibPermission.chartLib_otherSave"
                          class="span-item"
                        >
                          <span @click="saveChartOtherHandle">
                            <i class="el-icon-document-add" />&nbsp;<!-- 另存为 -->{{$t('Chart.chart_copy_btn')}}
                          </span>
                        </li>
                        <li 
                          v-permission="permissionBtn.chartLibPermission.chartLib_edit"
                          class="span-item"
                          v-if="chartInfo.IsEdit"
                          @click="editChartHandle"
                        >
                          <img
                            src="~@/assets/img/set_m/edit.png"
                            alt=""
                            style="width: 13px; height: 12px;"
                          />&nbsp;<!-- 编辑 -->{{$t('Chart.chart_edit_btn')}}
                        </li>
                        <li 
                          v-permission="permissionBtn.chartLibPermission.chartLib_copyOffice"
                          class="span-item copy"
                          @click="copyChartConfirm('office')"
                          v-if="!chartInfo.Disabled"
                        >
                          <i class="el-icon-document-copy" />&nbsp;<!-- 复制至office -->{{$t('Chart.chart_copyoffice')}}
                        </li>
                        <li 
                          v-permission="permissionBtn.chartLibPermission.chartLib_copyWechat"
                          class="span-item copy"
                          @click="copyChartConfirm('微信')"
                          v-if="!chartInfo.Disabled"
                        >
                          <img style="width: 13px; height: 12px;vertical-align: middle" src="~@/assets/img/chart_m/WeChat.jpg" />&nbsp;<!-- 复制至微信 -->{{$t('Chart.chart_copywx')}}
                        </li>
                        <li 
                          v-permission="permissionBtn.chartLibPermission.chartLib_enNameSetting"
                          class="span-item copy"
                          @click="openLangInfoDia"
                        >
                          <img style="width: 16px;vertical-align: middle" :src="$icons.to_en" />&nbsp;<!-- 编辑信息 -->{{$t('Edb.detail_en_btn')}}
                        </li>
                        <li 
                          v-permission="permissionBtn.chartLibPermission.chartLib_del"
                          class="span-item"
                          style="color: #ff4040"
                          @click="delChartHandle"
                          v-if="chartInfo.IsEdit"
                        >
                          <i class="el-icon-delete" style="color: #ff4040" />&nbsp;<!-- 删除 -->{{$t('Chart.chart_del_btn')}}
                        </li>
                        <li 
                          v-if="chartInfo.ForumChartInfoId==0"
                          v-permission="permissionBtn.chartLibPermission.chartLib_uploadToForum"
                          class="span-item copy"
                          @click="showUploadToForum=true;uploadToForumIntro=''"
                        >
                          <img style="width: 16px;vertical-align: middle" :src="$icons.upload_to_forum" />&nbsp;<!-- 上传至社区 -->{{$t('Chart.upload_to_forum')}}
                        </li>
                        <template v-else>
                        <li 
                          v-permission="permissionBtn.chartLibPermission.chartLib_updateToForum"
                          class="span-item copy"
                          @click="handleForumOpt('update')"
                        >
                          <img style="width: 16px;vertical-align: middle" :src="$icons.update_to_forum" />&nbsp;<!-- 同步至社区 -->{{$t('Chart.update_to_forum')}}
                        </li>
                        <li 
                          v-permission="permissionBtn.chartLibPermission.chartLib_withdrawfromForum"
                          class="span-item copy"
                          @click="handleForumOpt('withdraw')"
                        >
                          <img style="width: 16px;vertical-align: middle" :src="$icons.withdraw_from_forum" />&nbsp;<!-- 从社区撤回 -->{{$t('Chart.withdraw_from_forum')}}
                        </li>
                        </template>
                        
                    </ul>
                  </el-col>
                </el-row>
                <el-table
                  :data="tableData"
                  ref="tableRef"
                  highlight-current-row
                  border
                >
                  <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="toHistoryPage(scope.row.EdbInfoId,$route.matched)"
                          v-if="scope.row.EdbType===2"
                        />
                      </span>
                      <span v-else-if="item.key==='Frequency'">
                          {{ currentLang==='en' 
                              ? (scope.row[item.enKey]||getFrequencyTrans(scope.row[item.key])) 
                              : getFrequencyTrans(scope.row[item.key]) 
                          }}
                      </span>
                      <span v-else-if="item.key==='Unit'">
                          {{ 
                              currentLang==='en' 
                                  ? (scope.row[item.enKey]||getUnitTrans(scope.row[item.key])) 
                                  : getUnitTrans(scope.row[item.key]) }}</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="$t('Table.column_operations')"
                    key="Copy"
                    align="center"
                    width="110"
                  >
                    <template slot-scope="scope" v-if="scope.row.HaveOperaAuth">
                      <span 
                        v-permission="permissionBtn.chartLibPermission.chartLib_copyData"
                        class="editsty" @click="copyCode(scope.row)"
                      >
                        <i class="el-icon-document-copy" />&nbsp;<!-- 复制数据 -->{{$t('Edb.detail_copydata_btn')}}
                      </span>
                      <span 
                        v-permission="permissionBtn.chartLibPermission.chartLib_viewData"
                        class="editsty"
                        @click="viewTarget(scope.row)"
                      >
                        <!-- 查看数据 -->{{$t('Edb.detail_lookdata_btn')}}
                      </span>
                    </template>
                  </el-table-column>
                  <div slot="empty">
                    <tableNoData :text="$t('Table.no_edb_msg')" size="mini"/>
                  </div>
                </el-table>
              </div>
            </template>

            <noDataAuth v-if="chartInfo.HaveOperaAuth===false" :text="$t('MsgPrompt.no_chart_auth')"/>
          </div>
          <!-- ==============图表列表展示============= -->
          <div class="chart-public-cont" v-else>
            <span>{{$t('Chart.total_chart_show',{limit:public_total})}}</span>
            <div
              class="chart-public-list"
              ref="listChartPage"
              @scroll="loadMorePublicChart"
            >
              <div class="chart-list-item-wrap">
                  <div class="chart-list-item" v-for="chart in chartPublicList" :key="chart.ChartInfoId">
                      <div class="chart-item-top" style="position:relative;">
                          <!-- <div class="chartEn-mark" v-show="chart.IsEnChart">En</div> -->
                          <span class="text_oneLine" :style="{'padding-left':chart.IsEnChart?'24px':''}">{{ currentLang === 'en' ? (chart.ChartNameEn||chart.ChartName) : chart.ChartName }}</span>
                      </div>
                      <div class="chart-item-img" @click="detailShowHandle(chart)"
                      :style="{background: `no-repeat top/cover url('${!chart.HaveOperaAuth ? $icons.lock_big : chart.ChartImage}')`}"></div>
                      <div class="chart-item-bottom">
                          <span><!-- 创建时间 -->{{$t('Chart.list_chart_time')}}: {{ chart.CreateTime.slice(0,10) }}</span>
                      </div>
                  </div>
              </div>
            </div>
            <div v-if="!public_total" class="nodata">
              <tableNoData :text="$t('Common.no_chart_msg')"/>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 目录弹窗 -->
    <chartDialog
      :isOpenDialog="isOpenDialog"
      :title="dialog_title"
      :formData="dialogForm"
      @closeDia="isOpenDialog = false"
      @sucessCallback="sucessCallback"
    />
    <!-- 日期端选择弹窗 -->
    <DateChooseDia
      :isDateDia="isDateDia"
      :dateForm="dateForm"
      :earliestDate="earliestDate"
      @cancel="isDateDia = false"
      @dateBack="dataChangeBack"
    />
    <!-- 加入我的图库弹窗 -->
    <addMyClassifyDia
      :isAddMyDialog="isAddMyChart"
      :add_id="add_chart_id"
      :add_ids="add_ids"
      @cancel="isAddMyChart = false"
      @addSuccess="addMySuccess"
    />

    <!-- 图表另存 -->
    <SaveChartOther 
      :show.sync="isShowSaveOther" 
      fromType="chartsetting"
      :data="chartInfo"
      @ensure="getTreeData"
    />

    <!-- 设置对应版本信息弹窗 -->
		<setLangInfoDia
			:isOpenDialog="isLangInfoDia"
			:formData="formItemArray"
      :chartType="chartInfo.ChartType"
      :datainfo="chartInfo.ChartType===10?JSON.parse(chartInfo.ExtraConfig):null"
      :edblist="chartInfo.ChartType===10?tableData:[]"
			@cancel="isLangInfoDia=false" 
			@updateLang="updateLang"
		/>
    <!-- 上传图表至社区 -->
    <el-dialog
      :title="$t('Chart.upload_to_forum_title')"
      :visible.sync="showUploadToForum"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :center="true"
      v-dialogDrag
      custom-class="dialogclass"
      width="510px"
    >
      <el-form label-position="left" label-width="90px">
        <el-form-item :label="$t('Chart.upload_to_forum_tip')">
          <el-input
            type="textarea"
            :rows="6"
            :placeholder="$t('Chart.upload_to_forum_placeholder')"
            v-model="uploadToForumIntro">
          </el-input>
        </el-form-item>
        
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
          <el-button
            type="primary"
            plain
            size="medium"
            @click="showUploadToForum=false"
          >{{$t('Dialog.cancel_btn')}}</el-button>
          <el-button
            type="primary"
            size="medium"
            @click="handleForumOpt('upload')"
            >{{ $t('Dialog.confirm_btn')}}</el-button>
        </div>
    </el-dialog>


    <!-- 图表收藏弹窗 -->
		<edbCollectDia
			ref="edbCollectRef"
			:show.sync="isOpenEdbCollectDia"
			:edbId="collectEdbForm.edbId"
			:add_ids="collectEdbForm.collectClassifyIdList"
			@success="arr=>{chartInfo.CollectClassifyIdList = arr}"
		/>

    <!-- 添加收藏分类弹窗 -->
		<addCollectClassifyDia
			:show.sync="isOpenCollectClassifyDia"
			:form="collectClassifyForm"
			@confirm="getTreeData();isOpenEdbCollectDia&&$refs.edbCollectRef.getClassify()"
		/>

		<!-- 设置公开共享列表弹窗 -->
		<setSharedListDialog
			:show.sync="isOpenSetSharedDia"
			:type="sharedType"
      source="chart"
			@change="getTreeData"
		/>
  </div>
</template>

<script>
import { dataBaseInterface, mychartInterface } from '@/api/api.js';
import {
  copyOtherOptions
} from '@/utils/defaultOptions';
import { chartSetMixin } from './mixins/chartPublic';
import { edbCollectInterface } from '@/api/modules/chartApi';
import mPage from '@/components/mPage';
import Chart from './components/chart';
import chartDialog from './components/chartDialog';
import DateChooseDia from './components/DateChooseDia';
import addMyClassifyDia from './components/addMyClassifyDia';
import SaveChartOther from './components/SaveChartOther';
import changeLang from "./components/changeLang.vue"
import setEnNameDia from "./components/setEnNameDia.vue"
import setLangInfoDia from './components/setLangInfo.vue'
import collectEdbMenu from './databaseComponents/collectEdbMenu.vue';
import edbCollectDia from './databaseComponents/edbCollectDia.vue';
import addCollectClassifyDia from './databaseComponents/addCollectClassifyDia.vue';
import sharedMenu from './sharedComponents/sharedMenu.vue';
import setSharedListDialog from './sharedComponents/setSharedListDialog.vue';
export default {
  name: '',
  components: {
    mPage,
    chartDialog,
    Chart,
    DateChooseDia,
    addMyClassifyDia,
    SaveChartOther,
    changeLang,
    setEnNameDia,
    setLangInfoDia,
    collectEdbMenu,
    sharedMenu,
    setSharedListDialog,
    edbCollectDia,
    addCollectClassifyDia
  },
  directives: {
    drag(el, bindings) {
      el.onmousedown = function (e) {
        var init = e.clientX;
        // console.log(init);
        var box = $('#box')[0];
        // console.log(box.clientWidth)
        let total_wid = box.offsetWidth;
        var left = $('#left')[0];
        var right = $('#right')[0];
        var initWidth = left.offsetWidth;
        document.onmousemove = function (e) {
          var end = e.clientX;
          var newWidth = end - init + initWidth;
          left.style.width = newWidth + 'px';
          right.style.width = newWidth > 350 ? total_wid - newWidth + 'px' : total_wid - 350 + 'px';
        };
        document.onmouseup = function () {
          document.onmousemove = document.onmouseup = null;
          e.releaseCapture && e.releaseCapture();
        };
        e.setCapture && e.setCapture();
        return false;
      };
    },
  },
  mixins: [chartSetMixin],
  data() {
    return {
      showData: false,
      treeData: [], //树数据
      defaultShowNodes: [], //展开节点
      defaultProp: {
        label: 'ChartClassifyName',
        children: 'Children',
        isLeaf:'isLeaf'
      }, //树结构配置项
      loading: null,
      selected_chartid: '', //当前选中的图表id
      selected_chartClassify: '', //当前选中的图表所属分类
      new_label: '', //新的节点label值
      select_node: '', //当前选中的节点
      /* 右侧 */
      chartInfo: {}, //图表信息
      search_txt: '', //搜索词
      searchOptions: [], //搜索到的图表列表
      
      expandKey: [], //展开数组
      /* 新增编辑目录弹窗 */
      isOpenDialog: false,
      dialog_title: '',
      dialogForm: {
        level: '',
      },
      dynamicWidth: '',

      /* 季节性图 */
      season_year: '', //显示的年份
      selected_chartType: '', //选择的图表类型 获取图表信息时用
      calendar_type: '公历',
      isSlideLeft: false,
      dynamicNode: null, //当前选中的node对象 用于拖动宽度时动态改变label宽度
      /* 公共图库列表展示 */
      publicHaveMove: true, // 是否还有下一页
      default_classify: '',
      public_page_no: 1,
      public_page_size: 12,
      public_total: 0,
      chartPublicList: [],
      isAddMyChart: false, //加入图库弹窗
      add_chart_id: 0, //要加入的图表

      /* 左侧更改目录和坐标轴切换 */
      leftShowLabel: '目录',

      add_ids:[],//加入时已有的分类
      // 只看我的？
      isOnlyMe:false,

      search_page: 1,
			search_have_more: false,
			current_search:'',

      /* 查看历史弹窗 */
			isLookHistory: false,
			lookEdbId: 0,
      labelList:[],//标签列表

      CanOpClassify: false,//添加分类按钮控制

      showUploadToForum:false,//显示上传至社区弹窗
      uploadToForumIntro:'',//上传至社区简述


      /* 目录分类 */
			classifyTabs: [
				{ label: '我的图表',key: 'own' },
				{ label: '共享图表',key: 'shared' },
				{ label: '公共图表',key: 'public' },
			],
			classifyShowType:'own',
			
			collectClassifys:[],//收藏目录
			//指标收藏弹窗
			isOpenEdbCollectDia: false,
			collectEdbForm: {},
			//收藏分类弹窗
			isOpenCollectClassifyDia: false,
			collectClassifyForm: {},

			/* 设置共享弹窗 */
			isOpenSetSharedDia: false,
			sharedType:'',//shared/public
    };
  },
  watch: {
    /* 设置动态右侧区域宽度 */
    isSlideLeft(newval) {
      if (!newval) {
        this.$nextTick(() => {
          this.reloadRightWid();
        });
      }
    },
    // 公用图库关联分类
    default_classify(newval) {
      //重置滚动高度 防止触底加载
      if(this.$refs.listChartPage) this.$refs.listChartPage.scrollTop = 0;
      if (newval) {
        this.public_page_no = 1;
        this.getPublicChartList();
      }
    },
    selected_chartid(newval) {
      if (!newval) {

        this.year_select = this.yearSelector[0].value;
        this.calendar_type = '公历';
        this.season_year = '';
        this.tableData = [];
        this.chartInfo = {};
      } else {
        sessionStorage.removeItem('beforeOptions');
        
        newval && this.getChartDetail();
        this.formItemArray=[]
      }
    },
    /* 选中搜索图表 展开目录 选中图表 展示图表 */
    search_txt(newval) {
      if (newval) {
        let [search_obj] = this.searchOptions.filter(
          (item) => item.ChartInfoId === newval
        );
        this.select_node = search_obj.UniqueCode;
      
        this.selected_chartClassify = search_obj.ChartClassifyId; //图表所属分类
        this.year_select = search_obj.DateType; //年份选择
        this.calendar_type = search_obj.Calendar || '公历'; //公历/农历
        this.season_year = [
          search_obj.SeasonStartDate,
          search_obj.SeasonEndDate,
        ]; //季节年份区间
        this.select_date = [search_obj.StartDate, search_obj.EndDate];
        this.selected_chartType = search_obj.ChartType; //图表类型
        this.selected_chartid = newval;
      }
    },

		tableData: {
      handler(newval, oldval) {
        newval.length && !this.chartInfo.WarnMsg && this.setChartOptionHandle(newval);
      },
      deep: true,
    },
  },
  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;
    },
    //登录角色姓名
    roleName() {
      let name = localStorage.getItem('userName') || '';
      return name;
    },
    //禁用条件
    isDisabled() {
      if (
        this.selected_chartid &&
        this.role !== 'admin' &&
        this.chartInfo.SysUserId !== this.roleId
      ) {
        return true;
      } else {
        return false;
      }
    },
    /* 分享地址 */
    linkUrl() {
      const LINK_CHART_URL = this.$setting.dynamicOutLinks.ChartViewUrl+'/chartshow';
      return `${LINK_CHART_URL}?code=${this.chartInfo.UniqueCode}&fromType=share&lang=${this.currentLang}`
    },

    leftTabs() {
      return [
        {label: this.$t('EtaChartPage.tab_classify'),val:'目录'},
        {label: this.$t('EtaChartPage.tab_series'),val:'坐标轴'}
      ]
    }
  },
  methods: {
    getTreeData(params) {
      dataBaseInterface.chartClassify({IsShowMe:this.isOnlyMe}).then((res) => {
        if (res.Ret === 200) {
          this.showData = true;

          const arr=res.Data.AllNodes || [];
          this.treeData = arr.map(item=>{
						return {
							...item,
							isLeaf:item.Children.length?false:true,
						}
					})

          this.CanOpClassify = res.Data.CanOpClassify;

          this.$nextTick(() => {
            /* 新增完成后 处理树展开和选中图表 */
            params && this.selectCurrentNode(params);
          });
        }
      });
    },
    /* 节点变化时 */
    nodeChange(data, node) {
      this.search_txt = '';
      this.dynamicNode = node;
      sessionStorage.removeItem('beforeOptions');
      //详情时判断是否是本人添加图表 若不是不用做保存校验 新增时要进入保存校验逻辑
      if (
        this.selected_chartid &&
        this.chartInfo.HaveOperaAuth &&
        (this.role==='admin' || this.chartInfo.SysUserId===this.roleId || !this.chartInfo.SysUserId)
      ) {
        let arr = sessionStorage.getItem('defaultArr');
        if (arr && arr !== JSON.stringify(this.tableData)) {
          this.$confirm('您还未保存此图表，是否确认保存？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            showClose: false,
            closeOnClickModal: false,
          })
            .then(() => {
              this.saveChartHandle('');
            })
            .catch(() => {
              this.select_node = data.UniqueCode;
              this.selected_chartid = data.ChartInfoId;
              this.selected_chartType = data.ChartType;
              this.selected_chartClassify = data.ChartInfoId
                ? data.ChartClassifyId
                : '';
              this.calendar_type = data.ChartInfoId ? data.Calendar : '公历'; //公历/农历
              this.season_year = data.ChartInfoId
                ? [data.SeasonStartDate, data.SeasonEndDate]
                : ''; //季节年份区间
              this.year_select = data.ChartInfoId ? data.DateType : this.yearSelector[0].value; //图表年份选择
              this.select_date =
                this.year_select === 5 || this.year_select === 6
                  ? [data.StartDate, data.EndDate]
                  : '';
              this.tableData =
                !this.selected_chartClassify && this.tableData.length
                  ? []
                  : this.tableData;
            });
          return;
        }
      }
      this.select_node = data.UniqueCode;
      this.selected_chartid = data.ChartInfoId;
      this.selected_chartType = data.ChartType;
      this.selected_chartClassify = data.ChartInfoId
        ? data.ChartClassifyId
        : '';
      this.calendar_type = data.ChartInfoId ? data.Calendar : '公历'; //公历/农历
      this.season_year = data.ChartInfoId
        ? [data.SeasonStartDate, data.SeasonEndDate]
        : ''; //季节年份区间
      this.year_select = data.ChartInfoId ? data.DateType : this.yearSelector[0].value; //图表年份选择
      this.select_date =
        this.year_select === 5 || this.year_select === 6
          ? [data.StartDate, data.EndDate]
          : '';
      this.tableData =
        !this.selected_chartClassify && this.tableData.length
          ? []
          : this.tableData;

      //公用图库关联分类
      this.default_classify = !data.ChartInfoId ? data.ChartClassifyId : '';
    },
   
    // 只看我的 复选框改变事件
    onlyMeHandler(){
      this.getTreeData();
      this.getPublicChartList()
    },
    /* 添加一级目录 */
    addLevelOneHandle() {
      this.dialog_title = '添加';
      this.dialogForm = {
        level_1: '',
        parent_id: '',
        level: 0,
      };
      this.isOpenDialog = true;
    },
    /* 添加节点 */
    addNode(node, data) {
      this.dialog_title = '添加';
      /* 添加目录 */
      this.dialogForm = {
        level_1:
          node.level === 1
            ? (this.currentLang==='en'?data.ChartClassifyNameEn:data.ChartClassifyName)
            : node.level === 2
            ? (this.currentLang==='en'?node.parent.data.ChartClassifyNameEn:node.parent.data.ChartClassifyName)
            : (this.currentLang==='en'?node.parent.parent.data.ChartClassifyNameEn:node.parent.parent.data.ChartClassifyName),
        level_2:
          node.level === 1
            ? ''
            : node.level === 2
            ? (this.currentLang==='en'?data.ChartClassifyNameEn:data.ChartClassifyName)
            : (this.currentLang==='en'?node.parent.data.ChartClassifyNameEn:node.parent.data.ChartClassifyName),
        // level_3: node.level === 3 ? data.ChartClassifyName : '',
        parent_id: data.ChartClassifyId,
        level: node.level,
      };
      this.isOpenDialog = true;
      //存储当前要新增子级的目录code
      sessionStorage.setItem('expandCode', data.UniqueCode);
    },
    /* 编辑节点 */
    editNode(node, data) {

      this.dialog_title = '编辑';
      /* 编辑目录 */
      this.dialogForm = {
        level_1:
          node.level === 1
            ? (this.currentLang==='en'?data.ChartClassifyNameEn:data.ChartClassifyName)
            : node.level === 2
            ? (this.currentLang==='en'?node.parent.data.ChartClassifyNameEn:node.parent.data.ChartClassifyName)
            : (this.currentLang==='en'?node.parent.parent.data.ChartClassifyNameEn:node.parent.parent.data.ChartClassifyName),
        level_2:
          node.level === 1
            ? ''
            : node.level === 2
            ? (this.currentLang==='en'?data.ChartClassifyNameEn:data.ChartClassifyName)
            : (this.currentLang==='en'?node.parent.data.ChartClassifyNameEn:node.parent.data.ChartClassifyName),
        level_3: node.level === 3 ? data.ChartClassifyName : '',
        classify_id: data.ChartClassifyId,
        level: node.level,
      };
      this.isOpenDialog = true;
    },
    /* 删除节点校验 */
    removeNode(node, data) {
      dataBaseInterface
        .delChartCheck({
          ChartClassifyId: data.ChartClassifyId,
          ChartInfoId: data.ChartInfoId,
        })
        .then((res) => {
          if (res.Ret === 200) {
            /**
             * 0 可删除
             * 1 关联图表一
             * 2 有子目录无图表
             */
            const deleteLabelMap = {
              1: /* '该分类下关联图表不可删除' */this.$t('Chart.OptMsg.classify_del_fail'),
              2: /* '确认删除当前分类及包含的子分类吗？' */this.$t('Chart.OptMsg.classify_delall_confirm'),
              4: res.Data.TipsMsg
            }

            if([1,4].includes(res.Data.DeleteStatus)) this.$confirm(
                deleteLabelMap[res.Data.DeleteStatus],
                /* '删除失败' */this.$t('Chart.OptMsg.del_fail_tag'),
                {
                confirmButtonText: /* '知道了' */this.$t('Dialog.known'),
                showCancelButton:false,
                type: 'error'
              })
            else if([0,2].includes(res.Data.DeleteStatus)) this.$confirm(
                res.Data.DeleteStatus === 2 
                ? deleteLabelMap[res.Data.DeleteStatus]
                : data.ChartInfoId?this.$t('Chart.OptMsg.chart_del_confirm'):this.$t('Chart.OptMsg.classify_del_confirm'), 
                this.$t('Dialog.warn_tit'),
                {
                confirmButtonText: /* '确定' */this.$t('Dialog.confirm_btn'),
                cancelButtonText: /* '取消' */this.$t('Dialog.cancel_btn'),
                type: 'warning'
              }).then(() => {
                res.Data.DeleteStatus === 0 && data.ChartInfoId 
                ? this.delHandle(data.ChartClassifyId, data.ChartInfoId, 1)
                : this.delHandle(data.ChartClassifyId, data.ChartInfoId);
              }).catch(() => {         
              });
          }
        });
    },
    /* 删除方法 */
    delHandle(ChartClassifyId, ChartInfoId, type) {
      dataBaseInterface
        .delChartClassify({
          ChartClassifyId,
          ChartInfoId,
        })
        .then((res) => {
          if (res.Ret === 200) {
            this.$message.success(res.Msg);
            if (!res.Data.ChartInfoId) this.selected_chartid = '';
            if(type && res.Data.ChartInfoId){
                this.getTreeData({
                  code: res.Data.UniqueCode,
                  id: res.Data.ChartInfoId,
                  type: res.Data.ChartType,
                })
            }else{
                this.getTreeData();
            }
            //如果router.query里的图表被删除,则清掉参数
            if(Number(this.$route.query.id)===ChartInfoId){
                this.$router.replace({path: '/chartsetting'})
            }
          }
        });
    },
    /* 新增/编辑分类成功 */
    sucessCallback(type) {
      this.isOpenDialog = false;
      this.getTreeData();

      if (type === 'add') {
        //新增分类完成之后，展开父节点显示刚新增的分类，若已展开节点则不做处理
        let code = sessionStorage.getItem('expandCode');
        let flag = this.defaultShowNodes.some((item) => {
          return item === code;
        });
        // console.log(flag)
        !flag && code && this.defaultShowNodes.push(code);
        sessionStorage.removeItem('expandCode');
      }
    },
    /* 判断节点是否能被拖拽 */
    canDragHandle(node) {
      let canMove = false;
      if (node.data.Button.MoveButton) {
        canMove = true;
      }
      return canMove;
    },

    /* 判断节点是否能被拖入 4*/
    canDropHandle(draggingNode, dropNode, type) {
      let canDrop = false;
      // 移动的是一级目录
			if(draggingNode.level===1&&dropNode.level===1&&type!=='inner') {
				canDrop=true
			} 

			// 二级目录
			if(draggingNode.level===2){
				if((dropNode.level===1&&type==='inner')||(dropNode.level===2&&type!=='inner')){
					canDrop=true
				}
			}

			//三级目录
			if(draggingNode.level===3){
				if((dropNode.level===2&&type==='inner')||(dropNode.level===3&&type!=='inner')){
					canDrop=true
				}
			}
			//四级指标层
			if(draggingNode.level===4){
				if((dropNode.level===3&&type==='inner')||(dropNode.level===4&&type!=='inner')){
					canDrop=true
				}
			}

      return canDrop;
    },
    /* 拖拽完成 */
    dropOverHandle(b, a, i, e) {
      // console.log(i, a);
      // 被拖拽节点对应的 Node、结束拖拽时最后进入的节点、被拖拽节点的放置位置
      // 一/二级目录
      if (b.level === 1 || b.level === 2||b.level===3) {
        this.handleMoveCatalogue(b, a, i, e)
      }

      // 指标层
      if (b.level === 4) {
        this.handleMoveChart(b, a, i, e)
      }
    },

    // 移动的为一、二、三级目录
		handleMoveCatalogue(b,a,i,e){
			let list=a.parent.childNodes,targetIndex=0,PrevClassifyId=0,NextClassifyId=0,ParentClassifyId=0;

			list.forEach((item,index)=>{
				if(item.data.ChartClassifyId===b.data.ChartClassifyId){
					targetIndex=index
					return
				}
			})

			if(targetIndex===0){
				PrevClassifyId=0
        // i=='inner'时，list里面只有一个Node时会数组越界，后面会对'inner'的重新处理，这里不报错就行
				NextClassifyId=list[targetIndex+1] ? list[targetIndex+1].data.ChartClassifyId : 0
			}else if(targetIndex===list.length-1){
				PrevClassifyId=list[targetIndex-1].data.ChartClassifyId
				NextClassifyId=0
			}else{
				PrevClassifyId=list[targetIndex-1].data.ChartClassifyId
				NextClassifyId=list[targetIndex+1].data.ChartClassifyId
			}

			if(b.level===2){
				if(i==='inner'){
					ParentClassifyId=a.data.ChartClassifyId
					PrevClassifyId=0
					NextClassifyId=a.data.Children.length>1?a.data.Children[1].ChartClassifyId:0
				}else{
					ParentClassifyId=a.data.ParentId
				}
			}
			if(b.level===3){
				if(i==='inner'){
					ParentClassifyId=a.data.ChartClassifyId
					PrevClassifyId=0
					NextClassifyId=a.data.Children.length>1?a.data.Children[1].ChartClassifyId:0
				}else{
					ParentClassifyId=a.data.ParentId
				}
			}

      dataBaseInterface.chartClassifyMove({
        ClassifyId: b.data.ChartClassifyId,
        ParentClassifyId: ParentClassifyId,
        PrevClassifyId: PrevClassifyId,
        NextClassifyId:NextClassifyId
      }).then((res) => {
        if (res.Ret === 200) {
          this.$message.success(this.$t('MsgPrompt.move_success_msg'));
        }
        this.getTreeData();
      });
		},

		// 移动的为指标层 四级
		handleMoveChart(b,a,i,e){
			let PrevChartInfoId=0,NextChartInfoId=0,targetIndex=0, list=a.parent.childNodes.map(_ => _.data)
			if(i==='inner'){
				PrevChartInfoId=0
				NextChartInfoId=a.data.Children.length>1?a.data.Children[1].ChartInfoId:0
			}else{
				list.forEach((item,index)=>{
					if(item.ChartInfoId===b.data.ChartInfoId){
						targetIndex=index
						return
					}
				})

				if(targetIndex===0){
					PrevChartInfoId=0
					NextChartInfoId=list[targetIndex+1].ChartInfoId
				}else if(targetIndex===list.length-1){
					PrevChartInfoId=list[targetIndex-1].ChartInfoId
					NextChartInfoId=0
				}else{
					PrevChartInfoId=list[targetIndex-1].ChartInfoId
					NextChartInfoId=list[targetIndex+1].ChartInfoId
				}
			}	
			
      dataBaseInterface.chartMove({
        ChartClassifyId: a.data.ChartClassifyId,
        ChartInfoId: b.data.ChartInfoId,
        PrevChartInfoId: PrevChartInfoId,
        NextChartInfoId:NextChartInfoId
      }).then((res) => {
        if (res.Ret === 200) {
          this.$message.success(this.$t('MsgPrompt.move_success_msg'));
        }
        this.getTreeData();
      });
		},

    /* 拖拽覆盖添加背景色 */
    dropMouseOver(node1, node2, e) {
      if (
        ((node1.level === 2 && node2.level === 1) ||
          (node1.level === 3 && node2.level === 2)) &&
        (e.target.childNodes[0].className.includes('el-tree-node__content') ||
          e.target.className.includes('el-tree-node__content'))
      ) {
        // console.log(e.target.childNodes[0])
        e.target.childNodes[0].className.includes('el-tree-node__content')
          ? (e.target.childNodes[0].style.backgroundColor = '#409eff')
          : (e.target.style.backgroundColor = '#409eff');
      }
     
    },
    /* 拖拽离开/拖拽完成重置背景色 */
    dropMouseLeave(node1, node2, e) {
      let arrs = $('.el-tree-node__content');
      for (let a of arrs) {
        a.style.backgroundColor = 'transparent';
      }
    },
    // 树节点展开
    handleNodeExpand(data) {
      // 保存当前展开的节点
      let flag = this.defaultShowNodes.some((item) => item === data.UniqueCode);
			if (!flag) { // 不存在则存到数组里
				this.defaultShowNodes.push(data.UniqueCode)
			}
    },
    // 树节点关闭
    handleNodeCollapse(data) {
      this.defaultShowNodes.some((item, index) => {
        if (item === data.UniqueCode) {
          // 删除关闭节点
          this.defaultShowNodes.length = index;
        }
      });
    },

    // 懒加载tree
		handleTreeLoad(node,resolve){
			if(node.level===0){
				resolve(this.treeData)
			}
			if(node.level===1){
				let arr=[]
				this.treeData.forEach(item=>{
					if(item.UniqueCode===node.data.UniqueCode){
						arr=item.Children
					}
				})
				resolve(arr)
			}
			if(node.level===2){
				dataBaseInterface.getChartListForClassify({
          ChartClassifyId:node.data.ChartClassifyId,
          IsShowMe:this.isOnlyMe
        }).then(res=>{
					if(res.Ret===200){
						let arr=res.Data.AllNodes||[]
						arr=arr.map(item=>{
							return {
								...item,
								isLeaf:true
							}
						})
						resolve(arr)
					}else{
						resolve([])
					}
          this.changeTreeNode()
				})
			}
			if(node.level>2){
				resolve([])
			}
		},
		//绑定el-tree的load属性
		getLazyTreeData (node,resolve,maxLevel=3){
			if(node.level===0){
				resolve(this.treeData)
			}
			if(node.level>0&&node.level<=maxLevel){
				//获取对应层级的Child
				resolve(node.data.Children||[])
			}
			if(node.level===maxLevel){
				//调接口获取该分类下图表的数据
				dataBaseInterface.getChartListForClassify({
					ChartClassifyId:node.data.ChartClassifyId,
					IsShowMe:this.isOnlyMe
				}).then(res=>{
					if(res.Ret===200){
						let arr=res.Data.AllNodes||[]
						arr=arr.map(item=>{
							return {
								...item,
								isLeaf:true
							}
						})
						resolve(arr)
					}else{
						resolve([])
					}
					this.changeTreeNode()
				})
			}
			if(node.level>maxLevel){
				resolve([])
			}
		},

    /* 获取图表详情 回显参数 */
    async getChartDetail() {
      const res = await dataBaseInterface.getChartInfoById({
          ChartInfoId: this.selected_chartid
        })
      if(res.Ret===406){
        this.$message.warning(res.Msg)
        return
      }
      if (res.Ret !== 200) return;
      this.chartInfo = res.Data.ChartInfo;
      //如果是季节性图,存储额外参数(同期/右轴)
      if(this.chartInfo.ChartType===2){
        const {MaxMinLimits={},SamePeriodAverage={},SamePeriodStandardDeviation={},RightAxis={}} = res.Data.DataResp||{}
        this.chartInfo.SeasonAverageConfig = {MaxMinLimits,SamePeriodAverage,SamePeriodStandardDeviation}
        this.chartInfo.SeasonRightConfig = RightAxis
      }
      this.tableData = res.Data.EdbInfoList;

      // //将指标添加进标签列表中
      const {ChartNameEn,ChartName,ChartInfoId,UniqueCode,ChartClassifyId}=res.Data.ChartInfo;
      this.defaultShowNodes=this.findParentNodeHandle(this.treeData,ChartClassifyId).reverse();
      this.changeTreeNode()

       //滚动到高亮节点位置
      this.$refs.treeRef.setCurrentKey(this.select_node);
      setTimeout(() => {
        let node = document.getElementById(`node${this.select_node}`);
        let parent = document.getElementsByClassName('tree-cont')[0];

        //parent可视区间：[scrollTop,scrollTop+offsetHeight]
        //node位置:node.offsetTop
        const overTop = node.offsetTop+node.clientHeight+15<parent.scrollTop
        const overBottom = node.offsetTop+node.clientHeight+15>parent.scrollTop+parent.offsetHeight
        console.log(overBottom)
        if(overTop){
            parent.scrollTop = node.offsetTop-30
        }
        if(overBottom){
          parent.scrollTop =  node.offsetTop - parent.offsetHeight/2
        }
      },400)


      if(!this.chartInfo.HaveOperaAuth) return

      //处理下历史默认来源
			this.setDefaultSourceFrom();
  
      //初始化上下限
      this.setLimitData(this.tableData)
        
      // 设置起始日期和最新日期
      this.setExtremumDate()

      this.setDefaultDateSelect(); //设置默认的日期选中
      this.setDefaultPreviewOption(); //设置默认预览配置项

      sessionStorage.setItem('defaultArr',JSON.stringify(res.Data.EdbInfoList));
      
      // 时序组合图控制是否堆叠
      if(this.chartInfo.ChartType===6){
        this.IsHeap=res.Data.DataResp.IsHeap===1?true:false
      }
      const chartTypeMap = {
        7: this.initBarData, //柱形图
        10: this.initSectionScatterData, //截面散点
        11: this.initRadarData, //雷达图
        14: this.initSectionalCombinationChart
      }
      
      chartTypeMap[this.chartInfo.ChartType] && chartTypeMap[this.chartInfo.ChartType](res.Data);

    },

    getChartInfo(){
      this.getChartDetail()
    },

    /* 设置默认时间选中项 */
    setDefaultDateSelect() {
      this.year_select = this.chartInfo.DateType;
      this.select_date = [this.chartInfo.StartDate, this.chartInfo.EndDate];
      this.count_year = this.chartInfo.StartYear;
      this.calendar_type = this.chartInfo.Calendar; //日历类型
      
      if(this.chartInfo.ChartType==2){
        if(this.year_select==20){
          let latestYear = parseInt(this.tableData[0].LatestDate.substring(0,4))
          this.season_year=[`${latestYear-this.count_year+1}-01-01`,`${latestYear}-12-31`]
        }else if(this.year_select==6){
          this.season_year = [this.chartInfo.SeasonStartDate,this.tableData[0].LatestDate];
        }else{
          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}~至今` */ this.$t('Chart.data_tip_since',{date:this.chartInfo.StartDate})
          : this.chartInfo.DateType === 20
          ?/* `最近${this.chartInfo.StartYear}年` */ this.$t('Chart.date_tip_count',{year:this.chartInfo.StartYear})
          :/* '请选择时间段' */this.$t('Chart.choose_time');

    },
    // 设置默认预览配置项
    setDefaultPreviewOption(){
      if(this.chartInfo.ChartType==2){
        if(this.chartInfo.SeasonExtraConfig){
          this.SeasonExtraConfig = JSON.parse(this.chartInfo.SeasonExtraConfig)
        }else{
          // 返回空就是默认值
          this.SeasonExtraConfig.XStartDate="01-01"
          this.SeasonExtraConfig.XEndDate="12-31",
          this.SeasonExtraConfig.JumpYear=0
        }

        // 从DataList中取 ChartLegend
        this.SeasonExtraConfig.ChartLegend=[]
        const chartDataHandle = this.calendar_type === "农历"?
                            this.tableData[0].DataList.filter((item, index) => index > 0):
                            this.tableData[0].DataList

        chartDataHandle.map(item =>{
          this.SeasonExtraConfig.ChartLegend.push({Name:item.Years,Value:item.ChartLegend})
        })
      }
    },

    /* 获取图表详情信息  type为refresh刷新指标不存储时间 */
    async getPreviewChartInfo(type) {
      let dateArray=this.chartInfo.ChartType==2?this.season_year:this.select_date

      let params = {
        ChartType: this.chartInfo.ChartType,
        DateType: this.year_select,
        StartDate: [5 , 6].includes(this.year_select)
          ? dateArray[0]
          : '',
        EndDate: this.year_select === 5 ? dateArray[1] : '',
        Calendar: this.calendar_type,
        // ETA1.0.5 去除了这两个入参
        // SeasonStartDate: this.season_year ? this.season_year[0] : '',
        // SeasonEndDate: this.season_year ? this.season_year[1] : '',
        SeasonExtraConfig:this.SeasonExtraConfig,
        StartYear:this.count_year || 0,
        ChartEdbInfoList: this.tableData.map(_ => ({
          EdbInfoId: _.EdbInfoId,
          EdbInfoType: _.EdbInfoType,
          LeadValue: _.EdbInfoType ? 0 : Number(_.LeadValue),
          LeadUnit: _.EdbInfoType ? '' : _.LeadUnit,
          IsConvert:Number(_.IsConvert),
          ConvertType:Number(_.ConvertType),
          ConvertValue:Number(_.ConvertValue),
          ConvertUnit:Number(_.IsConvert)?_.ConvertUnit:'',
          ConvertEnUnit:Number(_.IsConvert)?_.ConvertEnUnit:'',
          IsAxis:_.IsAxis
        })),
        MarkersLines:this.chartInfo.MarkersLines||''
      }
      //季节性图 更改SeasonExtraConfig
      //如果是季节性图,带上额外参数(同期/右轴)
      if(this.chartInfo.ChartType===2){
        const {MaxMinLimits={},SamePeriodAverage={},SamePeriodStandardDeviation={}} = this.chartInfo.SeasonAverageConfig||{}
        const {SeasonRightConfig={}} = this.chartInfo
        params.SeasonExtraConfig = {
            ...this.SeasonExtraConfig,
            MaxMinLimits:MaxMinLimits.IsAdd?MaxMinLimits:{},
            SamePeriodAverage:SamePeriodAverage.IsAdd?SamePeriodAverage:{},
            SamePeriodStandardDeviation:SamePeriodStandardDeviation.IsAdd?SamePeriodStandardDeviation:{},
            RightAxis:SeasonRightConfig.IsAdd?SeasonRightConfig:{}
        }
      }
      const res = await dataBaseInterface.getSplinePreviewData(params)

      if(res.Ret !== 200) return
      //标识线回显
      this.chartInfo.MarkersLines = res.Data.ChartInfo.MarkersLines||''
      if(this.chartInfo.ChartType===2){
        //更新对应数据
        const {DataResp} = res.Data
        const {MaxMinLimits,SamePeriodAverage,SamePeriodStandardDeviation,
                RightAxis={
                    IndicatorType:1,
                    EdbInfoList:[]
                }} = DataResp
        this.chartInfo.SeasonAverageConfig = {
            MaxMinLimits,SamePeriodAverage,SamePeriodStandardDeviation
        }
        this.chartInfo.SeasonRightConfig = RightAxis
      }

      const { EdbInfoList } = res.Data;
      
      this.tableData.forEach((item) => {
        //只更新数据和显性字段
        let edbData = EdbInfoList.find(_ => _.EdbInfoId===item.EdbInfoId);
        item.DataList = edbData.DataList;
        
        item.StartDate = edbData.StartDate;
        item.ModifyTime = edbData.ModifyTime;
        item.MoveLatestDate = edbData.MoveLatestDate;
        item.LatestDate = edbData.LatestDate;
        item.LatestValue = edbData.LatestValue;
      });
    },

    /* 搜索 */
		searchHandle(query) {
			this.search_page = 1;
			this.current_search = query;
			this.searchApi(this.current_search)
		},

		searchApi(query,page=1) {
      /* 查找列表 */
      dataBaseInterface
        .chartSearchByEs({
          Keyword: query,
          IsShowMe:this.isOnlyMe,
          CurrentIndex: page
        })
        .then((res) => {
          if (res.Ret !== 200) return
          const { List,Paging } = res.Data;
          this.search_have_more = page < Paging.Pages;
          this.searchOptions = page === 1 ? List : [...this.searchOptions,...List];
        });
		},

		/* 聚焦获取当前检索 */
		inputFocusHandle(e) {
			this.search_page = 1;
			this.current_search = e.target.value;
      if(this.current_search) {
        this.searchApi(this.current_search)
      }else {
        this.searchOptions = [];
      }
		},

		searchLoad() {
			if(!this.search_have_more) return;
			this.searchApi(this.current_search,++this.search_page);
		},

    /* 保存当前图表配置 */
    saveChartHandle: _.debounce(function () {
      if (!this.chartInfo.ChartInfoId)  return

        //遍历每条线的指标配置
        let arr = this.tableData.map((item) => {
          return {
            ChartColor: item.ChartColor,
            PredictChartColor: item.PredictChartColor,
            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 = {
          ChartClassifyId: this.chartInfo.ChartClassifyId,
          ChartInfoId: this.chartInfo.ChartInfoId || 0,
          ChartEdbInfoList: arr,
        }

        let typeChartParam = {};
        switch(this.chartInfo.ChartType) {
          case 1:
          case 3:
          case 4:
          case 5:
          case 6:
            typeChartParam = {
              ...public_param,
              DateType: this.year_select,
              StartYear:this.count_year || 0,
              StartDate: [5,6].includes(this.year_select) ? this.select_date[0] : '',
              EndDate: this.year_select === 5 ? this.select_date[1] : '',
            }
            break
          case 2:
            typeChartParam = {
              ...public_param,
              DateType: this.year_select,
              StartYear:this.count_year || 0,
              Calendar: this.calendar_type,
              StartDate: this.season_year ? this.season_year[0] : '',
              EndDate: this.season_year ? this.season_year[1] : '',
            }
            break
          case 7:
          case 11:
            typeChartParam = {
               ...public_param,
              DateType: 6,
              LeftMin: String(this.chartLimit.min),
              LeftMax: String(this.chartLimit.max),
            }
            break
          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),
              })
            }
          case 14:
            typeChartParam = {
              ...public_param,
            }
            break
        }

        let params = typeChartParam;
        if(![7,10,11].includes(this.chartInfo.ChartType)){
            const {
                min,max,rightMin,rightMax,rightTwoMin,rightTwoMax
            } = this.chartLimit
            params = {
                ...params,
                LeftMin:min+'',
                LeftMax:max+'',
                RightMin:rightMin+'',
                RightMax:rightMax+'',
                Right2Min:rightTwoMin+'',
                Right2Max:rightTwoMax+'',
                //手动保存视为更改过上下限
                MinMaxSave:1
            }
        }
        dataBaseInterface.chartSave(params).then((res) => {
          if (res.Ret === 200) {
            // this.$message.success('保存成功');
            this.$message.success(this.$t('MsgPrompt.saved_msg'));
            sessionStorage.removeItem('beforeOptions');
            sessionStorage.setItem(
              'defaultArr',
              JSON.stringify(this.tableData)
            );
            this.getTreeData();
            //关联图表和图片
            this.setChartImage();
          }
        });
    }, 500),
    // 英文面板时候的判断
    copyChartConfirm(type){
        if(this.currentLang=='en'){
          // 是否所有数据都填写完
          let flag=true
          // 是否有英文表格名称
          if(!this.chartInfo.ChartNameEn) flag = false
          if(flag){
            for (const data of this.tableData) {
              // 单位中文名为空时 英文名不做判断
              if(data.EdbNameEn=="" || (data.UnitEn=="" && data.Unit!="")){
                flag = false
                break
              }
            }
          }
          if(!flag){
            this.$confirm(/* '英文名称未输入完整，分享图表上可能出现空名称的情况，确定继续分享吗？' */this.$t('Chart.OptMsg.copy_noenough_en'), /* '提示' */this.$t('Dialog.warn_tit'), {
                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('复制链接成功')
                this.$message.success(this.$t('Chart.OptMsg.copy_link_success'))
              }else{
                this.copyChartHandle(type)
              }
            })
            .catch(() => {});
          }else{
            if(type=='url'){
              this.shareUrl()
            }else{
              this.copyChartHandle(type)
            }
          }
        }else{
          if(type=='url'){
            this.shareUrl()
          }else{
            this.copyChartHandle(type)
          }
        }
    },
    /* 点击复制先用canvas画出 转成图片在放到粘贴板中 */
    copyChartHandle:_.debounce(function(type){{
      let chartsName = this.currentLang==='zh'?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 svg = this.$refs.chartRef.chart.getSVG({
        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]
          }
      });
      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();
      }
    },
    /* 点击删除图表 */
    delChartHandle() {
      this.$confirm(/* '删除后该图表将不能再引用，确认删除吗？' */this.$t('Chart.OptMsg.chart_del_confirm'), this.$t('Dialog.warn_tit'), {
        confirmButtonText: /* '确定' */this.$t('Dialog.confirm_btn'),
        cancelButtonText: /* '取消' */this.$t('Dialog.cancel_btn'),
        type: 'warning',
      })
        .then(() => {
          this.delHandle(
            this.selected_chartClassify || 0,
            this.selected_chartid,
            1
          );
        })
        .catch(() => {});
    },

    /* 年份改变 重新刷新图表接口  保存当前的图表配置和上下限 只改变图表 */
    changeYear(item) {
      this.year_select = item.value;
      this.select_date = '';
      this.dateTip = /* '请选择时间段' */this.$t('Chart.choose_time');
      // 图表已存在
      this.selected_chartid && this.getPreviewChartInfo();
    },
    /* 打开时间段弹窗 */
    openDateDia() {
      // 自定义时间段回显
			let selectDateStart = this.chartInfo.ChartType === 2?this.season_year[0]:this.select_date[0]
			let selectDateEnd = this.chartInfo.ChartType === 2?this.season_year[1]:this.select_date[1]

      this.dateForm = {
        date_type: this.year_select,
        start_date:
          this.year_select === 5 || this.year_select === 6
            ? selectDateStart
            : '',
        end_date: this.year_select === 5 ? selectDateEnd : '',
        count_year: this.year_select === 20 ? this.count_year : ''
      };
      this.isDateDia = true;
    },
    /* 保存完自定义日期 刷新数据  保存当前的图表配置和上下限 只改变图表*/
    dataChangeBack(data) {
      // console.log(data,'timeData');
      this.year_select = data.dateType;
      this.isDateDia = false;
      this.select_date = [data.start_date, data.end_date];
      this.count_year = data.count_year

      let dateStart = data.start_date
			let dateEnd = data.end_date
			let latestYear = parseInt(this.latestDate.substring(0,4))
			if(data.dateType==20){
				dateStart = `${latestYear-data.count_year+1}-01-01`
				dateEnd = `${latestYear}-12-31`
			}

      if(this.chartInfo.ChartType === 2){
        // 季节性图
				if(data.dateType==6){
					dateEnd = this.$moment(new Date()).format("YYYY-MM-DD")
				}
				this.season_year = [dateStart, dateEnd];
				// 因为原本季节性图不支持 DateType为5和6的 所以季节性也将StartDate和EndDate传过去
				this.select_date = [dateStart, dateEnd];
      }else{
				this.select_date = [dateStart, dateEnd];

        if(data.dateType==20){
          this.dateTip = /* `最近${data.count_year}年` */ this.$t('Chart.date_tip_count',{year:data.count_year})
        }else if (data.dateType === 5) {
          this.dateTip = `${data.start_date}~${data.end_date}`;
        } else {
          this.dateTip = /* `${data.start_date}~至今`; */ this.$t('Chart.data_tip_since',{date:data.start_date})
        }
      }
      this.getPreviewChartInfo();
    },

    /* 编辑图表 跳转 */
    editChartHandle() {
      this.$router.push({
        path: '/editchart',
        query: {
          code: this.chartInfo.UniqueCode
        }
      })
    },
    
    /* 根据unicode展开树结构并选中当前图表 重置图表配置 日期区间 */
    // 如果有chartData则说明是从图列表点击来的，如果没有 则说明是路由中带的参数此时要获取一下详情
    async selectCurrentNode({ code, id, type,chartData }) {
      let deep_arr = _.cloneDeep(this.treeData);
      // 查找选中的节点信息
      let select_obj = chartData?chartData:await this.findNode(deep_arr, id);
      // 查找图表的分类父级id
      this.select_node = code;
      
      // 重置筛选状态
      this.selected_chartClassify = select_obj.ChartClassifyId; //图表所属分类
      this.year_select = select_obj.DateType; //年份选择
      this.calendar_type = select_obj.Calendar || '公历'; //公历/农历
      this.season_year = [select_obj.SeasonStartDate, select_obj.SeasonEndDate]; //季节年份区间
      this.select_date = [select_obj.StartDate, select_obj.EndDate]; //曲线日期选择
      this.selected_chartType = select_obj.ChartType;
      this.selected_chartid = id;
    },
    
    /* 根据图表id 查找对象 */
    findNode(arr, id) {
      // 由于目录第三级图表改为懒加载 故从新增图跳转回来情况只能获取一下图详情了 不能直接去分类数据里面查了
      return new Promise((resolve,reject)=>{
        dataBaseInterface.chartInfo({
          ChartInfoId: id,
        }).then(res=>{
          if(res.Ret==200){
            resolve(res.Data.ChartInfo)
          }
        })
      })
     
    },
    /* 点击表格行展开配置项 */
    rowClickHandle(row) {
      this.expandKey =
        this.expandKey.length && this.expandKey[0] === row.EdbCode
          ? []
          : [row.EdbCode];
    },
    
    /* 设置row-key */
    getRowKey(row) {
      return row.EdbCode;
    },
    /* 控制展开一行收起其他行并高亮 */
    expandChangeHandle(row, expandedRows) {
      this.expandKey =
        this.expandKey.length && this.expandKey[0] === row.EdbCode
          ? []
          : [row.EdbCode];
      this.$refs.tableRef.setCurrentRow(row);
    },
    // 查找树节点所有父节点
    findParentNodeHandle(arr, id) {
      // 遍历取父级code push数组
      for (let i of arr) {
        if (i.ChartClassifyId === id) {
          return [i.UniqueCode];
        }
        if (i.Children) {
          let node = this.findParentNodeHandle(i.Children, id);
          if (node) {
            return node.concat(i.UniqueCode);
          }
        }
      }
    },
    // 通过分类id找到指标所属的分类
    findParentNodeForClassifyId(id,code){
      let arr=[]
			this.treeData.forEach(item=>{
				if(item.Children){
					item.Children.forEach(_item=>{
						if(_item.ChartClassifyId==id){
							arr=[item.UniqueCode,_item.UniqueCode]
						}
					})
				}
			})
			return [...arr]
    },

    /* 向左收起 展开 */
    slideHandle() {
      this.isSlideLeft = !this.isSlideLeft;
    },

    /* 季节图切换年份  保持当前配置 */
    seasonYearChange() {
      this.getPreviewChartInfo();
    },
    /* 一键刷新 超长等待..*/
    refreshHandle() {
      this.refreshLoading = this.$loading({
        lock: true,
        target: '.main-right',
        text: /* '刷新图表中...' */this.$t('Chart.OptMsg.refresh_ing_msg'),
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.8)',
      });
      dataBaseInterface
        .chartRefresh({
          ChartInfoId: this.selected_chartid,
        })
        .then((res) => {
          this.refreshLoading.close();
          if (res.Ret === 200) {
            [7,10,11,14].includes(this.chartInfo.ChartType) ? this.getChartDetail() : this.getPreviewChartInfo();
            // this.$message.success('刷新成功');
            this.$message.success(this.$t('MsgPrompt.refresh_success_msg'));
          }
        });
    },
    /* 重绘右侧区域宽度 */
    reloadRightWid() {
      let total_wid = $('#box')[0].offsetWidth;
      let left = $('#left')[0].offsetWidth;
      let rigtWid = total_wid - left - 20 + 'px';
      $('#right')[0].style.width = rigtWid;
    },

    /* 转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) {

      form.append('ChartInfoId',this.selected_chartid)
      await dataBaseInterface.setChartThumbnail(form)
    },

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

    /* ----------------公用图库part-------------------- */
    getPublicChartList() {
      mychartInterface
        .publicList({
          PageSize: this.public_page_size,
          CurrentIndex: this.public_page_no,
          ChartClassifyId: this.default_classify || 0,
          IsShowMe:this.isOnlyMe
        })
        .then((res) => {
          if (res.Ret !== 200) return;
          this.publicHaveMove = res.Data
            ? this.public_page_no < res.Data.Paging.Pages
            : false;
          this.chartPublicList = res.Data
            ? this.public_page_no === 1
              ? res.Data.List
              : [...this.chartPublicList, ...res.Data.List]
            : [];
          this.public_total = res.Data ? res.Data.Paging.Totals : 0;
        });
    },

    /* 加载更多 */
    loadMorePublicChart:_.throttle(function(e) {
      let scrollTop = this.$refs.listChartPage.scrollTop;
      let clientHeight = this.$refs.listChartPage.clientHeight;
      let scrollHeight = this.$refs.listChartPage.scrollHeight;
      console.log('scrollTop:',scrollTop)
      console.log('clientHeight:',clientHeight)
      console.log('scrollHeight:',scrollHeight)
			if(scrollTop + clientHeight >= scrollHeight-10 && this.publicHaveMove){
				this.public_page_no++;
				this.getPublicChartList();
			}
    },300),

    /* 点击图表区域跳转详情 选中左侧图表菜单 */
    detailShowHandle(item) {
      this.$nextTick(() => {
        let params = {
          code: item.UniqueCode,
          id: item.ChartInfoId,
          type: item.ChartType,
          chartData:item
        };
        this.selectCurrentNode(params);
        this.default_classify = '';
        this.reloadRightWid();
      })
    },

    /* 加入我的图库成功 */
    addMySuccess(params) {
      this.isAddMyChart = false;

      /* 判断是详情还是图库列表 */
      if (this.selected_chartid) {
        this.chartInfo.IsAdd = true;
        this.chartInfo.MyChartId = params.MyChartInfoId;
        this.chartInfo.MyChartClassifyId = params.MyChartClassifyId;
      } else {
        this.chartPublicList.forEach((item) => {
          if (item.ChartInfoId === this.add_chart_id) {
            item.IsAdd = true;
            item.MyChartId = params.MyChartInfoId;
            item.MyChartClassifyId = params.MyChartClassifyId
          }
        });
      }
    },

    changeTreeNode(){
        this.$refs.treeRef.setCurrentKey(this.select_node);
    },

    // 图表到社区的操作
    async handleForumOpt(type){
      if(type==='upload'){
        const res=await dataBaseInterface.chartUploadToForum({
          ChartInfoId:this.chartInfo.ChartInfoId,
          Description:this.uploadToForumIntro
        })
        if(res.Ret===200){
          this.$message.success(this.$t('MsgPrompt.upload_success_msg'))
          this.showUploadToForum=false
          this.getChartDetail()
        }
      }
      if(type==='update'){
        const res=await dataBaseInterface.chartUpdateToForum({
          ChartInfoId:this.chartInfo.ChartInfoId
        })
        if(res.Ret===200){
          this.$message.success(this.$t('MsgPrompt.operate_success_msg'))
          this.getChartDetail()
        }
      }

      if(type==='withdraw'){
        const res=await dataBaseInterface.chartWithdrawFromForum({
          ChartInfoId:this.chartInfo.ChartInfoId
        })
        if(res.Ret===200){
          this.$message.success(this.$t('MsgPrompt.operate_success_msg'))
          this.getChartDetail()
        }
      }
    },


    /* =======2.3目录拆分======== */
		/* 切换分类类型 */
		handleChangeClassifyType() {
			this.defaultShowNodes = [];
			this.public_page_no = 0;
			this.selected_edbid = 0;
			this.default_classify = 0;
			this.search_txt = '';
      this.$refs.listChartPage && (this.$refs.listChartPage.scrollTop = 0);

      this.getPublicChartList();

			
			['own','public'].includes(this.classifyShowType) && this.getTreeData();
			this.classifyShowType==='own' && this.getCollectClassifys();
		},

		//获取收藏指标分类
		async getCollectClassifys() {
			const res = await edbCollectInterface.getEdbCollectClassify({ParentId:0})

			this.collectClassifys = res.Data||[]
		},

		/* 收藏指标 */
		handleCollectEdb(info) {
			this.collectEdbForm = {
				edbId: info.EdbInfoId,
				collectClassifyIdList: info.CollectClassifyIdList||[]
			},
			this.isOpenEdbCollectDia = true
		},

		async handleRemoveCollect(item=null) {
			const res = await edbCollectInterface.edbCollectCancel({
				ClassifyId: this.select_classifyId,
				EdbInfoId: item?item.EdbInfoId:this.selected_edbid
			})

			if(res.Ret !== 200) return 
			this.$message.success('取消收藏成功')
			if(this.selected_edbid) {
				this.chartList = []
				this.selected_edbid = 0
			}
			this.getEdbChartList()
		},

		handleOpenCollectClassify(data=null) {
			this.collectClassifyForm = {
				name: data?data.ClassifyName:'',
				classifyId:data?data.ClassifyId:0
			}
			this.isOpenCollectClassifyDia = true
		},

		/* 收藏指标拖动 */
		async collectDragOver({oldIndex,newIndex}) {
			if(oldIndex===newIndex) return
			let NextEdbInfoId,PrevEdbInfoId;
			if(newIndex===0){
        PrevEdbInfoId=0
        NextEdbInfoId=this.chartList[newIndex+1].EdbInfoId
      }else if(newIndex===this.chartList.length-1){
        PrevEdbInfoId = this.chartList[newIndex-1].EdbInfoId
        NextEdbInfoId = 0
      }else{
        PrevEdbInfoId = this.chartList[newIndex-1].EdbInfoId
        NextEdbInfoId = this.chartList[newIndex+1].EdbInfoId
      }
			
			let params = {
				ClassifyId: this.select_classifyId,
				EdbInfoId: this.chartList[newIndex].EdbInfoId,
				NextEdbInfoId,
				PrevEdbInfoId,
			}

			const res = await edbCollectInterface.moveCollectEdb(params)
			if(res.Ret !== 200) return 
			this.$message.success('移动成功')
		},

		/* 设置指标共享弹窗 */
		handleOpenSetShared(type) {
			this.sharedType = type;
			this.isOpenSetSharedDia = true;
		}

  },

  mounted() {
    this.getCollectClassifys();
    if(this.$route.query.code) {
      this.getTreeData({code: this.$route.query.code,id: Number(this.$route.query.id)})
    } else {
      this.getTreeData();
      this.getPublicChartList();
    }
    window.addEventListener('resize', this.reloadRightWid);
  },
  destroyed() {
    window.removeEventListener('resize', this.reloadRightWid);
  },
};
</script>
<style lang="scss">
@import './css/chartfit.scss';
.chartSetting_container {
  * {box-sizing: border-box;}
  .flip-list-move {
    transition: transform 0.4s;
  }
  .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
    background-color: #409eff !important;
    border-color: #409eff;
  }
  .el-checkbox__input.is-disabled.is-indeterminate .el-checkbox__inner {
    background-color: #409eff !important;
    border-color: #409eff;
  }
  .el-card .el-card__header {
    padding: 14px 20px;
  }

  .main-left {
    .add-chart-cont {
      padding: 15px 20px;
      border: 1px solid #ECECEC;
      display: flex;
      box-shadow: 0px 3px 6px rgba(167, 167, 167, 0.09);
    }
    .left-tab {
      display: flex;
      align-items: center;
      padding: 20px 20px 0;
      .tab {
        cursor: pointer;
        font-size: 16px;
        border-bottom: 2px solid transparent;
        margin-right: 40px;
        padding-bottom: 5px;
        &.act{
          color: #409eff;
          border-color: #409eff;
        }
        &:hover {
          color: #409eff;
        }
      }
    }
  }
  .cont-bottom {
    .error-tip{ color: #D03F28; font-size: 16px;padding: 25px 0 0 25px; }
    .bottom-min {
      border: 1px solid #DCDFE6;
      margin-bottom: 20px;
      .right-actions {
        /* max-width: 160px; */
        min-width: 115px;
        height: 100%;
        padding: 20px 10px;
        border-left: 1px solid #DCDFE6;
        li {
          margin-bottom: 15px;
        }
        @media screen and (max-width: 1710px) {
          font-size: 12px;
        }
        .span-item {
          color: #409eff;
          cursor: pointer;
          &:hover {
            text-decoration: underline;
          }
          .el-icon-collection,
          .el-icon-document-copy {
            color: #409eff;
          }
        }
      }
      .calendar-cont {
        .el-radio-button__inner {
          padding: 8px 16px;
        }
      }
    }
  }

   /* ===================== */
  .chart-public-cont {
    color: #333;
    .el-card .el-card__header,
    .el-card__body {
      padding: 10px;
    }

    .chart-public-list {
      margin-top: 10px;
      display: flex;
      flex-wrap: wrap;
      max-height: calc(100vh - 143px);
      overflow: hidden;
      overflow-y: auto;
      .drag-cont {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
      }
      .dragShdow {
        box-shadow: 0 1px 8px rgba(64, 158, 255, 0.8);
        opacity: 0.5;
      }
      .public-chart-item {
        .item-top {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 16px;
          font-weight: 600;
        }
        .chart-img {
          width: 100%;
          height: 230px;
          object-fit: fill !important;
          cursor: pointer;
        }
        .item-bottom {
          margin-top: 10px;
          display: flex;
          justify-content: space-between;
          font-size: 12px;
          color: #666;
          .collected {
            color: #f00;
            cursor: pointer;
          }
          .join_txt {
            color: #409eff;
            cursor: pointer;
          }
        }
      }
      .chart-list-item{
          width:23%;
          min-width:230px;
          .chart-item-top,.chart-item-bottom{
              display: flex;
              justify-content: space-between;
          }
      }
    }
  }
  .nodata {
    /* height: calc(100vh - 240px); */
    text-align: center;
    font-size: 16px;
    color: #666;
  }
  .copy-excel {
    color: #409eff;
    font-size: 14px;
    padding-left: 50px;
    padding-right: 10px;
  }
  @media screen and (min-width: 1711px) {
    .el-icon-refresh {
      font-size: 17px;
      margin-left: 5px;
      cursor: pointer;
    }
    .chartSetting_top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding: 20px 30px;
      background: #fff;
      border: 1px solid #ececec;
      border-radius: 4px;
      box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
      .el-select__input {
        margin-left: 30px;
      }
    }
    .chartSetting_main {
      .slide-icon {
        padding: 20px 0;
        /* display: block; */
        box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.3);
        border-radius: 5px;
        cursor: pointer;
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        z-index: 99;
        &:hover {
          background-color: rgba(0, 0, 0, 0.05);
        }
        &.slide-left {
          right: 0;
        }
        &.slide-right {
          left: 0;
        }
      }
      .main-left {
        width: 400px;
        min-width: 350px;
        background: #fff;
        margin-right: 20px;
        border: 1px solid #ececec;
        border-radius: 4px;
        box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
        overflow: hidden;
        position: relative;
        box-sizing: border-box;
        .chartSetting_main_top {
          padding: 10px 20px 15px;
          .add-cont {
            cursor: pointer;
            font-size: 15px;
            color: #409eff;
          }
        }
        .tree-cont {
          padding: 0 20px 30px;
          // overflow: auto;
          height: calc(100vh - 320px);
        }
        .target_tree {
          font-size: 14px;
          color: #333;
          .label-input .el-input__inner {
            height: 25px;
            line-height: 25px;
          }
          .custom-tree-node {
            display: flex !important;
            justify-content: space-between;
            align-items: center;
            display: block;
            width: 90%;
            .node_label {
              margin-right: 2px;
            }
          }
          .el-tree__drop-indicator {
            height: 3px;
            background-color: #409eff;
          }
          .el-tree-node__content {
            margin-bottom: 5px !important;
          }
          .el-tree-node__children {
            .el-tree-node {
              /* margin-bottom: 8px !important; */
              margin-bottom: 0px !important;
              padding-left: 18px;
            }
            .el-tree-node__content {
              margin-bottom: 5px !important;
              padding-left: 0 !important;
            }
          }
          .expanded.el-icon-caret-right:before {
            content: url('../../assets/img/set_m/down.png') !important;
          }
          .el-icon-caret-right:before {
            content: url('../../assets/img/set_m/slide.png') !important;
          }
          .el-tree-node__expand-icon.is-leaf.el-icon-caret-right:before {
            content: '' !important;
          }
          .el-tree-node__expand-icon.expanded {
            -webkit-transform: rotate(0deg);
            transform: rotate(0deg);
          }
          .el-tree-node.is-current > .el-tree-node__content {
            background-color: #f0f4ff !important;
          }
          .el-tree-node__content {
            padding-right: 10px !important;
          }
        }
        .move-btn {
          height: 100%;
          width: 4px;
          /* opacity: 0; */
          position: absolute;
          right: 0px;
          top: 0;
          &:hover {
            cursor: col-resize;
            /* background-color: orange */
          }
        }
      }
      .main-right {
        flex:1;
        overflow: hidden;
        .mx-datepicker {
          width: 220px !important;
        }
        /* =================== */
        .chart-min-cont {
          background: #fff;
          border: 1px solid #ececec;
          height: calc(100vh - 114px);
          overflow: auto;
          /* overflow: hidden; */
          border-radius: 4px;
          box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
          .cont-top {
            padding: 12px 30px;
            border-bottom: 1px solid #ececec;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0px 3px 6px rgba(167, 167, 167, 0.09);
            .top-left {
              .year-btn {
                font-size: 14px;
                margin-right: 5px;
                margin-bottom: 5px;
              }
              .btn-sty {
                font-size: 16px;
                padding: 10px;
                border: 1px solid #409eff;
              }
              .date-setting{
                width: 210px;
                height: 40px;
                padding: 12px;
                border: 1px solid #DCDFE6;
                border-radius: 4px;
                cursor: pointer;
                font-size: 14px;
                color: #333333;
              }
            }
            .top-right {
              font-size: 16px;
              .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: 20px 30px;
            /* height: calc(100vh - 250px);
						overflow: auto; */
            .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;
            }
            .el-table__expanded-cell {
              padding: 20px 26px;
            }
            .highcharts-range-selector-group {
              display: none;
              .highcharts-input-group {
                display: none;
              }
            }
            .highcharts-axis-title {
              display: block;
            }
            .calendar-cont {
              display: block;
              margin: 30px auto 0;
              text-align: center;
            }
            .clear-margin {
              margin: 10px auto 0
            }
            /* =================== */
            .chart-show-cont {
              padding: 10px 160px 0 120px;
              position: relative;
              .chart-title {
                font-size: 16px;
                font-weight: normal;
                text-align: center;
                margin-bottom: 10px;
              }
              .chart-author {
                font-size: 14px;
                color: #333;
                position: absolute;
                bottom: -20px;
                right: 50px;
              }
              .chartWrapper {
                position: relative;
                .range-cont {
                  position: absolute;
                  top: 13%;
                  .min-data-input {
                    width: 60px;
                    display: block;
                    margin-top: 320px;
                  }
                  &.left {
                    left: -80px;
                  }
                  &.right {
                    right: -65px;
                  }
                  &.rightTwo {
                    right: -130px;
                  }
                  &.bottom {
                    width: 100%;
                    display: flex;
                    justify-content: space-between;
                    top: auto;
                    right: 0;
                    bottom: -2%;
                    .left {
                      width: 60px;
                      display: block;
                      flex-shrink: 0;
                    }
                  }
                }
              }
            }
            .options-cont {
              display: flex;
              flex-wrap: wrap;
              justify-content: space-between;
            }
          }
        }
      }
      .chartSetting-main{
          display: flex;
      }
      .chartSetting-label-list{
          margin-bottom: 22px;
      }
    }
  }

  .own-tree,.collect-tree {
    display: flex;
    flex-direction: column;
  }
  .own-tree {
    height: 60%;
  }
  .collect-tree {
    height: 40%;
    border-top: 1px solid #C8CDD9;
  }
  .tree-title {
    font-size: 15px;
    margin: 15px 0;
  }
  .tree-wrapper {
    flex: 1;
    overflow: auto;
  }
  .opt-wrapper {
    margin: 15px 0;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    color: #0052D9;
    gap: 10px;
    .opt-item {
      display: flex;
      align-items: center;
      font-size: 16px;
      cursor: pointer;
    }
  }

}
</style>
<style lang="scss">
.edb-item-style .el-input__icon {
	line-height: 27px;
}
</style>
