<template>
  <el-dialog v-model="visible" title="点位管理" width="40%" :before-close="closeDialog">
    <el-form :model="addForm" label-width="100px" :rules="rules" ref="ruleFormRef" size="large">
      <el-form-item label="点位名称:" prop="point_name">
        <el-input v-model="addForm.point_name" placeholder="请输入点位名称" clearable :disabled="type !== 'I'" />
      </el-form-item>
      <el-form-item label="点位地址:" prop="address">
        <el-input v-model="addForm.address" placeholder="请输入点位地址：0-65535" clearable type="number" />
      </el-form-item>
      <el-form-item label="寄存器:" prop="register">
        <el-select v-model="addForm.register" size="mini" placeholder="请选择寄存器" @change="changeRegister">
          <el-option v-for="item in registerArr" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="点位类型:" prop="point_type">
        <el-select v-model="addForm.point_type" size="mini" placeholder="请选择点位类型">
          <el-option v-for="item in datatypeArr" :disabled="item.disabled || item.disabled1" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="点位描述:" prop="point_description">
        <el-input v-model="addForm.point_description" placeholder="请输入点位描述（不超过50个字符）" clearable maxlength="50" />
      </el-form-item>
      <el-form-item label="读写权限:" prop="point_permissions">
        <el-select v-model="addForm.point_permissions" size="mini" placeholder="请选择读写权限">
          <el-option v-for="item in perOptions" :disabled="item.disabled" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="缩放系数:" prop="multiplier">
        <el-input v-model="addForm.multiplier" placeholder="请输入缩放系数" type="number" clearable />
      </el-form-item>
      <el-form-item label="点位单位:" prop="point_unit">
        <el-input v-model="addForm.point_unit" placeholder="请输入点位单位" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="large" @click="closeDialog">取消</el-button>
        <el-button size="large" type="primary" @click="saveP"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
import { onMounted, reactive, ref, toRefs, computed, nextTick } from "vue";
import infoApi from "@/api/infoApi.js";
import { ElMessage, ElMessageBox } from "element-plus";
export default {
  props: ["formData", "dialogVisible", "pointData", "type", "pointTypeOptions"],
  emits: ["dialogClose", "dialogSuccess"],
  setup(props, ctx) {
    const checkAddress = (rule, value, callback) => {
      let num = Number(value);
      if (value && (num >= 0 && num <= 65535)) {
        callback();
      } else {
        callback(new Error("点位地址：0-65535"));
      }
    };
    const validName = (rule, value, callback) => {
      var name = /^[a-zA-Z][a-zA-Z0-9_]{2,19}$/;
      if (name.test(value) || !value) {
        callback();
      } else {
        callback(new Error("名称只能以字母开头,仅支持字母,数字和下划线,最短3个字符起,且长度不能超过20个字符"));
      }
    };
    const ruleFormRef = ref(null);
    const state = reactive({
      addForm: {
      },
      datatypeArr: [],
      registerArr: [
        {
          label: 'coil_status',
          value: 1
        },
        {
          label: 'input_status',
          value: 2
        },
        {
          label: 'input_register',
          value: 3
        },
        {
          label: 'holding_register',
          value: 4
        }],

      byte_orderArr: [{
        label: 'null',
        value: 1
      }, {
        label: '12',
        value: 2
      }, {
        label: '21',
        value: 3
      }, {
        label: '4321',
        value: 4
      },
      {
        label: '2143',
        value: 5
      },
      {
        label: '1234',
        value: 6
      },
      {
        label: '3412',
        value: 7
      }, {
        label: '4312',
        value: 8
      }, {
        label: '3421',
        value: 9
      },
      {
        label: '2134',
        value: 10
      },
      {
        label: '1243',
        value: 11
      },
      {
        label: 'BIG',
        value: 12
      },
      {
        label: 'LIT',
        value: 13
      }],
      perOptions: [
        {
          label: '可读',
          value: 1
        },
        {
          label: '可写',
          value: 2
        }
      ],
      rules: {
        point_name: [{ required: true, message: "请输入点位名称", trigger: "blur" },
        { min: 3, max: 20, message: "长度在3到20个字符", trigger: "blur" },
        { required: true, validator: validName, trigger: "blur" },],
        address: [
          { required: true, message: "请输入点位地址", trigger: "blur" },
          { required: true, validator: checkAddress, trigger: "blur" }
        ],
        point_type: [{ required: true, message: "请选择点位类型", trigger: "blur" }],
        register: [{ required: true, message: "请输入寄存器", trigger: "blur" }],
        multiplier: [{ required: true, message: "请输入缩放系数", trigger: "blur" }],
        point_unit: [{ required: false, message: "请输入点位单位", trigger: "blur" }],
        point_permissions: [{ required: true, message: "请输入读写权限", trigger: "blur" }],
        point_description: [
          { required: false, message: "请输入点位描述", trigger: "blur" }
        ],
      },
    });
    const visible = computed(() => {
      return props.dialogVisible;
    });

    onMounted(() => {
      state.addForm = props.pointData;
      getPointData();
      changeRegister();
    });

    const getPointData = () => {
      state.datatypeArr = [];
      for (let i in props.pointTypeOptions) {
        let obj = {
          value: Number(i),
          label: props.pointTypeOptions[i],
          disabled: (Number(i) === 2 || Number(i) === 6 || Number(i) === 12) && (props.formData.template_type === 1)
        }
        state.datatypeArr.push(obj);
      }
    }

    const changeRegister = () => {
      if(state.addForm.register === 1) {
        state.datatypeArr.forEach(ele => { // 只能选择bool
          ele.disabled1 = ele.value!== 1
        })
        state.perOptions.forEach(ele => {// 可读可写
          ele.disabled = false;
        })
        state.addForm.point_type = 1;
        state.addForm.point_permissions = 1;
      }
      if(state.addForm.register === 2) {
        state.datatypeArr.forEach(ele => {// 只能选择bool
          ele.disabled1 = ele.value!== 1
        })
        state.perOptions.forEach(ele => {// 只能可读
          ele.disabled = ele.value === 2;
        })
        state.addForm.point_type = 1;
        state.addForm.point_permissions = 1;
      }
      if(state.addForm.register === 3) {
        state.datatypeArr.forEach(ele => {// 不支持bool
          ele.disabled1 = ele.value === 1
        })
        state.perOptions.forEach(ele => {// 只能可读
          ele.disabled = ele.value === 2;
        })
        state.addForm.point_type = 3;
        state.addForm.point_permissions = 1;
      }
      if(state.addForm.register === 4) {
        state.datatypeArr.forEach(ele => {// 不支持bool
          ele.disabled1 = ele.value === 1
        })
        state.perOptions.forEach(ele => {// 可读可写
          ele.disabled = false;
        })
        state.addForm.point_type = 3;
        state.addForm.point_permissions = 1;
      }
    }
    const closeDialog = () => {
      ctx.emit("dialogClose");
    };

    const saveP = async () => {
      await ruleFormRef.value.validate(async (valid) => {
        if (valid) {
          const param = {
            template_name: props.formData.template_name,
            ...state.addForm,
            address: Number(state.addForm.address),
            multiplier: Number(state.addForm.multiplier),
            register: Number(state.addForm.register)
          }
          const res = props.type === 'I' ? await infoApi.addP(param) : await infoApi.editP(param);
          if (res.code == 0) {
            ElMessage.success(res.message || "请求成功");
            ctx.emit("dialogSuccess");
          } else {
            ElMessage.error(res.data || res.message);
          }
        } else {
        }
      });


    };
    return {
      ...toRefs(state),
      visible,
      closeDialog,
      saveP,
      ruleFormRef,
      changeRegister
    };
  },
};
</script>
<style lang="scss" scoped>
.top-title {
  width: 100%;

  ::v-deep .el-card__body {
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-weight: 800;
    font-size: 16px;
  }
}

.btns {
  padding: 15px 0;
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.flex-center {
  display: flex;
  justify-content: center;
  padding: 10px 0;
  cursor: pointer;
}
</style>
