import { defineStore } from "pinia";
import { storage, storageSystem } from "@/utils/storage";
import { getToken, setToken, removeToken } from "@/utils/auth";
// 接口引用
import { login, logout, getInfo, getMobileTenantConfig, getCodeImg } from "@/api/login";
import { getUserProfile, appAdd, appDel, getPageAuthorization } from "@/api/system/user";
import { phoneVerify } from "@/api/common/index.js";
// 组件引用
import config from "@/config";
import tab from "@/plugins/modal.plugins.js";
import modal from "@/plugins/modal.plugins.js";
import common from "@/plugins/common.plugins.js";
import setting from "@/plugins/setting.plugins.js";

const useStores = defineStore("useStores", {
  state: () => ({
    token: getToken(),
    wxOpenId: storage.get("wxOpenId"),//微信openId
    userId: storage.get("userId"),//用户ID
    name: storage.get("name"),//用户名称
    nickName: storage.get("nickName"),//用户昵称
    phonenumber: storage.get("phonenumber"),//用户手机号
    deptId: storage.get("deptId"),//部门ID
    email: storage.get("email"),//邮箱
    sex: storage.get("sex"),//性别
    avatar: storage.get("avatar"),//用户头像
    roles: storage.get("roles"),//用户权限
    permissions: storage.get("permissions"),

    loginTitle: storage.get("loginTitle"),
    loginBottomTitle: storage.get("loginBottomTitle"),
    loginBg: storage.get("loginBg"),
    loginLogo: storage.get("loginLogo"),
    tenantId: storage.get("tenantId"),

    user: {},
    userArr: {},
    postGroup: "", //岗位
    roleGroup: "", //角色

    codeTime: 0,//验证码倒计时
    codeTimeInterval: null,//验证码倒计时定时器
  }),
  actions: {
    // 登录
    Login(data) {
      return new Promise((resolve, reject) => {
        login(data)
          .then((res) => {
            this.SET_TOKEN(res.data.access_token)
            setToken(res.data.access_token);
            this.codeTime = 0
            resolve();
          })
          .catch((error) => {
            modal.closeLoading();
            modal.msg(error);
            reject(error);
          });
      });
    },
    //获取登录页数据
    GetMobileTenantConfig(params) {
      getMobileTenantConfig(params).then((res) => {
        if (res.data.length > 0) {
          let data = res.data[0];
          this.SET_STORAGE_OBJECT_KEYS({
            loginTitle: data.loginTitle,
            loginBottomTitle: data.loginFooter,
            loginBg: data.loginBackUrl,
            loginLogo: data.loginLogo,
            tenantId: data.tenantId,
          })
        }
      });
    },
    // 获取用户信息
    GetUser() {
      getUserProfile().then((response) => {
        this.user = JSON.parse(JSON.stringify(response.data.user));
        this.user.phonenumber = this.user.phonenumber ? this.user.phonenumber.substr(0, 3) + "******" + this.user.phonenumber.substr(9) : "";
        this.userArr = JSON.parse(JSON.stringify(response.data.user));
        this.postGroup = response.postGroup;
        this.roleGroup = response.roleGroup;
      });
    },
    // 获取用户信息
    GetInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            var data = res.data;

            if (data.roles && data.roles.length > 0) {
              this.SET_ROLES(data.roles);
              this.SET_PERMISSIONS(data.permissions);
            } else {
              this.SET_ROLES(["ROLE_DEFAULT"]);
            }

            this.SET_STORAGE_OBJECT_KEYS({
              userId: data.user.userId,//用户ID
              name: data.user.userName,//用户名称
              nickName: data.user.nickName,//用户昵称
              phonenumber: data.user.phonenumber,//手机号码
              avatar: data.user.avatar,//头像
              deptId: data.user.deptId,//部门ID
              email: data.user.email,//邮箱
              sex: data.user.sex,//性别
            })

            resolve(res);
          })
          .catch((error) => {
            modal.msgError(error);
            reject(error);
          });
      });
    },
    /**
     * @获取手机验证码
     * @param { 手机号 } phone 
     * @param { 成功 } success 
     * @param { 失败 } error 
     */
    GetCodeImg({ phone, success, error }) {
      if (!phone) {
        modal.msg("请输入手机号");
        return;
      }
      if (!/^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/.test(phone)) {
        modal.msg("请输入正确的手机号");
        return;
      }

      if (this.codeTime > 0) {
        modal.msg("不能重复获取");
        return;
      } else {
        modal.loading("加载中");
        getCodeImg({
          phone: phone,
        }).then((res) => {
          if (res.status === "SUCCESS") {
            success(res)
            modal.closeLoading();
          } else {
            error(res)
          }
        });

        this.codeTime = 60;
        this.SetInterval("codeTime");
      }
    },
    // 手机验证码倒计时定时器
    SetInterval(key) {
      if (this.codeTimeInterval) {
        clearInterval(this.codeTimeInterval);
      }
      this.codeTimeInterval = setInterval(() => {
        this[key]--;
        if (this[key] < 1) {
          clearInterval(this.codeTimeInterval);
          this[key] = 0;
        }
      }, 1000);
    },
    /**
     * @手机验证码校验
     * @param { 数据 } data 
     * @param { 成功 } success 
     * @param { 失败 } error 
     */
    PhoneVerify({ data, success, error }) {
      if (!data.phone) {
        modal.msg("请输入手机号");
        return;
      }

      if (!/^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/.test(data.phone)) {
        modal.msg("请输入正确的手机号");
        return;
      }

      if (!data.verify) {
        modal.msg("请输入验证码");
        return;
      }

      phoneVerify({
        phone: data.phone,
        verify: data.verify,
      }).then((res) => {
        if (res.status === "SUCCESS") {
          success(res)
        } else {
          error(res)
        }
        modal.closeLoading();
      });
    },
    /**
     * @注册
     * @param { 数据 } data 
     * @param { 成功 } success 
     * @param { 失败 } error 
     */
    UserAdd({ data, success, error }) {
      if (!data.userName) {
        modal.showToast("用户名不能为空");
        return;
      }

      if (data.userName.length < 6) {
        modal.showToast("用户名长度在 6 个字符以上");
        return;
      }

      if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9][a-zA-Z0-9_]{6,}$/.test(data.userName)) {
        modal.showToast("仅支持英文(a-zA-Z)数字(0-9)和下划线(_)，且至少包含2项");
        return;
      }

      if (!data.nickName) {
        modal.showToast("昵称不能为空");
        return;
      }

      if (!data.email) {
        modal.showToast("邮箱不能为空");
        return;
      }

      if (!/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(data.email)) {
        proxy.$modal.showToast("邮箱格式不正确");
        return;
      }

      if (!data.newPassword) {
        modal.showToast("新密码不能为空");
        return;
      }

      if (data.newPassword.length < 6 || data.newPassword.length > 20) {
        modal.showToast("密码长度在 6 到 20 个字符");
        return;
      }

      if (!data.confirmPassword) {
        modal.showToast("确认密码不能为空");
        return;
      }

      if (data.confirmPassword != data.newPassword) {
        modal.showToast("两次输入的密码不一致");
        return;
      }

      modal.loading("加载中");
      appAdd({
        tenantId: this.tenantId,
        userName: data.userName,
        nickName: data.nickName,
        phonenumber: data.phone,
        email: data.email,
        password: data.newPassword,
        status: "0",
      }).then((res) => {
        if (res.status === "SUCCESS") {
          success(res)
          modal.closeLoading();
        }
      })
    },
    /**
     * @用户注销
     * @param { 数据 } data
     * @param { 成功 } success 
     * @param { 失败 } error 
     */
    UserDel({ data, success, error }) {
      modal.loading("加载中");
      appDel(data).then((res) => {
        if (res.status === "SUCCESS") {
          success(res)
          modal.closeLoading();
        }
      })
    },
    // 退出系统
    LogOut() {
      return new Promise((resolve, reject) => {
        var openId = null;
        // #ifdef H5
        openId = localStorage.getItem("wxOpenId") ? localStorage.getItem("wxOpenId") : "";
        // #endif

        logout({ openId: openId })
          .then(() => {
            setting.setBadge(0); // 设置角标值

            this.SET_TOKEN("");//清空token
            this.SET_ROLES([]);
            this.SET_PERMISSIONS([]);
            removeToken();
            storage.clean();
            resolve();
          })
          .catch((error) => {
            modal.msgError(error);
            reject(error);
          });
      });
    },
    /**
     * @获取微信OpenId
     * @param { 类型 } type 
     */
    GetWxOpenId(type, options) {
      let url = "https://manager.usky.cn/mobile/#/"
      if (type == 1 && common.isWechatMp()) {
        if (localStorage.getItem("wxOpenId")) {
          if (localStorage.getItem("App-Token")) {
            window.location.href = `${url}pages/index`;
          } else {
            getPageAuthorization({ openId: localStorage.getItem("wxOpenId") }).then((res) => {
              if (res?.data?.openid && res?.data?.accessToken) {
                localStorage.setItem("App-Token", res.data.accessToken)
                this.GetInfo()
                window.location.href = `${url}pages/index`;
              }
            })
          }
        } else {
          if (window.location.href.indexOf("openId=") == -1) {
            window.location.href = config.baseUrl + "/service-iot/weChat/getFirst1";
          } else {
            localStorage.setItem("wxOpenId", common.getUrlList().openId)
            this.GetWxOpenId(1)
          }
        }
      } else if (type == 2 && common.isWechatMp()) {
        if (localStorage.getItem("wxOpenId")) {
          if (!localStorage.getItem("App-Token")) {
            getPageAuthorization({ openId: localStorage.getItem("wxOpenId") }).then((res) => {
              if (res?.data?.openid && res?.data?.accessToken) {
                localStorage.setItem("App-Token", res.data.accessToken)
                this.GetInfo()
              } else {
                this.LogOut().then(() => {
                  window.location.href = `${url}pages/login`;
                })
              }
            })
          } else {
            this.GetInfo()
          }
        } else {
          window.location.href = config.baseUrl + "/service-iot/weChat/getFirst1";
        }
      }
    },
    SET_TOKEN(token) {
      this.token = token;
    },
    SET_ROLES(roles) {
      this.roles = roles;
      storage.set("roles", roles);
    },
    SET_PERMISSIONS(permissions) {
      this.permissions = permissions;
      storage.set("permissions", permissions);
    },
    SET_STORAGE_OBJECT_KEYS(LIST) {
      Object.keys(LIST).forEach(function (key) {
        storage.set(key, LIST[key]);
        useStores()[key] = LIST[key];
      });
    },
  },
});

export default useStores;