<!--
 * @Author: Jason Liu
 * @Date: 2022-04-22 15:37:44
 * @Desc: 用户选项卡
-->
<template>
  <a-drawer
    :loading="loading"
    placement="right"
    :destroy-on-close="true"
    :visible="show"
    width="480"
    @close="
      () => {
        show = false;
      }
    "
  >
    <template slot="title">
      {{ edit ? $t("维护用户信息") : $t("个人档案") }}
    </template>
    <a-spin :spinning="loading">
      <a-card :hoverable="true" class="user_detail_card">
        <div class="user_detail_title">
          <div class="user_avatar_uploader">
            <div class="ant-upload">
              <img :src="defaultimg" alt="avatar" />
            </div>
          </div>
          <a-upload
            v-if="false"
            name="file"
            list-type="picture-card"
            class="user_avatar_uploader"
            :show-upload-list="false"
            @change="uploadFun"
            :headers="{
              Authorization: `${$storage.get('tokey')}@${$storage.get('Bearer')}`,
            }"
            accept="image/png, image/jpeg, image/gif, image/jpg"
            :action="action"
            :beforeUpload="beforeUpload"
          >
            <img :src="defaultimg" alt="avatar" />
          </a-upload>
        </div>
        <a-form-model
          ref="userfrom"
          class="user_info_from"
          :model="user"
          :rules="rules"
          v-bind="layout"
        >
          <a-form-model-item has-feedback :label="$t('账号')" prop="userName">
            <a-input v-model="user.userName" :placeholder="$t('请输入用户账号')" />
          </a-form-model-item>
          <a-form-model-item has-feedback :label="$t('昵称')" prop="nickName">
            <a-input v-model="user.nickName" :placeholder="$t('请输入用户昵称')" />
          </a-form-model-item>
          <a-form-model-item has-feedback :label="$t('性别')" prop="sex">
            <a-select v-model="user.sex" :placeholder="$t('请选择性别')">
              <a-select-option value="1">{{ $t("男") }}</a-select-option>
              <a-select-option value="2">{{ $t("女") }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item has-feedback :label="$t('出生日期')" prop="birthDate">
            <a-date-picker
              :locale="locale"
              v-model="user.birthDate"
              :placeholder="$t('请选择出生日期')"
              :disabled-date="disabledDate"
            ></a-date-picker>
          </a-form-model-item>
          <a-form-model-item has-feedback :label="$t('手机号码')" prop="phonenumber">
            <a-input v-model="user.phonenumber" :placeholder="$t('请输入手机号码')" />
          </a-form-model-item>
          <a-form-model-item has-feedback :label="$t('邮箱')" prop="email">
            <a-input v-model="user.email" :placeholder="$t('请输入邮箱地址')" />
          </a-form-model-item>
          <a-form-model-item has-feedback :label="$t('用户简介')" prop="remark">
            <a-input
              v-model="user.remark"
              :placeholder="$t('请输入用户简介')"
              type="textarea"
            />
          </a-form-model-item>
        </a-form-model>
      </a-card>
    </a-spin>
    <div class="a_foot_nuttop">
      <a-space :size="12">
        <a-button @click="show = false">{{ $t("关闭") }}</a-button>
        <a-button type="primary" @click="submit" :loading="loading">{{
          $t("保存")
        }}</a-button>
      </a-space>
    </div>
  </a-drawer>
</template>
<script>
const user_avatar = require("w-vue-basis/src/assets/images/bg_header.png"); //用户头像
const $userService = require("w-vue-basis/src/api/userService");
const $appService = require("w-vue-basis/src/api/appService");

export default {
  name: "userCard",
  props: {
    value: {
      //是否显示
      type: Boolean,
      default() {
        return false;
      },
    },
    userId: {
      //用户ID
      type: [Number, String],
    },
    info: {
      //用户信息
      type: [Object],
    },
    edit: {
      //是否编辑
      type: Boolean,
      default() {
        return false;
      },
    },
  },
  data() {
    return {
      show: this.value,
      loading: false,
      action: `${$service.portalService}/common/upload`,
      defaultimg: `${user_avatar}`,
      user: {
        deptId: undefined, //部门
        userId: undefined,
        avatar: undefined,
        userName: undefined,
        nickName: undefined,
        sex: undefined,
        birthDate: undefined,
        phonenumber: undefined,
        email: undefined,
        remark: undefined,
      },
      rules: {},
      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 14 },
      },
    };
  },
  created() {
    this.rules = {
      userName: [{ required: true, message: $t("请输入用户账号"), trigger: "blur" }],

      nickName: [{ required: true, message: $t("请输入用户昵称"), trigger: "blur" }],

      phonenumber: [
        { required: true, message: $t("请输入手机号码"), trigger: "blur" },
        {
          validator: (rule, value, callback) => {
            let masage = "";
            var reg = /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[13589])\d{1}))\d{7}$/;
            if (!value) {
              masage = $t("请输入手机号码");
              return callback(new Error(`${masage}!`));
            } else if (!reg.test(value)) {
              masage = $t("手机号码格式不正确");
              return callback(new Error(`${masage}!`));
            } else {
              callback();
            }
          },
          trigger: "change",
        },
      ],

      sex: [{ required: true, message: $t("请选择性别"), trigger: "blur" }],
      email: [
        { required: true, message: $t("请输入邮箱地址"), trigger: "blur" },
        {
          validator: (rule, value, callback) => {
            let masage = "";

            if (value) {
              var reg = /^[a-z0-9]+([._-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/;
              if (!reg.test(value)) {
                masage = $t("邮箱格式不正确");
                return callback(new Error(`${masage}!`));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: "change",
        },
      ],
    };
  },
  methods: {
    /**
     * @Author: y_zp
     * @description: 设置不可选日期
     */
    disabledDate(cur) {
      return cur && cur > moment().endOf("day");
    },
    /**
     * @Author: Jason Liu
     * @description: 提交保存事件
     */
    submit() {
      this.$refs["userfrom"].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.user._X_ROW_KEY = undefined;
          $userService
            .saveUser({
              ...this.user,
              birthDate: this.user.birthDate
                ? moment(this.user.birthDate).format("YYYY-MM-DD")
                : "",
            })
            .then((req) => {
              this.$message.success($t("用户保存成功"));
              this.show = false;
              this.$emit("update");
              // 编辑当前账户，需要更新用户信息
              if (!this.edit) {
                $appService.getUserInfo();
              }
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    beforeUpload(file, fileList) {
      let type = file.type;
      if (["image/png", "image/jpg", "image/jpeg", "image/gif"].indexOf(type) == -1) {
        this.$message.warn($t("请选择图片"));
        return false;
      }
    },
    /**
     * @Author: y_zp
     * @description: 上传
     */
    uploadFun(info) {
      if (info.file.status === "done") {
        if (info.file.response.success) {
          this.user.avatar = `${info.file.response.data.fileName}`;
          //this.defaultimg = `${this.user.avatar}?time=${new Date().getTime()}`;
          this.$store.state.userInfo.avatar = this.user.avatar;
        } else {
          this.$message.error(info.file.response.errorDetail);
        }
      } else if (info.file.status === "error") {
        this.$message.error($t("上传失败，请重试"));
      }
    },
    /**
     * @Author: Jason Liu
     * @description: 获取用户信息
     */
    getUserInfo() {
      let info = this.$storage.userInfo;
      // 用户是唯一的
      $userService
        .getUserList({
          queryParams: {
            F_userName_eq: info.userId,
          },
          pageNum: 1,
          pageSize: 15,
        })
        .then((req) => {
          let val = req.data[0];
          this.user = {
            ...val,
            birthDate: val.birthDate ? moment(val.birthDate) : null,
          };
          // if (this.user.avatar) {
          //   this.defaultimg = `${this.user.avatar}`;
          // } else {
          this.defaultimg = `${user_avatar}`;
          // }
        });
    },
  },
  watch: {
    value(val) {
      this.show = val;
      if (val) {
        if (this.edit) {
          this.user = {
            ...this.info,
            birthDate: this.info.birthDate ? moment(this.info.birthDate) : null,
          };
          // if (this.user.avatar) {
          //   this.defaultimg = `${this.user.avatar}`;
          // } else {
          this.defaultimg = `${user_avatar}`;
          // }
        } else {
          this.getUserInfo();
        }
      }
    },
    show(val) {
      this.$emit("input", val);
    },
  },
};
</script>
<style lang="less">
.user_detail_card {
  width: 100%;
  border: none;
  .user_detail_title {
    text-align: center;
    p {
      font-size: 20px;
      margin: 5px 0 0;
    }
  }
  .user_avatar_uploader {
    .ant-upload {
      width: 108px;
      height: 108px;
      margin: 0;
      border-radius: 50%;
      margin-left: 0;
      display: block;
      padding: 0;
      float: none;
      margin: 0 auto;
      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
    }
    .ant-upload.ant-upload-select-picture-card .ant-upload {
      display: block;
      padding: 0;
    }
  }

  .user_info_from {
    margin: 0 16px;

    .ant-calendar-picker {
      width: 100%;
    }
    .ant-input,
    .ant-select-selection {
      border: inherit;
      border-bottom: thin solid #dedede;
      border-radius: 0;
      padding-left: 15px;
      outline: medium;
    }
    .ant-form-item {
      margin-bottom: inherit;
    }
  }
}
</style>
