<template>
  <el-dialog
    title="IP设备管控"
    :visible="true"
    width="30%"
    :before-close="handleClose"
  >
    <el-form
      ref="form"
      v-loading="loading"
      :model="form"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item
        v-loading="loadingIpDeviceStatus"
        label="操作"
        prop="deviceListBlock"
      >
        <el-select v-model="form.deviceListBlock">
          <el-option label="不限制" :value="null" />
          <el-option label="加入黑名单" :value="true" />
          <el-option label="加入白名单" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit()">提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { ipDeviceHandle } from "@/api/approval";
import { getUserIpDevice } from "@/api/app-user";
import { mapGetters } from "vuex";
export default {
  name: "AccountHandle",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      required: true
    }
  },
  data() {
    const commonRules = [
      { required: true, message: "必填字段不可为空", trigger: "blur" }
    ];
    return {
      loading: false,
      loadingIpDeviceStatus: true,
      form: {
        userId: "",
        deviceListBlock: ""
      },
      formRules: {
        // deviceListBlock: commonRules
      }
    };
  },
  computed: {
    ...mapGetters(["buttonPermissions"])
  },
  watch: {
    userId: {
      handler(newVal) {
        if (newVal) {
          this.form.userId = newVal;
          this.loadIpDeviceStatus(newVal);
        }
      },
      immediate: true
    }
  },
  methods: {
    loadIpDeviceStatus(userId) {
      const that = this;
      that.loadingIpDeviceStatus = true;
      getUserIpDevice(userId)
        .then(res => {
          const deviceListBlock =
            res && res.body && res.body.deviceListBlock !== undefined
              ? res.body.deviceListBlock
              : null;
          that.form.deviceListBlock = deviceListBlock;

          that.loadingIpDeviceStatus = false;
        })
        .catch(() => {
          that.loadingIpDeviceStatus = false;
        });
    },
    handleClose() {
      this.$emit("close");
    },
    submit() {
      const that = this;
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error("error submit!!");
          return false;
        }
        that.form.userId = that.userId;

        that.loading = true;
        console.log("that.form:", that.form);

        ipDeviceHandle(that.form)
          .then(res => {
            that.loading = false;
            that.$emit("success", Object.assign({}, that.form));
            that.handleClose();
          })
          .catch(err => {
            that.loading = false;
            that.$emit("fial", err);
            that.handleClose();
          });
      });
    }
  }
};
</script>
