<template>
  <Modal
    class="modify-org"
    v-model="modalIsShow"
    :title="title"
    :mask-closable="false"
    :width="modalWidth"
    @on-visible-change="visibleChange"
  >
    <div :class="['form-list', { 'form-list-1': isEdit }]">
      <Form
        class="modal-form"
        v-for="(itemForm, findex) in modalForms"
        :key="findex"
        :ref="`modalFormComp${findex}`"
        :model="itemForm"
        :rules="rules"
        :label-width="100"
      >
        <FormItem
          prop="name"
          :label="itemForm.userType === '1' ? '机构名称' : '项目经理'"
        >
          <Input
            size="large"
            v-model.trim="itemForm.name"
            placeholder="请输入名称"
            clearable
          ></Input>
        </FormItem>
        <FormItem prop="loginName" label="账号">
          <Input
            size="large"
            v-model.trim="itemForm.loginName"
            placeholder="请输入账号"
            :disabled="isEdit"
            clearable
          ></Input>
        </FormItem>
        <FormItem prop="password" label="密码" v-if="isEdit">
          <Input
            size="large"
            type="text"
            v-model.trim="itemForm.password"
            placeholder="输入密码"
            clearable
          ></Input>
        </FormItem>
      </Form>
    </div>
    <div slot="footer">
      <Button shape="circle" type="primary" :disabled="isSubmit" @click="submit"
        >确认</Button
      >
      <Button shape="circle" @click="cancel">取消</Button>
    </div>
  </Modal>
</template>

<script>
import { createOrg, updateOrgUser } from "@/api";
import { password } from "@/plugins/formRules";

const initModalForms = [
  {
    name: "",
    loginName: "",
    userType: "1"
  },
  {
    name: "",
    loginName: "",
    userType: "2"
  }
];

export default {
  name: "modify-org",
  props: {
    instance: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  computed: {
    isEdit() {
      return !!this.instance.length;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "机构信息";
    },
    modalWidth() {
      return this.isEdit ? 500 : 800;
    }
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForms: [],
      rules: {
        name: [
          {
            required: true,
            message: "请输入名称",
            trigger: "change"
          }
        ],
        loginName: [
          {
            required: true,
            pattern: /^[a-zA-Z0-9_-]{3,20}$/,
            message: "账号只能包含字母、数字、下划线以及短横线，长度3-20位",
            trigger: "change"
          }
        ],
        password
      }
    };
  },
  methods: {
    initData(val) {
      if (this.instance.length) {
        this.modalForms = this.instance.map(item => {
          return { ...item };
        });
      } else {
        this.modalForms = initModalForms.map(item => {
          return { ...item };
        });
      }
      // this.modalForms.forEach((item, index) => {
      //   this.$refs[`modalFormComp${index}`].resetFields();
      // });
    },
    visibleChange(visible) {
      if (visible) {
        this.initData();
      }
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async submit() {
      const validAll = this.modalForms.map((item, index) => {
        return this.$refs[`modalFormComp${index}`][0].validate();
      });
      const res = await Promise.all(validAll).catch(() => {});
      console.log(res);
      if (res.some(item => !item)) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      let data = null;
      if (this.isEdit) {
        data = await updateOrgUser(this.modalForms[0]).catch(() => {});
      } else {
        data = await createOrg({
          markUsers: this.modalForms
        }).catch(() => {});
      }
      this.isSubmit = false;

      if (!data) return;

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