import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, watch } from "vue";
import { ElForm, ElFormItem, ElInput, ElProgress } from "element-plus";
import type { UserInfo } from "types/user";
import { getUserInfoAPI } from "@/api/login";
import {
  putUpdateEmailAPI,
  putUpdatePasswordAPI,
  putUpdatePhoneAPI
} from "@/api/user";
import { isAllEmpty, isEmail, isPhone, storageLocal } from "@pureadmin/utils";
import { zxcvbn } from "@zxcvbn-ts/core";
import { setUserInfo, userInfoKey } from "@/utils/auth";

export const useUserInfo = () => {
  /** 密码正则（密码格式应为8-18位数字、字母、符号的任意两种组合） */
  const REGEXP_PWD =
    /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)]|[()])+$)(?!^.*[\u4E00-\u9FA5].*$)([^(0-9a-zA-Z)]|[()]|[a-z]|[A-Z]|[0-9]){8,18}$/;

  const pwdProgress = [
    { color: "#e74242", text: "非常弱" },
    { color: "#EFBD47", text: "弱" },
    { color: "#ffa500", text: "一般" },
    { color: "#1bbf1b", text: "强" },
    { color: "#008000", text: "非常强" }
  ];
  // 当前密码强度（0-4）
  const curScore = ref();
  const ruleFormRef = ref();
  /**密码表单 */
  const passwordForm = reactive({
    oldPassword: "",
    newPassword: ""
  });
  /**联系方式表单 */
  const phoneForm = reactive({
    password: "",
    phone: ""
  });
  /**邮箱*/
  const emailForm = reactive({
    password: "",
    email: ""
  });
  const userInfo = reactive<UserInfo>({
    id: "",
    username: "",
    gender: 1,
    avatar: "",
    email: "",
    nickname: "",
    phone: "",
    status: 0,
    create_time: "",
    update_time: "",
    roles: [],
    permissions: []
  });
  /**获取个人信息 */
  const getUserInfo = async () => {
    const res = await getUserInfoAPI();
    if (res.success) {
      Object.assign(userInfo, res.data);
      const user = storageLocal().getItem<object>(userInfoKey);
      storageLocal().setItem(userInfoKey, {
        ...user,
        avatar: res.data.avatar,
        nickname: res.data.nickname
      });
      setUserInfo(res.data);
    }
  };

  /**组件挂载执行 */
  onMounted(async () => {
    await getUserInfo();
  });
  watch(
    passwordForm,
    ({ newPassword }) =>
      (curScore.value = isAllEmpty(newPassword)
        ? -1
        : zxcvbn(newPassword).score)
  );
  /**密码校验规则 */
  const passwordRule = [
    {
      validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入新密码~"));
        } else if (!REGEXP_PWD.test(value)) {
          callback(
            new Error("密码格式应为8-18位数字、字母、符号的任意两种组合~")
          );
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ];
  /**手机好校验规则 */
  const phoneRule = [
    {
      validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入手机号码~"));
        } else if (!isPhone(value)) {
          callback(new Error("请输入正确的手机号码格式~"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ];
  /**邮箱校验规则 */
  const emailRule = [
    {
      validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入邮箱~"));
        } else if (!isEmail(value)) {
          callback(new Error("请输入正确的邮箱格式~"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ];
  /** 重置密码 */
  const handleReset = (row: UserInfo) => {
    addDialog({
      title: `重置 ${row.username}--${row.nickname} 的密码`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => (
        <div>
          <ElForm ref={ruleFormRef} model={passwordForm}>
            <ElFormItem
              prop="oldPassword"
              rules={[
                {
                  required: true,
                  message: "请输入旧密码~",
                  trigger: "blur"
                }
              ]}
            >
              <ElInput
                clearable
                show-password
                type="password"
                v-model={passwordForm.oldPassword}
                placeholder="请输入旧密码~"
              />
            </ElFormItem>
            <ElFormItem prop="newPassword" rules={passwordRule}>
              <ElInput
                clearable
                show-password
                type="password"
                v-model={passwordForm.newPassword}
                placeholder="请输入新密码~"
              />
            </ElFormItem>
          </ElForm>
          <div class="mt-4 flex">
            {pwdProgress.map(({ color, text }, idx) => (
              <div
                class="w-[19vw]"
                style={{ marginLeft: idx !== 0 ? "4px" : 0 }}
              >
                <ElProgress
                  striped
                  striped-flow
                  duration={curScore.value === idx ? 6 : 0}
                  percentage={curScore.value >= idx ? 100 : 0}
                  color={color}
                  stroke-width={10}
                  show-text={false}
                />
                <p
                  class="text-center"
                  style={{ color: curScore.value === idx ? color : "" }}
                >
                  {text}
                </p>
              </div>
            ))}
          </div>
        </div>
      ),
      closeCallBack: () => passwordForm,
      beforeSure: done => {
        ruleFormRef.value.validate(async (valid: any) => {
          if (valid) {
            // 表单规则校验通过
            const res = await putUpdatePasswordAPI(passwordForm);
            if (res.code === 200) {
              done();
              message(res.msg, {
                type: "success"
              });
            } else {
              message(res.msg, {
                type: "error"
              });
            }
          }
        });
      }
    });
  };

  /**更新手机号 */
  const handlePhone = (row: UserInfo) => {
    phoneForm.phone = row.phone;
    addDialog({
      title: `更新 ${row.username}--${row.nickname} 的联系号码`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => (
        <div>
          <ElForm ref={ruleFormRef} model={phoneForm}>
            <ElFormItem
              prop="password"
              rules={[
                {
                  required: true,
                  message: "请输入密码~",
                  trigger: "blur"
                }
              ]}
            >
              <ElInput
                clearable
                show-password
                type="password"
                v-model={phoneForm.password}
                placeholder="请输入密码~"
              />
            </ElFormItem>
            <ElFormItem prop="phone" rules={phoneRule}>
              <ElInput
                clearable
                type="text"
                v-model={phoneForm.phone}
                placeholder="请输入手机号~"
              />
            </ElFormItem>
          </ElForm>
        </div>
      ),
      closeCallBack: () => phoneForm,
      beforeSure: done => {
        ruleFormRef.value.validate(async (valid: any) => {
          if (valid) {
            // 表单规则校验通过
            const res = await putUpdatePhoneAPI(phoneForm);
            if (res.code === 200) {
              done();
              message(res.msg, {
                type: "success"
              });
            } else {
              message(res.msg, {
                type: "error"
              });
            }
          }
        });
      }
    });
  };
  /**更新邮箱 */
  const handleEmail = (row: UserInfo) => {
    emailForm.email = row.email;
    addDialog({
      title: `更新 ${row.username}--${row.nickname} 的联系邮箱`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => (
        <div>
          <ElForm ref={ruleFormRef} model={emailForm}>
            <ElFormItem
              prop="password"
              rules={[
                {
                  required: true,
                  message: "请输入密码~",
                  trigger: "blur"
                }
              ]}
            >
              <ElInput
                clearable
                show-password
                type="password"
                v-model={emailForm.password}
                placeholder="请输入密码~"
              />
            </ElFormItem>
            <ElFormItem prop="email" rules={emailRule}>
              <ElInput
                clearable
                type="text"
                v-model={emailForm.email}
                placeholder="请输入联系邮箱~"
              />
            </ElFormItem>
          </ElForm>
        </div>
      ),
      closeCallBack: () => emailForm,
      beforeSure: done => {
        ruleFormRef.value.validate(async (valid: any) => {
          if (valid) {
            // 表单规则校验通过
            const res = await putUpdateEmailAPI(emailForm);
            if (res.code === 200) {
              done();
              message(res.msg, {
                type: "success"
              });
            } else {
              message(res.msg, {
                type: "error"
              });
            }
          }
        });
      }
    });
  };

  return {
    userInfo,
    getUserInfo,
    handleReset,
    handlePhone,
    handleEmail
  };
};
