<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="name">
        <el-input v-model="addForm.name" placeholder="请输入设备名称（不超过10）" maxlength="10" clearable :disabled="type !== 'I'" />
      </el-form-item>
      <el-form-item label="设备id:" prop="id">
        <el-input v-model="addForm.id" placeholder="请输入设备id:1-255" clearable type="number" />
      </el-form-item>
      <el-form-item label="模板名称:" prop="template_name">
        <el-select v-model="addForm.template_name" size="mini" placeholder="请选择模板名称">
          <el-option v-for="item in modelArr" :key="item.name" :label="item.name" :value="item.name" />
        </el-select>
      </el-form-item>

      <el-form-item label="设备描述:" prop="description">
        <el-input v-model="addForm.description" placeholder="请输入点位描述（不超过50）" maxlength="50" 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="saveSet"> 保存 </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", "setData", "type"],
  emits: ["dialogClose", "dialogSuccess"],
  setup(props, ctx) {
    const checkSetId = (rule, value, callback) => {
      let num = Number(value);
      if (value && (num >= 1 && num <= 255)) {
        callback();
      } else {
        callback(new Error("设备ID：1-255"));
      }
    };
    const ruleFormRef = ref(null);
    const state = reactive({
      addForm: {
      },
      modelArr: [],
      rules: {
        name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
        template_name: [{ required: true, message: "请选择模板名称", trigger: "blur" }],
        id: [
          { required: true, message: "请输入设备ID", trigger: "blur" },
          { required: true, validator: checkSetId, trigger: "blur" }
        ],
      },
    });
    const visible = computed(() => {
      return props.dialogVisible;
    });

    onMounted(() => {
      state.addForm = props.setData;
      // 获取模板数据
      getTxTemplate();
    });
    const getTxTemplate = async () => {
      const param = {
        driver_name: props.formData.name
      }
      const res = await infoApi.getTxTemplate(param);
      if (res.code == 0) {
        // 获取数据
        state.modelArr = [];
        const data = res.data;
        for (let i in data) {
          let obj = {
            key: Number(i),
            name: data[i]
          }
          state.modelArr.push(obj);
        }
        state.addForm.template_name = state.modelArr[0].name;
      } else {
        ElMessage.error(res.data || res.message);
      }
    };
    const closeDialog = () => {
      ctx.emit("dialogClose");
    };

    const scanData = () => { };

    const saveSet = async () => {
      await ruleFormRef.value.validate(async (valid) => {
        if (valid) {
          const param = {
            driver_name: props.formData.name,
            ...state.addForm,
            id: Number(state.addForm.id)
          }
          const res = props.type === 'I' ? await infoApi.addSet(param) : await infoApi.editSet(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,
      saveSet,
      ruleFormRef
    };
  },
};
</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>
