<template>
    <!-- 数据源刷新设置 -->
    <div class="data-refresh-setting-wrap">
        <div class="top-top">
            <div class="tab-zone">
                <div class="tab-item" :class="item.value==settingTab?'active':''" v-for="item in tabList.filter(it => checkPer(it))" :key="item.value" @click="changeTab(item.value)">
                    {{ item.label }}
                </div>
            </div>
            <!-- <div class="refresh-rule-setting" v-if="settingTab=='status'">
                <el-button type="danger" plain @click="setEdbsRefreshStatus('暂停')" :disabled="!hasStatusSelection">{{$t('SystemManage.DataRefresh.disabled')}}</el-button>
                <el-button type="primary" plain @click="setEdbsRefreshStatus('启用')" :disabled="!hasStatusSelection">{{$t('SystemManage.DataRefresh.enabled')}}</el-button>
                <el-button type="primary" @click="openDefaultRefreshStatusDia">{{$t('SystemManage.DataRefresh.default_refresh_rule')}}</el-button>
            </div> -->
        </div>
        <!-- 刷新时间 -->
        <template v-if="settingTab=='time'">
            <div class="top-box">
                <div class="select-box">
                    <span>{{$t('SystemManage.DataRefresh.select_source')}}</span>
                    <el-select :placeholder="$t('SystemManage.DataRefresh.select_source_pld')" v-model="Source" @change="handleSourceChange">
                        <el-option v-for="item in SourceList" :key="item.Source" 
                        :label="item.SourceName" :value="item.Source"/>
                    </el-select>
                    <el-button type="primary" @click="showDialog(true)"
                        v-permission="permissionBtn.sysDepartPermission.refresh_default"
                    >{{$t('SystemManage.DataRefresh.default_time')}}</el-button>
                </div>
                
                <el-input :placeholder="$t('SystemManage.DataRefresh.indicator_name')" prefix-icon="el-icon-search" clearable
                    v-model="selectOption.keyWord" @input="selectOptionChange('keyWord')"
                    v-if="![34,11].includes(Source)&&Source"></el-input>
                
            </div>
            <div class="table-box" v-if="hasSelectOption">
                <div class="table-select" v-loading="selectOptionLoading">
                    <div class="select-list">
                        <!-- <el-select :placeholder="$t('SystemManage.DataRefresh.terminal_code_select')" :no-match-text="$t('SystemManage.DataRefresh.complete_data_source')" clearable
                            v-model="selectOption.terminalCode" @change="selectOptionChange('terminalCode')">
                            <el-option v-for="i in terminalCodeList" :key="i.TerminalCode"
                                :label="i.Name" :value="i.TerminalCode"/>
                        </el-select> -->
                        <el-cascader placeholder="数据查看分类" :no-match-text="$t('SystemManage.DataRefresh.complete_data_source')" clearable
                            v-model="selectOption.classify" @change="selectOptionChange('classify')"
                            :options="edbClassifyList" 
                            :show-all-levels="false"
                            collapse-tags
                            :props="{
                                emitPath:true,
                                value:'ClassifyId',
                                label:'ClassifyName',
                                children:'Children',
                                multiple:true
                            }" />
                        <!-- <el-cascader
                            :placeholder="$t('SystemManage.DataRefresh.table_creator')" :no-match-text="$t('SystemManage.DataRefresh.complete_data_source')" style="height: 40px;"
                            v-model="selectOption.user" @change="selectOptionChange('user')"
                            :options="userList"
                            :props="{
                                value: 'ItemId',
                                label: 'ItemName',
                                children: 'Children',
                                emitPath: false,
                                multiple:true,
                            }"
                            collapse-tags
                            :show-all-levels="false"
                            clearable
                            filterable 
                        /> -->
                        <el-select :placeholder="table_frequency" v-model="selectOption.frequency" @change="selectOptionChange('frequency')" multiple collapse-tags clearable>
                            <el-option v-for="i in frequencyList" :key="i.value"
                                :label="i.label" :value="i.value"
                            />
                        </el-select>
                        <!-- <el-select :placeholder="$t('SystemManage.DataRefresh.table_status')" v-model="selectOption.state" @change="selectOptionChange('state')" clearable>
                            <el-option :label="$t('SystemManage.DataRefresh.enable_op')" value="启用"/>
                            <el-option :label="$t('SystemManage.DataRefresh.pause_op')" value="暂停"/>
                        </el-select> -->
                    </div>
                    <div class="select-other">
                        <el-checkbox :indeterminate="isIndeterminate" v-model="isCheckAll" @change="listCheckAllChange">{{$t('SystemManage.DataRefresh.all_list')}}</el-checkbox>
                        <el-button type="primary" @click="showDialog(false)"
                            v-permission="permissionBtn.sysDepartPermission.refresh_time"
                            :disabled="!tableData.length"
                        >{{$t('SystemManage.DataRefresh.set_time')}}</el-button>
                        <!-- <el-button type="primary" @click="isSetStateDialogShow=true"
                            v-permission="permissionBtn.sysDepartPermission.refresh_state"
                            v-if="Source!=2"
                            :disabled="!tableData.length"
                        >{{$t('SystemManage.DataRefresh.set_status')}}</el-button> -->
                    </div>
                </div>
                <el-table :data="tableData" border
                    ref="edbDataRef"
                    @selection-change="selectionChange"
                    @select="selectHandle" 
                    @select-all="selectAllHandle"
                    @sort-change="handleSortChange"
                    >
                    <!-- 多选 -->
                    <el-table-column
                        align="center"
                        type="selection"
                        width="55">
                    </el-table-column>
                    <el-table-column v-for="column in columns" :key="column.key"
                        :prop="column.key"
                        :label="column.label"
                        :min-width="column.minWidth"
                        :sortable="column.sortable?column.sortable:false"
                        align="center"
                        >
                        <template slot-scope="{row}">
                            <span v-if="column.key==='IsStop'">
                                {{row.IsStop? $t('SystemManage.DataRefresh.pause_op') : $t('SystemManage.DataRefresh.enable_op') }}
                            </span>
                            <span v-else-if="column.key==='EndDate'">
                                {{row.EndDate ? row.EndDate.substring(0,10) : ''}}
                            </span>
                            <span v-else>
                                {{row[column.key]}}
                            </span>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination 
                    :current-page="currentPage"
                    :page-size="pageSize"
                    :total="total"
                    @current-change="handleCurrentChange"
                />
            </div>
        </template>
        <!-- 刷新状态 - 全拆开吧 -->
         <!-- 刷新规则不要了 -->
        <!-- 默认刷新时间，设置刷新时间 -->
        <el-dialog custom-class="refresh-setting-dialog"
            :title="dlgTextLangShow((isDefault?'默认':'设置')+'刷新时间')"
            :visible.sync="isSetTimeDialogShow"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
            @close="isSetTimeDialogShow=false"
            width="578px"
            top="5vh"
            v-dialogDrag
            center
        >
            <div class="dialog-container" v-loading="defaultDialogLoading">
                <!-- 默认刷新时间设置数据频度 -->
                <div class="default-box" v-if="isDefault&&Source!==11">
                    <label style="display: block;width:88px;text-align:right;padding-right: 12px;">{{$t('SystemManage.DataRefresh.data_frequency')}}</label>
                    <el-select style="margin-left: 10px;" v-model="defaultFrequency" @change="handleDefaultChange">
                        <el-option v-for="i in frequencyList" :key="i.value"
                            :label="i.label" :value="i.value"
                        />
                    </el-select>
                </div>
                <!-- 刷新配置 -->
                <div class="refresh-box">
                    <RefreshConfig
                        ref="refreshconfig"
                        :Source="Source"
                        :defaultForm="defaultForm"
                    ></RefreshConfig>
                </div>
                
            </div>
            <!-- 弹窗按钮 -->
            <div class="dialog-btn">
                <el-button type="primary" plain @click="isSetTimeDialogShow=false">{{$t('Dialog.cancel_btn')}}</el-button>
                <el-button type="primary" @click="handleSetRefreshTime">{{$t('Dialog.confirm_btn')}}</el-button>
            </div>
        </el-dialog>
        <!-- 设置刷新状态 -->
        <el-dialog custom-class="refresh-setting-dialog"
            :title="$t('SystemManage.DataRefresh.set_status')"
            :visible.sync="isSetStateDialogShow"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
            @close="isSetStateDialogShow=false"
            width="578px"
            top="5vh"
            v-dialogDrag
            center
        >
            <div class="dialog-container" style="text-align: center;margin:60px 0;">
                <el-radio label="暂停" v-model="isState">{{$t('SystemManage.DataRefresh.pause_op')}}</el-radio>
                <el-radio label="启用" v-model="isState">{{$t('SystemManage.DataRefresh.enable_op')}}</el-radio>
            </div>
            <!-- 弹窗按钮 -->
            <div class="dialog-btn">
                <el-button type="primary" plain @click="isSetStateDialogShow=false">{{$t('Dialog.cancel_btn')}}</el-button>
                <el-button type="primary" @click="setRefreshStatus">{{$t('Dialog.confirm_btn')}}</el-button>
            </div>
        </el-dialog>

        <!-- 默认刷新规则 -->
        <defaultRefreshStatusDia :show.sync="setDefaultRefreshStatusShow" :ruleData="settingRuleForm" @setRule="setDefaultRefreshRule"/>
        <referenceCountDia :show.sync="referenceCountShow" :dataList="statusEdbRelationDetailList" />
    </div>
</template>

<script>
import RefreshConfig from './components/refreshConfig.vue';
import { dataBaseInterface } from '@/api/api.js';
import {dataRefreshInterface,dataAuthInterface} from '@/api/modules/dataApi.js';
import defaultRefreshStatusDia from './components/defaultRefreshStatusDia.vue';
import referenceCountDia from './components/referenceCountDia.vue';
export default {
    components: { RefreshConfig ,defaultRefreshStatusDia,referenceCountDia},
    computed:{
        frequencyList() {
            return [
                {
                value: "日度",
                label: /* '日度'  */ this.$t("Edb.FreAll.day"),
                },
                {
                value: "周度",
                label: /* '周度' */ this.$t("Edb.FreAll.week"),
                },
                {
                value: "旬度",
                label: /* '旬度' */ this.$t("Edb.FreAll.dekad"),
                },
                {
                value: "月度",
                label: /* '月度' */ this.$t("Edb.FreAll.month"),
                },
                {
                value: "季度",
                label: /* '季度' */ this.$t("Edb.FreAll.quarter"),
                },
                {
                value: "半年度",
                label: /* '半年度' */ this.$t("Edb.FreAll.half_year"),
                },
                {
                value: "年度",
                label: /* '年度' */ this.$t("Edb.FreAll.year"),
                },
            ];
        },
        columns() {
            return [
                { key: "IndexCode", label:/* '指标编码' */ this.$t('SystemManage.DataRefresh.table_code')},
                { key: "IndexName", label:/* '指标全称' */ this.$t('SystemManage.DataRefresh.table_name'), minWidth: 150 },
                { key: "EndDate", label:/* '最新日期' */ this.$t('SystemManage.DataRefresh.table_date'), sortable: "custom" },
                { key: "EndValue", label:/* '最新值' */ this.$t('SystemManage.DataRefresh.table_value')},
                // { key: "SysUserRealName", label:/* '创建人' */ this.$t('SystemManage.DataRefresh.table_creator') },
                { key: "Frequency", label:/* '频度' */ this.$t('SystemManage.DataRefresh.table_frequency') },
                { key: "RefreshTime", label:/* '刷新时间' */ this.$t('SystemManage.DataRefresh.table_time'), minWidth: 150 },
                // { key: "IsStop", label:/* '刷新状态' */ this.$t('SystemManage.DataRefresh.table_status')},
            ];
        },
        tabList(){
            return [
                { value: "time", label:/* '刷新时间设置' */ this.$t('SystemManage.DataRefresh.time_setting_tab')},
                // { value: "status", label:/* '刷新状态设置' */ this.$t('SystemManage.DataRefresh.status_setting_tab')}
            ];  
        },
        hasStatusSelection(){
            if(this.statusDataSelectionItem.isSelectAll){
                return this.statusDataTotal - (this.statusDataSelectionItem.selectList ? this.statusDataSelectionItem.selectList.length : 0)
            }else{
                return this.statusDataSelectionItem.selectList ? this.statusDataSelectionItem.selectList.length : 0
            }
        }
    },
    data() {
        return {
            settingTab:'time',
            Source:'',
            SourceList:[],

            terminalCodeList:[],
            edbClassifyList:[],
            userList:[],

            selectOption:{
                frequency:'',//频度
                user:'',//创建人
                classify:'',//分类
                state:'',//状态
                terminalCode:'',//终端编码
                keyWord:'',//关键字
                sortType:'',//升序降序
                sortParam:'',//排序字段
            },
            hasSelectOption:false,
            selectOptionLoading:false,

            
            tableData: [],
            tableDataIds:[],
            pageSize:10,
            currentPage:1,
            total:0,

            isSetTimeDialogShow: false,//设置刷新时间弹窗
            defaultDialogLoading:false,//可能需要获取默认设置，增加loading
            isDefault:false,//是否是默认刷新时间
            defaultForm:{},//默认刷新时间的配置
            defaultFrequency:'日度',//默认刷新时间的频率

            isSetStateDialogShow:false,//设置刷新状态弹窗
            isState:'启用',//启用刷新or暂停刷新
            //全部全选
            isIndeterminate:false,
            isCheckAll:false,
            isSelectAll:false,//为true时，selectList是剔除的指标，为false时selectList是已选择的指标
            //已选择/已剔除的指标id
            selectList:[],//监听table的select-all select
            selectionReactCancel:false,

            // 刷新状态设置 
            settingRuleForm:{},
            setDefaultRefreshStatusShow:false,
            referenceCountShow:false,
            statusSourceList:[],
            statusEdbClassifyList:[],
            searchParams:{
                Source:'',
                Status:'',
                Frequency:'',
                SysUserId:'',
                ClassifyId:'',
                SortType:'',//排序类型
                SortParam:'',//排序字段
                Keyword:"",
                PageSize:10,
                CurrentIndex:1
            },
            SysUserIdArr:[],
            stopUserIdRequest:false, //阻止watch中的请求
            ClassifyIdArr:[],
            stopClassifyIdRequest:false, //阻止watch中的请求
            FrequencyArr:[],
            stopFrequencyArrRequest:false, //阻止watch中的请求
            statusTableData:[],
            statusTableDataIds:[],
            statusDataTotal:0,
            statusEdbRelationDetailList:[],
            statusDataSelectionItem:{
                isIndeterminate:false,
                isCheckAll:false,
                selectionReactCancel:false,
                isSelectAll:false,//为true时，selectList是剔除的指标，为false时selectList是已选择的指标
                //已选择/已剔除的指标id
                selectList:[],//监听table的select-all select
            }
        };
    },
    watch:{
        SysUserIdArr(value){
            if(value&&value.length>0){
                this.searchParams.SysUserId=value.join(',')
            }else{
                this.searchParams.SysUserId=''
            }
            if(!this.stopUserIdRequest){
                this.searchList()
            }else{
                this.stopUserIdRequest=false
            }
            
        },
        ClassifyIdArr(value){
            if(value&&value.length>0){
                this.searchParams.ClassifyId=value.join(',')
            }else{
                this.searchParams.ClassifyId=''
            }
            if(!this.stopClassifyIdRequest){
                this.searchList()
            }else{
                this.stopClassifyIdRequest=false
            }
        },
        FrequencyArr(value){
            if(value&&value.length>0){
                this.searchParams.Frequency=value.join(',')
            }else{
                this.searchParams.Frequency=''
            }
            if(!this.stopFrequencyArrRequest){
                this.searchList()
            }else{
                this.stopFrequencyArrRequest=false
            }
        },
        'searchParams.Source':{
            handler:function (value) {
                if(!value) return
                this.searchParams.Status=''
                // this.searchParams.Frequency=''
                // this.searchParams.ClassifyId=''
                // this.searchParams.SysUserId=''
                this.FrequencyArr=[]
                this.stopFrequencyArrRequest=true
                this.ClassifyIdArr=[]
                this.stopClassifyIdRequest=true
                this.SysUserIdArr=[]
                this.stopUserIdRequest=true
                this.searchParams.SortType=''
                this.searchParams.SortParam=''
                this.searchParams.Keyword=''
                this.getStatusClassifyList()
                if(this.settingTab=='status') this.searchList()
            }
        }
    },
    methods: {
        checkPer(it){
            if(it.value == 'status'){
                // 同 设置刷新状态的权限按钮 控制整个刷新状态设置tab
                return this.permissionBtn.isShowBtn('sysDepartPermission','refresh_state')
            }
            return true
        },
        changeTab(e){
            this.settingTab=e||'time'
            if(this.settingTab=='time'){
                this.$nextTick(()=>{
                    this.$refs.edbDataRef && this.adjustSelection()
                })
            }else{
                if(!(this.statusTableData && this.statusTableData.length>0)){
                    this.searchList()
                }else{
                    this.$nextTick(()=>{
                        this.$refs.statusTableRef && this.adjustStatusSelection()
                    })
                }
            }
        },
        //展示刷新时间弹窗
        showDialog(isDefault){
            this.isDefault = isDefault
            this.isSetTimeDialogShow = true
            if(isDefault){
                //判断数据源是否选择
                if(!this.Source){
                    // this.$message.warning("请选择数据源")
                    this.$message.warning(this.$t('SystemManage.DataRefresh.select_source_pld'))
                    return
                }
                //SMM不带频度
                if(this.Source===11){
                    this.defaultFrequency=''
                }else{
                    this.defaultFrequency = '日度'
                }
                this.handleDefaultChange()
            }else{
                //单独设置指标，需判断指标是否为单个
                if((this.total===1&&!this.selectList.length)||(!this.isSelectAll&&this.selectList.length===1)){
                    //单个则回显刷新时间
                    this.getEdbRefreshDetail()
                }else{
                    this.defaultForm={}
                }
                
            }
        },
        //获取对应频度下的默认刷新时间
        handleDefaultChange(){
            this.defaultDialogLoading = true
            dataRefreshInterface.getDefaultConfig({
                Frequency:this.defaultFrequency,
                Source:Number(this.Source),
            }).then(res=>{
                this.defaultDialogLoading = false
                if(res.Ret!==200) return 
                let configList = res.Data||[]
                configList = configList.map((item,index)=>{
                    return {
                        ...item,
                        key:index
                    }
                })
                this.defaultForm = {
                    configList
                }
            })
        },
        //获取单个指标的刷新时间
        getEdbRefreshDetail(){
            this.defaultDialogLoading = true
            let EdbInfoId = 0
            if(this.total===1){
                EdbInfoId = this.tableData[0].EdbInfoId
            }else{
                EdbInfoId = this.selectList[0]
            }
            dataRefreshInterface.getSimgleEdbRefreshTime({
                EdbInfoId,
                Source:Number(this.Source),
            }).then(res=>{
                this.defaultDialogLoading = false
                if(res.Ret!==200) return 
                let configList = res.Data||[]
                configList = configList.map((item,index)=>{
                    return {
                        ...item,
                        key:index
                    }
                })
                this.defaultForm = {
                    configList
                }
            })
        },
        //获取数据源列表
        getSourceList(){
            dataBaseInterface.getDataSource({IsBase:1}).then(res=>{
                if(res.Ret!==200) return 
                this.SourceList = res.Data||[]
                // 页面修改太麻烦了重复的太多了直接该数据了
                this.SourceList = this.SourceList.map(item => {
                    return {
                        ...item,
                        Source:item.EdbSourceId
                    }
                })
                this.statusSourceList=this.SourceList.filter(it => [2,34].includes(it.Source)).concat([
                    {Source:-1,SourceName:"计算指标"}
                ])
                this.searchParams.Source = this.statusSourceList[0]?this.statusSourceList[0].Source:''
            })
        },
        //一级数据源改变时，二级数据源和筛选项也重新赋值
        handleSourceChange(){
            const source = this.SourceList.find(i=>i.Source===this.Source)||{Child:[]}
            this.hasSelectOption = true
            if(this.hasSelectOption){
                this.resetSelect()
                this.tableData = []
            }
            this.getSelectOption()
            this.selectOptionChange()
        },
        handleSubSourceChange(){
            this.getSelectOption()
            this.selectOptionChange()
        },
        //获取终端编码列表
        async getTerminalCodeList(){
            if(!this.Source) return 
            const res = await dataRefreshInterface.getTerminalList({
                Source:Number(this.Source)
            })
            if(res.Ret!==200) return 
            this.terminalCodeList = res.Data?res.Data.List||[]:[]
        },
        //获取分类列表
        async getClassifyList(){
            if(!this.Source) return 
            const res = await dataRefreshInterface.getClassifyList({
                Source:Number(this.Source)
            })
            if(res.Ret!==200) return 
            this.edbClassifyList = res.Data||[]
        },
        //获取用户列表
        getUserList() {
            dataAuthInterface.userSearch({
                KeyWord: ''
            }).then(res => {
                if(res.Ret !== 200) return 
                this.userList = res.Data||[]
            })
        },
        async getSelectOption(){
            this.selectOptionLoading = true
            //获取终端编码列表
            await this.getClassifyList()
            //获取分类列表
            await this.getTerminalCodeList()
            this.selectOptionLoading = false
        },
        //切换数据源时重置表格选项
        resetSelect(){
            this.terminalCodeList=[]
            this.edbClassifyList = []
            this.selectOption = {
                frequency:'',
                user:'',
                classify:'',
                state:'',
                terminalCode:''
            }
            this.selectList=[]
        },
        //表格筛选项改变时触发
        selectOptionChange(type){
            this.currentPage = 1
            this.getTableData('optionChange')
        },
        handleCurrentChange(page){
            this.currentPage = page
            this.getTableData()
        },
        async getTableData(type){
            const {frequency,user,classify,state,terminalCode,keyWord,sortParam,sortType} = this.selectOption
            console.log(this.selectOption);
            
            const classifyArr = Array.isArray(classify)?classify:[]
            const classifyId = [...new Set(classifyArr.join(',').split(','))]
            const res = await dataRefreshInterface.getEdbTableList({
                Source:Number(this.Source),
                ClassifyId:classifyId.join(','),
                TerminalCode:terminalCode,
                SysUserId:Array.isArray(user)?user.join(','):user,
                Frequency:Array.isArray(frequency)?frequency.join(','):frequency,
                Keyword:keyWord,
                Status:state,
                SortParam:sortParam,
                SortType:sortType,
                PageSize:Number(this.pageSize),
                CurrentIndex:Number(this.currentPage)
            })
            if(res.Ret!==200) return 
            const {Paging,List} = res.Data||{}
            this.tableData = List||[]
            this.total = Paging.Totals||0
            if(this.tableData.length>0){
              this.tableDataIds = this.tableData.map(it => it.EdbInfoId)
            }else{
              this.tableDataIds = []
            }
            if(type==='optionChange'){
                //如果是表格筛选项改变导致重新请求数据
                //数据获取完成后，列表全选，表格全选
                this.selectList = []
                this.listCheckAllChange(true)
            }else{
                //若不是，数据获取完成后，查询列表全选的值
                //若当页有数据在selectList内，则勾选/剔除
                this.adjustSelection()
            }
        },
        //勾选/取消勾选表格项
        adjustSelection(){
            this.selectionReactCancel=true
            if(!this.isSelectAll){
                this.selectList.map(it =>{
                    let row = this.tableData.find(da => da.EdbInfoId==it)
                    if(row){
                        setTimeout(()=>{
                            this.$refs.edbDataRef && this.$refs.edbDataRef.toggleRowSelection(row,true)
                        },10)
                    }
                })
            }else{
                this.$refs.edbDataRef && this.$refs.edbDataRef.clearSelection()
                this.$refs.edbDataRef &&this.$refs.edbDataRef.toggleAllSelection()
                this.selectList.map(it =>{
                    let row = this.tableData.find(da => da.EdbInfoId==it)
                    if(row){
                        setTimeout(()=>{
                            this.$refs.edbDataRef && this.$refs.edbDataRef.toggleRowSelection(row,false)
                        },50)
                    }
                })
            }
            setTimeout(()=>{
                this.selectionReactCancel=false
            },50)
        },
        //列表全选改变
        listCheckAllChange(value){
            this.selectList = []
            this.isSelectAll = value
            this.$refs.edbDataRef && this.$refs.edbDataRef.clearSelection()
            if(value){
                this.$refs.edbDataRef && this.$refs.edbDataRef.toggleAllSelection()
            }
        },
        selectionChange(selection){
            if(this.selectionReactCancel) return 
            // selectAllHandle的触发在selectionChange后面，将selectionChange的逻辑延迟一下
            setTimeout(()=>{
                // 去重
                let duplicateArr = Array.from(new Set(this.selectList))
                //isSelectAll为true时，selectList表示需要剔除的项
                //isSelectAll为false时，selectList表示需要勾选的项
                //全选
                if((duplicateArr.length == this.total && (!this.isSelectAll))|| (duplicateArr.length == 0 && this.isSelectAll)){
                    this.isCheckAll = true
                    this.isIndeterminate=false
                //全不选
                }else if((duplicateArr.length == 0 && (!this.isSelectAll))|| (duplicateArr.length == this.total && this.isSelectAll)){
                    this.isCheckAll = false
                    this.isIndeterminate=false
                //半选
                }else{
                    this.isCheckAll = false
                    this.isIndeterminate=true
                }
            },1)
        },
        selectHandle(selection,row){
            if(this.selectionReactCancel) return 
            let check = false; 
            if(selection.some(it => it.EdbInfoId == row.EdbInfoId)){
                // 勾选
                if(this.isSelectAll){
                    check=false
                }else{
                    check=true
                }
            }else{
                // 取消勾选
                if(this.isSelectAll){
                    check=true
                }else{
                    check=false
                }
            }
            if(check){
                this.selectList.push(row.EdbInfoId)
                }else{
                this.selectList=this.selectList.filter(it => it!=row.EdbInfoId)
            }
        },
        selectAllHandle(selection){
            if(this.selectionReactCancel) return 
            let check = false; 
            if(selection && selection.length>0){
                // 全选
                if(this.isSelectAll){
                    check=false
                }else{
                    check=true
                }
            }else{
                // 全不选
                if(this.isSelectAll){
                    check=true
                }else{
                    check=false
                }
            }
            if(check){
                this.selectList =  [...this.selectList,...this.tableDataIds]
            }else{
                this.selectList = this.selectList.filter(it => !this.tableDataIds.includes(it))
            }
        },
        //设置刷新时间
        async handleSetRefreshTime(){
            //校验表格
            try{
                await this.$refs.refreshconfig.$refs.dynamicForm.validate()
            }catch(e){
                console.log(e)
                return
            }
            //转换数据格式
            const list = this.$refs.refreshconfig.getFormList()
            //判断是否是默认时间，走不同接口
            if(this.isDefault){
                this.setDefaultTime(list)
            }else{
                this.setRefreshTime(list)
            }
        },
        setRefreshTime(list){
            const {frequency,user,classify,state,terminalCode,keyWord} = this.selectOption
            const classifyArr = Array.isArray(classify)?classify:[]
            const classifyId = [...new Set(classifyArr.join(',').split(','))]
            dataRefreshInterface.setRefreshTime({
                Source:Number(this.Source),
                ClassifyId:classifyId.join(','),
                TerminalCode:terminalCode,
                SysUserId:Array.isArray(user)?user.join(','):user,
                Frequency:Array.isArray(frequency)?frequency.join(','):frequency,
                Keyword:keyWord,
                Status:state,
                IsSelectAll:this.isSelectAll,
                EdbSelectIdList:this.selectList,
                List:list
            }).then(res=>{
                if(res.Ret!==200) return
                // this.$message.success("设置刷新时间成功")
                this.$message.success(this.$t('SystemManage.DataRefresh.time_success_msg'))
                this.selectOptionChange()
                this.isSetTimeDialogShow = false
            })
        },
        setDefaultTime(list){
            dataRefreshInterface.setDefaultTime({
                Source:Number(this.Source),
                Frequency:this.defaultFrequency,
                List:list
            }).then(res=>{
                if(res.Ret!==200) return 
                // this.$message.success("设置默认刷新时间成功")
                this.$message.success(this.$t('SystemManage.DataRefresh.refresh_success_msg'))
                this.isSetTimeDialogShow = false
            })
        },
        setRefreshStatus(){
            const {frequency,user,classify,state,terminalCode,keyWord} = this.selectOption
            const classifyArr = Array.isArray(classify)?classify:[]
            const classifyId = [...new Set(classifyArr.join(',').split(','))]
            dataRefreshInterface.setRefreshStatus({
                Source:Number(this.Source),
                ClassifyId:classifyId.join(','),
                TerminalCode:terminalCode,
                SysUserId:Array.isArray(user)?user.join(','):user,
                Frequency:Array.isArray(frequency)?frequency.join(','):frequency,
                Keyword:keyWord,
                Status:state,
                IsSelectAll:this.isSelectAll,
                EdbSelectIdList:this.selectList,
                ModifyStatus:this.isState
            }).then(res=>{
                if(res.Ret!==200) return 
                this.$message.success(this.$t('SystemManage.DataRefresh.status_success_msg'))
                // this.$message.success("设置刷新状态成功")
                this.selectOptionChange()
                this.isSetStateDialogShow = false
            })
        },
        handleSortChange({prop,order}){
            if(order){
                this.selectOption.sortParam = 'end_date'
                this.selectOption.sortType = order==='ascending'?'asc':'desc'
            }else{
                this.selectOption.sortParam = ''
                this.selectOption.sortType = ''
            }
            this.selectOptionChange()
        },
        dlgTextLangShow(e){
            if(e==='默认刷新时间') return this.$t('SystemManage.DataRefresh.default_time')
            if(e==='设置刷新时间') return this.$t('SystemManage.DataRefresh.set_time')
            return e
        },
        // -----------------------------刷新状态设置
        //获取分类列表
        async getStatusClassifyList(){
            if(!this.searchParams.Source) return 
            const res = await dataRefreshInterface.getClassifyList({
                Source:2
            })
            if(res.Ret!==200) return 
            this.statusEdbClassifyList = res.Data||[]
        },
         getStatusDataList(type){
            dataRefreshInterface.getRelationEdbDataList(this.searchParams).then(res=>{
                if(res.Ret!==200) return 
                this.statusTableData=res.Data.List || []
                this.statusDataTotal=res.Data.Paging.Totals || this.statusTableData.length
                if(this.statusDataTotal>0){
                    this.statusTableDataIds = this.statusTableData.map(it => it.EdbInfoId)
                }else{
                    this.statusTableDataIds = []
                }
                if(type==='search'){
                    //如果是表格筛选项改变导致重新请求数据
                    //数据获取完成后，清空所选
                    this.statusDataSelectionItem.selectList = []
                    this.statusListCheckAllChange(false)
                }else{
                    //若不是，数据获取完成后，查询列表全选的值
                    //若当页有数据在selectList内，则勾选/剔除
                    this.adjustStatusSelection()
                }
            })
        },
        handleStatusListPageNoChange(page){
            this.searchParams.CurrentIndex = page
            this.getStatusDataList()
        },
        // 列表
        searchList(){
            this.searchParams.CurrentIndex=1
            this.getStatusDataList('search')
        },
        handleStatusTableSortChange({prop,order}){
            if(order){
                this.searchParams.SortParam = prop
                this.searchParams.SortType = order==='ascending'?'asc':'desc'
            }else{
                this.searchParams.SortParam = ''
                this.searchParams.SortType = ''
            }
            this.searchParams.CurrentIndex=1
            this.getStatusDataList()
        },
        //勾选/取消勾选表格项-刷新状态设置
        adjustStatusSelection(){
            this.statusDataSelectionItem.selectionReactCancel=true
            if(!this.statusDataSelectionItem.isSelectAll){
                this.statusDataSelectionItem.selectList.map(it =>{
                    let row = this.statusTableData.find(da => da.EdbInfoId==it)
                    if(row){
                        setTimeout(()=>{
                            this.$refs.statusTableRef && this.$refs.statusTableRef.toggleRowSelection(row,true)
                        },10)
                    }
                })
            }else{
                this.$refs.statusTableRef && this.$refs.statusTableRef.clearSelection()
                this.$refs.statusTableRef &&this.$refs.statusTableRef.toggleAllSelection()
                this.statusDataSelectionItem.selectList.map(it =>{
                    let row = this.statusTableData.find(da => da.EdbInfoId==it)
                    if(row){
                        setTimeout(()=>{
                            this.$refs.statusTableRef && this.$refs.statusTableRef.toggleRowSelection(row,false)
                        },50)
                    }
                })
            }
            setTimeout(()=>{
                this.statusDataSelectionItem.selectionReactCancel=false
            },50)
        },
        //列表全选改变-刷新状态设置
        statusListCheckAllChange(value){
            this.statusDataSelectionItem.selectList = []
            this.statusDataSelectionItem.isSelectAll = value
            this.$refs.statusTableRef && this.$refs.statusTableRef.clearSelection()
            if(value){
                this.$refs.statusTableRef && this.$refs.statusTableRef.toggleAllSelection()
            }
        },
        statusSelectionChange(selection){
            if(this.statusDataSelectionItem.selectionReactCancel) return 
            // selectAllHandle的触发在selectionChange后面，将selectionChange的逻辑延迟一下
            setTimeout(()=>{
                // 去重
                let duplicateArr = Array.from(new Set(this.statusDataSelectionItem.selectList))
                //isSelectAll为true时，selectList表示需要剔除的项
                //isSelectAll为false时，selectList表示需要勾选的项
                //全选
                if((duplicateArr.length == this.statusDataTotal && (!this.statusDataSelectionItem.isSelectAll)) 
                || (duplicateArr.length == 0 && this.statusDataSelectionItem.isSelectAll)){
                    this.statusDataSelectionItem.isCheckAll = true
                    this.statusDataSelectionItem.isIndeterminate=false
                //全不选
                }else if((duplicateArr.length == 0 && (!this.statusDataSelectionItem.isSelectAll)) 
                || (duplicateArr.length == this.statusDataTotal && this.statusDataSelectionItem.isSelectAll)){
                    this.statusDataSelectionItem.isCheckAll = false
                    this.statusDataSelectionItem.isIndeterminate=false
                //半选
                }else{
                    this.statusDataSelectionItem.isCheckAll = false
                    this.statusDataSelectionItem.isIndeterminate=true
                }
            },1)
        },
        statusSelectHandle(selection,row){
            if(this.statusDataSelectionItem.selectionReactCancel) return 
            let check = false; 
            if(selection.some(it => it.EdbInfoId == row.EdbInfoId)){
                // 勾选
                if(this.statusDataSelectionItem.isSelectAll){
                    check=false
                }else{
                    check=true
                }
            }else{
                // 取消勾选
                if(this.statusDataSelectionItem.isSelectAll){
                    check=true
                }else{
                    check=false
                }
            }
            if(check){
                this.statusDataSelectionItem.selectList.push(row.EdbInfoId)
                }else{
                this.statusDataSelectionItem.selectList=this.statusDataSelectionItem.selectList.filter(it => it!=row.EdbInfoId)
            }
        },
        statusSelectAllHandle(selection){
            if(this.statusDataSelectionItem.selectionReactCancel) return 
            let check = false; 
            if(selection && selection.length>0){
                // 全选
                if(this.statusDataSelectionItem.isSelectAll){
                    check=false
                }else{
                    check=true
                }
            }else{
                // 全不选
                if(this.statusDataSelectionItem.isSelectAll){
                    check=true
                }else{
                    check=false
                }
            }
            if(check){
                this.statusDataSelectionItem.selectList =  [...this.statusDataSelectionItem.selectList,...this.statusTableDataIds]
            }else{
                this.statusDataSelectionItem.selectList = this.statusDataSelectionItem.selectList.filter(it => !this.statusTableDataIds.includes(it))
            }
        },
        openReferenceCountDia(row){
            if(row.RelationNum==0) return 
            dataRefreshInterface.getRelationEdbDetail({EdbInfoId:row.EdbInfoId,CurrentIndex:1,PageSize:9999999}).then(res=>{
                if(res.Ret == 200){
                    this.statusEdbRelationDetailList=res.Data.List || []
                    this.referenceCountShow=true
                }
            })
        },
        async enableToggle(row){
            let isRequest=true
            if(!row.IsStop){
                isRequest=false
                await this.$confirm(this.$t('SystemManage.DataRefresh.disable_indicator_prompt'),this.$t('Confirm.prompt'),{
                    type:"warning"
                }).then(res=>{
                    isRequest=true
                }).catch(()=>{})
            }
            if(isRequest){
                dataBaseInterface.edbRefreshStatusSet({EdbInfoId:row.EdbInfoId,ModifyStatus:row.IsStop==1?'启用':'暂停'}).then(res=>{
                    if(res.Ret == 200){
                        row.IsStop=1-row.IsStop
                        this.$message.success(this.$t('MsgPrompt.operate_success_msg'))
                    }
                })
            }
        },
        async setEdbsRefreshStatus(state){
            let isRequest=true
            if(state=='暂停'){
                isRequest=false
                await this.$confirm(this.$t('SystemManage.DataRefresh.disable_indicator_prompt'),this.$t('Confirm.prompt'),{
                    type:"warning"
                }).then(res=>{
                    isRequest=true
                }).catch(()=>{})
            }
            if(!isRequest) return 
            
            let params={
                Source:Number(this.searchParams.Source),
                ClassifyId:this.searchParams.ClassifyId,
                SysUserId:this.searchParams.SysUserId,
                Frequency:this.searchParams.Frequency,
                Keyword:this.searchParams.Keyword,
                Status:this.searchParams.Status,
                IsSelectAll:this.statusDataSelectionItem.isSelectAll,
                EdbSelectIdList:this.statusDataSelectionItem.selectList,
                ModifyStatus:state
            }

            dataRefreshInterface.setRelationEdbsRefreshStatus(params).then(res=>{
                if(res.Ret == 200){
                    this.$message.success(this.$t('MsgPrompt.operate_success_msg'))
                    this.getStatusDataList()
                }
            })
        },
        openDefaultRefreshStatusDia(){
            dataRefreshInterface.getEdbStopRefreshRule({ConfKey:'EdbStopRefreshRule'}).then(res=>{
                if(res.Ret == 200){
                    this.settingRuleForm=res.Data.ConfVal?JSON.parse(res.Data.ConfVal):{}
                    this.setDefaultRefreshStatusShow=true
                }
            })
        },
        setDefaultRefreshRule(rule){
            let ruleText = rule?JSON.stringify({...rule,IsOpen:rule.IsOpen?1:0}):''
            dataRefreshInterface.setEdbStopRefreshRule({ConfKey:'EdbStopRefreshRule',ConfVal:ruleText}).then(res=>{
                if(res.Ret == 200){
                    this.$message.success(this.$t('MsgPrompt.operate_success_msg'))
                    this.setDefaultRefreshStatusShow=false
                }
            })
        },
    },
    mounted(){
        this.getSourceList()
        this.getUserList()
    }
};
</script>

<style scoped lang="scss">
.data-refresh-setting-wrap{
    min-height: calc(100vh - 120px);
    background-color: #fff;
    border:1px solid #C8CDD9;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    .top-top{
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom:solid 1px #E7E7E7 ;
        padding-right: 30px;
        height: 62px;
        .tab-zone{
            display: flex;
            align-items: center;
            flex: 1;
            height: 100%;
            .tab-item{
                cursor: pointer;
                color: #666666;
                padding: 0 16px;
                height: 100%;
                font-size: 16px;
                display: flex;
                align-items: center;
                box-sizing: border-box;
                border-bottom: solid 2px #ffffff;
            }
            .tab-item.active{
                color: #0052D9;
                border-bottom: solid 2px #0052D9;
            }
        }
    }
    .top-box,.table-box{
        box-sizing: border-box;
        padding:20px;
    }
    .top-box{
        // margin-bottom: 20px;
        display: flex;
        justify-content: space-between;
        .el-input{
            width:260px;
        }
        .select-box{
            .el-select{
                margin:0 20px;
            }
        }
    }
    .table-box{
        flex:1;
        .el-select{
            min-width:180px;
        }
        .table-select{
            display: flex;
            justify-content: space-between;
            .select-list{
                flex:1;
                display: flex;
                flex-wrap: wrap;
                gap:20px;
            }
            .select-other{
                .el-button{
                    margin-left:30px;
                }
            }
        }
        .el-table{
            margin:20px 0;
        }
        .el-pagination{
            text-align: right;
        }
    }
    .refresh-setting-dialog{
        margin-bottom: 0;
        .dialog-container{
            overflow: hidden;
            .default-box{
                display: flex;
                align-items: center;
                padding-bottom: 30px;
                margin-bottom: 30px;
                border-bottom: 1px solid #EBEFF6;
            }
            .refresh-box{
                max-height: 65vh;
                overflow-y: auto;
            }
        }
        .dialog-btn{
            text-align: center;
            padding: 25px 0;
        }
    }
    // 刷新状态设置
    .refresh-status-container{
        padding: 20px 30px;
        .refresh-status-search{
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            margin-left: -15px;
            margin-bottom: 12px;
            .select-source-box{
                display: flex;
                align-items: center;
                margin-left:15px;
                white-space: nowrap;
                margin-bottom: 8px;
                .el-select{
                    margin-left:15px;
                    margin-bottom: 0;
                }
            }
            .el-select{
                margin-left:15px;
                margin-bottom: 8px;
            }
            .refresh-status-search-left{
                display: flex;
                align-items: center;
                flex-wrap: wrap;
            }
            .select-item-small{
                max-width: 140px;
                margin-bottom: 8px;
                margin-left:15px;
            }
            .selection-box{
                margin-bottom: 8px;
                margin-left:15px;
                white-space: nowrap;
                span{
                    margin-left: 12px;
                }
            }
        }
        .el-table{
            margin:12px 0 20px;
        }
        .table-text-button{
            cursor: pointer;
            color: #0052D9;
            padding: 0 4px;
        }
        .el-pagination{
            text-align: right;
        }
    }
}
</style>