<template>
    <div>
      <el-dialog v-dialogDrag :modal-append-to-body='false' :title="$t('SandboxManage.SandFlow.add_node_data')" :visible.sync="show" 
    :close-on-click-modal="false" width="1000px" top="5vh" @close="cancelHandle" v-show="!dialogDisplayNone">
      <div class="add-link-box">
        <div class="link-box-option">
          <el-select v-model="addLinkSearchParams.linkType" placeholder="节点数据类型" style="width: 240px;" @change="changeLinkType">
            <el-option :label="item.label" :value="item.value" v-for="item in linkTypeList" :key="item.value"></el-option>
          </el-select>
          <el-select v-if="addLinkSearchParams.linkType==1"
            v-model="search_dataBaseId"
            v-loadMore="dataBaseSearchLoad"
            ref="searchRef"
            :filterable="!search_dataBaseId"
            remote
            clearable
            :placeholder="$t('SandboxManage.SandFlow.add_link_search_placeholder')"
            style="width: 240px"
            :remote-method="dataBaseSearch"
            @click.native="dataBaseInputFocus"
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
            <el-option
              v-for="item in dataBaseOptions"
              :key="item.EdbInfoId"
              :label="currentLang==='en'?(item.EdbNameEn||item.EdbName):item.EdbName"
              :value="item.EdbInfoId"
              :disabled="!item.HaveOperaAuth"
            >
              <div>
                <img 
                  :src="$icons.lock_ico2" 
                  width="18" 
                  height="18" 
                  style="vertical-align:middle" 
                  v-if="!item.HaveOperaAuth"
                />
                {{currentLang==='en'?(item.EdbNameEn||item.EdbName):item.EdbName}}
              </div>
            </el-option>
          </el-select>
          <el-select v-else-if="addLinkSearchParams.linkType==2"
            v-model="search_dataBaseId"
            v-loadMore="dataBaseSearchLoad"
            ref="searchRef"
            :filterable="!search_dataBaseId"
            remote
            clearable
            :placeholder="$t('Chart.Detail.chart_name')"
            style="width: 240px"
            :remote-method="dataBaseSearch"
            @click.native="dataBaseInputFocus"
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
            <el-option
              v-for="item in dataBaseOptions"
              :key="item.ChartInfoId"
              :label="currentLang==='en'?(item.ChartNameEn||item.ChartName):item.ChartName"
              :value="item.ChartInfoId"
              :disabled="!item.HaveOperaAuth"
            >
              <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>
          <el-input v-else v-model="reportKeyWord" @input="searchReport"
          :placeholder="$t('ReportManage.smart_title_creator_btn')" style="width: 240px;" clearable >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </div>
        <div class="link-box-tags">
            <div class="link-box-tag"  
                 v-for="(item,index) in linkListInShow" 
                 :key="item.RId" 
                :class="{'unchoose-tag':item.Id != activeItem.Id,'choosed-tag':item.Id == activeItem.Id}">
              <span @dblclick.stop="editLinkName(item)" 
                    v-if="!item.editing" 
                    @click="linkClick(item)"
                    :style="{color:item.Id == activeItem.Id?'#0052D9':'#666666'}">{{ item.Name }}</span>
              <el-input v-else @blur="editLinkNameFinish(item)" 
                v-model.trim="editingLabel" class="label-edit-input" ref="labelEditInput"/>
              <img src="~@/assets/img/sand_new/delete_outline_1.png" @click="linkDelete(item,index)">
            </div>
        </div>
        <div class="link-box-content">
          <!-- 指标 -->
          <div class="link-content-dataIndex" v-if="addLinkSearchParams.linkType==1 && databaseTableData && databaseTableData.length>0">
            <template v-if="databaseTableData[0].HaveOperaAuth">
              <el-table :data="databaseTableData" border style="box-shadow: rgba(155, 170, 219, 0.2) 0px 3px 6px;">
                <el-table-column :label="$t('Table.edb_id')" align="center">
                  <template slot-scope="scope">{{ scope.row.EdbCode }}</template>
                </el-table-column>
                <el-table-column :label="$t('Table.edb_name')" align="center" width="200">
                  <template slot-scope="scope">{{ currentLang==='en'?(scope.row.EdbNameEn||scope.row.EdbName):scope.row.EdbName }}</template>
                </el-table-column>
                <el-table-column :label="$t('Table.frequency')" align="center" width="50">
                  <template slot-scope="scope">{{ getFrequencyTrans(scope.row.Frequency||'null') }}</template>
                </el-table-column>
                <el-table-column :label="$t('Table.unit')" align="center" width="100">
                  <template slot-scope="scope">{{ currentLang==='en'?(scope.row.UnitEn||getUnitTrans(scope.row.Unit)):getUnitTrans(scope.row.Unit) }}</template>
                </el-table-column>
                <el-table-column :label="$t('Edb.Detail.e_latest_value')" align="center" width="100">
                  <template slot-scope="scope">{{ scope.row.LatestValue }}</template>
                </el-table-column>
                <el-table-column :label="$t('Edb.Detail.e_latest_date')" align="center" width="130">
                  <template slot-scope="scope">{{ scope.row.LatestDate }}</template>
                </el-table-column>
                <el-table-column :label="$t('Table.source')" align="center">
                  <template slot-scope="scope">{{ scope.row.SourceName }}</template>
                </el-table-column>
              </el-table>
              <ul class="link-count-wrap">
                  <li v-for="item in calculateOption" 
                      :key="item.source" 
                      class="link-count-item" 
                      :class="{'link-count-item-un':!handleCountChoose(item),'link-count-item-on':handleCountChoose(item)}"
                      @click="clickCountItem(item)">
                      <span>{{ item.label }}</span>
                      <img v-if="handleCountChoose(item) && item.source != 98 && item.source != 99"  
                        src="~@/assets/img/sand_new/blue_edit_icon.png" 
                        style="width: 13px;height: 13px;margin-left: 8px;" 
                        @click.stop="handleEditCal(item)">
                  </li>
              </ul>
              <div v-if="threeCalculation && threeCalculation.length > 0" class="calculate-result-wrap">
                 <div class="calculate-result-title">{{ $t('ETableChildren.calculate_result') }}</div>
                 <div class="calculate-result-table">
                     <div v-for="(item,index) in threeCalculation" :key="index" class="calculate-result-table-tr">
                          <div v-for="(v) in item" :key="v.source" class="calculate-result-table-item">{{ v.label }}：{{ v.value }}</div>
                     </div>
                 </div>
              </div>
            </template>

            <noDataAuth v-if="databaseTableData[0].HaveOperaAuth===false" :text="$t('MsgPrompt.no_edb_auth')"/>
          </div>
          <div class="link-content-chartIndex" v-else-if="addLinkSearchParams.linkType==2 && this.chartInfo && this.chartInfo.ChartInfoId">
            <template v-if="chartInfo.HaveOperaAuth">
              <div class="chart-name">{{ currentLang==='en'?(chartInfo.ChartNameEn||chartInfo.ChartName):chartInfo.ChartName }}</div>
              <Chart :options="options" :chartInfo="chartInfo" ref="chartRef" />
            </template>

            <noDataAuth v-if="chartInfo.HaveOperaAuth===false" :text="$t('MsgPrompt.no_chart_auth')"/>
          </div>
          <div class="link-content-dataIndex" v-else-if="addLinkSearchParams.linkType==3 && this.reportList.length>0">
            <el-table :data="this.reportList" border style="margin-bottom: 10px;" ref="reportTable"
            @select="reportSelect" @select-all="reportSelect"> 
              <el-table-column type="selection" width="40" align="center"></el-table-column>
              <el-table-column :label="$t('Table.report_title')" align="center" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span >{{ scope.row.Title }}</span>
                  <span  v-if="scope.row.MsgSendTime">
                    ({{ scope.row.MsgSendTime.substring(5, 7)}}{{ scope.row.MsgSendTime.substring(8, 10) }})
                  </span>
                  <span v-else-if="scope.row.PublishTime">
                    ({{ scope.row.PublishTime.substring(5, 7)}}{{ scope.row.PublishTime.substring(8, 10) }})
                  </span>
                  <span v-else-if="scope.row.CreateTime">
                    ({{ scope.row.CreateTime.substring(5, 7)}}{{ scope.row.CreateTime.substring(8, 10) }})
                  </span>
                </template>
              </el-table-column >
              <el-table-column :label="$t('Table.publish_time')" align="center">
                <template slot-scope="scope">
                  <span>{{scope.row.PrePublishTime?scope.row.PrePublishTime:scope.row.PublishTime}}</span>
                </template>
              </el-table-column>
            </el-table>
            <m-page :page_no="reportParams.CurrentIndex" :pageSize="5" :total="reportTotal" @handleCurrentChange="pageChange"/>
          </div>
          <tableNoData :text="$t('Table.prompt_slogan')" v-else/>
        </div>
        <div class="link-box-buttons">
          <el-button type="info" style="width:120px;color:#333333;background-color:#F4F8FE" @click="cancelHandle">{{$t('Dialog.cancel_btn')}}</el-button>
          <el-button type="primary" style="width:120px;margin-left: 30px;" @click="saveLink">{{$t('Dialog.confirm_btn')}}</el-button>
        </div>
      </div>
		</el-dialog>
    <calculateEdb
       :isShow.sync="isOpenCalculationDia"
       :calculationItem="calculationItem"
       :activeLink="activeItem"
       :linkList="linkListInShow"
       @editEdbName="handleEditEdbName"
       @addEdbItem="handleAddEdbItem"
       @changeActiveEdb="handleChangeActiveEdb"
       @edbDelete="handleEdbDelete"
       @addCalculation="handleAddCalculation"
       @handleCloseDialog="handleCloseDialog"
      ></calculateEdb>
    </div>
</template>

<script>
import { chartSetMixin } from '../../../dataEntry_manage/mixins/chartPublic'
import * as sheetInterface from "@/api/modules/sheetApi.js";
import mPage from "@/components/mPage.vue";
import Chart from '../../../dataEntry_manage/components/chart.vue'
import calculateEdb from './calculateEdb.vue';
import { dataBaseInterface,reportlist} from '@/api/api.js';
import * as preDictEdbInterface from '@/api/modules/predictEdbApi.js';
import { calculateOption } from "../../common/options"
  export default {
    components:{
      mPage,Chart,calculateEdb
    },
    props:{
      show:{
        reuqired:true,
        type:Boolean
      },
      linkList:{
        type:Array,
        default:()=>[]
      }
    },
    mixins:[chartSetMixin],
    watch:{
      /* 选中搜索指标 展开目录 选中指标 展示数据 */
      search_dataBaseId(newval) {
        if (newval) {
          if(this.linkListInShow.find(_=>_.Id == newval)){
               return this.$message.warning(this.$t('SandboxManage.SandFlow.data_already_exists'))
          }
          if(this.addLinkSearchParams.linkType==1){
            let search_obj = this.dataBaseOptions.find(
              (item) => item.EdbInfoId === newval
            );
            if(search_obj){
              this.activeItem = {
                RId:this.addLinkSearchParams.linkType+'-'+search_obj.EdbInfoId,
                Id:search_obj.EdbInfoId,
                Name:this.currentLang==='en'?(search_obj.EdbNameEn||search_obj.EdbName):search_obj.EdbName,
                Type:this.addLinkSearchParams.linkType,
                editing:false,
                databaseType:search_obj.EdbInfoType, //0 普通指标 | 1 预测指标
                EdbType:search_obj.EdbType || 0,
                detailParams:{
                  code:search_obj.UniqueCode,
                  id:search_obj.EdbInfoId,
                  classifyId:search_obj.ClassifyId
                },
                calculationMethod:[],
              }
              this.checkedLinkList.push(this.activeItem)
              this.handleLinkListInShow()
              this.activeItemRId=this.addLinkSearchParams.linkType+'-'+search_obj.EdbInfoId
              this.initGetData()
            }
          }else{
            let search_obj = this.dataBaseOptions.find(
              (item) => item.ChartInfoId === newval
            );
            if(search_obj){
              this.activeItem = {
                RId:this.addLinkSearchParams.linkType+'-'+search_obj.ChartInfoId,
                Id:search_obj.ChartInfoId,
                Name: this.currentLang==='en'?(search_obj.ChartNameEn||search_obj.ChartName):search_obj.ChartName,
                Type:this.addLinkSearchParams.linkType,
                editing:false,
                detailParams:{
                  code:search_obj.UniqueCode,
                  id:search_obj.ChartInfoId
                },
                calculationMethod:[],
              }
              this.checkedLinkList.push(this.activeItem)
              this.handleLinkListInShow()
              this.activeItemRId=this.addLinkSearchParams.linkType+'-'+search_obj.ChartInfoId
              this.getChartDetail(search_obj.ChartInfoId)
            }
          }
        }
      },
      edbData: {
        handler(newval, oldval) {
          newval.length && !this.chartInfo.WarnMsg && this.setChartOptionHandle(newval);
        },
        deep: true,
      },
      show(value){
        if(value){
          this.isOpenCalculationDia = false;
          this.checkedLinkList = JSON.parse(JSON.stringify(this.linkList.map(_=>({calculationMethod:[],..._}))))
          this.handleLinkListInShow()
          let firstCheckedLink = this.checkedLinkList[0]
          if(firstCheckedLink){
            this.addLinkSearchParams.linkType = firstCheckedLink.Type;
            this.activeItemRId='';
            this.linkClick(firstCheckedLink)
          }else{
            this.addLinkSearchParams.linkType=1
          }
          this.doDataInit()
        }
      },
      activeItem:{
        deep:true,
        handler(){
          this.handleThreeCalculation()
        }
      },
    },
    computed:{
        linkTypeList(){
            return [
                {value:1,label:this.$t('SandboxManage.SandFlow.link_type_opt1')},
                {value:2,label:this.$t('SandboxManage.SandFlow.link_type_opt2')},
                {value:3,label:this.$t('SandboxManage.SandFlow.link_type_opt3')}
            ]
        },
        calculateOption(){
          return calculateOption
        },
    },
    data() {
      return {
        addLinkSearchParams:{
          linkType:1
        },
        //添加链接：指标
        search_dataBaseId:'',
        dataBaseParams:{
          pages:1,
          searchText:'',
          search_have_more:false
        },
        dataBaseOptions:[],

        databaseTableData:[],
        databaseList:[],
        databaseHaveMore:false,
        databasePageNo:1,
        chartInfo:{},
        edbData:[],
        options:{},
        reportKeyWord:'',
        reportParams:{
          CurrentIndex:1,
          PageSize:5,
        },
        reportList:[],
        selections:[],
        checkedLinkList:[],
        linkListInShow:[],//当前种类下的标签
        reportTotal:0,
        editingLabel:'',
        activeItemRId:'',
        activeItem:'',
        threeCalculation:[],//三个一组
        isOpenCalculationDia:false,
        calculationItem:{},
        dialogDisplayNone:false,
      }
    },
    methods: {
      handleThreeCalculation(){
        let i = this.checkedLinkList.findIndex(_=>_.RId == this.activeItem.RId);
        if(i < 0) return;
        if(!this.checkedLinkList[i].calculationMethod) this.checkedLinkList[i].calculationMethod = [];
        
        let data = this.checkedLinkList[i].calculationMethod || [];
        let arr = [];
        if(data && data.length > 0) {
          for(var x=0;x<data.length;x+=3){
              arr.push(data.slice(x,x+3));
          }
        } 
        this.threeCalculation = arr || [];
      },
      handleCountChoose(item){
        let i = this.checkedLinkList.findIndex(_=>_.RId == this.activeItem.RId);
        if(i < 0) return false;
        let arr = this.checkedLinkList[i].calculationMethod || [];
        return arr.find(_=>_.source == item.source || _.source == item.source2);
      },
      handleEditCal(v){ //编辑状态
          const getManySourseJump = (item) => {
            let i = this.checkedLinkList.find(_=>_.RId == this.activeItem.RId);
            if(i && i.calculationMethod && i.calculationMethod.length > 0){
              let calItem =  i.calculationMethod.find(_=>_.source == item.source || _.source == item.source2);
              let _ = !calItem ? item : {
                ...item,
                source:calItem.source
              }
              return _;
            } else {
              return item;
            }

          }
          let hasManySource = v.source2 ? true : false;
          this.calculationItem = !hasManySource ? v : getManySourseJump(v);
          this.isOpenCalculationDia = true;
          this.dialogDisplayNone = true;
      },
      clickCountItem(item){
         let i = this.checkedLinkList.findIndex(_=>_.RId == this.activeItem.RId);
         if(i < 0) return;
         if(!this.checkedLinkList[i].calculationMethod) this.checkedLinkList[i].calculationMethod = [];
         let isChoosed = this.checkedLinkList[i].calculationMethod.findIndex(_=>_.source == item.source || _.source == item.source2);
         if(isChoosed >= 0){ //已经选中
          this.checkedLinkList[i].calculationMethod.splice(isChoosed,1)
         } else { //未选中
              if(item.source == 99 || item.source == 98){ //最新值和最新日期
                this.checkedLinkList[i].calculationMethod.unshift({
                  ...item,
                  value:item.source == 99 ? this.databaseTableData[0].LatestValue : this.databaseTableData[0].LatestDate
                 })
              } else {
                this.calculationItem = item;
                this.isOpenCalculationDia = true;
                this.dialogDisplayNone = true;
              }
        };
        this.handleThreeCalculation();
      },
      handleAddCalculation({item}){
        let i = this.checkedLinkList.findIndex(_=>_.RId == this.activeItem.RId);
        if(i < 0) return;
        if(!this.checkedLinkList[i].calculationMethod) this.checkedLinkList[i].calculationMethod = [];
        let x = this.calculateOption.find(_=>item.source == _.source || item.source == _.source2);
        let isChoosed = this.checkedLinkList[i].calculationMethod.findIndex(_=>_.source == x.source || _.source == x.source2);
        if(isChoosed >= 0) {
          this.checkedLinkList[i].calculationMethod.splice(isChoosed,1);
        }
        this.checkedLinkList[i].calculationMethod.unshift(item);
        this.handleThreeCalculation();
      },
      changeLinkType(){
        this.doDataInit();
        this.handleLinkListInShow();
          let firstCheckedLink = this.linkListInShow[0];
          if(firstCheckedLink){
            this.activeItemRId=''
            this.linkClick(firstCheckedLink)
          }
          this.doDataInit();
      },
      handleLinkListInShow(){
        this.linkListInShow = (this.checkedLinkList || []).filter(_=>_.Type == this.addLinkSearchParams.linkType);
      },
      doDataInit(){
        this.search_dataBaseId=''
        this.dataBaseOptions=[]
        this.dataBaseParams={
          pages:1,
          searchText:'',
          search_have_more:false
        }

        this.databaseTableData=[]
        this.databaseList=[]
        this.databaseHaveMore=false
        this.databasePageNo=1
        
        this.chartInfo={}
        this.edbData=[]

        this.reportKeyWord=''
        this.reportList=[]
      },
      /* 搜索 */
      dataBaseSearch(query) {
        this.dataBaseParams.pages = 1;
        this.dataBaseParams.searchText = query;
        this.dataBaseSearchApi(this.dataBaseParams.searchText)
      },
      // 加载更多
      dataBaseSearchLoad() {
        if(!this.dataBaseParams.search_have_more) return;
        this.dataBaseSearchApi(this.dataBaseParams.searchText,++this.dataBaseParams.pages);
      },
      /* 聚焦获取当前检索 */
      dataBaseInputFocus(e) {
        this.dataBaseParams.pages = 1;
        this.dataBaseParams.searchText = e.target.value;
        if(this.dataBaseParams.searchText) {
          this.dataBaseSearchApi(this.dataBaseParams.searchText);
        }else {
          this.searchOptions = [];
          this.dataBaseParams.search_have_more=false
        }

      },
      dataBaseSearchApi(query,page=1) {
        if(this.addLinkSearchParams.linkType==1){
          sheetInterface.searchTarget({
            KeyWord:query,
            CurrentIndex: page
          }).then(res => {
            if(res.Ret !== 200) return
            const { List,Paging } = res.Data;
            this.dataBaseParams.search_have_more = page < Paging.Pages;
            this.dataBaseOptions = page === 1 ? List : this.dataBaseOptions.concat(List);
          })
        }else{
          dataBaseInterface.chartSearchByEs({
            Keyword: query,
            IsShowMe:false,
            CurrentIndex: page
          })
          .then((res) => {
            if (res.Ret !== 200) return
            const { List,Paging } = res.Data;
            this.dataBaseParams.search_have_more = page < Paging.Pages;
            this.dataBaseOptions = page === 1 ? List : [...this.dataBaseOptions,...List];
          });
        }

      },
      initGetData() {
        this.databasePageNo = 1;
        if(this.$refs.edb_detail_data){
          this.$refs.valueUl.scrollTop=0
        }
        this.getDatabaseList();
      },
      getDatabaseList(){
        // 0-普通指标 1-预测指标
        let api = this.activeItem.databaseType==0?(dataBaseInterface.targetList):(preDictEdbInterface.edbDataInfo)
        api({
          PageSize: 20,
          CurrentIndex: this.databasePageNo,
          EdbInfoId: this.search_dataBaseId || this.activeItem.Id,
        }).then(res => {
          if(res.Ret === 200) {
            if(res.Data) {
              this.databaseTableData = [res.Data.Item] || [];
              this.databaseHaveMore =  this.databasePageNo < res.Data.Paging.Pages ? true : false;
              this.databaseList = this.databasePageNo === 1 ? (res.Data.Item.DataList || []) : this.databaseList.concat(res.Data.Item.DataList);
            }else {
              this.databaseTableData = [];
              this.databaseList = [];  
            }
          }
        })
      },
      databaseScrollHandle:_.throttle(function() {
        let scrollTop = this.$refs.valueUl.scrollTop;
        let clientHeight = this.$refs.valueUl.clientHeight;
        let scrollHeight = this.$refs.valueUl.scrollHeight;
        if(scrollTop===0) return
        if(scrollTop + clientHeight >= scrollHeight-10 && this.databaseHaveMore){
          this.databasePageNo++
          this.getDatabaseList()
        }
		  },200),
      async getChartDetail(ChartInfoId) {
        const res = await dataBaseInterface.getChartInfoById({ChartInfoId})
        if (res.Ret !== 200) return;
        this.chartInfo = res.Data.ChartInfo || {}
        this.edbData = res.Data.EdbInfoList|| []
        //初始化上下限
        this.setLimitData(this.edbData)
        const chartTypeMap = {
          7: this.initBarData, //柱形图
          10: this.initSectionScatterData, //截面散点
          // (res.Data)
          11: this.initRadarData, //雷达图
          14:this.initSectionalCombinationChart, //截面组合图
        }
        chartTypeMap[this.chartInfo.ChartType] && chartTypeMap[this.chartInfo.ChartType](res.Data);

      },
      editLinkName(item){
        this.editingLabel = item.Name
        item.editing=true
        this.$nextTick(() => {
          this.$refs.labelEditInput[0].focus();
        });
      },
      // 链接点击
      /*
        config.noInfo - 研报类型的不提示
      */
      linkClick(item,config={}){
        if(this.activeItemRId == item.RId) return
        this.activeItemRId = item.RId
        this.activeItem = item
        this.addLinkSearchParams.linkType=item.Type
        this.handleLinkListInShow();
        if(item.Type==3){
          if(!config.noInfo){
            this.$message.info('研报类型的暂无回显')
          }
        }else if(item.Type==1){          
          this.doDataInit()
          this.initGetData() 
        }else if(item.Type==2){
          this.doDataInit()
          this.getChartDetail(item.Id)
        }

      },
      linkDelete(item,index){
        let rId = item.RId
        this.linkListInShow.splice(index,1);
        this.checkedLinkList.splice(this.checkedLinkList.findIndex(_=>_.RId == rId),1);
        if(this.activeItemRId == rId){
          let firstCheckedLink = this.linkListInShow[0]
          if(firstCheckedLink){
            this.linkClick(firstCheckedLink,{noInfo:true})
          }else{
            this.activeItemRId = "";
            this.activeItem = {};
          }
          this.doDataInit()
        }

        if(item.Type==3){
          let deleteId=this.selections.filter(it=> it.Id==item.Id)
          if(deleteId[0]){
            this.$refs.reportTable && this.$refs.reportTable.toggleRowSelection(deleteId[0],false)
          }
        }
      },
      editLinkNameFinish(item){
        if (this.editingLabel) {
          item.editing=false
          item.Name = this.editingLabel
          let i = this.checkedLinkList.findIndex(_=>_.RId == item.RId);
          if(i >= 0) this.checkedLinkList[i].Name = this.editingLabel;
        } else {
          this.$message.warning('不能为空');
        }
      },
      handleEditEdbName(options){
          let {item} = options;
          let i = this.checkedLinkList.findIndex(_=>_.RId == item.RId);
          if(i >= 0) this.checkedLinkList[i].Name = item.Name;
          let j = this.linkListInShow.findIndex(_=>_.RId == item.RId);
          if(j >= 0) this.linkListInShow[j].Name = item.Name;
      },
      handleAddEdbItem(options){
          let {item} = options;
          this.doDataInit()
          this.activeItem = item;
          this.checkedLinkList.push(item)
          this.handleLinkListInShow()
          this.activeItemRId=item.RId;
          this.initGetData()
      },
      handleChangeActiveEdb({item}){
         if(!item) return;
         this.linkClick(item)
      },
      handleEdbDelete({item}){
        let index = this.linkListInShow.findIndex(_=>_.RId == item.RId)
        this.linkDelete(item,index)
      },
      searchReport(){
        this.reportParams.CurrentIndex=1
        if(!this.reportKeyWord){
          this.reportList=[]
          this.reportTotal=0
        }else{
          this.getReportList()
        }
      },
      getReportList(){
        let params={
          CurrentIndex: this.reportParams.CurrentIndex,
          PageSize: this.reportParams.PageSize,
          KeyWord:this.reportKeyWord,
          State:2
        }
        reportlist(params).then((res) => {
          if (res.Ret === 200) {
            this.reportList = res.Data.List || [];
            this.reportTotal = parseInt(res.Data.Paging.Totals);
          }
        });    
      },
      pageChange(page_no){
        this.reportParams.CurrentIndex = page_no;
        this.getReportList();
      },
      reportSelect(selection){
        this.selections=selection
        let allIds = this.reportList.map(it => {
          return it.Id
        })
        let simpleSelections = selection.map(it => {
          return {Id:it.Id,Code:it.ReportCode,Name:it.Title}
        })

        let unselectIds=[]

        if(simpleSelections.length>0){
          allIds.map(id =>{
            if(simpleSelections.every(sele => id!=sele.Id )){
              unselectIds.push(id)
            }
          })
        }else{
          unselectIds=allIds
        }
        //没有就增加
        simpleSelections.map(item =>{
          let rId = this.addLinkSearchParams.linkType+'-'+item.Id
          if(this.checkedLinkList.every(sele => rId!=sele.RId )){
            this.checkedLinkList.push({
              RId:rId,
              Id:item.Id,
              Name:item.Name,
              Type:this.addLinkSearchParams.linkType,
              editing:false,
              detailParams:{id:item.Id,code:item.Code},
              calculationMethod:[]
            })
            this.handleLinkListInShow()
          }
        })
        //有就去掉
        unselectIds.map(item =>{
          let rId = this.addLinkSearchParams.linkType+'-'+item
          let index = this.checkedLinkList.findIndex(link => rId==link.RId)
          if(index!=-1){
            this.checkedLinkList.splice(index,1)
            this.handleLinkListInShow()
          }
        })
      },
      saveLink(){
        this.$emit("saveLink", this.checkedLinkList);
      },
      handleCloseDialog(){
        this.dialogDisplayNone = false;
      },
      cancelHandle(){
        this.linkListInShow = [];
        this.$emit("update:show", false);
      }
    },
  }
</script>

<style lang="scss" scoped>
    .add-link-box{
      max-height: 72vh;
      overflow: auto;
      padding: 15px 40px 35px;
      .link-box-option{
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
      }
      .link-box-content{
        margin-bottom: 30px;
        .link-content-dataIndex{
          display: flex;
          flex-direction: column;
          .link-count-wrap{
             margin-top: 13px;
             display: flex;
             justify-content: start;
             align-items: center;
             flex-wrap: wrap;
             .link-count-item{
                cursor: pointer;
                display: flex;
                justify-content: center;
                align-items: center;
                margin-top: 20px;
                margin-right: 20px;
                font-size: 14px;
                box-sizing: border-box;
                height: 40px;
                padding: 4px 8px 4px 8px;
                border-radius: 4px;
             }
             .link-count-item-on{
              border: 1px solid #0052D9;
              color: #666666;
              background: #ECF2FE;
             }
             .link-count-item-un{
              border: 1px solid #C8CDD9;
              color: #666666;
             }
          }

          .calculate-result-wrap{
             margin-top: 20px;
             .calculate-result-title{
                font-size: 14px;
                color: #333333;
                margin-bottom: 10px;
             }
             .calculate-result-table{
                border: 1px solid #C8CDD9;
                box-sizing: border-box;
                padding: 0 20px;
                border-radius: 4px;
                .calculate-result-table-tr:nth-of-type(n+2){
                  border-top: 1px solid #C8CDD9;
                }
                .calculate-result-table-tr{
                  height: 50px;
                  display: flex;
                  align-items: center;
                  .calculate-result-table-item{
                    width: 33.3%;
                    color: #333333;
                    font-weight: 400;
                  }
                }
             }
          }

          .delete-button{
            color: #AD352F;
            font-size: 14px;
            cursor: pointer;
          }
        }
        .link-content-chartIndex{
          .chart-name{
            font-size: 16px;
            text-align: center;
            color: #333333;
          }
        }
      }
      .link-box-tags{
        display: flex;
        align-items: center;
        overflow-x: auto;
        margin-bottom: 20px;
        .unchoose-tag{
          border: 1px solid #C8CDD9;
        }
        .choosed-tag{
          border: 1px solid #0052D9;
          background: rgba(236, 242, 254, 1);
        }
        .link-box-tag{
          display: flex;
          align-items: center;
          padding: 0 8px;
          height: 40px;
          max-width: 250px;
          margin-right: 30px;
          border-radius: 4px;
          cursor: pointer;
          &:last-child{
            margin-right: 0;
          }
          span{
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          img{
            height: 16px;
            width: 16px;
            margin-left: 8px;
          }
        }
      }
      .link-box-buttons{
        margin-top: 60px;
        display: flex;
        align-items: center;
        justify-content: center;

      }
    }
</style>