<template>
    <div>
        <div class="createMisBox" v-if="selects == 1">
            <div>
                <h1 style="font-size: 16px;font-weight: bolder;">{{ editAndAdd }}</h1>
            </div>
            <div class="formBox" v-loading="saveLoading">
                <el-form ref="myForm" :inline="true" label-position="top" :model="newMission" class="demo-form-inline"
                    style="width: 1200px;margin: 0 auto;" :rules="missionRules" require-asterisk-position="right"
                    label-width="500px">
                    <el-form-item label="检测任务名称" prop="misName">
                        <el-input class="bestInput" v-model="newMission.misName" placeholder="请输入任务名称" clearable />
                    </el-form-item>
                    <el-form-item label="任务编号" prop="misNum">
                        <el-input class="bestInput" disabled v-model="newMission.misNum" placeholder="自动生成任务编号..."
                            clearable />
                    </el-form-item>
                    <el-form-item label="检测变电站" prop="flashId">
                        <el-select style="width: 340px;height: 40px;" v-model="newMission.flashId" placeholder="请选择变电站"
                            clearable @change="flashChange">
                            <template v-for="(item, index) in flashList">
                                <el-option :label="item.label" :value="item.value" />
                            </template>
                        </el-select>
                        <img @click="addFlash" style="width: 40px;height: 40px;"
                            src="../../../assets/icon/create_misBtn.png" alt="">
                    </el-form-item>
                    <el-form-item label="检测模型" prop="cmodel">
                        <el-input class="bestInput" style="width: 600px;" disabled placeholder="输入内容"
                            v-model="newMission.cmodel"></el-input>
                        <el-button @click="modelOpen" style="height: 40px;margin-left: 5px;" type="primary" plain><el-icon>
                                <Coin style="color: #449DFD;" />
                            </el-icon>选择模型</el-button>
                    </el-form-item>
                    <el-form-item label="报告模板" prop="reportNow">
                        <el-select class="bestInput" style="width: 400px;height: 40px;" @chang="bmChange"
                            v-model="newMission.reportNow" placeholder="请选择模板" clearable>
                            <el-option v-for="(item, index) in rmList" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="misMes">
                        <template #label>
                            <span style="color: red;">任务说明</span>
                        </template>
                        <el-input style="width: 1136px;" v-model="newMission.misMes"></el-input>
                    </el-form-item>
                    <el-form-item label="SCD文件">
                        <!-- <div style="width:100%;text-align: left;">{{ scdName }}</div> -->
                        <el-upload ref="upload" class="upload-demo" :http-request="nowUpload" :limit="2"
                            element-loading-text="上传中..." element-loading-background="rgba(255, 255, 255, 0.8)"
                            :show-file-list="false">
                            <template #trigger>
                                <el-button style="border-bottom: 1px solid #7BBAFD;width: calc(100vw - 1000px);"
                                    type="primary" plain>{{ scdName ? scdName : '选择SCD文件' }}</el-button>
                            </template>
                        </el-upload>
                        <span style="margin-left: 10px;" v-loading="scdLoading">{{ textIs ? scdLoading ? ' 正在进行SCD间隔装置分析' :
                            ' SCD分析已完成' : '' }}
                        </span>
                    </el-form-item>
                </el-form>
            </div>
            <!-- 间隔、装置列表 -->
            <div>
                <el-button style="width: 200px;height: 30px;" @click="backMent">返回</el-button>
                <el-button style="width: 200px;height: 30px;" @click="saveMent" type="primary">保存</el-button>
            </div>
            <div class="gapAndUnit" v-if="successScd">
                <!-- 间隔列表 -->
                <div class="gapBox">
                    <div style="display: flex;justify-content: flex-start;align-items: center;margin: 5px;">
                        <div>
                            <img src="../../../assets/icon/DotsNine.png" alt="">
                        </div>
                        <div style="height: 24px;line-height: 22px;margin-left: 5px;">
                            <span>间隔列表</span>
                        </div>
                    </div>
                    <!-- <p :class="jgSelect == index ? 'result' : ''" v-for="(item, index) in jgList"
                        style="text-align: left;cursor: pointer;" @click="jgClick(item, index)">
                        {{ item.name }}
                    </p> -->
                    <el-tree :props="anyProps" :data="anyData" @node-click="handleCheckChange" />
                </div>
                <!-- 装置列表 -->
                <div class="unitBox">
                    <div style="display: flex;justify-content: flex-start;align-items: center;margin: 10px 10px;">
                        <div>
                            <img src="../../../assets/icon/HardDrives.png" alt="">
                        </div>
                        <div style="height: 24px;line-height: 22px;margin-left: 5px;">
                            <span>装置列表——间隔：<em>{{ jg }}</em></span>
                            <span>检测模型：<em>{{ flashLevel ? flashLevel : '' }}</em></span>
                        </div>
                        <div
                            style="position: absolute;top: 0px;right: 0px;display: flex;justify-content: center;align-items: center;">

                            <!-- <div style="margin: 0 10px;">
                                <el-checkbox label="开启检测" size="large" />
                            </div> -->

                            <div style="margin: 5px;">
                                <el-button type="primary" size="small" plain @click="checkTime">选择装置</el-button>
                            </div>
                        </div>
                    </div>
                    <div v-loading="iedLoading" style="margin: 10px;float: left;">
                        <!-- <div v-for="(item, index) in mx">
                            {{ item.ied_name }}
                        </div> -->
                        <el-tag v-for="(item, index) in mx" :key="item.ied_name" @click="tagClick(item, index)" size="large"
                            :class="item.isChoose ? 'mx-2' : 'mx-1'" closable="true" effect="plain" @close="tagClose(item)">
                            {{ '[' + item.ied_name + ']' + (item.attr_desc || '') }}
                        </el-tag>
                    </div>
                </div>
            </div>
            <div v-if="successScd">
                <el-button style="width: 200px;height: 30px;" @click="backMent">返回</el-button>
                <el-button style="width: 200px;height: 30px;" type="primary" @click="iedSave">保存</el-button>
            </div>
        </div>
        <!-- 模态框组件 -->
        <div>
            <LookScd v-if="scdLooks" :scdLooks="scdLooks" @nowBack="nowBack" @lookNum="lookNum"></LookScd>
            <ModelTree v-if="treeMool" :treeMool="treeMool" :treeNeed="treeNeed" :checkedNodeNames="checkedNodeNames"
                @treeBack="treeBack" @treeNum="treeNum">
            </ModelTree>
            <FlashCreate v-if="fcModal" :fcModal="fcModal" @fcBack="fcBack"></FlashCreate>
            <CheckIed v-if="iedModal" :iedModal="iedModal" :loadScdId="loadScdId" @iedBack="iedBack"
                @iedArrBack="iedArrBack"></CheckIed>
        </div>
    </div>
</template>

<script>
import { ref, onMounted, reactive, watch, onBeforeUnmount } from 'vue';
import flashPower from '../../../api/flashPower'
import report from '@/api/report';
import scd from "@/api/scd"
import task from '@/api/task';
import cid from '@/api/cid/cid';
import LookScd from '../modalComp/LookScd.vue';
import ModelTree from '../modalComp/ModelTree.vue';
import FlashCreate from '../modalComp/FlashCreate.vue';
import CheckIed from '../modalComp/CheckIed.vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
export default {
    props: {
        btnSelect: {
            type: Number,
            require: true
        },
        taskList: {
            type: Array,
            require: true
        },
        editRow: {
            type: Object,
            require: true
        },
        status: {
            type: Number,
            require: true
        }
    },
    setup(props, { emit }) {
        let selects = props.btnSelect
        let arrList = props.taskList
        let newMission = ref({
            misName: "",
            misNum: "",
            flashId: "",
            reportNow: "",
            misMes: "",
            scdFolder: "",
            misId: "",
            cmodel: "",
        })//创建任务提交表单
        let missionRules = ref({
            misName: [
                { required: true, message: '请输入名称', trigger: 'blur' },
            ],
            flashId: [
                { required: true, message: "请选择变电站", trigger: "blur" }
            ],
            reportNow: [
                { required: true, message: "请选择模板", trigger: "blur" }
            ],
            misMes: [
                { required: true, message: "请输入任务说明", trigger: "blur" }
            ],
            cmodel: [
                { required: true, message: "请选择检测模型", trigger: "blur" }
            ],
        })//表单验证
        let flashList = ref([])//表单选择的变电站
        let scdLooks = ref(false)//选择scd文件时的显示与否
        let treeMool = ref(false)//选择模型模态框
        let btnName = ref('点击选择scd文件')
        let jg = ref("请选择")
        let jgList = ref([])//间隔列表
        let jgSelect = ref()//选择间隔
        let jgid = ref("")//间隔id
        let mx = ref([])
        let mxList = ref([])//模型列表
        let mxId = ref("")//模型id
        let rmList = ref([])//报告模板list
        let scdId = ref('')//lookscd.vue返回的scdid
        let scdName = ref('')//lookscd.vue返回的scdname
        let cmodel = ref('')
        let fcModal = ref(false)//创建变电站模态框
        let scdLoading = ref(false)//上传scd文件后进行分析
        let loadScdId = ref(0)//上传成功后拿到的scdid
        let successScd = ref(false)//保存任务后继续选择的间隔模型
        let iedModal = ref(false)//checkied.vue模态框状态
        let loadAreaId = ref("")
        let iedName = ref("")//一串ied名称字符串
        let iedLoading = ref(false)//加载ied
        let needEdit = ref({})//需要编辑的任务
        let anyProps = ref({
            label: "area_name",
            id: "area_id",
        })
        let treeNeed = ref([])//modelTree.vue需要的回显数据
        let checkedNodeNames = ref([])
        let anyData = ref([])
        let states = ref(0)
        let flashLevel = ref("")
        const myForm = ref(null)//表单ref
        let saveLoading = ref(false)
        let editAndAdd = ref("新建检测任务")
        let textIs = ref(false)
        watch(() => props.editRow, (newVal) => {
            needEdit.value = newVal
        })
        watch(() => props.status, (newValue, oldValue) => {
            if (newValue !== 2) {
                resetForm(); // 重置表单数据
            }
        });
        function resetForm() {
            if (myForm.value) {
                myForm.value.resetFields();
                states.value = 1
            }
        };
        function reload() {
            states.value = props.status
            if (states.value == 2) {
                if (props.editRow.name) {
                    needEdit.value = props.editRow
                    newMission.value.misName = needEdit.value.name//任务名称
                    newMission.value.misNum = needEdit.value.code
                    newMission.value.misId = needEdit.value.id //任务id
                    newMission.value.flashId = needEdit.value.station_id//变电站id
                    newMission.value.misMes = needEdit.value.memo//备注或描述
                    newMission.value.reportNow = needEdit.value.report_id//报告模板
                    loadScdId.value = needEdit.value.scd_id//scdid
                    editAndAdd.value = '编辑检测任务'
                    task.getTaskById({ id: needEdit.value.id - 0 }).then(res => {
                        if (res.data != null) {
                            let modelnames = res.data.models.map((item, index) => {
                                return item.model_name
                            })
                            let arr = res.data.models.map((item, index) => {
                                return item.sys_model_id
                            })
                            newMission.value.cmodel = modelnames.join(',')
                            mxId.value = arr
                            treeNeed.value = arr
                            checkedNodeNames.value = modelnames
                            loadScdId.value = res.data.scd_id
                            scdName.value = res.data.scd_info.scd_name
                            successScd.value = true
                            scd.getLoadScd({ scd_id: res.data.scd_id * 1 }).then(res => {
                                if (res.code == 0) {
                                    successScd.value = true
                                    anyData.value = res.data
                                }
                            })
                        }
                    })
                } else {
                    return
                }
            } else {
                return
            }
        }
        function searchAllFlash() {
            flashPower.getAllArea({}).then(res => {
                flashPower.getAllFlashPower({ pid: res.data[0].pid }).then(res => {
                    if (res.data == null) {
                        return
                    } else {
                        flashList.value = res.data.map(item => {
                            return {
                                label: item.area_name,
                                value: item.id
                            }
                        })
                    }
                })
            })
            report.getReport({}).then(res => {
                rmList.value = res.data
            })
        }
        //变电站下拉框change事件
        function flashChange(e) {
            // searchScd(e)
            newMission.value.flashId = e
        }
        function bmChange(e) {
            newMission.value.reportNow = e.id
        }
        function jgClick(row, num) {
            jg.value = row.name
            jgSelect.value = num
            jgid.value = row.id
        }
        // 选择scd文件
        function chooseScdFile() {
            scdLooks.value = true
        }
        // lookscd组件传回得数据
        function nowBack(data, names, sid) {
            scdLooks.value = data
            if (names && sid) {
                newMission.value.scdFolder = sid
                btnName.value = names
                scd.getScdMiddle({ scd_id: sid }).then(res => {
                    console.log(res, 'sid');
                })
                scd.getIedMiddle({ scd_id: sid }).then(res => {
                    console.log(res, 'ied');
                })
            }
        }
        // t
        function saveMent() {//保存检测任务
            myForm.value.validate((val) => {
                if (val) {
                    saveLoading.value = true
                    task.createTask({
                        // id: newMission.value.misId - 0,
                        code: newMission.value.misNum,
                        id: needEdit.value.id - 0,
                        name: newMission.value.misName,
                        station_id: newMission.value.flashId - 0,
                        memo: newMission.value.misMes,
                        report_id: newMission.value.reportNow - 0,
                        scd_id: loadScdId.value - 0,
                        modelids: mxId.value.toString()
                    }).then(res => {
                        if (res.code == 0) {
                            ElMessage({
                                message: "创建成功",
                                type: "success"
                            })
                            saveLoading.value = false
                            // emit("createBack", 0)
                            scd.getLoadScd({ scd_id: loadScdId.value - 0 }).then(res => {
                                if (res.code == 0) {
                                    successScd.value = true
                                    anyData.value = res.data
                                    console.log(anyData.value, 'any')
                                } else {
                                    ElMessage({
                                        message: res.msg,
                                        type: "error"
                                    })

                                }
                            })
                        } else {
                            ElMessage({
                                message: res.msg,
                                type: "error"
                            })
                            saveLoading.value = false
                        }
                    })
                }
            })

        }
        function nowUpload(e) {
            if (scdLoading.value) {
                return
            }
            const loading = ElLoading.service({
                lock: true,
                text: '文件上传中',
                background: 'rgba(0, 0, 0, 0.7)',
            })
            cid.fileUpload({ station_id: newMission.value.flashId - 0, data_type: 'a_scd', file: e.file }).then(res => {
                scdLoading.value = true
                if (res.code == 0) {
                    loading.close()
                }
                scdName.value = res.data.filename
                scd.loadScd({ station_id: newMission.value.flashId - 0, scd_path: res.data.path, scd_name: res.data.filename }).then(the => {
                    // scd.getLoadScd({ scd_id: the.data - 0 }).then(lod => {
                    //     console.log(lod,'rsasdas');
                    if (the.code == 0) {
                        loadScdId.value = the.data - 0
                        scdLoading.value = false
                        textIs.value = true
                    }
                    // })
                })
            })
        }
        function handleCheckChange(e) {
            jg.value = e.area_name
            loadAreaId.value = e.area_id
            flashLevel.value = e.model_name.split(']')[1]
            iedLoading.value = true
            scd.getTikIed({ scd_id: loadScdId.value - 0, area_id: e.area_id - 0 }).then(res => {
                if (res.data != null) {
                    mx.value = res.data.map(item => ({ ...item, isChoose: false }));
                    iedName.value = mx.value.map(item => item.ied_name).join(',')
                    iedLoading.value = false
                } else {
                    mx.value = []
                    iedLoading.value = false
                }
            })
        }
        function iedSave() {
            scd.stickIed({ scd_id: loadScdId.value - 0, area_id: loadAreaId.value - 0, ied_ids: iedName.value }).then(res => {
                console.log(res, 'res');
                if (res.code == 0) {
                    ElMessage({
                        type: "success",
                        message: "间隔装置设置保存成功！",
                        duration: 1500,
                    })
                    emit("createBack", 0)
                } else {
                    ElMessage({
                        type: "error",
                        message: res.msg,
                        duration: 3000,
                    })
                }
            })
        }
        function tagClose(row, num) {
            ElMessageBox.confirm('确认从该间隔移除当前装置' + row.ied_name + '吗？', '删除装置').then(() => {
                mx.value.splice(mx.value.indexOf(row), 1)
                iedName.value = mx.value.map(item => item.ied_name).join(',');
            }).catch(() => { })
        }
        function tagClick(row, num) {
            // 将所有对象的 isChoose 属性设置为 false
            mx.value.forEach(item => {
                item.isChoose = false;
            });
            // 将当前点击的对象的 isChoose 属性设置为 true
            row.isChoose = true;
        }
        function checkTime() {
            iedModal.value = true
        }
        function addFlash() {
            fcModal.value = true
        }
        function backMent() {
            emit("createBack", 0)
        }
        function treeBack(data) {
            treeMool.value = data
        }
        function modelOpen() {
            treeMool.value = true
        }
        function treeNum(data, name) {
            mxId.value = data
            // cmodel.value = name.toString()
            newMission.value.cmodel = name.toString()
        }
        function lookNum(name, id) {
            scdId.value = id
            scd.getScdMiddle({ scd_id: id }).then(res => {
                jgList.value = res.data
            })
            scdName.value = name
        }
        function fcBack(data) {
            fcModal.value = data
        }
        function iedBack(data) {
            iedModal.value = data
        }
        function iedArrBack(data) {
            for (let i = 0; i < data.length; i++) {
                let obj = mx.value.filter(item => item.ied_name == data[i].ied_name)
                if (obj != null && obj.length > 0) {
                    ElMessage({
                        type: "info",
                        message: data[i].ied_name + ":该装置已存在！",
                        duration: 3000,
                    })
                    return
                }
            }
            mx.value = mx.value.concat(data)
            iedName.value = mx.value.map(item => item.ied_name).join(',');
        }

        onMounted(() => {
            searchAllFlash()
            reload()
        })
        onBeforeUnmount(() => {
            resetForm()
        })
        return {
            selects,
            arrList,
            newMission,
            searchAllFlash,//获取变电站
            missionRules,//表单验证
            flashList,//表单选择的变电站
            flashChange,//变电站下拉框change事件
            scdLooks,//选择scd文件时的显示与否
            chooseScdFile,// 选择scd文件
            nowBack, // lookscd组件传回得数据
            btnName,//按钮内修改文字
            treeMool,//选择模型显示与否
            treeBack,//modeltree传回数据
            modelOpen,//选择模型打开模态框
            jg,//间隔
            jgList,//间隔列表
            jgSelect,//选择
            jgClick,//间隔点击
            jgid,//间隔id
            mx,//模型
            mxList,//模型列表
            treeNum,//modelTree.vue返回的id函数
            mxId,//模型id
            rmList,//报告模板列表
            scdId,//lookscd.vue返回的数据
            scdName,//lookscd.vue返回的数据
            saveMent,//保存检测任务
            bmChange,
            backMent,//返回切换
            cmodel,
            addFlash,//新建变电站
            fcModal,//创建变电站模态框
            fcBack,//flashcreate.vue返回的模态框值
            nowUpload,//文件上传
            scdLoading,
            loadScdId,//上传成功后拿到的scdid
            successScd,//保存任务后继续选择的间隔模型
            handleCheckChange,//树形组件
            anyData,
            anyProps,
            iedModal,//checkied.vue模态框状态
            iedBack,//checkied.vue返回模态框状态
            checkTime,//打开选择ied
            iedArrBack,//checkied.vue返回选择数组
            tagClose,
            loadAreaId,//area_id
            iedSave,//保存ied状态
            iedName,//一串ied字符串
            iedLoading,
            needEdit,//需要编辑的任务
            treeNeed,//modelTree.vue需要的回显id
            checkedNodeNames,
            states,
            myForm,//表单ref
            resetForm,
            flashLevel,
            tagClick,//tag标签的点击事件
            editAndAdd,
            textIs,
            saveLoading,
        }
    },
    components: {
        LookScd,
        ModelTree,//选择模型
        FlashCreate,//创建变电站
        CheckIed,//选择ied
    }
}
</script>

<style scoped>
em {
    font-style: normal;
    color: #5779D7;
    margin-right: 5px;
}

.createMisBox {
    width: 100%;
    height: calc(100vh - 150px);
    text-align: center;
    margin-top: 20px;
    /* line-height: calc(100vh - 150px); */
}

.formBox {
    width: 1136px;
    height: 360px;
    margin: 0 auto;
    /* border-bottom: 1px dashed #dbdbdb; */
}

.bestInput {
    width: 360px;
    height: 40px;
    border-radius: 2px 2px 2px 2px;
}

.gapAndUnit {
    width: 1136px;
    /* height: 150px; */
    /* border: 1px solid black; */
    margin: 5px auto;
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.gapBox {
    width: 288px;
    height: calc(100vh - 640px);
    overflow-y: auto;
    border: 1px solid #5779D7;
}

.unitBox {
    width: 832px;
    height: calc(100vh - 640px);
    overflow-y: auto;
    border: 1px solid #5779D7;
    position: relative;
}

.result {
    color: #5779D7;
}

.chooseSpan {
    width: 150px;
    height: 30px;
    margin-left: 10px;
    border: 1px solid blue;
    text-align: center;
    line-height: 30px;
}

.mx-1 {
    float: left;
    min-width: 100px;
    height: 30px;
    margin-right: 10px;
    margin-top: 5px;
    margin-bottom: 5px;
    border: 1px solid #5779D7;
    color: black;
}

.mx-2 {
    float: left;
    min-width: 100px;
    height: 30px;
    margin-right: 10px;
    margin-top: 5px;
    margin-bottom: 5px;
    border: 1px solid #5779D7;
    background-color: rgba(89, 120, 213, 0.3);
    color: #5779D7;
}

:deep(.el-form--inline .el-form-item) {
    margin-right: 12px !important;
}

:deep(.el-select .el-input__wrapper) {
    height: 38px;
}

.demo-form-inline:nth-child(2) {
    background-color: red;
}

.my-red-label {
    color: red;
}

:deep(.el-tag--large .el-tag__close) {
    margin-left: 25px;
}

:deep(.el-icon svg) {
    /* color: red; */
}
</style>