<template>
  <el-dialog
		:visible.sync="show"
		:close-on-click-modal="false"
		:modal-append-to-body="false"
		@close="handleClose"
		custom-class="batch-move-dialog fit-screen-dialog"
		center
		top="2vh"
		v-dialogDrag
    :title="`批量移动${sourceLabel}`"
	>
      <div class="list-wrap">
          <div class="filter-wrap">
            <div>
                <el-cascader
                    style="width: 240px"
                    v-model="filterObj.classify"
                    :options="classifyOption"
                    clearable
                    collapse-tags
                    placeholder="选择分类"
                    @change="handleFilter"
                    :props="cascaderProps"
                    :show-all-levels="false"
                    :key="cascaderKey"
                    ref="classifyRef"
                />

                <div>
                  关联子分类
                  <el-switch
                    v-model="filterObj.relevanceChild"
                    :active-value="true"
                    :inactive-value="false"
                    style="margin-left: 5px;"
                    @change="cascaderKey++"
                  />
                </div>
                
                <el-select
                  v-if="source==='edb'"
                  v-model="filterObj.source"
                  style="width: 200px"
                  placeholder="请选择计算方式"
                  clearable
                  multiple
                  collapse-tags
                  @change="handleFilter"
                >
                  <el-option
                    v-for="item in sourceOption"
                    :key="item.type"
                    :label="item.name"
                    :value="item.type"
                  >
                  </el-option>
                </el-select>

                <el-select
                  v-if="source==='chart'"
                  v-model="filterObj.chartTypes"
                  style="width: 200px"
                  placeholder="图表类型"
                  clearable
                  multiple
                  collapse-tags
                  @change="handleFilter"
                >
                  <el-option
                    v-for="item in sourceOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>

                <el-input 
                  v-model="filterObj.keyWord" 
                  :placeholder="`${sourceLabel}名称`"
                  style="width: 200px;"
                  @change="handleFilter"
                  clearable
                >
                  <i slot="prefix" class="el-input__icon el-icon-search"/>
                </el-input>
                
                <el-checkbox 
                    label="列表全选" 
                    v-model="filterObj.checkAll" 
                    :indeterminate="filterObj.checkSome" 
                    style="margin-left:10px"
                    @change="listCheckAllChange"
                />
            </div>
          </div>
          <div class="table-wrap">
              <el-table 
                  :data="list" 
                  border
                  ref="table"
                  height="50vh"
                  v-loading="listLoading"
                  @selection-change="selectionChange"
                  @select="selectHandle" 
                  @select-all="selectAllPageHandle"
              >
                <el-table-column type="selection" min-width="50" align="center" :selectable="filterEdbAuth"/>

                <el-table-column 
                  :label="item.label" 
                  align="center" 
                  v-for="item in tableColumns" 
                  :key="item.key" 
                  :width="item.widthsty"
                  :min-width="item.minwidthsty"
                >
                  <template slot-scope="{row}">
                      <!-- 公开状态 -->
                      <span v-if="item.key==='PublicStatus'">
                         {{ publicStatusLabel.get(row.PublicStatus) }}
                      </span>

                      <span v-else>{{ row[item.key] }}</span>
                  </template>
                </el-table-column>
              </el-table>

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

          <div class="type-wrap">
            <label class="el-form-item__label">移动至新分类</label>
            <cascader
								v-model="filterObj.newClassify"
								:options="classifyOption"
								clearable
								placeholder="选择新分类"
                style="width: 240px"
								:config="{ checkStrictly: true,emitPath:false }"
							/>
          </div>

          <div class="bot">
            <el-button type="primary" plain @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleConfirm">确定</el-button>
          </div>
      </div>
  </el-dialog>
</template>

<script>
import mPage from '@/components/mPage.vue'
import { dataBaseInterface } from '@/api/api.js';
import { edbBaseV2Interface,chartBaseV2Interface } from '@/api/modules/chartApi';
import { getComputedTypes } from '../databaseComponents/util';
export default {
    components:{ mPage, },
    props:{
      show:{
          type: Boolean
      },
      source: { //指标或图库
        type: String,
        default: 'edb'
      },
      type: { //设置类型 设置共享shared 设置公开public
			  type: Number
		  },
      classifyShowType: { //分类类型 own  public
        type: String
      }
    },
    computed:{
      // 最大添加指标的上限
      MAXAddNUM(){
          let num=100
          return num
      },

      tableColumns() {
        let columns = [
          {
            label: '指标名称',
            key: 'EdbName',
            minwidthsty: '250px',
            show: this.source==='edb'
          },
          {
            label: '图表名称',
            key: 'ChartName',
            minwidthsty: '250px',
            show: this.source==='chart'
          },
          {
            label: '分类',
            key: 'ClassifyName',
            show: true
          },
          {
            label: '图表类型',
            key: 'Source',
            show: this.source==='chart'
          },
          {
            label: '计算方式',
            key: 'SourceName',
            widthsty:'100px',
            show: this.source==='edb'
          },
        ]

        let filterColumns = columns.filter(_ => _.show);

        return filterColumns;
      },

      sourceLabel() {
        return this.source==='edb'?'指标':'图表';
      },

      cascaderProps() {
        return {
            label: 'ClassifyName',
            value: 'ClassifyId',
            children: 'Children',
            multiple: true,
            emitPath: false,
            checkStrictly: !this.filterObj.relevanceChild
        }
      },
      
      Idkey() {
        return this.source==='edb'?'EdbInfoId':'ChartInfoId';
      },
    },
    watch: {
      show(n){
        if(!n) return
        
        this.getClassifyOpts();
        this.$nextTick(() => {
          this.getList('init');
        })
      }
    },
    data() {
      return {
        filterObj: {
          classify: [],
          relevanceChild:true,
          pageNo: 1,
          pageSize: 20,
          source: [],
          chartTypes: [],
          keyWord: '',
          checkAll: false, //控制全选显示状态
          checkSome: false,
          newClassify: ''
        },
        sourceOption: getComputedTypes(),
        classifyOption: [],
        cascaderKey:0,

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

      //目录 指标/图库
      async getClassifyOpts() {
        let res;
        if(this.source === 'edb') { //指标
          res = this.classifyShowType==='own'
              ? await dataBaseInterface.menuListV3({ClassifyType: 2})
              : await edbBaseV2Interface.getPublicClassifyBase()
        }else {//图库
          res = this.classifyShowType==='own'
              ? await dataBaseInterface.chartClassify()
              : await chartBaseV2Interface.getPublicClassifyBase()
        }

        if(res.Ret!==200) return 

        this.classifyOption = res.Data.AllNodes || [];
        this.filterNodes(this.classifyOption)
      },

      filterNodes(arr) {
        arr.length && arr.forEach(item => {
          item.Children && item.Children.length && this.filterNodes(item.Children)
          if(!item.Children.length) {
            delete item.Children
          }
        })
      },

      async getList(type='pageChange') {
        let apiMap = {
          'edb': this.getEdbList,
          'chart': this.getChartList
        }
        apiMap[this.source](type)
      },

      //指标列表
      async getEdbList(type) {
        const { 
          pageNo,
          pageSize,
          source,
          keyWord,
        } = this.filterObj;

        let checkedClassify = this.$refs.classifyRef.getCheckedNodes();
        let ClassifyIdList = checkedClassify.length 
          ? checkedClassify.map(_ => _.data.ClassifyId)
          : []

        const res = this.classifyShowType === 'own'
          ? await dataBaseInterface.targetSearchByPage({
              PageSize:pageSize,
              Source: source.join(','),
              CurrentIndex:pageNo,
              ClassifyId:ClassifyIdList.join(','),
              KeyWord: keyWord,
              EdbType: 2,
              EdbAuth: 1
          })
          : await edbBaseV2Interface.getPublicSearchList({
              EdbPublicList: [3],
              SourceList:source,
              Keyword: keyWord,
              ClassifyIdList,
              CurrentIndex: pageNo,
              PageSize: pageSize
          })

        if(res.Ret !== 200) return
        this.list = res.Data.List||[];
        this.total = res.Data.Paging.Totals;

        if(type==='filter'){
          this.listCheckAllChange(true)
        }else {
          //页码变化 选中项不做清空
          this.checkedSomeSelection()
        }

      },

      //图表列表
      async getChartList() {

      },

      handleFilter(val) {
        this.filterObj.pageNo = 1;
        if(!val||!val.length) {
          this.isSelectAll = false;
          this.checkedList = [];
          this.filterObj.checkAll = false;
          this.filterObj.checkSome = false;
        }
        this.getList((val.length)?'filter':'');
      },

      async handleConfirm() {
        const {
          source,
          keyWord,
          newClassify
        } = this.filterObj;
        let checkedClassify = this.$refs.classifyRef.getCheckedNodes();
        let ClassifyIdList = checkedClassify.length 
          ? checkedClassify.map(_ => _.data.ClassifyId)
          : [];
        
        let res;
        if(this.source === 'edb') { //指标

          let params = {
            SourceList:source,
            Keyword: keyWord,
            ClassifyIdList,
            IsSelectAll: this.isSelectAll,
            NoEdbIdList: this.isSelectAll ? this.checkedList.map(_ =>_.EdbInfoId) : [],
            EdbIdList: this.isSelectAll ? [] : this.checkedList.map(_ =>_.EdbInfoId),
            NewClassifyId: newClassify
          }
          res = this.classifyShowType==='own'
              ? await edbBaseV2Interface.moveOwnBatch(params)
              : await edbBaseV2Interface.movePublicBatch(params)
        }else {//图库
          let params = {
            Keyword: keyWord,
            ClassifyIdList,
            IsSelectAll: this.isSelectAll,
            NoChartIdList: this.isSelectAll ? this.checkedList.map(_ =>_.ChartInfoId) : [],
            ChartIdList: this.isSelectAll ? [] : this.checkedList.map(_ =>_.ChartInfoId),
            NewClassifyId: newClassify
          }
          res = this.classifyShowType==='own'
              ? await chartBaseV2Interface.moveOwnBatch(params)
              : await chartBaseV2Interface.movePublicBatch(params)
        }

        if(res.Ret!==200) return 
        this.$message.success('移动成功')
        this.handleClose();
        this.$emit('confirm')
      },

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

        if(!this.isSelectAll){
            this.checkedList.map(_ =>{
                let row = this.list.find(item => item[this.Idkey]==_[this.Idkey])
                if(row){ //设置部分选中
                    setTimeout(()=>{
                        this.$refs.table.toggleRowSelection(row,true)
                    },20)
                }
            })
        }else{
            this.$refs.table &&this.$refs.table.toggleAllSelection()
            this.checkedList.map(_ =>{
                let row = this.list.find(item => item[this.Idkey]==_[this.Idkey])
                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(_ => _[this.Idkey] === row[this.Idkey]);

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

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

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

            let pageIds = this.list.map(_ => _[this.Idkey]);
            this.checkedList = this.checkedList.filter(_ => !pageIds.includes(_[this.Idkey]))
          }
      },

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

      handleClose() {
        this.filterObj = {
          classify: [],
          relevanceChild:true,
          pageNo: 1,
          pageSize: 10,
          source: [],
          chartTypes: [],
          keyWord: '',
          checkAll: false, //控制全选显示状态
          checkSome: false,
          newClassify:''
        }
        this.list = [];
        this.isSelectAll = false;
        this.checkedList = [];
        this.selectionReactCancel =false;
        this.$emit('update:show',false)
      }
    },
}
</script>

<style lang="scss" scoped>
.batch-move-dialog{
    max-width: 1200px;
    width:90vw;
	  overflow: hidden;
}
.list-wrap{
    .type-wrap{
        display: flex;
    }
    .table-wrap{
        margin-top: 20px;
    }
    .filter-wrap {
      margin-top: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      gap: 10px;
      >div {
        display: flex;
        align-items: center;
        gap: 10px;
      }
    }

    .bot {
      margin: 50px 0;
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 30px;
      .el-button {
        width: 120px;
      }
    }
}
</style>