<template>
    <el-dialog :modal-append-to-body='false' title="添加链接" :visible.sync="show" 
    :close-on-click-modal="false" width="872px" top="5vh">
      <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="指标ID/指标名称"
            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="item.EdbName"
              :value="item.EdbInfoId"
            >
            </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="图表名称"
            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="item.ChartName"
              :value="item.ChartInfoId"
            >
            </el-option>
          </el-select>
          <el-input v-else v-model="reportKeyWord" @input="searchReport"
          placeholder="标题 / 创建人" 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">
            <el-table :data="databaseTableData" border style="box-shadow: rgba(155, 170, 219, 0.2) 0px 3px 6px;">
              <el-table-column label="指标Id" align="center">
                <template slot-scope="scope">{{ scope.row.EdbCode }}</template>
              </el-table-column>
              <el-table-column label="指标名称" align="center" width="200">
                <template slot-scope="scope">{{ scope.row.EdbName }}</template>
              </el-table-column>
              <el-table-column label="频度" align="center" width="50">
                <template slot-scope="scope">{{ scope.row.Frequency }}</template>
              </el-table-column>
              <el-table-column label="单位" align="center">
                <template slot-scope="scope">{{ scope.row.Unit }}</template>
              </el-table-column>
              <el-table-column label="起始时间" align="center" width="100">
                <template slot-scope="scope">{{ scope.row.StartDate }}</template>
              </el-table-column>
              <el-table-column label="更新时间" align="center" width="160">
                <template slot-scope="scope">{{ scope.row.ModifyTime }}</template>
              </el-table-column>
              <el-table-column label="来源" align="center">
                <template slot-scope="scope">{{ scope.row.SourceName }}</template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="50">
                <template slot-scope="scope">
                  <span class="delete-button">删除</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">暂无数据</li>
            </ul>
          </div>
          <div class="link-content-chartIndex" v-else-if="addLinkSearchParams.linkType==2 && this.chartInfo && this.chartInfo.ChartInfoId">
            <div class="chart-name">{{ this.chartInfo.ChartName }}</div>
            <Chart :options="options" ref="chartRef" />
          </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="报告标题" 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="发布时间" 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="暂无数据" 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">取消</el-button>
          <el-button type="primary" style="width:120px;margin-left: 30px;" @click="saveLink">确定</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';

  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.checkedLinkList.push({
                RId:this.addLinkSearchParams.linkType+'-'+search_obj.EdbInfoId,
                Id:search_obj.EdbInfoId,
                Name: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.activeItemRId=this.addLinkSearchParams.linkType+'-'+search_obj.EdbInfoId
              this.initGetData()
            }
          }else{
            let search_obj = this.dataBaseOptions.find(
              (item) => item.ChartInfoId === newval
            );
            if(search_obj){
              this.checkedLinkList.push({
                RId:this.addLinkSearchParams.linkType+'-'+search_obj.ChartInfoId,
                Id:search_obj.ChartInfoId,
                Name:search_obj.ChartName,
                Type:this.addLinkSearchParams.linkType,
                editing:false,
                detailParams:{
                  code:search_obj.UniqueCode,
                  id:search_obj.ChartInfoId
                }
              })
              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.addLinkSearchParams.linkType=1
          this.changeLinkType()
          this.checkedLinkList = JSON.parse(JSON.stringify(this.linkList))
        }
      }
    },
    data() {
      return {
        linkTypeList:[
          {value:1,label:"ETA指标/预测指标"},
          {value:2,label:"ETA图库"},
          {value:3,label:"ETA研报"}
        ],
        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:'',
      }
    },
    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(){
        dataBaseInterface.targetList({
          PageSize: 20,
          CurrentIndex: this.databasePageNo,
          EdbInfoId: this.search_dataBaseId,
        }).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|| []

        const chartTypeMap = {
          7: this.initBarData, //柱形图
          10: this.initSectionScatterData //截面散点
        }

        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();
        });
      },
      linkClick(item){
        if(this.activeItemRId == item.RId) return
        this.activeItemRId = item.RId
        if(item.Type==3){
          this.$message.info('研报类型的暂无回显')
        }else if(item.Type==1){
          this.addLinkSearchParams.linkType=item.Type
          this.changeLinkType()
          this.initGetData() 
        }else if(item.Type==2){
          this.addLinkSearchParams.linkType=item.Type
          this.changeLinkType()
          this.getChartDetail(item.Id)
        }

      },
      linkDelete(item,index){
        if(this.activeItemRId == item.RId){
          this.activeItemRId=""
          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)
          }
        }
        this.checkedLinkList.splice(index,1)
      },
      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>