<template>
  <div class="selfData-page">
    <div class="header">
      <div class="left">
        <el-select
          v-model="filterObj.source"
          @change="filterChange"
          :placeholder="$t('SelftDataPage.ph_channel')"
          clearable
        >
          <el-option 
            v-for="item in sourceOptions" 
            :key="item.EdbBusinessSourceId" 
            :label="item.SourceName" 
            :value="item.EdbBusinessSourceId"
          />
        </el-select>

        <el-select
          v-model="filterObj.frequency"
          @change="filterChange"
          :placeholder="$t('Edb.InputHolderAll.input_fre')"
          clearable
        >
          <el-option v-for="item in frequencyOptions" :key="item.val" :label="item.label" :value="item.val"/>
        </el-select>

        <el-input 
          v-model="filterObj.keyWord" 
          :placeholder="$t('Edb.InputHolderAll.input_name_orid')"
          style="width: 250px;"
          @change="filterChange"
          clearable
          >
          <i slot="prefix" class="el-input__icon el-icon-search"/>
        </el-input>

        <el-checkbox 
            v-model="filterObj.checkAll"
            :indeterminate="filterObj.checkSome"
            :disabled="tableData.length===0"
            style="margin-left:20px" 
            @change="listCheckAllChange"
          ><!-- 列表全选 -->{{$t('SystemManage.OperateAuth.all_select')}}</el-checkbox>
      </div>

      <el-button 
        v-permission="permissionBtn.dataSourcePermission.selfData_addEdb"
        type="primary" 
        @click="handleCheckEdb('multiple')"
      ><!-- 添加到指标库 -->{{$t('YsDataPage.add_base_btn')}}</el-button>
    </div>

    <div class="main">
      <el-table
        :data="tableData"
        ref="table"
        element-loading-text="加载中..."
        v-loading="tableLoading"
        border
        style="margin:20px 0"
        @selection-change="selectionChange"
        @select="selectHandle" 
        @select-all="selectAllPageHandle"
        @sort-change="handleSortChange"
      >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column
            v-for="item in tableColums"
            :key="item.label"
            :label="item.label"
            :prop="item.key"
            :width="item.widthsty"
            :min-width="item.minwidthsty"
            :sortable="item.sortable?true:false"
            align="center"
          >
            <template slot-scope="{row}">
              <template v-if="item.key==='handle'">
                <span v-permission="permissionBtn.dataSourcePermission.selfData_detail"
                  class="editsty"
                  @click="lookDataHandle(row)"
                >
                  <!-- 查看详情 -->{{$t('Edb.detail_lookdata2_btn')}}
                </span>

                <span 
                  class="editsty"
                  v-if="!row.EdbInfoId" 
                  @click="handleCheckEdb('single',row)"
                >
                  <!-- 添加到指标库 -->{{$t('YsDataPage.add_base_btn')}}
                </span>
              </template>

              <template v-else-if="item.key==='IndexName'">
                <span style="white-space: pre-wrap;">{{ row.IndexName }}</span>
              </template>

              <span v-else>{{ row[item.key] }}</span>
            </template>
          </el-table-column>
          
          <div slot="empty" style="padding: 100px 0">
            <tableNoData :text="$t('Table.prompt_slogan')" size="mini"/>
          </div>
      </el-table>

      <div style="height:35px;margin: 20px 0;">
        <m-page
          :page_no="page_no"
          :pageSize="pageSize"
          :total="total"
          @handleCurrentChange="pageChange"
        />
      </div>
    </div>

    <!-- 查看数据弹窗 -->
    <lookEdbDataDia
      :isShow.sync="isLookDataDia"
      :edbInfo="lookEdbInfo"
    />

    <!-- 加入指标库弹窗 -->
    <addToBaseDia
      :isShow.sync="isAddToBaseDia"
      :list="addToBaseList"
      @success="pageChange(1)"
    />

    <!-- 操作提示弹窗 -->
    <el-dialog 
      :title="$t('BloombergPage.operation_prompt')"
      :visible.sync="isHintDialogShow"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      @close="isHintDialogShow=false"
      width="578px"
      v-dialogDrag
      center>
      <div class="hint-dialog-wrap">
          <p style="margin-bottom: 20px;">{{ hintText }}</p>
          <ul>
              <li v-for="(item,index) in existEdbList" :key="index" class="hint-item" @click="goToEdbBase(item)">
                  {{ index+1 }}、{{ item.IndexName }}({{ item.IndexCode }})
              </li>
          </ul>
      </div>
      <div style="text-align: center;margin-bottom: 30px;">
          <el-button type="primary" @click="handleCloseHintDia">{{$t('Dialog.known')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { selfDataInterface } from '@/api/modules/dataSource';
import mPage from '@/components/mPage.vue';
import lookEdbDataDia from './components/lookEdbDataDia.vue';
import addToBaseDia from './components/addToBaseDia.vue';
export default {
  components: { mPage,lookEdbDataDia,addToBaseDia },
  computed: {
    tableColums() {
        return [
          {
            label: this.$t('Edb.Detail.e_id'),
            key: 'IndexCode',
          },
         {
            label: this.$t('Edb.Detail.e_name'),
            key: 'IndexName',
          },
          {
            label: this.$t('Edb.Detail.e_fre'),
            key: 'Frequency',
          },
          {
            label: this.$t('Edb.Detail.e_unit'),
            key: 'Unit',
          },
          {
            label: /* '渠道' */this.$t('SelftDataPage.col_channel'),
            key: 'SourceName',
          },
          {
            label: /* '指标开始时间' */this.$t('SelftDataPage.col_start_time'),
            key: 'StartDate',
            sortable:true,
          },
          {
            label: /* '指标最新时间' */this.$t('SelftDataPage.col_newest_time'),
            key: 'EndDate',
            sortable:true,
          },
          {
            label: /* '入库时间' */this.$t('SelftDataPage.col_create'),
            sortable:true,
            key: 'CreateTime'
          },
          {
            label: this.$t('Table.column_operations'),
            key: 'handle'
          },

        ]
    },

    frequencyOptions(){
      return [
        { label:'日度',val: '日度' },
        { label:'周度',val: '周度' },
        { label:'旬度',val: '旬度' },
        { label:'月度',val: '月度' },
        { label:'季度',val: '季度' },
        { label:'半年度',val: '半年度' },
        { label:'年度',val: '年度' },
      ]
    },

    hintText(){
        let key = 0
        if(this.existEdbList.length) key++
        if(!this.addToBaseList.length) key++

        return {
            0:'',
            1:this.$t('YsDataPage.haved_all_msg'),//本次添加的指标均已在指标库中，请勿重复添加！
            2:this.$t('YsDataPage.haved_some_msg'),//指标库中已存在以下指标，会自动过滤！
        }[key]
    }
  },
  data() {
    return {
      tableLoading: false,
      total: 0,
      
      tableData: [],

      sourceOptions: [],

      isSelectAll: false, //真正意义上的全选或不全选
      checkedList: [], //不全选勾选中的 或 全选取消勾的
      selectionReactCancel:false,//手动设置选中中

      filterObj: {
        page_no: 1,
        pageSize: 10,
        source: '',
        frequency: '',
        keyWord: '',
        sortParam:'',
        sortType:'',
        checkAll: false, //控制全选显示状态
        checkSome: false
      },

      /* 查看数据弹窗 */
      isLookDataDia: false,
      lookEdbInfo: {},

      /* 加入指标库弹窗 */
      isAddToBaseDia: false,
      addToType: 'multiple',
      addToBaseList: [],//可加入的指标
      existEdbList: [],//已存在的指标

      /* 提示弹窗 */
      isHintDialogShow: false,

    }
  },
  mounted(){
    this.getSource();
    this.getTableData('init');
  },
  methods:{
    getSource() {
      selfDataInterface.getSourceList().then(res => {
        if(res.Ret!==200 ) return

        this.sourceOptions = res.Data || [];
      })
    },

    getTableData(type='pageChange') {
      this.tableLoading = true;

      const { frequency,page_no,pageSize,keyWord,source,sortParam,sortType } = this.filterObj;

      let params = {
        Frequency: frequency,
        CurrentIndex: page_no,
        PageSize: pageSize,
        Keywords: keyWord,
        Source: source,
        SortField: sortParam,
        SortRule: sortType
      }
			selfDataInterface.getEdbList(params).then(res => {
        this.tableLoading = false;
        if( res.Ret!==200 )return

        const { Data } = res;

        this.tableData = Data.List || [];
        this.total = Data.Paging.Totals;
        
        if(type==='filter'){
          this.listCheckAllChange(true)
        }else {
          //页码变化 选中项不做清空
          this.checkedSomeSelection()

        }
			});
    },

    /* 设置当页数据勾选状态 */
    checkedSomeSelection() {
      this.selectionReactCancel=true

      if(!this.isSelectAll){
          this.checkedList.map(_ =>{
              let row = this.tableData.find(item => item.IndexCode==_.IndexCode)
              if(row){ //设置部分选中
                  setTimeout(()=>{
                      this.$refs.table.toggleRowSelection(row,true)
                  },20)
              }
          })
      }else{
          this.$refs.table &&this.$refs.table.toggleAllSelection()
          this.checkedList.map(_ =>{
              let row = this.tableData.find(item => item.IndexCode==_.IndexCode)
              if(row){ //设置部分不勾选
                  setTimeout(()=>{
                      this.$refs.table.toggleRowSelection(row,false)
                  },20)
              }
          })
      }
      setTimeout(()=>{
          this.selectionReactCancel=false
      },30)
    },

    //列表全选或全不选
    listCheckAllChange(value){
      this.checkedList = []
      this.isSelectAll = value
      this.$refs.table && this.$refs.table.clearSelection()

      value && this.$refs.table && this.$refs.table.toggleAllSelection()
    },

    selectionChange() {
      if(this.selectionReactCancel) return

        //设置全选框状态 选中 半选 不选
        setTimeout(()=>{
            let filterChecked = Array.from(new Set(this.checkedList))
            //全选
            if(
              (filterChecked.length===this.total&&this.total>0 && (!this.isSelectAll))
                || (filterChecked.length === 0 && this.isSelectAll)
            ){
                this.filterObj.checkAll = true
                this.filterObj.checkSome = false
            //不选
            }else if(
              (filterChecked.length === 0 && (!this.isSelectAll))
              || (filterChecked.length === this.total && this.isSelectAll)
            ){
                this.filterObj.checkAll = false
                this.filterObj.checkSome = false
            //半选
            }else{
                this.filterObj.checkAll = false
                this.filterObj.checkSome=true
            }
        },1)
    },

    //单选
    selectHandle(selection,row){ //当前选中的项是进选中还是取消选中中
        if(this.selectionReactCancel) return 

        //当前项是选中还是取消选
        let haveChecked = selection.some(_ => _.IndexCode === row.IndexCode);

        //全选取消选和不全选选中才有意义
        if((haveChecked&&!this.isSelectAll) || (!haveChecked&&this.isSelectAll)) {
          this.checkedList.push(row)
        }else {
          this.checkedList=this.checkedList.filter(_ => _.IndexCode!==row.IndexCode)
        }
    },

    //整列选
    selectAllPageHandle(selection){
        if(this.selectionReactCancel) return 
        
        //当前页是选中还是取消
        let haveChecked = selection && selection.length>0;

        //全选取消选和不全选选中才有意义
        if((haveChecked&&!this.isSelectAll) || (!haveChecked&&this.isSelectAll)) {
          this.checkedList = [...this.checkedList,...this.tableData]
        }else {

          let pageIds = this.tableData.map(_ => _.IndexCode);
          this.checkedList = this.checkedList.filter(_ => !pageIds.includes(_.IndexCode))
        }
    },

    handleSortChange({prop,order}) {
      const propMap={
          'StartDate':1,
          'EndDate':2,
          'ModifyTime':3
      }
      this.filterObj.sortParam = order?propMap[prop]||'':''
      this.filterObj.sortType = order?order==='ascending'?1:2:''

      this.filterChange()
    },

    // 页码改变
    pageChange(page) {
      this.filterObj.page_no = page;
      this.getTableData('pageChange')
    },

    filterChange(val) {
      this.filterObj.page_no = 1;
      if(!val) {
        this.isSelectAll = false
        this.checkedList = []
        this.filterObj.checkAll = false
        this.filterObj.checkSome = false
      }
      this.getTableData(val?'filter':'')
    },

    /* 查看数据 */
    lookDataHandle(item) {

      this.lookEdbInfo = item;
      this.isLookDataDia =  true
    },

    handleCheckEdb(type='multiple',data={}){

      if(type==='multiple' && !this.checkedList.length && !this.isSelectAll) return this.$message.warning('请选择指标')

      const {frequence,keyWord,sortParam,sortType} = this.filterObj

      selfDataInterface.checkEdb({
          Frequency:frequence,
          Keywords:keyWord,
          SortField:sortParam||0,
          SortRule:sortType||0,
          ListAll:type==='single'?false:this.isSelectAll,
          IndexCodes:type==='single'?[data.IndexCode]:this.checkedList.map(_=>_.IndexCode)
      }).then(res=>{
          if(res.Ret!==200) return 

          const edbList = res.Data||[]
          this.existEdbList = edbList.filter(i=>i.EdbExist===1)
          this.addToBaseList = edbList.filter(i=>i.EdbExist===0)

          this.existEdbList.length&&(this.isHintDialogShow=true)
          !this.existEdbList.length&&this.handleCloseHintDia()
      })
    },

    //提示弹窗关闭
    handleCloseHintDia(){
        this.isHintDialogShow = false
        //判断是否要展示下一个弹窗
        if(!this.addToBaseList.length) return
        
        if(this.addToBaseList.length>100) return this.$message.warning('批量添加指标数量不得超过100个！')

        this.isAddToBaseDia = true
    },

    //跳转至指标详情
    goToEdbBase(data){
        const {EdbClassifyId,EdbInfoId,EdbUniqueCode} = data||{}
        const { href } = this.$router.resolve({
            path:'/database',
            query:{
                code:EdbUniqueCode,
                id:EdbInfoId,
                classifyId:EdbClassifyId,
            }
        })
        window.open(href,"_blank")
    }

  },
}
</script>
<style scoped lang='scss'>
.selfData-page {
    min-height: calc(100vh - 120px);
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border: 1px solid #c8cdd9;
    border-radius: 4px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, .05);
    padding: 20px;
    box-sizing: border-box;

    .header {
      display: flex;
      justify-content: space-between;
      .left {
        display: flex;
        align-items: center;
        gap: 10px;
      }
    }
}
.hint-dialog-wrap{
    padding-bottom:30px;
    .hint-item{
        cursor: pointer;
        margin-bottom: 10px;
        &:hover{
            color:#409EFF;
            text-decoration: underline;
        }
    }
}
</style>
