package com.yeejoin.amos.boot.module.elevator.biz.controller;

import com.alibaba.fastjson.JSON;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.bo.RoleBo;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.elevator.biz.utils.JsonUtils;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.ApplicationModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(tags = "跳转应用相关API")
@RequestMapping(value = "/platformConfig")
public class PlatformConfigController extends BaseController {
    @Value("classpath:/json/appApplyInfo.json")
    private org.springframework.core.io.Resource applyInfo;

    @Resource
    private RedisUtils redisUtils;

    /**
     * 查询当前登录人的应用信息【燃气管道系统和气瓶安全追溯系统】
     *
     * @return List<Map < String, Object>> 查询当前登录人的应用信息【燃气管道系统和气瓶安全追溯系统】
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询当前登录人的应用信息【燃气管道系统和气瓶安全追溯系统】", notes = "查询当前登录人的应用信息【燃气管道系统和气瓶安全追溯系统】")
    @GetMapping(value = "/queryApplyByToken")
    public ResponseModel<Map<String, Object>> queryApplyByToken() {
        Map<String, List<Map<String, Object>>> resourceJson = JsonUtils.getResourceJson(applyInfo);
        List<Map<String, Object>> applyList = resourceJson.get("appApplyInfo");
        //存放配置文件中取出的应用code和图片信息 key：应用Code  value：图片信息
        Map<String, String> appCodeImageMap = new HashMap<>();
        //存放应用code用于下面过滤
        List<String> list = new ArrayList<>();
        applyList.forEach(item -> {
            appCodeImageMap.put(String.valueOf(item.get("appKey")), String.valueOf(item.get("image")));
            list.add(String.valueOf(item.get("appKey")));
        });
        String exeUserId = RequestContext.getExeUserId();
        AgencyUserModel result = Privilege.agencyUserClient.queryByUserId(exeUserId).getResult();
        Map<String, String> appCodeMap = Privilege.applicationClient.queryAgencyApplications().getResult().stream().filter(t -> list.contains(t.getAppCode())).collect(Collectors.toMap(ApplicationModel::getAppCode, ApplicationModel::getAppName));
        List<Map<String, Object>> resultList = new ArrayList<>();
        result.getAppCodes().stream().filter(list::contains).forEach(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("appCode", item);
            map.put("appName", appCodeMap.get(item));
            map.put("image", appCodeImageMap.get(item));
            resultList.add(map);
        });
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("current", 1);
        resultMap.put("total", resultList.size());
        resultMap.put("records", resultList);
        return ResponseHelper.buildResponse(resultMap);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getCompanyMessage")
    @ApiOperation(httpMethod = "GET", value = "查询当前人所有单位-下拉选择", notes = "查询当前人所有单位")
    public ResponseModel<Object> getCompanyMessage() {
        List<Map<String, Object>> list = new ArrayList<>();
        String exeUserId = RequestContext.getExeUserId();
        FeignClientResult<AgencyUserModel> agencyUserModelFeignClientResult = Privilege.agencyUserClient.queryByUserId(exeUserId);
        if (!ObjectUtils.isEmpty(agencyUserModelFeignClientResult) && !ObjectUtils.isEmpty(agencyUserModelFeignClientResult.getResult()) && !ObjectUtils.isEmpty(agencyUserModelFeignClientResult.getResult().getCompanys())) {
            List<CompanyModel> companies = agencyUserModelFeignClientResult.getResult().getCompanys();
            companies.forEach(item -> {
                HashMap<String, Object> result = new HashMap<>();
                result.put("name", item.getCompanyName());
                result.put("value", item.getSequenceNbr());
                list.add(result);
            });
            return ResponseHelper.buildResponse(list);
        } else {
            return ResponseHelper.buildResponse(null);

        }
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getRoles")
    @ApiOperation(httpMethod = "GET", value = "查询当前人某单位下角色-下拉选择", notes = "查询当前人某单位下角色")
    public ResponseModel<Object> getRoles(@RequestParam Long companyId) {
        String exeUserId = RequestContext.getExeUserId();
        FeignClientResult<AgencyUserModel> agencyUserModelFeignClientResult = Privilege.agencyUserClient.queryByUserId(exeUserId);
        if (!ObjectUtils.isEmpty(agencyUserModelFeignClientResult) && !ObjectUtils.isEmpty(agencyUserModelFeignClientResult.getResult()) && !ObjectUtils.isEmpty(agencyUserModelFeignClientResult.getResult().getOrgRoles())) {
            Map<Long, List<RoleModel>> orgRoles = agencyUserModelFeignClientResult.getResult().getOrgRoles();
            if (!ObjectUtils.isEmpty(orgRoles)) {
                List<RoleModel> roleModels = orgRoles.get(companyId);
                return ResponseHelper.buildResponse(roleModels);
            }
        }
        return ResponseHelper.buildResponse(null);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/changeUserMessage")
    @ApiOperation(httpMethod = "POST", value = "跳转选择公司、角色后修改用户登录缓存西信息", notes = "跳转选择公司、角色后修改用户登录缓存西信息")
    public ResponseModel<Object> changeUserMessage(@RequestParam(value = "companyId") String companyId,
                                                   @RequestParam(value = "roleId") String roleId) {
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        if (!ObjectUtils.isEmpty(reginParams) && !ObjectUtils.isEmpty(reginParams.getCompany())) {
            // 所选公司覆盖
            CompanyBo company = reginParams.getCompany();
            company.setSequenceNbr(Long.valueOf(companyId));
            reginParams.setCompany(company);
            // 所选角色覆盖
            RoleBo role = reginParams.getRole();
            FeignClientResult<RoleModel> roleModelFeignClientResult = Privilege.roleClient.seleteOne(Long.valueOf(roleId));
            role.setRoleName(roleModelFeignClientResult.getResult().getRoleName());
            role.setRoleType(roleModelFeignClientResult.getResult().getRoleType());
            role.setSequenceNbr(Long.valueOf(roleId));
            reginParams.setRole(role);
            String result = JSON.toJSONString(reginParams);
            redisUtils.set(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken()), result);
            return ResponseHelper.buildResponse(company);
        } else {
            return ResponseHelper.buildResponse(null);
        }
    }
}
