<template>
  <Popup ref="popup" title="账号信息" @closed="dialogClosed">
    <el-form :model="form" :rules="rules" ref="form" label-width="80px">
      <el-form-item label="院区名称" prop="wardId">
        <el-select v-model="form.wardId" @change="form.deptIds = []">
          <el-option
            v-for="item in wardListOptions"
            :key="item.id"
            :disabled="item.disabled"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户姓名" prop="nickName">
            <el-input v-model="form.nickName" :maxlength="32"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="账户名称" prop="userName">
            <el-input v-model="form.userName" :maxlength="32"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="使用科室" prop="deptIds">
            <TreeDept ref="treeDept" v-model="form.deptIds" :props="{ multiple: true }" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="账户角色" prop="roleId">
            <el-select v-model="form.roleId">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="联系电话" prop="phoneNumber" required>
        <el-input v-model="form.phoneNumber"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" required>
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="password2" required>
        <el-input type="password" v-model="form.password2"></el-input>
      </el-form-item>
      <el-form-item label="账号状态" prop="status" required>
        <el-switch
          :value="form.status === ACCOUNT_STATUS.getValueByName('enabled')"
          @change="form.status = $event ? ACCOUNT_STATUS.getValueByName('enabled') : ACCOUNT_STATUS.getValueByName('disabled')"
        />
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </Popup>
</template>

<script>
import Popup from "@/components/Popup";
import TreeDept from "@/components/TreeDept";
import { validContact, validPasword } from "@/utils/validate";
const DEFAULT_PASSWORD = "________";
import { ACCOUNT_STATUS } from '@/enums/index'
import {
  getAllHospitalList,
  getRoleAllList,
  addAccount,
  editAccount,
} from "@/api/admin";
export default {
  components: {
    Popup,
    TreeDept,
  },
  data() {
    return {
      ACCOUNT_STATUS,
      loading: false,
      form: this.getFormDefaultValue(),
      rules: {
        wardId: [{ required: true, message: "请选择院区", trigger: "change" }],
        nickName: [
          { required: true, message: "请输入用户姓名", trigger: "blur" },
          { max: 32, message: "长度不能超过32个字符", trigger: "blur" },
        ],
        userName: [
          { required: true, message: "请输入账户名称", trigger: "blur" },
          { max: 32, message: "长度不能超过32个字符", trigger: "blur" },
        ],
        deptIds: [{ required: true, message: "请输入选择科室", trigger: "change" }],
        roleId: [{ required: true, message: "请输入选择角色", trigger: "change" }],
        phoneNumber: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback("请输入联系电话");
              }
              if (!validContact(value)) {
                return callback("联系电话不正确");
              }
              callback();
            },
            trigger: "blur",
          },
        ],
        password: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback("请输入密码");
              }
              if (value === DEFAULT_PASSWORD) {
                return callback();
              }
              if (!validPasword(value)) {
                return callback("密码长度8位以上，由数字、大小写字母、特殊字符(@#$%^&+=!)组成");
              }
              callback();
            },
            trigger: "blur",
          },
        ],
        password2: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback("请输入确认密码");
              }
              if (value !== this.form.password) {
                return callback("两次输入密码不一致");
              }
              callback();
            },
            trigger: "blur",
          },
        ],
      },
      cascaderProps: {
        emitPath: false,
        label: "name",
        value: "id",
        leaf: "children",
        multiple: true,
        // checkStrictly: true,
      },
      wardList: [],
      roleList: [],
      defaultValue: {},
    };
  },
  created() {
    this.loadHospital();
    this.loadRoleList();
  },
  computed: {
    // 院区如果禁用了，需要回显，但是不可以选择
    wardListOptions() {
      if (!this.defaultValue.wardId) {
        return this.wardList;
      }
      if (this.wardList.find((item) => item.id === this.defaultValue.wardId)) {
        return this.wardList;
      }
      return [
        {
          id: this.defaultValue.wardId,
          name: this.defaultValue.wardName,
          disabled: true,
        },
        ...this.wardList,
      ];
    },
  },
  watch: {
    "form.wardId"() {
      if (this.form.wardId) {
        this.$nextTick(() => {
          this.$refs.treeDept.loadDept({ wardId: this.form.wardId });
        });
      }
    },
  },
  methods: {
    loadRoleList() {
      getRoleAllList().then((res) => {
        this.roleList = res.data;
      });
    },
    loadHospital() {
      getAllHospitalList().then((res) => {
        this.wardList = res.data || [];
      });
    },
    getFormDefaultValue() {
      return {
        wardId: "",
        nickName: "",
        userName: "",
        deptIds: [],
        roleId: "",
        phoneNumber: "",
        password: "",
        password2: "",
        status: ACCOUNT_STATUS.getValueByName('enabled'),
      };
    },
    open(params) {
      const defaultValue = {};
      if (params) {
        for (const key of [...Object.keys(this.form), "id"]) {
          this.form[key] = params[key];
        }
        this.form.password = DEFAULT_PASSWORD;
        this.form.password2 = DEFAULT_PASSWORD;
        defaultValue.wardId = params.wardId;
        defaultValue.wardName = params.wardName;
      }
      this.defaultValue = defaultValue;
      this.$refs.popup.open(params);
      this.promise = {};
      return new Promise((resolve, reject) => {
        this.promise.resolve = resolve;
        this.promise.reject = reject;
      });
    },
    handleCancel() {
      this.$refs.popup.close();
    },
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          try {
            const params = {
              ...this.form,
              password: this.form.password === DEFAULT_PASSWORD ? undefined : this.form.password,
              password2: undefined,
            };

            if (this.form.id) {
              await editAccount(params);
              this.$message.success("修改成功");
            } else {
              await addAccount(params);
              this.$message.success("新增成功");
            }
            this.$refs.popup.close();
            this.promise.resolve();
          } finally {
            this.loading = false;
          }
        } else {
          // 表单校验失败
          return false;
        }
      });
    },
    dialogClosed() {
      this.form = this.getFormDefaultValue();
      this.$refs.treeDept.clear();
      this.$nextTick(this.$refs.form.clearValidate);
      // this.promise.reject();
    },
  },
};
</script>
