<template>
    <!-- 批量添加至指标库 -->
    <el-dialog
        :visible.sync="isOpenDialog"
        :close-on-click-modal="false"
        :modal-append-to-body="false"
        top="5vh"
        :title="$t('SteelChemicalPage.batch_add_edb_btn')"
        @close="$emit('close')"
        custom-class="batch-add-edb-dia"
        center
        width="70%"
        v-dialogDrag
    >
        <div class="dialog-container">
            <div class="select-box">
                <el-cascader v-model="searchClassify"
                    :options="classifyList"
                    :props="{
                        children:'Children',
                        label:'ClassifyName',
                        value:'BaseFromMysteelChemicalClassifyId',
                        multiple:true,
                        emitPath:false,
                    }"
                    :placeholder="$t('Edb.InputHolderAll.input_classify')"
                    @change="getEdbList"
                ></el-cascader>
                <el-input style="width:240px;" v-model="searchName"
                    :placeholder="$t('Edb.InputHolderAll.input_name_orid')"
                    prefix-icon="el-icon-search"
                    @input="getEdbList"
                />
            </div>
            <div class="select-table">
                <el-table :data="edbList" border 
                :row-class-name="tableRowClassName"
                @selection-change="handleSelectionChange" 
                v-loading="tableLoading">
                    <el-table-column  type="selection" width="55" align="center"></el-table-column>
                    <el-table-column :label="$t('Edb.Detail.e_id')" align="center" width="120" prop="edbId"></el-table-column>
                    <el-table-column :label="$t('Table.edb_name')" align="center">
                        <template slot-scope="{row}">
                            <el-input v-model="row.edbName" :placeholder="$t('Table.edb_name')"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('Edb.Detail.e_fre')" align="center" width="140">
                        <template slot-scope="{row}">
                            <el-select 
                                v-model="row.frequency" 
                                :placeholder="$t('CustomAnalysisPage.select_frequency')" 
                                clearable>
                                <el-option
                                    v-for="item in frequencyArr"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('Edb.Detail.e_unit')" align="center" width="140">
                        <template slot-scope="{row}">
                            <selectUnit v-model="row.unit" />
                        </template>
                    </el-table-column>
                    <!-- 操作 -->
                    <el-table-column align="center">
                        <template slot="header" slot-scope="{row}">
                            <!-- <span>{{$t('EtaBasePage.catalogue_directory')}}</span> -->
                            <el-radio-group v-model="classifyType" @change="handleClassifyTypeChange">
                                <el-radio :label="1" style="margin-right:5px"><!-- 分目录 -->{{$t('EtaBasePage.subdirectory_radio')}}</el-radio>
                                <el-radio :label="2"><!-- 同目录 -->{{$t('EtaBasePage.directory_radio')}}</el-radio>
                            </el-radio-group>
                            <el-cascader v-if="classifyType===2" v-model="selectClassify"
                                :options="edbClassifyList"
                                :props="{
                                    label: 'ClassifyName',
                                    value: 'ClassifyId',
                                    children: 'Children',
                                    checkStrictly: true,
                                    emitPath:false
                                }"
                                :placeholder="$t('SteelChemicalPage.batch_add_placeholder')"
                            >
                            </el-cascader>
                        </template>
                        <template slot-scope="{row,$index}">
                            <el-cascader 
                                v-model="row.classify"
                                :options="edbClassifyList"
                                :props="{
                                    label: 'ClassifyName',
                                    value: 'ClassifyId',
                                    children: 'Children',
                                    checkStrictly: true,
                                    emitPath:false
                                }"
                                :placeholder="$t('SteelChemicalPage.batch_add_placeholder')"
                                style="width:100%;"
                                :disabled="classifyType===2"
                            ></el-cascader>
                        </template>
                    </el-table-column>
                    <div class="no-data" slot="empty">
                        <tableNoData :text="$t('Table.prompt_slogan')"/>
                    </div>
                </el-table>
            </div>
        </div>
        <div class="footer-container" slot="footer">
            <el-button type="primary" plain @click="$emit('close')">{{ $t('Dialog.cancel_btn') }}</el-button>
            <el-button type="primary" @click="handleAddEdb" :loading="btnloading">{{ $t('ManualEdbListPage.add_tobase_btn') }}</el-button>
        </div>
        <!-- 操作提示弹窗 -->
        <el-dialog 
            :title="$t('BloombergPage.operation_prompt')"
            :visible.sync="isHintDiaShow"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
            @close="handleCloseDia"
            width="578px"
            v-dialogDrag
            center>
            <div class="hint-dialog-wrap">
                <p style="margin-bottom: 20px;">{{ hintText }}</p>
                <ul>
                    <li v-for="(item,index) in hintList" :key="index" class="hint-item" @click="gotoEdbDetail(item)">
                        {{ index+1 }}、{{ item.IndexName }}({{ item.IndexCode }})
                    </li>
                </ul>
            </div>
            <div style="text-align: center;margin-bottom: 30px;">
                    <el-button type="primary" @click="handleCloseDia">{{$t('Dialog.known')}}</el-button>
                </div>
        </el-dialog>
    </el-dialog>
</template>

<script>
import { steelInterface } from "@/api/modules/thirdBaseApi";
import { dataBaseInterface } from '@/api/api.js';
import selectUnit from '@/components/selectUnit.vue';
import { frequencySelectList } from '@/utils/defaultOptions';
export default {
    components:{ selectUnit },
    props:{
        isOpenDialog:{
            type:Boolean,
            default:false
        }
    },
    watch:{
        isOpenDialog(newval){
            if(newval){
                this.initDia()
            }
        }
    },
    data() {
        return {
            classifyList:[],//钢联化工数据库的目录
            searchName:'',
            searchClassify:'',
            classifyType:1,//1分目录 2同目录
            selectClassify:'',
            frequencyArr:frequencySelectList(),
            edbList:[
                /* {
                    edbId:'123456',
                    edbName:'指标名称指标名称',
                    frequency:'日度',
                    unit:'吨',
                    classify:'',
                    isHighlight:false
                }, */
            ],
            tableLoading:false,
            edbClassifyList:[],//指标库目录
            selectEdbList:[],//勾选的指标

            isHintDiaShow:false,
            hintList:[],
            hintText:'',
            btnloading:false,
        };
    },
    methods: {
        tableRowClassName({row}){
            return row.isHighlight?'highlight-row':''
        },
        initDia(){
            this.getClassifyList()
            this.getClassifyOpt()
            this.searchClassify = ''
            this.searchName = ''
            this.edbList = []
            this.selectEdbList = []
            this.selectClassify=''
            this.btnloading=false
        },
        //获取钢联化工数据库目录
        getClassifyList(){
            steelInterface.classifyList().then((res) => {
                if(res.Ret!==200) return 
                this.classifyList = res.Data||[]
            })
        },
        filterNodes(arr) {
            arr.length &&
                arr.forEach((item) => {
                    item.Children.length && this.filterNodes(item.Children);
                    if (!item.Children.length) {
                        delete item.Children;
                    }
                });
        },
        // 获取指标分类列表
        async getClassifyOpt(){
            const res=await dataBaseInterface.menuListV3()
            if (res.Ret !== 200) return
            this.filterNodes(res.Data.AllNodes||[]);
            this.edbClassifyList = res.Data.AllNodes || [];
        },
        //获取对应目录下的钢联化工指标
        getEdbList(){
            //每一次筛选项改变清空选择框
            this.selectEdbList = []
            this.classifyType = 1
            //tableData
            this.tableLoading = true
            steelInterface.searchEdbBatch({
                BaseFromMysteelChemicalClassifyIds:Array.isArray(this.searchClassify)?this.searchClassify.join(','):'',
                Keyword:this.searchName||''
            }).then(res=>{
                this.tableLoading = false
                if(res.Ret!==200) return 
                this.edbList = res.Data?res.Data.map(item=>{
                    return {
                        edbId:item.IndexCode||'',
                        edbName:item.IndexName||'',
                        frequency:item.FrequencyName||'',
                        unit:item.UnitName||'',
                        classify:'',
                        isHighlight:false
                    }
                }):[]
            })
           
        },
        handleSelectionChange(val){
            this.selectEdbList = val
        },
        handleAddEdb(){
            //校验所选指标
            if(!this.selectEdbList.length){
                return this.$message.warning(this.$t('Edb.InputHolderAll.input_select_edb'))
            }
            if(this.selectEdbList.length>30){
                return this.$message.warning(this.$t('SteelChemicalPage.batch_add_max_msg'))
            }
            //校验所选指标信息是否完整
            if(this.classifyType===2&&!this.selectClassify){
                return this.$message.warning(this.$t('CustomAnalysisPage.select_appropriate_category'))
            }
            //重置tableData的高亮
            this.edbList.forEach(i=>i.isHighlight=false)
            let messageList = [] //有问题的列表
            this.selectEdbList.forEach((item)=>{
                item.isHighlight=false
                if(!this.checkEdbData(item)){
                    item.isHighlight = true
                    messageList.push(item)
                }
            })
            //message轻提示 同时标出不完整的行
            if(messageList.length){
                return this.$message.warning(/* '部分指标信息未填写完整，请检查' */this.$t('SteelChemicalPage.batch_add_hint1'))
            }

            this.btnloading = true
            //添加检测
            steelInterface.batchAddEdbCheck({
                IndexCodes:this.selectEdbList.map(i=>i.edbId)
            }).then(res=>{
                if(res.Ret!==200) return (this.btnloading=false)
                const edbList = res.Data||[]
                const afterAddList = edbList.filter(i=>i.EdbExist===1) //已添加进指标库的指标
                const beforeAddList = edbList.filter(i=>i.EdbExist===0) //需要添加进指标库的指标
                //已选择的指标均添加进指标库 弹窗提示
                if(!beforeAddList.length){
                    return this.showHintDialog('all',afterAddList)
                }
                //剩余指标进行重名校验
                this.batchNameCheck(afterAddList,beforeAddList)
            })
            
        },
        //重名检测
        batchNameCheck(afterAddList,beforeAddList){
            const indexCodeList = beforeAddList.map(i=>i.IndexCode)
            let checkList = []
            indexCodeList.forEach(i=>{
                const item = this.selectEdbList.find(s=>s.edbId===i)
                item&&checkList.push(item)
            })
            steelInterface.batchCheckEdbName(checkList.map(i=>{
                return {
                    EdbCode:i.edbId,
                    EdbName:i.edbName,
                    Frequency:i.frequency
                }
            })).then(res=>{
                if(res.Ret!==200) return (this.btnloading=false)
                const checkedList = res.Data.filter(i=>i.Exist)
                if(checkedList.length){
                    checkedList.forEach(i=>{
                        const item = this.selectEdbList.find(s=>s.edbId===i.EdbCode)
                        item&&(item.isHighlight = true)
                    })
                    return this.$message.warning(/* '部分指标名称已存在，请重新填写' */this.$t('SteelChemicalPage.batch_add_hint2'))&&(this.btnloading=false)
                }else{
                    //通过重名校验后添加进指标库
                    this.batchAddEdb(afterAddList,checkList)
                }
            })
            
        },
        checkEdbData(edbData){
            return edbData.edbName&&edbData.frequency&&edbData.unit&&(this.classifyType===1?edbData.classify:true)
        },
        //显示操作提示弹窗
        showHintDialog(type,list){
            this.btnloading = false
            this.isHintDiaShow = true
            this.hintList = list
            this.hintText = type==='all'
            ?this.$t('YsDataPage.haved_all_msg') //本次添加的指标均已在指标库中，请勿重复添加！
            :this.$t('YsDataPage.haved_some_msg') //指标库中已存在以下指标，会自动过滤！
        },
        //添加进指标库
        batchAddEdb(afterAddList=[],checkList){
            //checkList
            steelInterface.batchAddToLib(checkList.map(i=>{
                return {
                    EdbCode:i.edbId,
                    EdbName:i.edbName,
                    Unit:i.unit,
                    Frequency:i.frequency,
                    ClassifyId:this.classifyType===1?Number(i.classify):Number(this.selectClassify),
                }
            })).then(res=>{
                if(res.Ret!==200) return (this.btnloading=false)
                //若afterAddList有值 弹窗提示部分指标已加入
                if(afterAddList.length){
                    this.showHintDialog('',afterAddList)
                }else{
                    this.$message.success(this.$t('MsgPrompt.add_msg2'))
                    this.$emit('close')
                }
            })
            
            
        },
        //跳转至指标库
        gotoEdbDetail(data){
            const {EdbClassifyId,EdbInfoId,EdbUniqueCode} = data||{}
            const href = this.$router.resolve({
                path:'/database',
                query:{
                    code:EdbUniqueCode,
                    id:EdbInfoId,
                    classifyId:EdbClassifyId,
                }
            }).href
            window.open(href,"_blank")
        },
        handleCloseDia(){
            //两个弹窗都关掉
            this.isHintDiaShow=false
            this.$emit('close')
        }
    },
};
</script>

<style lang="scss">
.batch-add-edb-dia{
    .dialog-container{
        .el-input{
            width:100%;
        }
        .el-table .highlight-row{
            background-color:#fef0f0 !important;
        }
    }
}
</style>
<style scoped lang="scss">
.batch-add-edb-dia{
    .dialog-container{
        .select-box{
            margin-bottom:20px;
        }
        .select-table{
            max-height:600px;
            overflow-y:auto;
        }
    }
    .hint-dialog-wrap{
            padding-bottom:30px;
            .hint-item{
                cursor: pointer;
                margin-bottom: 10px;
                &:hover{
                    color:#409EFF;
                    text-decoration: underline;
                }
            }
        }
}
</style>
