<template>
  <el-dialog :visible.sync="visible" title="远程配网" width="400px">
    <el-form :model="form" ref="form" :rules="rules" label-position="top">
      <el-row>
        <form-col :span="24" label="WIFI名称" prop="wifiName">
          <el-input v-model="form.wifiName" placeholder="请输入WIFI名称"/>
        </form-col>
        <form-col :span="24" label="WIFI密码" prop="wifiPwd">
          <el-input v-model="form.wifiPwd" placeholder="请输入WIFI密码" type="password"/>
        </form-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button plain @click="cancel">取 消</el-button>
      <el-button plain type="primary" @click="submit" :loading="submitLoading">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { deviceSetWifi } from '@/api/system/device'

export default {
  name: "DeviceSetWifiDialog",
  props: {
    show: {
      type: Boolean,
      default: false
    },
    deviceId: {
      type: String,
      default: null,
    }
  },
  data() {
    return {
      submitLoading: false,
      form: {
        wifiName: null,
        wifiPwd: null
      },
      rules: {
        wifiName: [
          { required: true, message: '请输入WIFI名称', trigger: 'blur' }
        ],
        wifiPwd: [
          { required: true, message: '请输入WIFI密码', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    visible: {
      set(val) {
        this.$emit('update:show', val);
      },
      get() {
        return this.show;
      }
    }
  },
  methods: {
    cancel() {
      this.visible = false
    },
    submit(){
      this.$refs.form.validate(valid => {
        if (valid) {
          let data = {deviceId: this.deviceId, ...this.form};
          this.submitLoading = true;
          deviceSetWifi(data).then(res => {
            if (res.code === 200) {
              this.$message.success(`配网成功！新的WIFI为：${data.wifiName}`);
              this.$emit('success', data);
              this.visible = false;
            }
          }).finally(() => {
            this.submitLoading = false;
          })
        }
      })
    }
  }
}
</script>
