<template>
    <el-dialog :modal-append-to-body='false' :title="$t('SandboxManage.SandFlow.add_link')" :visible.sync="show" 
    :close-on-click-modal="false" width="872px" top="5vh" @close="cancelHandle">
      <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-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">
                  <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('Table.start_time')" align="center" width="100">
                  <template slot-scope="scope">{{ scope.row.StartDate }}</template>
                </el-table-column>
                <el-table-column :label="$t('Table.update_time')" align="center" width="160">
                  <template slot-scope="scope">{{ scope.row.ModifyTime }}</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-column :label="$t('Table.column_operations')" align="center" width="50">
                  <template slot-scope="scope">
                    <span class="delete-button">{{$t('Table.delete_btn')}}</span>
                  </template>
                </el-table-column>
              </el-table>
              <ul 
                class="value-ul" 
                ref="valueUl" 
                @scroll="databaseScrollHandle" 
                v-show="databaseList.length">
                <li
                  class="value-item"
                  v-for="item in databaseList"
                  :key="item.EdbDataId"
                >
                  <span class="value-label">
                    <span style="position: relative;">
                      <i class="new-tag" v-if="databaseTableData[0].LatestDate===item.DataTime"></i>
                      {{item.DataTime}}
                    </span>
                  </span>
                  <span :class="['value-label',{'predict-act': databaseTableData[0].DataInsertConfig.Date===item.DataTime}]" style="min-width:200px;text-align:center;">
                    <span :class="['value-style',{'predict-act': databaseTableData[0].DataInsertConfig.Date===item.DataTime}]">{{item.Value}}</span>
                  </span>
                </li>
                <li class="nodata value-item" v-if="!databaseList.length">{{$t('Table.prompt_slogan')}}</li>
              </ul>
            </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-tags">
          <div class="link-box-tag" v-for="(item,index) in checkedLinkList" :key="item.RId">
            <span @dblclick.stop="editLinkName(item)" v-if="!item.editing" @click="linkClick(item)">{{ 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-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>
</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 { dataBaseInterface,reportlist} from '@/api/api.js';
import * as preDictEdbInterface from '@/api/modules/predictEdbApi.js';
  export default {
    components:{
      mPage,Chart
    },
    props:{
      show:{
        reuqired:true,
        type:Boolean
      },
      linkList:{
        type:Array,
        default:()=>[]
      }
    },
    mixins:[chartSetMixin],
    watch:{
      /* 选中搜索指标 展开目录 选中指标 展示数据 */
      search_dataBaseId(newval) {
        if (newval) {
          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 预测指标
                detailParams:{
                  code:search_obj.UniqueCode,
                  id:search_obj.EdbInfoId,
                  classifyId:search_obj.ClassifyId
                }
              }
              this.checkedLinkList.push(this.activeItem)
              
              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
                }
              }
              this.checkedLinkList.push(this.activeItem)
              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.checkedLinkList = JSON.parse(JSON.stringify(this.linkList))
          let firstCheckedLink = this.checkedLinkList[0]
          if(firstCheckedLink){
            this.activeItemRId=''
            this.linkClick(firstCheckedLink)
          }else{
            this.addLinkSearchParams.linkType=1
          }
          this.changeLinkType()
        }
      }
    },
    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')}
            ]
        }
    },
    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:[],
        reportTotal:0,
        editingLabel:'',
        activeItemRId:'',
        activeItem:''
      }
    },
    methods: {
      // -------------------------------添加链接
      changeLinkType(){
        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, //截面散点
          11: this.initRadarData(res.Data)
        }
        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
        if(item.Type==3){
          if(!config.noInfo){
            this.$message.info('研报类型的暂无回显')
          }
        }else if(item.Type==1){          
          this.changeLinkType()
          this.initGetData() 
        }else if(item.Type==2){
          this.changeLinkType()
          this.getChartDetail(item.Id)
        }

      },
      linkDelete(item,index){
        let rId = item.RId
        this.checkedLinkList.splice(index,1)
        if(this.activeItemRId == rId){
          let firstCheckedLink = this.checkedLinkList[0]
          if(firstCheckedLink){
            this.linkClick(firstCheckedLink,{noInfo:true})
          }else{
            this.activeItemRId = ""
            this.addLinkSearchParams.linkType=1
          }
          this.changeLinkType()
        }

        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
        } else {
          this.$message.warning('不能为空');
        }
      },
      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}
            })
          }
        })
        //有就去掉
        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)
          }
        })
      },
      saveLink(){
        this.$emit("saveLink", this.checkedLinkList);
      },
      cancelHandle(){
        this.$emit("update:show", false);
      }
    },
  }
</script>

<style lang="scss" scoped>
    .add-link-box{
      padding: 15px 40px 35px;
      .link-box-option{
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 30px;
      }
      .link-box-content{
        margin-bottom: 30px;
        .link-content-dataIndex{
          display: flex;
          flex-direction: column;
          .value-ul {
            flex-grow: 1;
            overflow-y: auto;
            margin-top: 10px;
            height: 200px;
            border-bottom: 1px solid #EBEFF6;
            .value-item {
              /* width: 100%; */
              padding: 10px 0;
              border: 1px solid #dcdfe6;
              border-bottom: none;
              display: flex;
              justify-content: space-around;
              >span{
                padding:0 16px;
                box-sizing: border-box;
              }
              .value-label {
                position: relative;
                color: #666;
                .value-style{
                  padding:5px;
                  border-radius: 4px;
                  &.predict-act {
                    color: orange;
                  }
                }
                &.date{
                  &::after{
                    content: '';
                    position:absolute;
                    right:0;
                    top:-14px;
                    height:calc(100% + 28px);
                    width:1px;
                    background-color: #dcdfe6;
                  }
                }
              }
              .predict-act {
                color: orange;
              }
              .new-tag {
                width: 6px;
                height: 6px;
                display: inline-block;
                position: absolute;
                left: -12px;
                top: 50%;
                transform: translateY(-50%);
                border-radius: 50%;
                background: #f00;
              }
            }
            .nodata {
              text-align: center;
              padding: 40px 0;
              color: #999;
            }
          }
          .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;
        .link-box-tag{
          display: flex;
          align-items: center;
          padding: 0 8px;
          height: 30px;
          max-width: 250px;
          background-color: #F8F8F8;
          margin-right: 30px;
          cursor: pointer;
          &:last-child{
            margin-right: 0;
          }
          span{
            color: #666666;
            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>