package com.rongwei.savecheck.controller;

import com.alibaba.fastjson.JSON;
import com.rongwei.rwadmincommon.system.domain.SysOrganizationDo;
import com.rongwei.rwadmincommon.system.domain.SysRoleDo;
import com.rongwei.rwadmincommon.system.vo.SysOrganizationVo;
import com.rongwei.rwadmincommon.system.vo.SysUserVo;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.utils.StringUtils;
import com.rongwei.rwcommon.vo.ColumnQueryType;
import com.rongwei.rwcommon.vo.CriteriaQuery;
import com.rongwei.rwcommon.vo.SearchColumnVo;
import com.rongwei.sfcommon.utils.CommonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.rongwei.safecommon.utils.SaveConstans.*;

/**
 * CxCommonController class
 *
 * @author XH
 * @date 2023/11/17
 */
@RestController
@RequestMapping("/common")
@RefreshScope
public class CxCommonController {
    @Value("#{'${pagepart.blacklist}'.split(',')}")
    private List<String> blackListPagePartIds;

    @Value("#{'${control.rolecode}'.split(',')}")
    private List<String> controlRoleCode;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    public static final SearchColumnVo SEARCH_COLUMN_VO = new SearchColumnVo() {{
        setField("TENANTID");
        setFieldType("string");
        setSymbol("like");
    }};

    public static final ColumnQueryType COLUMN_QUERY_TYPE = new ColumnQueryType() {{
        setLastTyepRelation(AND);
        setColumnInnerRelation(AND);
    }};

    @PostMapping("/criteria/query")
    public R weekForYear(@RequestBody Map<String, Object> map) {
        logger.info("增加tenantId查询条件");
        if (map.isEmpty()) {
            logger.error("接口参数异常");
            return R.ok(new CriteriaQuery());
        }
        CriteriaQuery criteriaQuery = JSON.parseObject(JSON.toJSONString(map.get("query")), CriteriaQuery.class);
        if (criteriaQuery == null) {
            logger.error("查询参数异常");
            return R.ok(new CriteriaQuery());
        }
        if(StringUtils.isBlank(criteriaQuery.getPagePartId())){
            logger.error("查询参数异常");
            return R.ok(criteriaQuery);
        }
        // 如果ID在黑名单中直接返回
        if (blackListPagePartIds.contains(criteriaQuery.getPagePartId())) {
            return R.ok(criteriaQuery);
        }
        SysUserVo currentUser = CommonUtil.getCurrentUser();
        if (currentUser == null) {
            logger.error("无法获取到当前登陆人的信息");
            return R.ok(criteriaQuery);
        }
        List<SysRoleDo> roleDos = currentUser.getRoleDos();
        if (roleDos == null || roleDos.isEmpty()) {
            logger.error("无法获取到当前登陆人的角色信息");
            return R.ok(criteriaQuery);
        }
        // 判断是否拥有特殊角色  只有这些角色可以看所有厂区的数据
        SysRoleDo sysRoleDo = roleDos.stream().filter(role -> controlRoleCode.contains(role.getCode())).findFirst().orElse(null);
        if (sysRoleDo != null) {
            return R.ok(criteriaQuery);
        }
        List<SysOrganizationVo> organizationDoList = currentUser.getOrganizationDoList();
        if (organizationDoList == null || organizationDoList.isEmpty()) {
            logger.error("无法获取到当前登陆人所属的组织机构");
            return R.ok(criteriaQuery);
        }
        String topOrgId = organizationDoList.stream()
                .filter(org -> MINUS_ONE.equals(org.getPid()))
                .map(SysOrganizationDo::getId)
                .distinct()
                .collect(Collectors.joining(","));
        if (StringUtils.isBlank(topOrgId)) {
            topOrgId = organizationDoList.stream().map(info -> info.getFullpid().split(",")[1]).distinct().collect(Collectors.joining(","));
        }
        SEARCH_COLUMN_VO.setValue(topOrgId);
        COLUMN_QUERY_TYPE.setColumns(Arrays.asList(SEARCH_COLUMN_VO));
        List<ColumnQueryType> columnQueryTypes = criteriaQuery.getColumnQueryTypes();
        columnQueryTypes.add(COLUMN_QUERY_TYPE);
        criteriaQuery.setColumnQueryTypes(columnQueryTypes);
        return R.ok(criteriaQuery);
    }
}
