package com.ruoyi.web.controller.screen;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.domain.grid.GridRegion;
import com.ruoyi.system.domain.grid.GridRegionExample;
import com.ruoyi.system.domain.grid.GridRegionUser;
import com.ruoyi.system.domain.grid.GridRegionUserExample;
import com.ruoyi.system.domain.grid.enums.GridRegionSearchParam;
import com.ruoyi.system.domain.grid.vo.GridCompanySearchParam;
import com.ruoyi.system.mapper.grid.GridRegionMapper;
import com.ruoyi.system.mapper.grid.GridRegionUserMapper;
import com.ruoyi.system.mapper.task.ext.TkCommonTaskExtMapper;
import com.ruoyi.system.service.grid.*;
import com.ruoyi.system.service.system.ISysUserService;
import com.ruoyi.system.service.task.TkCommonTaskService;
import com.ruoyi.web.controller.screen.res.CommonCountItem;
import com.ruoyi.web.controller.screen.res.InfoWithTypeRes;
import com.ruoyi.web.controller.screen.res.SimpleUserInfo;
import io.swagger.annotations.Api;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * * Author: brenda
 * * 2024/12/13
 **/
@Api(tags = "大屏接口-网格态势-社会治理")
@RestController
@RequestMapping("/api/grid/screen/social")
public class ScreenSocialController {

    @Autowired
    private GridPeopleService gridPeopleService;
    @Autowired
    private GridHouseService gridHouseService;
    @Autowired
    private GridCompanyService gridCompanyService;
    @Autowired
    private GridShopService gridShopService;
    @Autowired
    private GridRegionMapper gridRegionMapper;
    @Autowired
    private GridWgLogService gridWgLogService;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private GridRegionUserService gridRegionUserService;
    @Autowired
    private TkCommonTaskExtMapper tkCommonTaskExtMapper;
    @Autowired
    private GridRegionUserMapper gridRegionUserMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    TkCommonTaskService tkCommonTaskService;

    /**
     * 用户信息
     * @return
     */
    @GetMapping("/getInfo/user")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SimpleUserInfo simpleUserInfo = new SimpleUserInfo();
        BeanUtils.copyProperties(user, simpleUserInfo);
        return AjaxResult.success(simpleUserInfo);
    }

    @GetMapping("/getInfo/roles")
    public AjaxResult getInfoRoles() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        return AjaxResult.success(roles);
    }

    @GetMapping("/getInfo/grid")
    public AjaxResult getInfoGrid() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //网格
        GridRegionUserExample example = new GridRegionUserExample();
        GridRegionUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(user.getUserId());
        criteria.andIsValidEqualTo("1");
        List<GridRegionUser> relationship = gridRegionUserService.selectByExample(example);
        return AjaxResult.success("请求成功", CollectionUtils.isEmpty(relationship)?"":relationship.stream().map(GridRegionUser::getWgId).collect(Collectors.joining(",")));
    }

    /**
     * 网格对象按字典分类型统计和总量
     *
     * @param wgCode
     * @return
     */
    @GetMapping(value = "/infoWithType")
    public AjaxResult infoWithType(@RequestParam(value = "wgCode", required = false) String wgCode) {
        InfoWithTypeRes res = new InfoWithTypeRes();

        // 人口
        res.setPeopleAllNum(gridPeopleService.countAll(wgCode));
        res.setSpecialPeopleNum(gridPeopleService.countSpecialPeople(wgCode) != null ? gridPeopleService.countSpecialPeople(wgCode) : 0);
        // 住宅类型分类统计
        int houseAllNum = gridHouseService.countAll(wgCode);
        res.setHouseAllNum(houseAllNum);
        // 企业
        res.setCompanyAllNum(gridCompanyService.countAll(wgCode));
        // 商铺
        res.setShopAllNum(gridShopService.countAll(wgCode));

        // 地块
        GridRegionSearchParam param = new GridRegionSearchParam();
        param.setLevel("4");
        if (StringUtils.isNotBlank(wgCode)) {
            List<String> wgCodes = Arrays.asList(wgCode.split(","));
            param.setWgCodeLikes(wgCodes);
        }
        int wgCount = gridRegionMapper.countByParams(param);
        res.setWgCount(wgCount);
        return AjaxResult.success(res);
    }

    @GetMapping(value = "/peopleRkbqList")
    public AjaxResult peopleRkbqList(@RequestParam(value = "wgCode", required = false) String wgCode) {
        List<Map<String, Object>> peopleList = gridPeopleService.countGridPeople(wgCode);
        List<CommonCountItem> itemList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(peopleList)){
            for(Map<String, Object> map : peopleList){
                CommonCountItem item = new CommonCountItem();
                item.setName(map.get("name").toString());
                item.setNumber((Long) map.get("number"));
                itemList.add(item);
            }
        }
        return AjaxResult.success(itemList);
    }

    @GetMapping(value = "/houseCountList")
    public AjaxResult houseCountList(@RequestParam(value = "wgCode", required = false) String wgCode) {
        List<Map<String, Object>> houseList = gridHouseService.countGridHouse(wgCode);
        List<CommonCountItem> itemList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(houseList)){
            for(Map<String, Object> map : houseList){
                CommonCountItem item = new CommonCountItem();
                item.setName(map.get("name").toString());
                item.setNumber((Long) map.get("number"));
                itemList.add(item);
            }
        }
        return AjaxResult.success(itemList);
    }

    @GetMapping(value = "/countWsPeopleRklxByGrid")
    public AjaxResult countWsPeopleRklxByGrid(@RequestParam(value = "wgCode", required = false) String wgCode) {
        return AjaxResult.success(gridPeopleService.countGridPeopleRklxByGrid(wgCode));
    }

    @GetMapping("/statistic/WsShopTypeNum")
    public AjaxResult countWsShop(@RequestParam(value = "wgCode", required = false) String wgCode){
        return AjaxResult.success(gridShopService.countGridShopFive(wgCode));
    }

    @GetMapping(value = "/infoAll")
    public AjaxResult infoAll(@RequestParam(value = "wgCode", required = false) String wgCode,
                              @RequestParam(value = "startTime", required = false) String startTime,
                              @RequestParam(value = "endTime", required = false) String endTime) {
        return AjaxResult.success(gridWgLogService.infoAll(wgCode, startTime, endTime));
    }

    /**
     * 公司列表
     * @param wgCode
     * @param value
     * @return
     */
    @GetMapping("/allCompanyList")
    public AjaxResult getCompanyList(@RequestParam(value = "wgCode")String wgCode,
                                     @RequestParam(value = "value", required = false) String value,
                                     @RequestParam(value = "name", required = false) String name){
        GridCompanySearchParam param = new GridCompanySearchParam();
        if(com.ruoyi.common.utils.StringUtils.isNotBlank(wgCode)){
            param.setWgCodeLikes(Arrays.asList(wgCode.split(",")));
        }
        if(StringUtils.isNotBlank(name)){
            param.setCompanyName(name);
        }
        if(StringUtils.isNotBlank(value)){
            param.setValue(value);
        }
        return AjaxResult.success(gridCompanyService.getAllCompanyList(param));
    }

    @RequestMapping(value = "/getRegionByWgcode", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getRegionByWgcode(@RequestParam("wgCode") String wgCode) {
        GridRegionExample example = new GridRegionExample();
        GridRegionExample.Criteria criteria = example.createCriteria();
        criteria.andIsValidEqualTo("1");
        if (!StringUtils.isNotEmpty(wgCode)) {
            return AjaxResult.error("网格code不能为空");
        }
        criteria.andWgCodeEqualTo(wgCode);
        List<GridRegion> regionList = gridRegionMapper.selectByExample(example);
        return AjaxResult.success(CollectionUtils.isEmpty(regionList)?null : regionList.get(0));
    }

    /**
     * 弹框-网格绑定的2，3级网格员人数数量
     * @param wgCode
     * @return
     */
    @RequestMapping(value = "/countByWgcode", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult countByWgcode(@RequestParam("wgCode") String wgCode) {
        GridRegionExample example = new GridRegionExample();
        example.createCriteria().andWgParentIdEqualTo(wgCode).andIsValidEqualTo("1");
        long count = gridRegionMapper.countByExample(example);
        return AjaxResult.success(count);
    }

    @RequestMapping(value = "/oneGridUserByWgcode", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult oneGridUserByWgcode(@RequestParam("wgCode") String wgCode) {
        List<GridRegionUser> bsRegionUsers = gridRegionUserMapper.selectOneGridUserByWgCode(wgCode);
        List<SimpleUserInfo> simpleUserInfoList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(bsRegionUsers)){
            for(GridRegionUser user : bsRegionUsers){
                SimpleUserInfo simpleUserInfo = getSimpleUserInfo(user.getUserId(), user.getWgId());
                if(simpleUserInfo != null){
                    simpleUserInfoList.add(simpleUserInfo);
                }
            }
        }
        return AjaxResult.success(simpleUserInfoList);
    }

    @RequestMapping(value = "/twoGridUserByWgcode", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult twoGridUserByWgcode(@RequestParam("wgCode") String wgCode) {
        List<SimpleUserInfo> simpleUserInfoList = new ArrayList<>();
        GridRegion gridRegion = gridRegionMapper.getWgLevel(wgCode);
        List<GridRegionUser> reginUsers = gridRegionUserMapper.selectTwoGridUserByWgCode(wgCode);
        if(CollectionUtils.isNotEmpty(reginUsers)){
            for(GridRegionUser user : reginUsers){
                SimpleUserInfo simpleUserInfo = getSimpleUserInfo(user.getUserId(), user.getWgId());
                if(simpleUserInfo != null){
                    simpleUserInfoList.add(simpleUserInfo);
                }
            }
        }
        return AjaxResult.success(simpleUserInfoList);
    }

    @RequestMapping(value = "/threeGridUserByWgcode", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult threeGridUserByWgcode(@RequestParam("wgCode") String wgCode) {
        List<GridRegionUser> threeGirdUser = gridRegionUserMapper.selectThreeGirdUserByWgCode(wgCode);
        List<SimpleUserInfo> simpleUserInfoList = new ArrayList<>();
        if (!threeGirdUser.isEmpty()) {
            for (GridRegionUser bsRegionUser : threeGirdUser) {
                SimpleUserInfo simpleUserInfo = getSimpleUserInfo(bsRegionUser.getUserId(), bsRegionUser.getWgId());
                if(simpleUserInfo != null){
                    simpleUserInfoList.add(simpleUserInfo);
                }
            }
        }
        return AjaxResult.success(simpleUserInfoList);
    }

    /**
     * 只显示2，3级网格员，根据当前点击的网格code的level来找
     * @param wgCode
     * @return
     */
    @RequestMapping(value = "/allGridUser", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult allGridUser(@RequestParam("wgCode") String wgCode) {
        List<SimpleUserInfo> simpleUserInfoList = new ArrayList<>();
        List<GridRegionUser> threeGirdUser = gridRegionUserMapper.selectChildGirdUserByWgCode(wgCode);
        if(CollectionUtils.isNotEmpty(threeGirdUser)){
            for(GridRegionUser user : threeGirdUser){
                SimpleUserInfo simpleUserInfo = getSimpleUserInfo(user.getUserId(), user.getWgId());
                if(simpleUserInfo != null){
                    simpleUserInfoList.add(simpleUserInfo);
                }
            }
        }
        if(CollectionUtils.isNotEmpty(simpleUserInfoList)){
            simpleUserInfoList = simpleUserInfoList.stream().sorted(Comparator.comparing(SimpleUserInfo::getWgLevel)).collect(Collectors.toList());
        }
        return AjaxResult.success(simpleUserInfoList);
    }

    private SimpleUserInfo getSimpleUserInfo(String userId, String wgId){
        SysUser sysUser = sysUserService.selectUserById(userId);
        if(sysUser != null){
            SimpleUserInfo simpleUserInfo = new SimpleUserInfo();
            BeanUtils.copyProperties(sysUser, simpleUserInfo);
            simpleUserInfo.setWgCode(wgId);
            GridRegion gridRegion = gridRegionMapper.getWgLevel(wgId);
            simpleUserInfo.setWgName(gridRegion.getWgName());
            simpleUserInfo.setWgLevel(gridRegion.getLevel());
            if(StringUtils.isNotBlank(gridRegion.getLevel())){
                if("2".equals(gridRegion.getLevel())){
                    simpleUserInfo.setRoleName("二级网格员");
                }else{
                    simpleUserInfo.setRoleName("三级网格员");
                }
            }
            return simpleUserInfo;
        }
        return null;
    }
}
