<template>
  <div>
    <div class="createMisBox" v-if="selects == 1">
      <div>
        <h1 style="font-size: 18px; font-weight: bolder; color: #1a2447">
          {{ 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> -->
            <div class="choose-base" @click="modelOpen">
              <img :src="database" alt="" />
              选择模型
            </div>
          </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 style="color: #ccc; font-size: 12px"
            >模型说明：如果更改了检查模型，保存后需要对间隔列表及装置进行"重新解析"</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
                > -->
                <div class="clk-scd">
                  <img :src="scdicon" alt="" />
                  {{ scdName ? scdName : "点击选择SCD文件" }}
                </div>
              </template>
            </el-upload>
            <span
              style="margin-left: 10px; color: #3be078"
              v-loading="scdLoading"
              >{{
                textIs
                  ? scdLoading
                    ? "正在进行SCD间隔装置分析"
                    : "SCD分析已完成"
                  : ""
              }}
            </span>
          </el-form-item>
        </el-form>
      </div>
      <!-- 间隔、装置列表 -->
      <div>
        <el-button class="backs" @click="backMent">返回</el-button>
        <el-button
          style="width: 124px; height: 30px; background: #255ce7"
          @click="saveMent"
          type="primary"
          >保存</el-button
        >
      </div>
      <div class="gapAndUnit" v-if="successScd">
        <!-- 间隔列表 -->
        <div class="gapBox">
          <div
            class="interval"
            style="justify-content: space-between; margin: 5px"
          >
            <div class="interval">
              <img
                src="../../../assets/icon/DotsNine.png"
                alt=""
                class="img-interval"
                style="vertical-align: middle"
              />
              <span
                style="
                  font-size: 16px;
                  font-weight: 400;
                  height: 24px;
                  line-height: 24px;
                  margin-left: 5px;
                "
                >间隔列表</span
              >
            </div>
            <div class="img-interval border-r" @click="addInterval">
              <img :src="addPng" class="img-interval" />
            </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" /> -->
          <el-tree
            :props="anyProps"
            :data="anyData"
            @node-click="handleCheckChange"
            node-key="id"
            highlight-current
          >
            <template #default="{ node, data }">
              <div class="trees interval">
                <el-badge
                  v-if="data.isLog"
                  :value="data.filterLength"
                  class="item"
                >
                  <span>{{ node.label }}</span>
                </el-badge>
                <span v-else>{{ node.label }}</span>
                <img
                  v-if="loadAreaId == data.area_id"
                  @click="delInterval(data)"
                  :src="ClosePng"
                  alt=""
                  class="img-interval-child"
                />
              </div>
            </template>
          </el-tree>
        </div>
        <!-- 装置列表 -->
        <div
          class="unitBox"
          v-loading="iedLoading"
          element-loading-text="正在解析间隔..."
        >
          <div
            style="
              display: flex;
              justify-content: flex-start;
              align-items: center;
              margin: 10px 10px;
              height: 43px;
            "
          >
            <div>
              <img
                src="../../../assets/icon/HardDrives.png"
                alt=""
                style="vertical-align: middle"
              />
            </div>
            <div style="height: 24px; margin-left: 5px">
              <span style="font-size: 16px; font-weight: 400"
                >装置列表——间隔：<em style="color: #255ce7">{{ jg }}</em></span
              >
              <span
                :title="flashLevel ? flashLevel : ''"
                style="
                  font-size: 16px;
                  cursor: pointer;
                  font-weight: 400;
                  margin-left: 30px;
                "
                >检测模型：<em style="color: #255ce7">{{
                  flashLevel ? flashLevel.slice(0, 4) : ""
                }}</em></span
              >
            </div>
            <div
              style="
                position: absolute;
                top: 5px;
                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 
                  >追加装置</el-button
                >
              </div> -->
              <div class="choose-base" @click="checkTime">追加装置</div>
              <div class="choose-base" @click="setIedExtrefNo">端子编号</div>
              <!-- <div style="margin: 5px">
                <el-button
                  type="primary"
                  size="small"
                  plain
                  @click="setIedExtrefNo"
                  >端子编号</el-button
                >
              </div> -->
            </div>
          </div>
          <div 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
              effect="plain"
              @close="tagClose(item, index)"
              style="cursor: pointer"
            >
              {{ "[" + item.ied_name + "]" + (item.attr_desc || "") }}
              <span style="color: rgb(112, 112, 210); font-weight: bold">{{
                item.ied_no ? "NO:" + item.ied_no : ""
              }}</span>
            </el-tag>
          </div>
        </div>
      </div>
      <div v-if="successScd">
        <el-button class="backs cancel-add" @click="backMent">返回</el-button>
        <el-button style="width: 100px; height: 30px" @click="aginParseArea"
          >重新解析</el-button
        >
        <el-button class="sure-add" 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"
        :spaceInterval="spaceInterval"
        :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>
    <el-dialog
      v-model="openAddInterval"
      width="25vw"
      style="height: 400px"
      append-to-body
      draggable
    >
      <template #header>
        <div class="my-header">
          <div class="title">添加间隔</div>
        </div>
      </template>
      <el-form
        :model="queryParams"
        :rules="rules"
        ref="queryRef"
        label-width="120px"
      >
        <el-form-item label="间隔名称" prop="area_name">
          <el-input v-model="queryParams.area_name" clearable></el-input>
        </el-form-item>
        <el-form-item label="间隔所属模型" prop="model_id">
          <el-select
            ref="levelRef"
            v-model="queryParams.model_id"
            placeholder="请选择所属模型"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in spaceInterval"
              :key="dict.model_id"
              :label="dict.model_name"
              :value="dict.model_id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="检测间隔类型" prop="area_type">
          <el-select
            ref="levelRef"
            v-model="queryParams.area_type"
            placeholder="请选择间隔类型"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in IntavalType"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span
          class="dialog-footer"
          style="display: flex; justify-content: center"
        >
          <el-button type="primary" class="sure-add" @click="sureAdd">
            确认
          </el-button>
          <el-button @click="cancelClick" class="cancel-add">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  reactive,
  watch,
  onBeforeUnmount,
  toRefs,
  nextTick,
} from "vue";
import { debounce } from "lodash";
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 database from "@/assets/image/database.png";
import clickChose from "@/assets/image/click_chose.png";
import scdicon from "@/assets/image/scdicon.png";
import addPng from "@/assets/image/scdcheck/add.png";
import ClosePng from "@/assets/image/Close.png";
import systemRow from "@/api/systemRow";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
const props = defineProps({
  btnSelect: {
    type: Number,
    require: true,
  },
  taskList: {
    type: Array,
    require: true,
  },
  editRow: {
    type: Object,
    require: true,
  },
  status: {
    type: Number,
    require: true,
  },
});
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(""); //area_id
let iedName = ref(""); //一串ied名称字符串
let iedLoading = ref(false); //加载ied
let needEdit = ref({}); //需要编辑的任务
const openAddInterval = ref(false); //打开添加间隔
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);
let filterLength = ref(0); //装置筛选有无attr_desc属性时的数组长度
let editTask_models = ref([]); //编辑任务时的原模型列表。保存时需要与选择的模型进行差异对比
const spaceInterval = ref([]); //所属间隔的数据
watch(
  () => props.editRow,
  (newVal) => {
    needEdit.value = newVal;
  }
);
watch(
  () => props.status,
  (newValue, oldValue) => {
    if (newValue !== 2) {
      resetForm(); // 重置表单数据
    }
  }
);
const resetForm = () => {
  if (myForm.value) {
    myForm.value.resetFields();
    states.value = 1;
  }
};
const 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 && res.data.models != null) {
          let modelnames = res.data.models.map((item, index) => {
            return item.model_name;
          });
          editTask_models.value = res.data.models;
          spaceInterval.value = res.data.models;
          let treeNeedAry = [];
          spaceInterval.value = [];
          let arr = res.data.models.map((item, index) => {
            treeNeedAry.push(item.sys_model_id);
            spaceInterval.value.push({
              model_id: item.model_id,
              model_name: item.model_name,
            });
            return item.model_id;
          });
          newMission.value.cmodel = modelnames.join(",");
          mxId.value = arr;
          treeNeed.value = treeNeedAry;
          checkedNodeNames.value = modelnames;
          loadScdId.value = res.data.scd_id;
          scdName.value = res.data.scd_info.scd_name;
          successScd.value = true;
          loadAreaInfo(res.data.scd_id * 1);
        }
      });
    } else {
      return;
    }
  } else {
    return;
  }
};
const modelId = ref(null);
const areaType = ref("");
const loadAreaInfo = (scdid) => {
  mx.value = [];
  scd.getLoadScd({ scd_id: scdid }).then((res) => {
    iedLoading.value = false;
    if (res.code == 0) {
      successScd.value = true;
      anyData.value = [];
      if (res.data == null) {
        ElMessage({
          message: "未解析到间隔",
          type: "info",
        });
        return;
      }
      modelId.value = res.data.length ? res.data[0].model_id : null;
      anyData.value = res.data.map((item) => {
        //获取可能有问题的ied数量，比如没找到的装置
        let alertieds =
          item.ieds == null
            ? []
            : item.ieds.filter((r) => {
                return r.attr_desc == null || r.attr_desc == "";
              });
        return {
          ...item,
          isLog: alertieds.length > 0 ? true : false,
          filterLength: alertieds.length,
        }; // 使用展开运算符为每个对象添加一个名为 isLog 的新属性，并设置其值为 true
      });
    }
  });
};
//获取变电站
const 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事件
const flashChange = (e) => {
  // searchScd(e)
  newMission.value.flashId = e;
};
const bmChange = (e) => {
  newMission.value.reportNow = e.id;
};
//间隔点击
const jgClick = (row, num) => {
  jg.value = row.name;
  jgSelect.value = num;
  jgid.value = row.id;
};
// 选择scd文件
const chooseScdFile = () => {
  scdLooks.value = true;
};
// lookscd组件传回得数据
const 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");
    });
  }
};
const saveMent = () => {
  successScd.value = false;
  //保存检测任务
  myForm.value.validate((val) => {
    if (val) {
      let tmpmodelid = mxId.value.toString().split(",");
      for (let i = 0; i < tmpmodelid.length; i++) {
        for (let j = 0; j < editTask_models.value.length; j++) {
          if (editTask_models.value[j].sys_model_id == null) {
            tmpmodelid[i] = editTask_models.value[j].model_id;
            break;
          }
          if (
            tmpmodelid[i] == editTask_models.value[j].sys_model_id ||
            tmpmodelid[i] == editTask_models.value[j].model_id
          ) {
            tmpmodelid[i] = editTask_models.value[j].model_id;
            break;
          }
        }
      }
      mxId.value = tmpmodelid.join(",");
      console.log("保存检测任务时的model_id", mxId.value);
      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)
            loadAreaInfo(loadScdId.value * 1);
            reload(); //编辑 的时候
          } else {
            ElMessage({
              message: res.msg,
              type: "error",
            });
            saveLoading.value = false;
          }
        });
    }
  });
};
//文件上传
const 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;
          }
          // })
        });
    });
};
//树形组件
const handleCheckChange = (e) => {
  console.log("e====", e);
  jg.value = e.area_name;
  loadAreaId.value = e.area_id;
  flashLevel.value = e.model_name.split("]")[1];
  //优先从间隔结果中查找其ied装置列表，如果没找到，则尝试调用接口获取
  let areaInfo = anyData.value.filter((r) => {
    return r.area_id == e.area_id;
  });
  if (
    areaInfo.length > 0 &&
    areaInfo.ieds != null &&
    areaInfo.ieds.length > 0
  ) {
    mx.value = areaInfo[0].ieds.map((item) => ({
      ...item,
      isChoose: false,
    }));
    iedName.value = mx.value.map((item) => item.ied_name).join(",");
    return;
  }
  //调用接口获取
  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(",");
        // 该循环是为了判断树形结构上是否有提示
        let ccc = res.data.map((param) => {
          if (!param.attr_desc) {
            return param;
          }
        });
        iedLoading.value = false;
      } else {
        mx.value = [];
        iedLoading.value = false;
      }
    });
};
const aginParseArea = () => {
  ElMessageBox.confirm("将清除原来的间隔数据，确定吗？", "间隔解析")
    .then(() => {
      iedLoading.value = true;
      scd
        .aginParseArea({ scd_id: loadScdId.value * 1 })
        .then((res) => {
          if (res.code == 0) {
            ElMessage({
              type: "success",
              message: "间隔解析成功！",
              duration: 1500,
            });
            loadAreaInfo(loadScdId.value * 1);
          } else {
            ElMessage({
              type: "error",
              message: res.msg,
              duration: 3000,
            });
            iedLoading.value = false;
          }
        })
        .catch((res) => {
          ElMessage({
            type: "error",
            message: "服务器发生异常！",
            duration: 3000,
          });
        });
    })
    .catch(() => {});
};
//保存ied状态
const iedSave = () => {
  scd
    .stickIed({
      scd_id: loadScdId.value - 0,
      area_id: loadAreaId.value - 0,
      ied_ids: iedName.value,
    })
    .then((res) => {
      if (res.code == 0) {
        ElMessage({
          type: "success",
          message: "间隔装置设置保存成功！",
          duration: 1500,
        });
        loadAreaInfo(loadScdId.value * 1);
      } else {
        ElMessage({
          type: "error",
          message: res.msg,
          duration: 3000,
        });
      }
    });
};
const tagClose = (row, num) => {
  console.log("row", row, num);
  ElMessageBox.confirm(
    "确认从该间隔移除当前装置" + row.ied_name + "吗？",
    "删除装置"
  )
    .then(() => {
      mx.value.splice(num, 1);
      iedName.value = mx.value.map((item) => item.ied_name).join(",");
    })
    .catch(() => {});
};
//tag标签的点击事件
const tagClick = (row, num) => {
  // 将所有对象的 isChoose 属性设置为 false
  mx.value.forEach((item) => {
    item.isChoose = false;
  });
  // 将当前点击的对象的 isChoose 属性设置为 true
  row.isChoose = true;
};
//打开选择ied
const checkTime = () => {
  iedModal.value = true;
};
//新建变电站
const addFlash = () => {
  fcModal.value = true;
};
const emit = defineEmits(["createBack"]);
//返回切换
const backMent = () => {
  emit("createBack", 0);
};
//modeltree传回数据
const treeBack = (data) => {
  console.log("data", data);
  treeMool.value = data;
};
//选择模型打开模态框
const modelOpen = () => {
  treeMool.value = true;
};
//模型树选择返回的模型数据 //modelTree.vue返回的id函数
const treeNum = (data, name, chooseData) => {
  mxId.value = data;
  console.log("选中树返回的model_id   mxId.value ", chooseData);
  // cmodel.value = name.toString()
  newMission.value.cmodel = name.toString();
  spaceInterval.value = chooseData;
};
const lookNum = (name, id) => {
  scdId.value = id;
  scd.getScdMiddle({ scd_id: id }).then((res) => {
    jgList.value = res.data;
  });
  scdName.value = name;
};
//flashcreate.vue返回的模态框值
const fcBack = (data) => {
  fcModal.value = data;
};
//checkied.vue返回模态框状态
const iedBack = (data) => {
  iedModal.value = data;
};
//checkied.vue返回选择数组
const 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(",");
};
//设置装置信号端子收发编号
const setIedExtrefNo = () => {
  if (mx.value == null || mx.value.length == 0) {
    ElMessage({
      message: "请先选择一个装置",
      type: "info",
    });
    return;
  }
  //获取当前选择的装置
  const ied = mx.value.filter((item) => {
    return item.isChoose == true;
  });
  if (ied.length == 0 || ied[0].attr_name == "") {
    ElMessage({
      message: "请先选择一个有效的装置",
      type: "info",
    });
    return;
  }
  ElMessageBox.prompt(
    '当装置是通过编号来确认端子信号收发(如PM接收的"线路5A相失灵"端子)时才设置此编号：',
    "装置端子编号",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPattern: /^[^\s]{0,5}$/,
      inputErrorMessage: "编号格式不正确：只支持不超过5位的字符！",
      inputValue: ied[0].ied_no,
    }
  )
    .then(({ value }) => {
      // 用户点击确定，value 是输入的内容
      scd
        .setAreaIedNo({
          area_id: loadAreaId.value * 1,
          ied_name: ied[0].attr_name,
          ied_no: value,
        })
        .then((res) => {
          if (res != null && res.code == 0) {
            ElMessage({
              message: "操作成功",
              type: "success",
            });
            ied[0].ied_no = value;
            let areaInfo = anyData.value.filter((r) => {
              return r.area_id == loadAreaId.value;
            });
            areaInfo.ieds = []; //清除ieds，以便下次点击间隔时触发从后台重新获取装置列表
          } else {
            ElMessage({
              message: "操作失败:" + res.msg,
              type: "success",
            });
          }
        });
    })
    .catch(() => {
      // 用户点击取消或关闭对话框
    });
};
//新增间隔
const data = reactive({
  queryParams: {
    scd_id: loadScdId.value - 0,
  },
});
const queryRef = ref(null);
const { queryParams } = toRefs(data);
// 表单重置
const reset = () => {
  queryParams.value = {
    scd_id: loadScdId.value - 0,
    model_id: null, //电压等级
    area_type: null, //间隔
    area_name: null, //装置类型
  };
  if (!queryRef.value) return;
  queryRef.value.resetFields();
};
//添加间隔
const rules = reactive({
  model_id: [{ required: true, message: "请选择间隔模型", trigger: "change" }],
  area_name: [{ required: true, message: "请输入间隔名称", trigger: "blur" }],
});
const addInterval = () => {
  reset();
  openAddInterval.value = true;
};
const sureAdd = debounce(async () => {
  queryRef.value.validate(async (val) => {
    if (val) {
      const data = {
        ...queryParams.value,
        model_id: queryParams.value.model_id * 1,
      };
      const res = await task.intervalAdd(data);
      const meg =
        res && res.code == 0
          ? { type: "success", message: `添加成功` }
          : { type: "error", message: res.msg };
      ElMessage(meg);
      loadAreaInfo(loadScdId.value * 1);
      openAddInterval.value =  res && res.code == 0?false:true;
    }
  });
}, 500);
const cancelClick = () => {
  reset();
  openAddInterval.value = false;
};
//删除间隔
const delInterval = (data) => {
  console.log("data", data);
  ElMessageBox.confirm(`确认删除 [${data.area_name}] 间隔吗？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await task.intervalDel({
        scd_id: loadScdId.value - 0,
        area_id: data.area_id,
      });
      const meg =
        res && res.code == 0
          ? { type: "success", message: `删除成功` }
          : { type: "error", message: `删除失败` };
      ElMessage(meg);
      if (res && res.code == 0) {
        loadAreaInfo(loadScdId.value * 1);
      }
    })
    .catch(() => {});
};
//获取间隔类型
const IntavalType = ref(null);
const getIntavalType = async () => {
  const res = await systemRow.getChildren({ code: "area_type" });
  IntavalType.value = res ? res.data : null;
};
onMounted(() => {
  searchAllFlash();
  getIntavalType();
  reload();
});
onBeforeUnmount(() => {
  resetForm();
});
</script>

<style scoped lang="scss">
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 #A3ADE0;
  color: #1a2447;
  padding: 19px 7px;
  :deep(.el-icon svg) {
    /* color: red; */
    color: #a3ade0;
  }
}

.mx-2 {
  float: left;
  min-width: 100px;
  height: 30px;
  margin-right: 10px;
  margin-top: 5px;
  margin-bottom: 5px;
  border: 1px solid #255ce7;
  background-color: #f6f9ff;
  color: #255ce7;
  padding: 19px 7px;
  :deep(.el-icon svg) {
    /* color: red; */
    color: #255ce7;
  }
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 12px !important;
  margin-bottom: 10px !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;
}

.choose-base {
  height: 42px;
  margin-left: 5px;
  width: 112px;
  font-size: 14px;
  color: #255ce7;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background: url("~@/assets/image/scdcheck/bgscd.png") no-repeat center;
  background-size: 112px 48px;
  img {
    width: 20px;
    height: 20px;
    margin: 0 4px 0 0;
  }
}
:deep(.el-form-item__label) {
  color: #1a2447;
}

.clk-scd {
  width: 954px;
  background: url("~@/assets/image/click_chose.png") no-repeat center;
  color: #255ce7;
  background-size: 954px 45px;
  height: 45px;
  line-height: 45px;
  img {
    width: 20px;
    height: 20px;
    margin: 0 4px 0 0;
    vertical-align: middle;
  }
}
.backs {
  width: 124px;
  height: 30px;
  background: #f1f3f9;
  box-shadow: inset 0px 2px 1px 0px rgba(255, 255, 255, 0.6),
    0px 2px 4px 0px rgba(138, 157, 205, 0.63);
}
.interval {
  display: flex;
  align-items: center;
}
.img-interval {
  width: 20px;
  height: 20px;
}
.img-interval-child {
  width: 14px;
  height: 14px;
  border: 1px solid #e50505;
  border-radius: 3px;
}
.border-r {
  border: 1px solid #255ce7;
  border-radius: 3px;
}
.trees {
  width: 90%;
  justify-content: space-between;
  img {
    margin-right: 3px;
  }
}
.my-header {
  border-bottom: 1px solid #a3ade0;
  font-size: 16px;
  color: #1a2447;

  .title {
    padding-bottom: 15px;
  }
}
.sure-add {
  width: 100px;
  height: 30px;
  background: #255ce7;
}
.cancel-add {
  width: 100px;
  height: 30px;
  background: #f1f3f9;
}
</style>