<template>
    <!-- 数据源刷新设置 -->
    <div class="data-refresh-setting-wrap">
        <div class="top-box">
            <div class="select-box">
                <span>选择数据源</span>
                <el-select placeholder="请选择数据源" v-model="Source" @change="handleSourceChange">
                    <el-option v-for="item in SourceList" :key="item.Source" 
                    :label="item.SourceName" :value="item.Source"/>
                </el-select>
                <el-select placeholder="请选择数据源" v-model="SubSource" v-if="SubSourceList.length" @change="handleSubSourceChange">
                    <el-option v-for="item in SubSourceList" :key="item.Source" 
                    :label="item.SubSourceName" :value="item.SubSource"/>
                </el-select>
                <el-button type="primary" @click="showDialog(true)"
                    v-permission="permissionBtn.sysDepartPermission.refresh_default"
                >默认刷新时间</el-button>
            </div>
            
            <el-input placeholder="指标ID/指标名称" prefix-icon="el-icon-search" clearable
                v-model="selectOption.keyWord" @input="selectOptionChange('keyWord')"
                v-if="![34,11].includes(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="终端编码" no-match-text="请选择完整数据源" 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="ETA指标库分类" no-match-text="请选择完整数据源" clearable
                        v-model="selectOption.classify" @change="selectOptionChange('classify')"
                        :options="edbClassifyList"
                        :props="{
                            emitPath:false,
                            value:'ClassifyId',
                            label:'ClassifyName',
                            children:'Children'
                        }" />
                    <el-cascader
                        placeholder="创建人" no-match-text="请选择完整数据源" 
                        v-model="selectOption.user" @change="selectOptionChange('user')"
                        :options="userList"
                        :props="{
                            value: 'ItemId',
                            label: 'ItemName',
                            children: 'Children',
                            emitPath: false
                        }"
                        collapse-tags
                        :show-all-levels="false"
                        clearable
                        filterable 
                    />
                    <el-select placeholder="频度" v-model="selectOption.frequency" @change="selectOptionChange('frequency')" clearable>
                        <el-option v-for="i in frequencyList" :key="i"
                            :label="i" :value="i"
                        />
                    </el-select>
                    <el-select placeholder="刷新状态" v-model="selectOption.state" @change="selectOptionChange('state')" clearable>
                        <el-option label="启用刷新" value="启用"/>
                        <el-option label="暂停刷新" value="暂停"/>
                    </el-select>
                </div>
                <div class="select-other">
                    <el-checkbox :indeterminate="isIndeterminate" v-model="isCheckAll" @change="listCheckAllChange">列表全选</el-checkbox>
                    <el-button type="primary" @click="showDialog(false)"
                        v-permission="permissionBtn.sysDepartPermission.refresh_time"
                        :disabled="!tableData.length"
                    >设置刷新时间</el-button>
                    <el-button type="primary" @click="isSetStateDialogShow=true"
                        v-permission="permissionBtn.sysDepartPermission.refresh_state"
                        :disabled="!tableData.length"
                    >设置刷新状态</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?'暂停刷新':'启用刷新'}}
                        </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>
        <!-- 默认刷新时间，设置刷新时间 -->
        <el-dialog custom-class="refresh-setting-dialog"
            :title="(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;">数据频度</label>
                    <el-select style="margin-left: 10px;" v-model="defaultFrequency" @change="handleDefaultChange">
                        <el-option v-for="i in frequencyList" :key="i"
                            :label="i" :value="i"
                        />
                    </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">取消</el-button>
                <el-button type="primary" @click="handleSetRefreshTime">确定</el-button>
            </div>
        </el-dialog>
        <!-- 设置刷新状态 -->
        <el-dialog custom-class="refresh-setting-dialog"
            title="设置刷新状态"
            :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">暂停刷新</el-radio>
                <el-radio label="启用" v-model="isState">启用刷新</el-radio>
            </div>
            <!-- 弹窗按钮 -->
            <div class="dialog-btn">
                <el-button type="primary" plain @click="isSetStateDialogShow=false">取消</el-button>
                <el-button type="primary" @click="setRefreshStatus">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import RefreshConfig from './components/refreshConfig.vue';
import {dataRefreshInterface,dataAuthInterface} from '@/api/modules/dataApi.js';
export default {
    components: { RefreshConfig },
    data() {
        return {
            Source:'',
            SourceList:[],
            SubSource:'',
            SubSourceList:[],

            frequencyList:['日度','周度','旬度','月度','季度','半年度','年度'],
            terminalCodeList:[],
            edbClassifyList:[],
            userList:[],

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

            columns: [
                {key: 'EdbInfoId',label: '指标编码'},
                {key: 'IndexName',label: '指标全称'},
                {key: 'EndDate',label: '最新日期',sortable:'custom'},
                {key: 'EndValue',label: '最新值'},
                {key: 'SysUserRealName',label: '创建人'}, 
                {key: 'Frequency',label: '频度'},
                {key: 'RefreshTime',label: '刷新时间',minWidth:150},
                {key: 'IsStop',label: '刷新状态'}
            ],
            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,
        };
    },
    methods: {
        //展示刷新时间弹窗
        showDialog(isDefault){
            this.isDefault = isDefault
            this.isSetTimeDialogShow = true
            if(isDefault){
                //判断数据源是否选择
                if(!this.Source){
                    this.$message.warning("请选择数据源")
                    return
                }
                /* if(this.SubSourceList.length&&!this.SubSource){
                    this.$message.warning("请选择完整数据源")
                    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),
                SubSource:Number(this.SubSource)
            }).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),
                SubSource:Number(this.SubSource)
            }).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(){
            dataRefreshInterface.getDataSourceList().then(res=>{
                if(res.Ret!==200) return 
                this.SourceList = res.Data||[]
            })
        },
        //一级数据源改变时，二级数据源和筛选项也重新赋值
        handleSourceChange(){
            const source = this.SourceList.find(i=>i.Source===this.Source)||{Child:[]}
            this.SubSourceList = source.Child
            this.SubSource=''
            this.hasSelectOption = ![34,11].includes(this.Source)
            if(this.hasSelectOption){
                this.resetSelect()
                this.tableData = []
            }
            //如果没有二级数据源，则请求表格筛选项数据；钢联化工，SMM没有筛选项数据
            if(!this.SubSourceList.length&&this.hasSelectOption){
                this.getSelectOption()
                this.getTableData('optionChange')
            }
        },
        handleSubSourceChange(){
            this.getSelectOption()
            this.getTableData('optionChange')
        },
        //获取终端编码列表
        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.getTableData('optionChange')
        },
        handleCurrentChange(page){
            this.currentPage = page
            this.getTableData()
        },
        async getTableData(type){
            const {frequency,user,classify,state,terminalCode,keyWord,sortParam,sortType} = this.selectOption
            const res = await dataRefreshInterface.getEdbTableList({
                Source:Number(this.Source),
                SubSource:Number(this.SubSource),
                ClassifyId:classify,
                TerminalCode:terminalCode,
                SysUserId:user,
                Frequency: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.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.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
            dataRefreshInterface.setRefreshTime({
                Source:Number(this.Source),
                SubSource:Number(this.SubSource),
                ClassifyId:Number(classify),
                TerminalCode:terminalCode,
                SysUserId:user,
                Frequency:frequency,
                Keyword:keyWord,
                Status:state,
                IsSelectAll:this.isSelectAll,
                EdbSelectIdList:this.selectList,
                List:list
            }).then(res=>{
                if(res.Ret!==200) return
                this.$message.success("设置刷新时间成功")
                this.getTableData('optionChange')
                this.isSetTimeDialogShow = false
            })
        },
        setDefaultTime(list){
            dataRefreshInterface.setDefaultTime({
                Source:Number(this.Source),
                SubSource:Number(this.SubSource),
                Frequency:this.defaultFrequency,
                List:list
            }).then(res=>{
                if(res.Ret!==200) return 
                this.$message.success("设置默认刷新时间成功")
                this.isSetTimeDialogShow = false
            })
        },
        setRefreshStatus(){
            const {frequency,user,classify,state,terminalCode,keyWord} = this.selectOption
            dataRefreshInterface.setRefreshStatus({
                Source:Number(this.Source),
                SubSource:Number(this.SubSource),
                ClassifyId:Number(classify),
                TerminalCode:terminalCode,
                SysUserId:user,
                Frequency: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.getTableData('optionChange')
                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()
        }
    },
    mounted(){
        this.getSourceList()
        this.getUserList()
    }
};
</script>

<style scoped lang="scss">
.data-refresh-setting-wrap{
    min-height: calc(100vh - 120px);
    display: flex;
    flex-direction: column;
    .top-box,.table-box{
        box-sizing: border-box;
        padding:20px;
        background-color: #fff;
        border:1px solid #C8CDD9;
        border-radius: 4px;
    }
    .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;
        }
    }
}
</style>
