import { login, logout, getInfo } from '@/api/login';
import { getZhiHuiToken, getProfile, updateUserInfo } from '@/api/zhihui/index.js';
import { getToken, setToken, removeToken, setZHToken, getZHToken, removeZHToken } from '@/utils/auth';
import defAva from '@/assets/images/profile.jpg';

const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    id: '',
    name: '',
    avatar: '',
    zhFirmId: '',
    zhGroupIds: '',
    zhUserId: '',
    roles: [],
    permissions: [],
    zh_token: getZHToken(),
  }),
  actions: {
    // 登录
    login(userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then(res => {
            setToken(res.token);
            this.token = res.token;

            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then(async res => {
            const user = res.user;
            const avatar = user.avatar == '' || user.avatar == null ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;

            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              this.roles = res.roles;
              this.permissions = res.permissions;
            } else {
              this.roles = ['ROLE_DEFAULT'];
            }
            this.id = user.userId;
            this.name = user.userName;
            this.avatar = avatar;
            this.zhFirmId = user.zhFirmId;
            this.zhGroupIds = user.zhGroupIds;
            this.zhUserId = user.zhUserId;
            // if (!getZHToken()) {
            //   let data = await getZhiHuiToken({ userId: this.id, company: '658a430eeb6212118e8c3575' });
            //   if (data.code == 200) {
            //     let ref = JSON.parse(data.data);
            //     this.zh_token = ref.access_token;
            //     setZHToken(ref.access_token);
            //   }
            // }
            if (!this.zhUserId) {
              let e = await getProfile();
              if (e.statusCode == 200) {
                let option = {
                  userId: this.id,
                  zhUserId: e.data._id,
                  zhFirmId: this.zhFirmId,
                  zhGroupIds: this.zhGroupIds,
                };
                if (e.data?.company?.length > 0) {
                  option.zhFirmId = e.data?.company[0]._id;
                }
                if (e.data?.team?.length > 0) {
                  let ids = e.data?.team?.map(item => item._id);
                  option.zhGroupIds = ids.join(',');
                }
                updateUserInfo(option);
              }
            }
            resolve(res);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        logout(this.token)
          .then(() => {
            this.token = '';
            this.roles = [];
            this.permissions = [];
            removeToken();
            removeZHToken();
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    getZhiHuiToken() {
      return new Promise((resolve, reject) => {
        getZhiHuiToken()
          .then(data => {
            if (data.code == 200) {
              let ref = JSON.parse(data.data);
              this.zh_token = ref.access_token;
              setZHToken(ref.access_token);
              resolve(ref.access_token);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    updateZHInfo(zhFirmId, zhGroupIds) {
      return new Promise((resolve, reject) => {
        this.zhFirmId = zhFirmId;
        this.zhGroupIds = zhGroupIds;
        let option = {
          userId: this.id,
          zhFirmId: this.zhFirmId,
          zhGroupIds: this.zhGroupIds,
        };
        updateUserInfo(option);
        resolve();
      });
    },
  },
});

export default useUserStore;
