<template>
  <div class="filedAddBoxMapp">
    <el-dialog
      class="AddDialogBox"
      title="新增映射配置"
      :visible.sync="mappDialogShow"
      @close="hide"
      width="620px"
      :close-on-click-modal="false"
    >
      <div class="mappSeting">
        <div class="mappInput">
          <h3>输入</h3>
          <div class="iedClass">
            <b>ied名称：</b>
            <el-select
              v-model="iedValue"
              placeholder="请选择"
              @change="changeIed"
            >
              <el-option
                v-for="item in iedOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
          <div class="iedClass">
            <b>逻辑设备：</b>
            <el-select
              v-model="deviceValue"
              placeholder="请选择"
              @change="changeDevice"
            >
              <el-option
                v-for="item in deviceOptions"
                :key="item.id"
                :label="item.paramIndex"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
          <div class="deviceList">
            <p
              v-for="(item, index) in deviceList"
              :key="index"
              :class="{ errorRed: leftIndex === item }"
            >
              {{ item }}
            </p>
          </div>
        </div>
        <el-divider direction="vertical"></el-divider>
        <div class="mappOutput">
          <h3>输出</h3>
          <div class="iedClass">
            <b>server名称：</b>
            <el-select
              v-model="serverValue"
              placeholder="请选择"
              @change="changeServer"
            >
              <el-option
                v-for="item in serverOptions"
                :key="item.id"
                :label="item.filename"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
          <div class="iedClass">
            <b>逻辑设备：</b>
            <el-select
              v-model="serveIecValue"
              placeholder="请选择"
              @change="changeServerDevice"
            >
              <el-option
                v-for="item in serveIecOptions"
                :key="item.inst"
                :label="item.paramIndex"
                :value="item.inst"
              >
              </el-option>
            </el-select>
          </div>
          <div class="deviceList serverList">
            <p
              v-for="(item, index) in deviceList"
              :key="index"
              :class="{ errorRed: rightIndex === outputValues[item] }"
            >
              <el-select
                v-model="outputValues[item]"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="outItem in serverdeviceList"
                  :key="outItem"
                  :label="outItem"
                  :value="outItem"
                ></el-option>
              </el-select>
            </p>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hide">取 消</el-button>
        <el-button type="primary" @click="submitForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  listIedConfigApi,
  icdlistParamindexApi,
  ieclistFileApi,
  serverlistParamindexApi,
  addTransformApi,
} from "@/utils/api/index";
export default {
  data() {
    return {
      mappDialogShow: false,
      //左侧
      iedValue: "",
      iedOptions: [],
      deviceValue: "",
      deviceOptions: [],
      deviceList: [],
      //右侧
      serverValue: "",
      serverOptions: [],
      serveIecValue: "",
      serveIecOptions: [],
      serverdeviceList: [],
      //输出
      outputValues: {}, // 用于存储每个设备列表项的选择值
      leftIndex: -1,
      rightIndex: -1,
    };
  },
  created() {},
  mounted() {
    // 初始化时，给每个对象添加 selected 和 value 属性
  },
  watch: {},
  methods: {
    //左侧输入
    //获取led列表
    getLedList() {
      listIedConfigApi()
        .then((res) => {
          console.log(res);
          this.iedOptions = res.data;
        })
        .catch((err) => {
          console.log(err); //代码错误、请求失败捕获
        });
    },
    //切换ied选项
    changeIed(val) {
      console.log(val);
      let selectOption = this.iedOptions.find((item) => {
        return item.id === val;
      });
      this.deviceValue = "";
      this.deviceList = [];
      this.getDeviceList(selectOption);
    },
    //获取逻辑设备
    getDeviceList(val) {
      icdlistParamindexApi({
        iedName: val.name,
      })
        .then((res) => {
          console.log(res);
          this.deviceOptions = res.data;
        })
        .catch((err) => {
          console.log(err); //代码错误、请求失败捕获
        });
    },
    //切换逻辑设备
    changeDevice(val) {
      console.log(val);
      let selectdevice = this.deviceOptions.find((item) => {
        return item.id === val;
      });
      console.log(selectdevice);
      this.deviceList = selectdevice.attList;
    },
    //右侧serve输出
    //获取serve文件列表
    getSeverList() {
      ieclistFileApi()
        .then((res) => {
          console.log(res);
          this.serverOptions = res.data;
        })
        .catch((err) => {
          console.log(err); //代码错误、请求失败捕获
        });
    },
    //切换server
    changeServer(val) {
      console.log(val);
      let serverSelectOption = this.serverOptions.find((item) => {
        return item.id === val;
      });
      this.serveIecValue = "";
      this.serverdeviceList = [];
      this.getserverDeviceList(serverSelectOption);
    },
    //获取serer服务设备
    getserverDeviceList(val) {
      serverlistParamindexApi({
        fileId: val.id,
      })
        .then((res) => {
          console.log(res);
          this.serveIecOptions = res.data;
        })
        .catch((err) => {
          console.log(err); //代码错误、请求失败捕获
        });
    },
    //切换逻辑设备
    changeServerDevice(val) {
      console.log(val);
      let selectserver = this.serveIecOptions.find((item) => {
        return item.inst == val;
      });
      console.log(selectserver);
      this.serverdeviceList = selectserver.attList;
    },
    submitForm() {
      let params = [];
      this.deviceList.forEach((item) => {
        console.log(`设备项: ${item}, 选择的值: ${this.outputValues[item]}`);
        if (
          this.outputValues[item] !== undefined &&
          this.outputValues[item] !== ""
        ) {
          params.push({
            rptFrom: item,
            rptTo: this.outputValues[item],
          });
        }
      });
      console.log(params);
      this.callApiWithParams(params);
    },
    async callApiWithParams(params) {
      for (let index = 0; index < params.length; index++) {
        // 使用 index 变量来追踪当前索引
        try {
          const param = params[index]; // 通过索引获取当前参数
          const res = await addTransformApi(param);
          if (res.success === false) {
            console.log(`在索引 ${index} 处发生错误: ${res.errorMsg}`);
            this.$message({
              showClose: true,
              message: res.errorMsg,
              type: "error",
            });
            if (res.errorMsg && res.errorMsg.includes("From")) {
              this.leftIndex = param.rptFrom;
              this.rightIndex = "";
            }
            if (res.errorMsg && res.errorMsg.includes("To")) {
              this.rightIndex = param.rptTo;
              this.leftIndex = "";
            }
            return; // 停止循环
          }
          this.$set(this.outputValues, param.rptTo, "");
          console.log(`调用成功（索引 ${index}）:`, res);
        } catch (err) {
          console.error(`调用接口时发生错误（索引 ${index}）:`, err);
          //alert(`在索引 ${index} 处调用接口时发生错误，已停止后续调用。`);
          return; // 停止循环
        }
      }
      this.$message({
        showClose: true,
        message: `所有映射配置均已成功`,
        type: "success",
      });
      this.mappDialogShow = false;
      this.$parent.getiecListForm(); //刷新
    },
    //获取监测设备类型

    display() {
      this.mappDialogShow = true;
      this.getLedList();
      this.getSeverList();
    },
    hide() {
      this.mappDialogShow = false;
      console.log("我关闭了");
      this.outputValues = {};
      // this.formInfo = {};
      // this.$refs.formInforef.resetFields(); // 重置表单字段值
      // console.log(this.formInfo);
    },
  },
};
</script>
<style lang="less">
.filedAddBoxMapp {
  .AddDialogBox {
    .el-dialog__body {
      padding: 10px 20px;
    }

    .mappSeting {
      display: flex;
      justify-content: space-around;
      height: 400px;
      .el-divider--vertical {
        height: 100%;
        margin: 0 1%;
      }
      .mappInput,
      .mappOutput {
        width: 49%;
        height: 400px;
        h3 {
          //font-weight: normal;
          line-height: 32px;
        }
        .iedClass {
          display: flex;
          align-items: center;
          margin-bottom: 12px;
          b {
            width: 84px;
            font-weight: normal;
          }
        }
        .el-select {
          width: 200px;
        }
      }
      .deviceList {
        overflow-y: auto;
        height: 284px;
        .el-select {
          width: 240px !important;
        }
        p {
          height: 40px;
          line-height: 40px;
        }
        .errorRed {
          color: #f00;
          .el-input__inner {
            border: 1px solid #f00;
          }
        }
      }
      .serverList {
        width: 100%;
        .el-select {
          width: 300px;
        }
      }
    }
  }
}
</style>
