package com.ruoyi.web.controller.screen;

import com.google.common.collect.Lists;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.party.domain.*;
import com.ruoyi.party.domain.vo.ExcellentPartyMemberVo;
import com.ruoyi.party.domain.vo.PartyOrganizationVo;
import com.ruoyi.party.service.api.*;
import com.ruoyi.system.domain.grid.GridRegion;
import com.ruoyi.system.mapper.system.SysDictDataMapper;
import com.ruoyi.system.service.grid.GridRegionService;
import com.ruoyi.web.controller.screen.res.CommonPercentCountItem;
import com.ruoyi.web.controller.screen.res.OrgStructureDetail;
import com.ruoyi.web.controller.screen.res.PartyOrganizationDetail;
import com.ruoyi.web.controller.screen.res.PartyStatisticsCommonItem;
import io.swagger.annotations.Api;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * * Author: brenda
 * * 2024/12/19
 **/
@Api(tags = "大屏接口-党建")
@RestController
@RequestMapping("/api/grid/screen/party")
public class ScreenPartyController {

    @Autowired
    private IPartyMemberService partyMemberService;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private IPartyActivityService partyActivityService;
    @Autowired
    private IPartyOrganizationService partyOrganizationService;
    @Autowired
    private IExcellentPartyMemberService excellentPartyMemberService;
    @Autowired
    private IExcellentPartyService excellentPartyService;
    @Autowired
    private GridRegionService gridRegionService;

    //党龄
    @RequestMapping(value="getDl",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getDl(String orgId) {
        List<Map<String, String>> list = partyMemberService.getDl(orgId);
        List<PartyStatisticsCommonItem> itemList = new ArrayList<>();
        List<Object> rlist = new ArrayList<Object>();
        int wnyxCounts = 0;  //5年以下
        int wdsnCounts = 0;  //5到10年
        int sdswCounts = 0;  //10-15
        int swdesCounts = 0;  //15-20
        int esysCounts = 0;  //>20
        if (CollectionUtils.isNotEmpty(list)) {
            for (Map<String, String> map : list) {
                int dYear = 0;
                if (map.get("dyear") != null) {
                    String d = String.valueOf(map.get("dyear")); //党龄
                    dYear = Integer.parseInt(d);
                }
                if (dYear < 5) {
                    wnyxCounts++;
                    continue;
                }
                if (dYear <= 10) {
                    wdsnCounts++;
                    continue;
                }
                if (dYear <= 15) {
                    sdswCounts++;
                    continue;
                }
                if (dYear <= 20) {
                    swdesCounts++;
                    continue;
                }
                esysCounts++;
            }
        }
        PartyStatisticsCommonItem item1 = new PartyStatisticsCommonItem("5年以下", wnyxCounts);
        PartyStatisticsCommonItem item2 = new PartyStatisticsCommonItem("5~10年", wdsnCounts);
        PartyStatisticsCommonItem item3 = new PartyStatisticsCommonItem("10~15年", sdswCounts);
        PartyStatisticsCommonItem item4 = new PartyStatisticsCommonItem("15~20年", swdesCounts);
        PartyStatisticsCommonItem item5 = new PartyStatisticsCommonItem("20年以上", esysCounts);
        itemList.add(item1);
        itemList.add(item2);
        itemList.add(item3);
        itemList.add(item4);
        itemList.add(item5);
        return AjaxResult.success(itemList);
    }

    private List<SysDictData> getDataByType(String type){
        return sysDictDataMapper.selectDictDataByType(type);
    }

    /**
     * 党组织活动分布
     * @return
     */
    @RequestMapping(value="/getPartyActivity",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getPartyActivity(String orgId){
        return AjaxResult.success(this.getPartyActivityList(orgId));
    }

    private List<PartyStatisticsCommonItem> getPartyActivityList(String orgId){
        List<SysDictData> sysDictData = getDataByType("service_type");
        Map<String, SysDictData> treeMap = sysDictData.stream().collect(Collectors.toMap(SysDictData::getDictValue, x -> x));
        List<Map<String,Object>> list= partyActivityService.getPartyActivity(orgId);
        List<PartyStatisticsCommonItem> itemList = new ArrayList<>();
        if(!org.springframework.util.CollectionUtils.isEmpty(list)){
            for(Map<String, Object> map : list){
                PartyStatisticsCommonItem item = new PartyStatisticsCommonItem();
                String fwlx = map.get("fwlx").toString();
                if(treeMap.containsKey(fwlx)){
                    item.setType(treeMap.get(fwlx).getDictLabel());
                    item.setCount(Integer.parseInt(map.get("count").toString()));
                    itemList.add(item);
                }
            }
        }
        return itemList;
    }

    /**
     * 党组织活动排行
     * @return
     */
    @RequestMapping(value="/getPartyActivityTop",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getPartyActivityTop(String orgId){
        List<SysDictData> sysDictData = getDataByType("service_type");
        Map<String, String> treeMap = sysDictData.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<String> values = Lists.newArrayList(treeMap.values());
        List<PartyStatisticsCommonItem> itemList = this.getPartyActivityList(orgId);
        if(CollectionUtils.isNotEmpty(itemList)){
            List<String> keyItemList = itemList.stream().map(PartyStatisticsCommonItem::getType).collect(Collectors.toList());
            values.removeAll(keyItemList);
        }
        if(!org.springframework.util.CollectionUtils.isEmpty(values)){
            for(String key : values){
                PartyStatisticsCommonItem item = new PartyStatisticsCommonItem(key, 0);
                itemList.add(item);
            }
        }
        if(CollectionUtils.isNotEmpty(itemList)){
            itemList = itemList.stream().sorted(Comparator.comparing(PartyStatisticsCommonItem::getCount).reversed()).collect(Collectors.toList());
        }
        return AjaxResult.success(itemList);
    }

    /**
     * 性别分布
     * @return
     */
    @RequestMapping(value="/getSexCount",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getSexCount(){
        List<CommonPercentCountItem> itemList = new ArrayList<>();
        List<PartyMember> memberList = partyMemberService.selectPartyMemberList(new PartyMember());
        int total = memberList.size();
        itemList.add(new CommonPercentCountItem(Long.parseLong(String.valueOf(total)), "总计", "100%"));
        if(CollectionUtils.isNotEmpty(memberList)){
            DecimalFormat decimalFormat = new DecimalFormat("0.00%");
            int nan = memberList.stream().filter(e -> "男".equals(e.getXb())).collect(Collectors.toList()).size();
            int nv = memberList.stream().filter(e -> "女".equals(e.getXb())).collect(Collectors.toList()).size();
            double percent = ((double)nan/total);
            double otherPercent = ((double)nv/total);
            itemList.add(new CommonPercentCountItem(Long.parseLong(String.valueOf(nan)), "男", decimalFormat.format(percent)));
            itemList.add(new CommonPercentCountItem(Long.parseLong(String.valueOf(nv)), "女", decimalFormat.format(otherPercent)));
        }
        return AjaxResult.success(itemList);
    }

    @RequestMapping(value="/getPartyInfo",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getPartyInfo(){
        List<PartyStatisticsCommonItem> itemList = new ArrayList<>();
        Integer partyCount = partyMemberService.getPartyCount();
        Integer organizationCount = partyOrganizationService.countOrg();
        Integer excellentMemberCount = excellentPartyMemberService.selectExcellentPartyMemberList(new ExcellentPartyMember()).size();
        Integer excellentPartyCount = excellentPartyService.selectExcellentPartyList(new ExcellentParty()).size();
        PartyStatisticsCommonItem item1 = new PartyStatisticsCommonItem("党员数量", partyCount);
        PartyStatisticsCommonItem item2 = new PartyStatisticsCommonItem("党组织数量", organizationCount);
        PartyStatisticsCommonItem item3 = new PartyStatisticsCommonItem("优秀党员", excellentMemberCount);
        PartyStatisticsCommonItem item4 = new PartyStatisticsCommonItem("优秀党支部", excellentPartyCount);
        itemList.add(item1);
        itemList.add(item2);
        itemList.add(item3);
        itemList.add(item4);
        return AjaxResult.success(itemList);
    }

    @RequestMapping(value="/getAgeStatistics",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getAgeStatistics(){
        List<String> ageList = partyMemberService.getAgeList();
        List<PartyStatisticsCommonItem> itemList = new ArrayList<>();
        int count1 = 0;
        int count2 = 0;
        int count3 = 0;
        int count4 = 0;
        int count5 = 0;
        if(CollectionUtils.isNotEmpty(ageList)){
            count1 = (int) ageList.stream().filter(e -> Integer.parseInt(e) < 20).count();
            count2 = (int) ageList.stream().filter(e -> Integer.parseInt(e) >= 20 && Integer.parseInt(e) < 30).count();
            count3 = (int) ageList.stream().filter(e -> Integer.parseInt(e) >= 30 && Integer.parseInt(e) < 40).count();
            count4 = (int) ageList.stream().filter(e -> Integer.parseInt(e) >= 40 && Integer.parseInt(e) < 50).count();
            count5 = (int) ageList.stream().filter(e -> Integer.parseInt(e) >=50).count();
        }
        PartyStatisticsCommonItem item1 = new PartyStatisticsCommonItem("20岁以下", count1);
        PartyStatisticsCommonItem item2 = new PartyStatisticsCommonItem("20~30岁", count2);
        PartyStatisticsCommonItem item3 = new PartyStatisticsCommonItem("30~40岁", count3);
        PartyStatisticsCommonItem item4 = new PartyStatisticsCommonItem("40~50岁", count4);
        PartyStatisticsCommonItem item5 = new PartyStatisticsCommonItem("50岁以上", count5);
        itemList.add(item1);
        itemList.add(item2);
        itemList.add(item3);
        itemList.add(item4);
        itemList.add(item5);
        return AjaxResult.success(itemList);
    }

    @GetMapping("/excellentMemberList")
    @ResponseBody
    public AjaxResult excellentMemberList(){
        List<ExcellentPartyMemberVo> list = excellentPartyMemberService.selectExcellentPartyMemberList(new ExcellentPartyMember());
        return AjaxResult.success(list);
    }

    @GetMapping("/activityList")
    @ResponseBody
    public AjaxResult activityList(String orgId){
        List<SysDictData> sysDictData = getDataByType("service_type");
        Map<String, SysDictData> treeMap = sysDictData.stream().collect(Collectors.toMap(SysDictData::getDictValue, x -> x));
        PartyActivity partyActivity = new PartyActivity();
        partyActivity.setSsdzzmc(orgId);
        List<PartyActivity> list = partyActivityService.selectPartyActivityList(partyActivity);
        if(CollectionUtils.isNotEmpty(list)){
            list.forEach( e ->{
                if(StringUtils.isNotBlank(e.getFwlx())){
                    if(treeMap.containsKey(e.getFwlx())){
                        e.setFwlxString(treeMap.get(e.getFwlx()).getDictLabel());
                    }
                }
            });
        }
        return AjaxResult.success(list);
    }

    /**
     * 党组织列表
     * @return
     */
    @GetMapping("/orgList")
    @ResponseBody
    public AjaxResult orgList(String wgCode, String name){
        PartyOrganization partyOrganization = new PartyOrganization();
        if(StringUtils.isNotBlank(wgCode)){
            partyOrganization.setSswg(wgCode);
        }
        if(StringUtils.isNotBlank(name)){
            partyOrganization.setDzzmc(name);
        }
        List<PartyOrganization> list = partyOrganizationService.selectPartyOrganizationList(partyOrganization);
        return AjaxResult.success(list);
    }

    /**
     * 党组织组织架构详情
     * @return
     */
    @GetMapping("/orgStructureDetail")
    @ResponseBody
    public AjaxResult orgStructureDetail(String orgId){
        List<SysDictData> sysDictData = getDataByType("party_org_type");
        Map<String, SysDictData> treeMap = sysDictData.stream().collect(Collectors.toMap(SysDictData::getDictValue, x -> x));
        OrgStructureDetail detail = new OrgStructureDetail();
        PartyOrganization partyOrganization = partyOrganizationService.getByDzzdm(orgId);
        if(partyOrganization == null){
            return AjaxResult.success(new OrgStructureDetail());
        }
        if(StringUtils.isNotBlank(partyOrganization.getDzzsj())){
            detail.setName(partyOrganization.getDzzsj());
            detail.setPhone(partyOrganization.getDzzlxdh());
            PartyMember partyMember2 = new PartyMember();
            partyMember2.setMz(partyOrganization.getDzzsj());
            partyMember2.setDzzmc(orgId);
            List<PartyMember> memberList = partyMemberService.selectPartyMemberList(partyMember2);
            if(CollectionUtils.isNotEmpty(memberList)){
                detail.setPic(memberList.get(0).getDyphoto());
            }
        }
        if(StringUtils.isNotBlank(partyOrganization.getZzlb())){
            if(treeMap.containsKey(partyOrganization.getZzlb())){
                detail.setOrgType(treeMap.get(partyOrganization.getZzlb()).getDictLabel());
            }
        }
        PartyMember partyMember = new PartyMember();
        partyMember.setDzzmc(orgId);
        List<PartyMember> memberList = partyMemberService.selectPartyMemberList(partyMember);
        detail.setPartyCount(memberList.size());
        return AjaxResult.success(detail);
    }

    /**
     * 获取党组织管理详细信息
     */
    @GetMapping(value = "/org/detail/{orgId}")
    public AjaxResult getOrgInfo(@PathVariable("orgId") String orgId)
    {
        List<SysDictData> ortTypeList = getDataByType("party_org_type");
        List<SysDictData> sdgxTypeList = getDataByType("sdgx_type");
        PartyOrganization partyOrganization = partyOrganizationService.getByDzzdm(orgId);
        if(partyOrganization == null){
            return AjaxResult.error("党组织不存在");
        }
        PartyOrganizationVo partyOrganizationVo = partyOrganizationService.selectPartyOrganizationById(partyOrganization.getId().toString());
        Map<String, SysDictData>  orgMap = ortTypeList.stream().collect(Collectors.toMap(SysDictData::getDictValue, x -> x));
        Map<String, SysDictData>  sdgxMap = sdgxTypeList.stream().collect(Collectors.toMap(SysDictData::getDictValue, x -> x));
        if(StringUtils.isNotBlank(partyOrganizationVo.getSdgx())){
            SysDictData sdgx = sdgxMap.get(partyOrganizationVo.getSdgx());
            partyOrganizationVo.setSdgxName(sdgx == null?"":sdgx.getDictLabel());
        }
        if(StringUtils.isNotBlank(partyOrganizationVo.getZzlb())){
            SysDictData zzlb = orgMap.get(partyOrganizationVo.getZzlb());
            partyOrganizationVo.setZzlbName(zzlb == null?"":zzlb.getDictLabel());
        }
        PartyOrganizationDetail detail = new PartyOrganizationDetail();
        BeanUtils.copyProperties(partyOrganizationVo, detail);
        if(StringUtils.isNotBlank(detail.getSswg())){
            GridRegion gridRegion = gridRegionService.getWgByCode(detail.getSswg());
            detail.setWgName(gridRegion == null?"":gridRegion.getWgName());
        }
        return AjaxResult.success(detail);
    }

    @GetMapping("/partyMemberList/{orgId}")
    public AjaxResult getPartyMemberList(@PathVariable("orgId") String orgId){
        PartyOrganization partyOrganization = partyOrganizationService.getByDzzdm(orgId);
        if(partyOrganization == null){
            return AjaxResult.error("党组织不存在");
        }
        String name = partyOrganization.getDzzmc();
        PartyMember partyMember = new PartyMember();
        partyMember.setDzzmc(orgId);
        List<PartyMember> partyMemberList = partyMemberService.selectPartyMemberList(partyMember);
        if(CollectionUtils.isNotEmpty(partyMemberList)){
            partyMemberList.forEach(e -> e.setDzzmc(name));
        }
        return AjaxResult.success(partyMemberList);
    }

}
