<template>
  <div class="edu-training-edit">
    <DialogCom :title="title" @close="onHide" :visible.sync="isShow" width="960px">
      <div class="page-body">
        <el-form :model="formData" :rules="formDataRules" size="small" ref="form" label-position="right"
                 label-width="120px" label-prefix=":">
          <el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="机构名称">
                  <org-tree :disabled="this.isEdit"
                    v-model="formData.orgId"
                    @defaultKey="getDefaultKey"
                    @defaultOrg="getDefaultOrg"
                    @click="clickTreeNode"
                    :defaultCheckSub="false"
                    :showCheckSub="false"
                    wholeTree
                    ref="orgTree"
                  ></org-tree>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="iotCode" label="所属主机">
                  <el-select :disabled="this.isEdit"
                    prop="iotCode"
                    label="检查人员"
                    v-model="formData.iotCode"
                    placeholder="请选择所属主机"
                  >
                    <el-option
                      v-for="dict in hostConnectList"
                      :key="dict.value"
                      :label="dict.key"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <!-- 设备名称 -->
              <el-col :span="12">
                <el-form-item prop="deviceName" label="设备名称">
                  <el-input
                    v-model="formData.deviceName"
                    :maxlength="32"
                    placeholder="请输入设备名称"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <!-- 设备产品 -->
              <el-col :span="12">
                <el-form-item label="产品类型" prop="deviceProduct">
                  <el-select style="width: 100%" @change="productChange(formData.deviceProduct)"
                             v-model="formData.deviceProduct" placeholder="请选择产品类型" :disabled="this.isEdit">
                    <el-option
                      v-for="item in productList"
                      :key="item.id"
                      :label="item.displayName"
                      :value="item.name"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 产品型号 -->
            <el-col :span="12">
              <el-form-item label="产品型号" prop="models">
                <el-select style="width: 100%" v-model="formData.models" placeholder="请选择产品型号" :disabled="this.isEdit">
                  <el-option
                    v-for="item in modelList"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 主机Ip -->
            <el-col :span="12">
              <el-form-item label="主机Ip" prop="serverIp">
                <el-input v-model="formData.serverIp" placeholder="请输入主机Ip"/>
              </el-form-item>
            </el-col>
            <!-- 监听地址 -->
            <el-col :span="12">
              <el-form-item label="监听地址" prop="listenAddress" v-if="this.showListenAddress()">
                <el-input v-model="formData.listenAddress" placeholder="请输入监听地址"/>
              </el-form-item>
            </el-col>
            <!-- 监听端口 -->
            <el-col :span="12">
              <el-form-item label="监听端口" prop="listenPort" v-if="this.showListenAddress()">
                <el-input v-model="formData.listenPort" maxlength="50" placeholder="请输入监听端口"/>
              </el-form-item>
            </el-col>
            <!-- 用户名 -->
            <el-col :span="12">
              <el-form-item label="用户名" prop="userName" v-if="this.showUserName()">
                <el-input v-model="formData.userName" maxlength="50" placeholder="请输入用户名"/>
              </el-form-item>
            </el-col>
            <!-- 密码 -->
            <el-col :span="12">
              <el-form-item label="密码" prop="password" v-if="this.showUserName()">
                <el-input v-model="formData.password" show-password maxlength="50" placeholder="请输入密码"/>
              </el-form-item>
            </el-col>
            <!-- 主机类型 -->
            <el-col :span="12">
              <el-form-item label="主机类型" prop="hostDeviceType" v-if="formData.deviceProduct=='BOSCH_CMS'">
                <el-select style="width: 100%" v-model="formData.hostDeviceType" placeholder="请输入主机类型" :disabled="this.isEdit">
                  <el-option
                    v-for="item in hostDeviceTypeList"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 主机端口 -->
            <el-col :span="12">
              <el-form-item label="主机端口" prop="serverPort" v-if="this.showUserName()">
                <el-input v-model="formData.serverPort" placeholder="请输入主机端口"/>
              </el-form-item>
            </el-col>
            <!-- 控制地址 -->
            <el-col :span="12">
              <el-form-item label="控制地址" prop="iotAddress" v-if="formData.deviceProduct=='BOSCH_CMS'">
                <el-input v-model="formData.iotAddress" placeholder="请输入主机端口"/>
              </el-form-item>
            </el-col>
            <!-- 用户代码 -->
            <el-col :span="12">
              <el-form-item label="用户代码" prop="deviceUserCode" v-if="formData.deviceProduct=='HengTong_CKWU01C'">
                <el-input v-model="formData.deviceUserCode" placeholder="请输入主机端口"/>
              </el-form-item>
            </el-col>
            <!-- MAC地址 -->
            <el-col :span="12">
              <el-form-item label="MAC地址" prop="deviceMac" v-if="this.showMacAddress()">
                <el-input v-model="formData.deviceMac" placeholder="请输入MAC地址"/>
              </el-form-item>
            </el-col>
            <!-- 主机操作码 -->
            <el-col :span="12">
              <el-form-item label="主机操作码" prop="deviceUserCode" v-if="this.showMacAddress()">
                <el-input v-model="formData.deviceUserCode" placeholder="请输入主机操作码"/>
              </el-form-item>
            </el-col>
            <!-- 主机端口 -->
            <el-col :span="12">
              <el-form-item label="主机端口" prop="serverPort" v-if="this.showMacAddress()">
                <el-input v-model="formData.serverPort" placeholder="请输入主机端口"/>
              </el-form-item>
            </el-col>
            <!-- 监听端口 -->
            <el-col :span="12">
              <el-form-item label="监听端口" prop="listenPort" v-if="formData.deviceProduct=='FengYe_H402'">
                <el-input v-model="formData.listenPort" maxlength="50" placeholder="请输入监听端口"/>
              </el-form-item>
            </el-col>

            <el-col :span="12" prop="enable">
              <el-form-item label="启用">
                <el-radio-group v-model="formData.enable">
                  <el-radio :label="0">启用</el-radio>
                  <el-radio :label="1">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider class="custom-divider"></el-divider>
          <el-row :gutter="48" style="margin-top: 1px">
            <el-col :span='12' style='text-align: left'> 子系统</el-col>
            <el-col :span='12' style='text-align: right'>
              <span>子系统数量 :</span>
              <el-input-number style="margin-left: 15px" @change="subSystemNumsChange" v-model="formData.subSystemNums"
                               :min="1" :max="16" label="描述文字" size="small"></el-input-number>
            </el-col>
          </el-row>
          <el-table class="w-auto" max-height="350" border :data="formData.subSystemList">
            <el-table-column label="子系统号" width="120" align="center">
              <template slot-scope="r">
                <el-input v-model="r.row.subSystemIndex" maxlength="50" placeholder=""/>
              </template>
            </el-table-column>

            <el-table-column label="子系统名称" align="center">
              <template slot-scope="r">
                <el-input v-model="r.row.subSystemName" maxlength="50" placeholder=""/>
              </template>
            </el-table-column>
            <el-table-column label="是否启用" width="160" align="center">
              <template slot-scope="r">
                <el-radio-group v-model="r.row.enable">
                  <el-radio :label="0">启用</el-radio>
                  <el-radio :label="1">禁用</el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column label="操作列表" width="90" align="center">
              <template slot-scope="r">
                <btn-tip type="text" v-if="showSubSystemDeleted(r.row)" @click="deleteSunSystem(r.row, r.$index)">删除
                </btn-tip>
              </template>
            </el-table-column>
          </el-table>
          <el-divider class="sensor-divider"></el-divider>

          <el-row :gutter="48" style="margin-top: 1px">
            <el-col :span='12' style='text-align: left'> 报警输入</el-col>
            <el-col :span='12' style='text-align: right'>
              <span>报警输入数量 :</span>
              <el-input-number style="margin-left: 15px" @change="inputSensorNumsChange"
                               v-model="formData.inputSensorNums" :min="1"
                               label="描述文字" size="small"></el-input-number>
            </el-col>
          </el-row>
          <el-table class="w-auto" max-height="350" border :data="formData.inputSensorList">
            <el-table-column label="序号" width="120" align="center">
              <template slot-scope="r">
                <el-input v-model="r.row.inputSensorIndex" maxlength="50" placeholder=""/>
              </template>
            </el-table-column>

            <el-table-column label="名称" align="center">
              <template slot-scope="r">
                <el-input v-model="r.row.inputSensorName" maxlength="50" placeholder=""/>
              </template>
            </el-table-column>
            <el-table-column label="网络模块" align="center">
              <template slot-scope="r">
                <el-input v-model="r.row.moduleAddress" maxlength="50" placeholder="" disabled/>
              </template>
            </el-table-column>
            <el-table-column label="子系统号" align="center">
              <template slot-scope="r">
                <el-input v-model="r.row.subSystemIndex" maxlength="50" placeholder=""/>
              </template>
            </el-table-column>
            <el-table-column label="防区类型" align="center">
              <template slot-scope="r">
                <el-select prop="sensorType" v-model="r.row.sensorType">
                  <el-option
                    v-for="dict in sensorTypeList"
                    :key="dict.key"
                    :label="dict.label"
                    :value="dict.key"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="是否启用" width="160" align="center">
              <template slot-scope="r">
                <el-radio-group v-model="r.row.enable">
                  <el-radio :label="0">启用</el-radio>
                  <el-radio :label="1">禁用</el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column label="操作列表" width="90" align="center">
              <template slot-scope="r">
                <btn-tip type="text" v-if="showInputSensorDeleted(r.row)" @click="deleteInputSensor(r.row, r.$index)">删除
                </btn-tip>
              </template>
            </el-table-column>
          </el-table>

        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmit">确 定</el-button>
        <el-button @click="onHide">取 消</el-button>
      </div>
    </DialogCom>
  </div>
</template>

<script>
import {mapMutations, mapState} from "vuex";
import {alarmHostDeviceInfo, editAlarmHostDevice, getProductDisplayName} from "@/api/iot/deviceInfo";
import KSelect from "@/components/common/userselect.vue";
import OrgTree from "@/components/orgTree/orgQuerySelector.vue";
import * as iotApi from "@/api/iot/alarmRule";
import BtnTip from "@/components/btnTip/index.vue";

export default {
  components: {BtnTip, KSelect, OrgTree},
  data() {
    const params = this.$route.params;
    return {
      id: params ? params.id : null,
      isShow: false,
      title: '',
      formData: this.reset(),
      productList: [],
      modelList: [],
      isEdit:false,
      hostConnectList: [],
      sensorTypeList: [
        {key: 'Other', label: '其他'},
        {key: 'Displacement', label: '位移'},
        {key: 'Broken', label: '破碎'},
        {key: 'Infrared', label: '红外'},
        {key: 'Soaking', label: '水浸'},
        {key: 'Shock', label: '震动'},
        {key: 'Tamper', label: '防拆'},
        {key: 'Humidity', label: '湿度'},
        {key: 'Temperature', label: '温度'},
        {key: 'Intrusion', label: '入侵'},
        {key: 'DoorSensor', label: '门磁'},
        {key: 'Smoke', label: '烟感'},
        {key: 'IMDualIdentification', label: '红外微波双鉴'},
        {key: 'Microwave', label: '微波'},
        {key: 'EmergencyButton', label: '紧急按钮'},
      ],
      hostDeviceTypeList: [
        {id: 17, label: 'ICP_CMS6_CHI_V1_00'},
        {id: 18, label: 'AMAX2000'},
        {id: 19, label: 'ICP_CMS6_CHI_V1_10'},
        {id: 20, label: 'ICP_CMS8_CHI_V1_10'},
        {id: 21, label: 'ICP_CMS40_CHI_V1_00'},
        {id: 22, label: 'ICP_CMS6_CHI_V1_20'},
        {id: 23, label: 'ICP_CMS8_CHI_V1_20'},
        {id: 25, label: 'ICP_CMS40_CHI_V2_10'},
        {id: 29, label: 'ICP_CMS40_CHI_V2_20'},
        {id: 43, label: 'ICP_CMS40_CHI_V2_30'},
        {id: 50, label: 'ICP_CMS40_CHI_V2_40'}
      ],
      formDataRules: {
        deviceName: [{required: true, message: "请输入设备名称", trigger: 'blur'}],
        deviceProduct: [{required: true, message: "请选择产品类型", trigger: 'blur'}],
        iotCode: [{required: true, message: "请选择所属主机", trigger: 'blur'}],
        serverIp: [
          {required: true, message: '请输入主机Ip', trigger: 'blur'},
          {validator: this.validateIp, trigger: 'blur'}
        ],
        serverPort: [
          {required: true, message: '请输入主机端口', trigger: 'blur'},
          {validator: this.validatePort, trigger: 'blur'}
        ],
        userName: [{required: true, message: "请输入用户名", trigger: 'blur'}],
        password: [{required: true, message: "请输入密码", trigger: 'blur'}],
        models: [{required: true, message: "请选择产品型号", trigger: 'blur'}],
        listenAddress: [{required: true, message: "请输入监听地址", trigger: 'blur'}],
        listenPort: [{required: true, message: "请输入监听端口", trigger: 'blur'}],
        hostDeviceType: [{required: true, message: "请输入主机类型", trigger: 'blur'}],
        iotAddress: [{required: true, message: "请输入主机端口", trigger: 'blur'}],
        deviceMac: [{required: true, message: "请输入MAC地址", trigger: 'blur'}],
        deviceUserCode: [{required: true, message: "请输入主机操作码", trigger: 'blur'}],
      },
    };
  },
  dicts: [],
  props: {},
  watch: {},

  created() {

  },
  mounted() {

  },
  computed: {
    ...mapState(["loginUser", "org"]),
  },
  methods: {
    ...mapMutations([]),
    reset(other = {}) {
      return {
        id: null,
        orgId: "",
        iotCode: "",
        deviceName: "",
        deviceProduct: "",
        serverIp: "",
        serverPort: "",
        userName: "",
        password: "",
        listenAddress: "",
        listenPort: "",
        deviceMac: "",
        deviceUserCode: "",
        iotAddress: "",
        models: "",
        hostDeviceType: "",
        enable: 0,
        subSystemNums: 1,
        subSystemList: [{
          subSystemIndex: 0,
          subSystemName: '子系统1',
          enable: 0
        }],
        inputSensorNums: 1,
        inputSensorList: [{
          inputSensorIndex: 0,
          inputSensorName: '报警输入1',
          moduleAddress: '0',
          subSystemIndex: '0',
          sensorType: 'Other',
          enable: 0
        }],

        ...other,
      };
    },
    async refresh(id, other) {
      if (!id) {
        this.reset(other);
      } else {
        alarmHostDeviceInfo(id).then((response) => {
          this.formData = response.data;
          this.initModels(this.formData.deviceProduct);
        })
      }
    },
    async show(id, orgId, name, other = {}) {
      this.formData = this.reset(other);
      this.formData.orgId = orgId;
      this.title = '新增' + name;
      this.isEdit=false;
      this.initData();
      if (id) {
        this.title = '编辑' + name;
        this.formData.id = id;
        this.isEdit=true;
        await this.refresh(id, other);
      }

      this.isShow = true;
    },
    onHide() {
      this.isShow = false;
      this.formData = this.reset();
      this.$nextTick(() => {
        this.$refs.form.clearValidate(); // 确保在 DOM 更新之后清除表单验证状态
      });
    },
    async onSubmit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          editAlarmHostDevice(this.formData).then(r => {
            if (!this.formData.id) {
              this.$modal.msgSuccess("新增成功");
            } else {
              this.$modal.msgSuccess("修改成功");
            }
            this.flushList();
            this.onHide();
          })
        }
      });
    },
    flushList(){
      setTimeout(() => {
        this.$emit("reload", this.formData);
      },2000);
    },
    getDefaultOrg(org) {
      this.orgName = org.name;
      this.formData.orgId = org.id;
    },
    getDefaultKey(key) {
      this.formData.orgId = key;
    },
    // 节点单击事件
    clickTreeNode(data) {
      if (!data) {
        return;
      }
      this.formData.orgId = data.id;
      this.orgChange();
    },
    initData() {
      getProductDisplayName('AlarmHost').then((response) => {
        this.productList = response.data;
      })
      this.getConnectHostOrg();
    },
    orgChange(){
      this.formData.iotCode = null;
      this.getConnectHostOrg();
    },
    getConnectHostOrg() {
      if (!this.formData.orgId) {
        return;
      }
      iotApi.getCurOrgConnectHost(this.formData.orgId).then((response) => {
        this.hostConnectList = response.data;
      });
    },
    productChange(item) {
      // 找到选中的产品类型
      let selectedProduct = this.productList.find(s => s.name === item);
      if (selectedProduct) {
        // 提取models字段并转换为数组
        const models = JSON.parse(selectedProduct.models);
        // 将提取的models数组赋值给modelList
        this.modelList = models;
        this.formData.models = this.modelList[0];
      }
      this.productChangeAndInitDta();
    },
    initModels(item) {
      // 找到选中的产品类型
      let selectedProduct = this.productList.find(s => s.name === item);
      if (selectedProduct) {
        // 提取models字段并转换为数组
        const models = JSON.parse(selectedProduct.models);
        // 将提取的models数组赋值给modelList
        this.modelList = models;
      }
    },
    validateIp(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入主机Ip'));
      }
      const ipRegex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
      if (!ipRegex.test(value)) {
        callback(new Error('主机Ip格式不正确'));
      } else {
        callback();
      }
    },
    validatePort(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入主机端口'));
      }
      const port = parseInt(value, 10);
      if (isNaN(port)) {
        callback(new Error('主机端口必须是一个数字'));
      } else if (port < 1 || port > 65535) {
        callback(new Error('主机端口必须在1到65535之间'));
      } else {
        callback();
      }
    },
    showListenAddress() {
      let arr = ['InAnter_BM1600NTSmall'];
      return arr.includes(this.formData.deviceProduct);
    },
    showUserName() {
      let arr = [
        'DaHuaAlarmHost',
        'BOSCH_CMS',
        'Hik_DS19A',
        'HengTong_CKWU01C',
      ];
      return arr.includes(this.formData.deviceProduct);
    },
    showMacAddress() {
      let arr = [
        'HoneywellOCX_IPM',
        'HikModule',
      ];
      return arr.includes(this.formData.deviceProduct);
    },
    productChangeAndInitDta() {
      if (this.formData.id) {
        //说明是编辑,可能存在原始数据,此处就不做自动填充
        return;
      }
      let deviceProduct = this.formData.deviceProduct;
      if (deviceProduct === "DaHua" || deviceProduct === "DaHuaAlarmHost") {
        this.formData.serverPort = "37777";
        this.formData.userName = "admin";
        this.formData.password = "admin123";
      } else if (deviceProduct === "BOSCH_CMS") {
        this.formData.serverPort = "7700";
        this.formData.userName = "00001";
        this.formData.password = "1234";
        this.formData.hostDeviceType = "50";
      } else if (deviceProduct === "Hik_DS19A") {
        this.formData.serverPort = "8000";
        this.formData.userName = "admin";
        this.formData.password = "";
      } else if (deviceProduct === "HoneywellOCX_IPM") {
        this.formData.serverPort = "8000";
        this.formData.deviceUserCode = "1234";
        this.formData.deviceMac = "00-00-00-00-00-00";
      } else if (deviceProduct === "HikModule") {
        this.formData.serverPort = "4001";
        this.formData.deviceUserCode = "1234";
        this.formData.deviceMac = "00-00-00-00-00-00";
      } else if (deviceProduct === "FengYe_H402") {
        this.formData.listenPort = "9100";
      } else if (deviceProduct === "HengTong_CKWU01C") {
        this.formData.serverPort = "4001";
        this.formData.userName = "admin";
        this.formData.password = "12345678";
        this.formData.deviceUserCode = "1234";
      } else if (deviceProduct === "InAnter_BM1600NTSmall") {
        this.formData.listenPort = "502";
      }
    },
    deleteSunSystem(row, index) {
      if (this.formData.subSystemList.length === 1) {
        return;
      }
      this.formData.subSystemList.splice(index, 1);
      this.formData.subSystemNums = this.formData.subSystemList.length;
    },
    showSubSystemDeleted(row) {
      //如果当前元素在this.formData.subSystemList第一个的位置 不显示删除按钮
      return this.formData.subSystemList.indexOf(row) != 0;

    },
    subSystemNumsChange(nums) {
      while (this.formData.subSystemList.length < nums) {
        let end = this.formData.subSystemList[this.formData.subSystemList.length - 1];

        let data={
          subSystemIndex: Number(end.subSystemIndex) + 1,
          subSystemName: '',
          enable: 0
        };
        data.subSystemName =`子系统${data.subSystemIndex+1}`
        this.formData.subSystemList.push(data);
      }

      while (this.formData.subSystemList.length > nums) {
        this.formData.subSystemList.pop();
      }
      this.formData.subSystemNums = this.formData.subSystemList.length;
    },

    deleteInputSensor(row, index) {
      if (this.formData.inputSensorList.length === 1) {
        return;
      }
      this.formData.inputSensorList.splice(index, 1);
      this.formData.inputSensorNums = this.formData.inputSensorList.length;
    },
    showInputSensorDeleted(row) {
      //如果当前元素在this.formData.subSystemList第一个的位置 不显示删除按钮
      return this.formData.inputSensorList.indexOf(row) != 0;

    },
    inputSensorNumsChange(nums) {
      while (this.formData.inputSensorList.length < nums) {
        let end = this.formData.inputSensorList[this.formData.inputSensorList.length - 1];

        let data={
          inputSensorIndex: Number(end.inputSensorIndex) + 1,
          inputSensorName: '',
          moduleAddress: '0',
          subSystemIndex: '0',
          sensorType: 'Other',
          enable: 0
        }
        data.inputSensorName=`报警输入${data.inputSensorIndex+1}`
        this.formData.inputSensorList.push(data);
      }

      while (this.formData.inputSensorList.length > nums) {
        this.formData.inputSensorList.pop();
      }
      this.formData.inputSensorNums = this.formData.inputSensorList.length;
    }
  },
};
</script>

<style lang="scss" scoped>
.custom-divider {
  margin-top: 1px;
}

.sensor-divider {
  margin-top: 30px;
}
</style>
