<template>
  <Modal
    class="modify-client-user"
    v-model="modalIsShow"
    :title="title"
    :mask-closable="false"
    @on-visible-change="visibleChange"
  >
    <Form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      :key="modalForm.id"
      :label-width="100"
    >
      <FormItem prop="loginName" label="账号">
        <Input
          v-model.trim="modalForm.loginName"
          placeholder="请输入账号"
          clearable
        ></Input>
      </FormItem>
      <FormItem prop="password" label="密码">
        <Input
          v-model.trim="modalForm.password"
          placeholder="请输入密码"
          clearable
        ></Input>
      </FormItem>
    </Form>
    <div slot="footer">
      <Button type="text" @click="cancel">取消</Button>
      <Button type="primary" :disabled="isSubmit" @click="submit">确认</Button>
    </div>
  </Modal>
</template>

<script>
import { updateClientUser } from "@/api";
import { password } from "@/plugins/formRules";

const initModalForm = {
  id: "",
  loginName: "",
  password: ""
};

export default {
  name: "modify-client-user",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "采集账号";
    }
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      rules: {
        loginName: [
          {
            required: true,
            pattern: /^[a-zA-Z0-9_-]{2,19}$/,
            message: "账号只能包含字母、数字、下划线以及短横线，长度3-20位",
            trigger: "change"
          }
        ],
        password
      }
    };
  },
  methods: {
    initData(val) {
      if (val.id) {
        this.modalForm = this.$objAssign(initModalForm, val);
      } else {
        this.modalForm = { ...initModalForm };
      }
    },
    visibleChange(visible) {
      if (visible) {
        this.initData(this.instance);
      }
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate();
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      let result = true;
      await updateClientUser(this.modalForm).catch(() => {
        result = false;
      });
      this.isSubmit = false;

      if (!result) return;

      this.$Message.success(this.title + "成功！");
      this.$emit("modified");
      this.cancel();
    }
  }
};
</script>
