<template>
  <el-form
    ref="userForm"
    size="small"
    :model="user"
    :rules="userFormRules"
    label-width="150px"
    style="width: 800px"
  >
    <el-card class="Basic" shadow="never" size="small">
      <div slot="header" class="clearfix">
        <span>{{ $t("system:userlist:title:Information") }}</span>
      </div>
      <el-form-item
        v-if="user.UserCode"
        :label="$t('system:userlist:table:S/N')"
        prop="UserCode"
      >
        <el-input v-model="user.UserCode" disabled />
      </el-form-item>

      <el-form-item
        :label="$t('system:userlist:table:UserName')"
        class="my_new_pwd"
        prop="UserName"
      >
        <el-input v-model="user.UserName" />
      </el-form-item>

      <el-form-item
        :label="$t('system:userlist:table:LastName')"
        prop="LastName"
      >
        <el-input v-model="user.LastName" />
      </el-form-item>
      <el-form-item
        :label="$t('system:userlist:table:FirstName')"
        prop="FirstName"
      >
        <el-input v-model="user.FirstName" />
      </el-form-item>
      <!-- <el-form-item
        :label="$t('system:userlist:table:Gender')"
        prop="Sex"
        style="margin-right: 40px"
      >
        <el-radio-group v-model="user.Sex">
          <el-radio :label="1">Male</el-radio>
          <el-radio :label="0">Female</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item :label="$t('system:userlist:table:Email')" prop="EMail">
        <el-input v-model="user.EMail" />
      </el-form-item>
      <el-form-item :label="$t('system:userlist:table:Phone')" prop="Phone">
        <el-input v-model="user.Phone" />
      </el-form-item>
      <el-form-item
        v-if="type == 1"
        :label="$t('system:userlist:table:Disable')"
      >
        <el-switch
          v-model="user.Status"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
      <!-- <el-form-item label="IsTestUser:">
        <el-switch v-model="user.IsTestUser" />
      </el-form-item> -->
      <el-form-item
        :label="$t('system:userlist:table:UserType')"
        prop="UserTypeId"
      >
        <el-select
          ref="userType"
          v-model="user.UserTypeId"
          size="small"
          placeholder=""
          style="width: 100%"
          :disabled="user.CanEditUserType === false"
        >
          <template v-for="(userType, key) of userTypeOptions">
            <el-option
              :key="key"
              :label="userType.UserType"
              :value="userType.Id"
            />
          </template>
        </el-select>
      </el-form-item>
      <!-- <el-form-item
        :label="$t('trials:researchForm:form:checkCode')"
        prop="checkCode"
        v-if="!IsCanConnectInternet"
      >
        <el-input v-model="user.checkCode" type="number" />
        <span style="color: red"
          >请输入，校验码用于用户首次登录、重置密码时的校验</span
        >
      </el-form-item> -->
    </el-card>

    <el-card
      class="Affiliation"
      shadow="never"
      style="margin-top: 10px"
      size="small"
    >
      <div slot="header" class="clearfix">
        <span>{{ $t("system:userlist:title:Affiliation") }}</span>
      </div>
      <el-form-item prop="IsZhiZhun">
        <el-radio-group
          v-model="user.IsZhiZhun"
          @change="OrgnizationTypeChanged"
          :disabled="IsZhiZhunDisabled"
        >
          <el-radio :label="true">{{
            $t("system:userlist:title:Internal")
          }}</el-radio>
          <el-radio :label="false">{{
            $t("system:userlist:title:External")
          }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('system:userlist:table:OrganizationName')">
        <el-input
          v-model="user.OrganizationName"
          :disabled="user.IsZhiZhun === true"
        />
      </el-form-item>

      <el-form-item
        :label="$t('system:userlist:table:Department')"
        prop="DepartmentName"
      >
        <el-input v-model="user.DepartmentName" />
      </el-form-item>
      <el-form-item
        :label="$t('system:userlist:table:Position')"
        prop="PositionName"
      >
        <el-input v-model="user.PositionName" />
      </el-form-item>
    </el-card>
    <el-form-item>
      <el-button
        type="primary"
        size="small"
        :disabled="isDisabled"
        style="margin: 10px 15px"
        @click="handleSave"
        >{{ $t("passwordReset:button:submit") }}</el-button
      >
    </el-form-item>
  </el-form>
</template>
<script>
import {
  getUser,
  addUser,
  updateUser,
  getUserTypeListByUserType,
} from "@/api/admin.js";
import { getHospital } from "@/api/hospital.js";
export default {
  name: "UserInfo",
  props: {
    userId: { type: String, default: "" },
  },
  data() {
    var validatePassword = (rule, value, callback) => {
      var lang = zzSessionStorage.getItem("lang")
        ? zzSessionStorage.getItem("lang")
        : "zh";
      /* eslint-disable */
      var reg1 = /^[a-zA-Z0-9_]{4,16}$/; //密码必须是8位以上、必须含有字母、数字、特殊符号
      console.log(!reg1.test(value));
      if (!reg1.test(value)) {
        callback(
          lang === "zh"
            ? new Error(
                "1）新建账号，用户名字符长度最小为4个字符，最大为16个字符，只可使用字母、数字、下划线；"
              )
            : new Error(
                "For a new account, the username must have:1) At least 4 characters;2) At most 16 characters;3)Only letters, numbers, and underscores are allowed."
              )
        );
      } else {
        callback();
      }
    };
    return {
      user: {
        UserName: "",
        LastName: "",
        FirstName: "",
        Sex: "9",
        EMail: "",
        Phone: "",
        UserTypeId: "",
        IsZhiZhun: "",
        OrganizationName: "",
        DepartmentName: "",
        PositionName: "",
        IsTestUser: false,
        verifyCode: "",
        checkCode: "",
      },
      userFormRules: {
        checkCode: [
          {
            required: true,
            message: "Please Input",
            trigger: ["blur", "change"],
          },
        ],
        UserName: [
          { required: true, validator: validatePassword, trigger: "blur" },
        ],
        UserTypeId: [
          {
            required: true,
            message: "Please Select",
            trigger: ["blur", "change"],
          },
        ],
        IsZhiZhun: [
          {
            required: true,
            message: "Please Select",
            trigger: ["blur", "change"],
          },
        ],
        OrganizationName: [
          { required: true, message: "Please specify", trigger: "blur" },
        ],
        LastName: [
          { required: true, message: "Please specify", trigger: "blur" },
          { max: 50, message: "The maximum length is 50" },
        ],
        FirstName: [
          { required: true, message: "Please specify", trigger: "blur" },
          { max: 50, message: "The maximum length is 50" },
        ],
        Phone: [
          {
            max: 20,
            min: 7,
            message: "The length is 7 to 20",
            trigger: ["blur"],
          },
        ],
        EMail: [
          {
            required: true,
            message: "Please input the email address",
            trigger: "blur",
          },
          {
            type: "email",
            message: "Please input the correct email address",
            trigger: ["blur"],
          },
          { max: 50, message: "The maximum length is 50" },
        ],
        Sex: [{ required: true, message: "Please specify", trigger: "blur" }],
        Status: [
          { required: true, message: "Please specify", trigger: "blur" },
        ],
        DepartmentName: [{ max: 50, message: "The maximum length is 50" }],
        PositionName: [{ max: 50, message: "The maximum length is 50" }],
      },
      userTypeOptions: [],
      isDisabled: false,
      type: 0, // 1为编辑，0为新增
      IsCanConnectInternet: true, // 是否连接互联网
      hospitalName: null, // 医院名称
      IsZhiZhunDisabled: false,
    };
  },
  watch: {
    "user.UserTypeId": {
      handler() {
        if (this.user.UserTypeId) {
          let name = this.getUserType(this.user.UserTypeId);
          if (["PM", "PI", "SR", "OA"].includes(name)) {
            this.user.IsZhiZhun = true;
            this.user.OrganizationName = this.hospitalName;
            return (this.IsZhiZhunDisabled = true);
          }
        }
        this.user.IsZhiZhun = false;
        this.user.OrganizationName = null;
        this.IsZhiZhunDisabled = false;
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    this.getUserTypeList();
    if (this.userId !== "") {
      this.getUserInfo();
      this.type = 1;
    } else {
      this.type = 0;
    }
    this.getInfo();
  },
  methods: {
    getUserType(id) {
      let obj = this.userTypeOptions.find((item) => item.Id === id);
      return obj.UserTypeShortName;
    },
    // 获取医院信息
    async getInfo() {
      try {
        let res = await getHospital();
        if (res.IsSuccess) {
          this.IsCanConnectInternet = res.Result.IsCanConnectInternet;
          this.hospitalName = res.Result.HospitalName;
        }
      } catch (err) {
        console.log(err);
      }
    },
    handleSave() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          this.isDisabled = true;
          const selectedUserType = this.userTypeOptions.filter(
            (item) => item.Id === this.user.UserTypeId
          );
          if (selectedUserType.length > 0) {
            this.user.UserTypeEnum = selectedUserType[0].UserTypeEnum;
          }
          this.user.BaseUrl = `${location.protocol}//${location.host}/login`;
          this.user.RouteUrl = `${location.protocol}//${location.host}/email-recompose`;
          if (this.user.Id) {
            updateUser(this.user)
              .then((res) => {
                this.isDisabled = false;
                this.$message.success("Updated successfully");
              })
              .catch(() => {
                this.isDisabled = false;
              });
          } else {
            addUser(this.user)
              .then((res) => {
                this.isDisabled = false;
                this.user.Id = res.Result.Id;
                this.user.UserCode = res.Result.UserCode;
                this.$emit("getUserId", res.Result.Id);
                this.$message.success("Added successfully");
                this.$router.push({ path: "/system/user/list" });
              })
              .catch(() => {
                this.isDisabled = false;
              });
          }
        }
      });
    },
    getUserTypeList() {
      getUserTypeListByUserType(0).then((res) => {
        if (res.IsSuccess) {
          let arr = [2, 4, 5, 8, 9, 12, 14];
          if (this.hasPermi(["role:oa"])) {
            arr = [4, 5, 8, 9, 12, 14];
          }
          this.userTypeOptions = res.Result.map((item) => {
            if (arr.includes(item.UserTypeEnum)) {
              return item;
            }
          }).filter((item) => item);
        }
      });
    },
    getUserInfo() {
      getUser(this.userId).then((res) => {
        this.user = res.Result;
        this.user.Status = parseFloat(this.user.Status);
      });
    },
    OrgnizationTypeChanged(val) {
      if (val) {
        this.user.OrganizationName = this.hospitalName;
      } else {
        this.user.OrganizationName = "";
      }
    },
  },
};
</script>
<style scoped>
::v-deep .is-error.my_new_pwd {
  margin-bottom: 40px;
}
</style>

