import { v4 as uuidv4 } from "uuid";
import IMSDK from "openim-uniapp-polyfill";
import { businessGetUserInfo } from "@/pages_im/api/login";
import { getSubDepartment } from "@/pages_im/api/orgnizaition";
import { filterEmptyValue, getPurePath } from "@/pages_im/util/common";
import { getUserInDepartment } from "@/pages_im/api/orgnizaition";

const state = {
  selfInfo: {},
  organizationData: {},
  authData: {},
  cacheMap: {},
  isSyncing: false,
  reinstall: false,
  progress: 0,
  rootFontSize: uni.getStorageSync("RootFontSize") || "14px",
};

const mutations = {
  SET_SELF_INFO(state, info) {
    state.selfInfo = {
      ...info,
    };
  },
  SET_ORGANIZATION_DATA(state, data) {
    state.organizationData = {
      ...data,
    };
  },
  SET_AUTH_DATA(state, data) {
    state.authData = {
      ...data,
    };
  },
  INIT_CACHE_MAP(state, data) {
    state.cacheMap = {
      ...data
    }
  },
  UPDATE_CACHE_MAP(state, data) {
    const tmp =  {...state.cacheMap}
    tmp[data.key] = {...data}
    state.cacheMap = tmp
    uni.setStorageSync("CacheMap", tmp);
  },
  DELETE_CACHE_MAP(state, key) {
    const tmp =  {...state.cacheMap}

    delete tmp[key]
    state.cacheMap = tmp
    uni.setStorageSync("CacheMap", tmp);
  },
  SET_IS_SYNCING(state, data) {
    state.isSyncing = data;
  },
  SET_REINSTALL(state, data) {
    state.reinstall = data;
  },
  SET_PROGRESS(state, data) {
    state.progress = data;
  },
  SET_ROOT_FONT_SIZE(state, data) {
    state.rootFontSize = data;
  },
};

const actions = {
  async getSelfInfo({ commit }) {
    try {
      const { data } = await IMSDK.asyncApi(IMSDK.IMMethods.GetSelfUserInfo,uuidv4());
	  
      // const { users } = await businessGetUserInfo(data.userID);
      // let businessData = users[0] ?? {};
      // filterEmptyValue(businessData);
      // const { users:members } = await getUserInDepartment(data.userID)
	  
	  var userId=uni.getStorageSync('userId');
	  var avatar=uni.getStorageSync('avatar');
	  var nickName=uni.getStorageSync('nickName');
	  var uid="U"+userId;
	  let businessData={userID:uid,nickname:nickName,faceURL:avatar};
      commit("SET_SELF_INFO", {
        ...data,
        ...businessData,
        //members: members[0]?.members || []
		members:  []
      });
      // const res = await getSubDepartment();
      // commit("SET_ORGANIZATION_DATA", res);
    } catch (e) {
      console.log(e);
      //uni.$u.toast("获取个人信息失败");
    }
  },
  async updateBusinessInfo({ commit, state }) {
    try {
      const { users } = await businessGetUserInfo(state.selfInfo.userID);
      const businessData = users[0] ?? {};
      filterEmptyValue(businessData);
      commit("SET_SELF_INFO", {
        ...state.selfInfo,
        ...businessData,
      });
    } catch (e) {
      console.log(e);
    }
  },
  initCache({ commit}) {
    const cacheMap = uni.getStorageSync("CacheMap") || {};
    commit("INIT_CACHE_MAP", cacheMap);
  },
  addCacheTask({ commit, state }, { key, url}) {
    const task = state.cacheMap[key] || {};
    if (task.state){
      return;
    }
    task.state = "pending";
    commit("UPDATE_CACHE_MAP", {
      key,
      ...task
    });

    const failedCallback = () => {
      uni.showToast({
        title: "下载失败",
        icon: 'none'
      })
      commit("DELETE_CACHE_MAP", key);
    }

    uni.downloadFile({
      url,
      success: (res) => {
        if (res.statusCode === 200) {
          uni.saveFile({
            tempFilePath: res.tempFilePath,
            success: ({ savedFilePath }) => {
              task.state = "success";
              task.path = savedFilePath;
              commit("UPDATE_CACHE_MAP", {
                key,
                ...task
              });
              uni.showToast({
                title: `文件已保存到${getPurePath(savedFilePath)}`,
                icon: 'none'
              })
            },
            fail: function (err) {
              failedCallback()
            },
          });
        } else {
          failedCallback()
        }
      },
      fail: () => {
        failedCallback()
      },
    });
  },
  addLocalPathToCache({ commit }, { key, path }) {
    commit("UPDATE_CACHE_MAP", {
      key,
      state: "success",
      path
    });
  },
  deleteCacheData({ commit}, key) {
    commit("DELETE_CACHE_MAP", key);
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
