package com.yeejoin.amos.boot.module.jg.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.jg.api.enums.CompanyTypeEnum;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.GroupModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import lombok.extern.slf4j.Slf4j;
import org.typroject.tyboot.core.foundation.context.RequestContext;

import java.util.List;

@Slf4j
public class FillingEditPermForCurrentUser extends BaseUseRegisterResultData {

    private final CompanyBo company;

    private static final String COMPANY_TYPE = "companyType";

    private static final String HAS_PERMISSION = "hasPermission";


    public FillingEditPermForCurrentUser(JSONObject data, CompanyBo company) {
        super(data);
        this.company = company;
    }


    @Override
    public JSONObject getData() {
        JSONObject data = super.getData();
        fillingEditPermission(data);
        return data;
    }


    private void fillingEditPermission(JSONObject jsonObject) {
        jsonObject.put(HAS_PERMISSION, false);
        // 当前登录人所在用户组
        List<GroupModel> groupModels = FeignUtil.remoteCall(() -> Privilege.groupClient.queryByUserId(RequestContext.getExeUserId()));
        // 有权限编辑设备的用户组（value为用户组名称）
        List<DictionarieValueModel> hasPermGroup = FeignUtil.remoteCall(() -> Systemctl.dictionarieClient.dictValues("USE_REG_PERMISSION_GROUP"));
        if (groupModels.stream().anyMatch(g -> hasPermGroup.stream().anyMatch(h -> h.getDictDataValue().equals(g.getGroupName())))) {
            jsonObject.put(HAS_PERMISSION, true);
        }
        if(company != null) {
            if (company.getLevel().equals(BaseController.COMPANY_TYPE_COMPANY)) {
                jsonObject.put(COMPANY_TYPE, BaseController.COMPANY_TYPE_COMPANY);
            } else {
                jsonObject.put(COMPANY_TYPE, BaseController.COMPANY_TYPE_SUPERVISION);
            }
        }
    }
}
