<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-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%" v-model="formData.deviceType" placeholder="请选择设备类型" :disabled="this.isEdit">
                  <el-option
                    v-for="item in deviceTypeList"
                    :key="item.key"
                    :label="item.label"
                    :value="item.key"
                  />
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="设备品牌" prop="deviceBrand">
                <el-select style="width: 100%" v-model="formData.deviceBrand" placeholder="请选择设备品牌" :disabled="this.isEdit">
                  <el-option
                    v-for="item in brandList"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <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-row>

          <el-row>
            <el-col :span="24" 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-form>

      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmit">确 定</el-button>
        <el-button @click="onHide">取 消</el-button>
        <!--        <el-button type="primary" @click="onSave">保存</el-button>-->

      </div>
    </DialogCom>
  </div>
</template>

<script>
import {mapMutations, mapState} from "vuex";
import {
  addDvrHostDevice, brandList,
  dvrHostDeviceInfo,
  editDvrHostDevice, editNetHostDevice,
  getProductDisplayName, netHostDeviceInfo,
  updateDvrHostDevice
} from "@/api/iot/deviceInfo";
import KSelect from "@/components/common/userselect.vue";
import OrgTree from "@/components/orgTree/orgQuerySelector.vue";
import {addConfig, updateConfig} from "@/api/system/config";
import * as iotApi from "@/api/iot/alarmRule";
import {getCurOrgConnectHost} from "@/api/iot/alarmRule";

export default {
  components: {KSelect, OrgTree},
  data() {
    const params = this.$route.params;
    return {
      id: params ? params.id : null,
      isShow: false,
      title: '',
      formData: this.reset(),
      deviceTypeList: [],
      modelList: [],
      hostConnectList: [],
      isEdit:false,
      brandList: [],
      formDataRules: {
        deviceName: [{required: true, message: "请输入设备名称", trigger: 'blur'}],
        deviceType: [{required: true, message: "请选择设备类型", trigger: 'blur'}],
        iotCode: [{required: true, message: "请选择所属主机", trigger: 'blur'}],
        deviceBrand: [{required: true, message: "请选择设备品牌", trigger: 'blur'}],
        serverIp: [
          {required: true, message: '请输入主机Ip', trigger: 'blur'},
          {validator: this.validateIp, trigger: 'blur'}
        ],
      },
    };
  },
  dicts: [],
  props: {},
  watch: {},

  created() {

  },

  mounted() {

  },
  computed: {
    ...mapState(["loginUser", "org"]),
  },
  methods: {
    ...mapMutations([]),
    reset(other = {}) {
      return {
        id: null,
        orgId: null,
        iotCode: null,
        deviceName: null,
        deviceType: null,
        serverIp: "",
        enable: 0,

      };
    },
    async refresh(id, other) {
      if (!id) {
        this.reset(other);
      }else {
        netHostDeviceInfo( id).then((response) => {
          this.formData =response.data;
        })
      }

    },
    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.$nextTick(() => {
        this.$refs.form.clearValidate(); // 确保在 DOM 更新之后清除表单验证状态
      });*/
      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) {
          editNetHostDevice(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);
      },200);
    },
    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();
    },
    orgChange(){
      this.formData.iotCode = null;
      this.getConnectHostOrg();
    },
    getConnectHostOrg() {
      if (!this.formData.orgId) {
        return
      }
      iotApi.getCurOrgConnectHost(this.formData.orgId).then((response) => {
        this.hostConnectList = response.data;
      });
    },
    initBrand() {
      brandList("BrandModelType").then((response) => {
        this.brandList = response.data;
      });
    },
    initDeviceType(){
      this.deviceTypeList=[];
      this.deviceTypeList.push({key:'24',label:'门禁主机'});
    },
    initData(){
      this.getConnectHostOrg();
      this.initBrand();
      this.initDeviceType();
    },


    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();
      }
    },
  },

};
</script>

<!-- <style lang="scss" scoped>
.k-textarea{
  .el-textarea {
    .el-textarea__inner  {
      font-size: 15px !important;
    }
  }
}
</style> -->
