import {getInfo, login, logout} from "@/api/login";
import {getToken, removeToken, setToken} from "@/utils/auth";
import defAva from "@/assets/images/profile.jpg";
import md5 from "js-md5";
import {companyList} from "@/api/dataList/enterprise";
import {expertList} from "@/api/expert/expert";
import {listCasDemand} from "../../api/dataApproval/enterpriseServiceDemand";
import {expertAchievementList} from "../../api/dataApproval/achivement";
import {businessList} from "../../api/Businessneeds";
import {enterpriseProductApprovalList} from "../../api/dataApproval/enterpriseProduct";
import {
    getUnApprovalCount,
    resetUnApprovalCount,
} from "../../api/dataApproval/count";
import {casLaboratoryList} from "@/api/dataList/laboratory";

const useUserStore = defineStore("user", {
    state: () => ({
        token: getToken(),
        name: "",
        avatar: "",
        roles: [],
        permissions: [],
        unApprovedBusiness: 0,
        unApprovedExpert: 0,
        unApprovedAchivement: 0,
        unApprovedTechnology: 0,
        unApprovedService: 0,
        unApprovedProduct: 0,
        unApprovedLab: 0,
        serviceDemandTotal: 0,
        achievementTotal: 0,
        technologyTotal: 0,
        productTotal: 0,
    }),
    actions: {
        // 登录
        login(userInfo) {
            const username = userInfo.username.trim();
            const password = md5(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((res) => {
                        const user = res.user;
                        const avatar =
                            !user.avatar
                                ? defAva
                                : import.meta.env.VITE_APP_BASE_API + user.avatar.substring(user.avatar.indexOf("/file"));

                        if (res.roles && res.roles.length > 0) {
                            // 验证返回的roles是否是一个非空数组
                            this.roles = res.roles;
                            this.permissions = res.permissions;
                        } else {
                            this.roles = ["ROLE_DEFAULT"];
                        }
                        this.name = user.userName;
                        this.avatar = avatar;
                        resolve(res);
                        // return res;
                    })
                    .catch((error) => {
                        reject(error);
                    });
            });
        },

        async getApprovalCount() {
            this.getUnApprovedBusiness();
            this.getUnApprovedExpert();
            this.getUnApprovedAchivement();
            this.getUnApprovedTechnology();
            this.getUnApprovedService();
            this.getUnApprovedProduct();
            this.getServiceDemandTotal();
            this.getAchievementTotal();
            this.getProductTotal();
            this.getTechnologyTotal();
            this.getUnApprovedLab();
        },

        async resetUnApproval(name, field) {
            await resetUnApprovalCount(name);
            this[field] = 0;
        },

        async getUnApprovedBusiness() {
            const resp = await companyList({
                examineStatus: 0,
                pageSize: 1,
                pageNum: 10,
            });
            this.unApprovedBusiness = resp.total;
        },
        async getUnApprovedExpert() {
            const resp = await expertList({
                examineStatus: 0,
                pageSize: 1,
                pageNum: 10,
            });
            this.unApprovedExpert = resp.total;
        },
        async getUnApprovedAchivement() {
            const resp = await getUnApprovalCount("achievement");
            this.unApprovedAchivement = resp.data ?? 0;
        },
        async getUnApprovedTechnology() {
            const resp = await getUnApprovalCount("technology");
            this.unApprovedTechnology = resp.data ?? 0;
        },
        async getUnApprovedService() {
            const resp = await getUnApprovalCount("service");
            this.unApprovedService = resp.data ?? 0;
        },
        async getUnApprovedProduct() {
            const resp = await getUnApprovalCount("product");
            this.unApprovedProduct = resp.data ?? 0;
        },

        async getServiceDemandTotal() {
            const resp = await listCasDemand();
            this.serviceDemandTotal = resp.total;
        },
        async getAchievementTotal() {
            const resp = await expertAchievementList();
            this.achievementTotal = resp.total;
        },
        async getTechnologyTotal() {
            const resp = await businessList();
            this.technologyTotal = resp.total;
        },
        async getProductTotal() {
            const resp = await enterpriseProductApprovalList();
            this.productTotal = resp.total;
        },
        async getUnApprovedLab() {
            const resp = await casLaboratoryList({
                examineStatus: 0,
                pageSize: 1,
                pageNum: 10,
            });
            this.unApprovedBusiness = resp.total;
        },
        // 退出系统
        logOut() {
            return new Promise((resolve, reject) => {
                logout(this.token)
                    .then(() => {
                        this.token = "";
                        this.roles = [];
                        this.permissions = [];
                        removeToken();
                        resolve();
                    })
                    .catch((error) => {
                        reject(error);
                    });
            });
        },
    },
});

export default useUserStore;
