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.bean.BeanCopyUtil;
import com.ruoyi.party.domain.PartyOrganization;
import com.ruoyi.party.service.api.IPartyOrganizationService;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.grid.ext.*;
import com.ruoyi.system.domain.grid.vo.SimpleGridShopItem;
import com.ruoyi.system.mapper.grid.GridCompanyEconomyInfoExtMapper;
import com.ruoyi.system.mapper.grid.GridCompanyEconomyInfoMapper;
import com.ruoyi.system.mapper.grid.GridCompanyLandExtMapper;
import com.ruoyi.system.service.grid.*;
import com.ruoyi.system.service.other.BsCommonService;
import com.ruoyi.system.service.system.ISysUserService;
import com.ruoyi.system.service.video.VideoDeviceChannelService;
import com.ruoyi.web.controller.screen.res.*;
import com.ruoyi.web.controller.screen.res.GridCompanyLandWithEcoExt;
import io.swagger.annotations.Api;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * * Author: brenda
 * * 2024/12/24
 **/
@Api(tags = "大屏接口-数字图层")
@RestController
@RequestMapping("/api/grid/screen/number")
public class ScreenNumberController {

    @Autowired
    private GridCompanyPeopleService gridCompanyPeopleService;
    @Autowired
    private BsCommonService bsCommonService;
    @Autowired
    private GridRegionService gridRegionService;
    @Autowired
    private GridPeopleService gridPeopleService;
    @Autowired
    private GridHouseService gridHouseService;
    @Autowired
    private GridInterviewService gridInterviewService;
    @Autowired
    private GridCompanyService gridCompanyService;
    @Autowired
    private GridShopService gridShopService;
    @Autowired
    private IPartyOrganizationService partyOrganizationService;
    @Autowired
    private VideoDeviceChannelService videoDeviceChannelService;
    @Autowired
    private GridShopStaffService gridShopStaffService;
    @Autowired
    private GridCompanyEconomyInfoExtMapper wsCompanyEconomyInfoExtMapper;
    @Autowired
    private GridCompanyLandExtMapper gridCompanyLandExtMapper;
    @Autowired
    private GridGroupLandService gridGroupLandService;
    @Autowired
    private GridGroupService gridGroupService;
    @Autowired
    private GridCompanyLandService gridCompanyLandService;
    @Autowired
    private GridRegionUserService gridRegionUserService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    GridCompanyLandExtMapper wsCompanyLandExtMapper;
    @Autowired
    GridCompanyEconomyInfoMapper wsCompanyEconomyInfoMapper;

    @GetMapping("/infoAll")
    public AjaxResult infoAll(@RequestParam("wgCode") String wgCode){
        Map<String, Object> map = new HashMap<String, Object>();
        //网格数
        GridRegionExample wgsExample = new GridRegionExample();
        wgsExample.createCriteria().andIsValidEqualTo("1").andWgTypeEqualTo("1").andWgCodeLike(wgCode + "%").andLevelEqualTo("3");
        long wgsCount = gridRegionService.countByExample(wgsExample);
        //地块数
        GridRegionExample dksExample = new GridRegionExample();
        dksExample.createCriteria().andIsValidEqualTo("1").andWgTypeEqualTo("1").andWgCodeLike(wgCode + "%").andLevelEqualTo("4");
        long dksCount = gridRegionService.countByExample(dksExample);
        //专属网格数
        GridRegionExample regionExample = new GridRegionExample();
        regionExample.createCriteria().andIsValidEqualTo("1").andWgTypeEqualTo("1")
                .andWgCodeLike(wgCode + "%").andLevelEqualTo("3").andYlzd2EqualTo("1");
        long zsCount = gridRegionService.countByExample(regionExample);
        map.put("jjDk", dksCount);
        map.put("zsWg", zsCount);
        map.put("jcWg", wgsCount - zsCount);
        map.put("company", gridCompanyService.countAll(wgCode));
        map.put("shop", gridShopService.countAll(wgCode));
        PartyOrganization partyOrganization = new PartyOrganization();
        partyOrganization.setSswg(wgCode);
        List<PartyOrganization> partyOrganizationList = partyOrganizationService.selectPartyOrganizationList(partyOrganization);
        map.put("org", partyOrganizationList.size());
        map.put("video", videoDeviceChannelService.getVideoCount(null));
        return AjaxResult.success(map);
    }

    /**
     * 企业关联人口信息
     */
    @GetMapping(value = "/companyToPeopleList")
    public AjaxResult companyToPeoplePage(@RequestParam(value = "companyId") String companyId) {
        List<GridCompanyPeople> companyPeopleList = gridCompanyPeopleService.selectGridCompanyPeopleByCompanyId(companyId, null, null);
        List<CommonPeopleItem> companyPeopleExtList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(companyPeopleList)){
            for(GridCompanyPeople people : companyPeopleList){
                CommonPeopleItem item = new CommonPeopleItem();
                GridPeople gridPeople = gridPeopleService.selectByPrimaryKey(people.getPeopleId());
                if(gridPeople != null){
                    item.setName(gridPeople.getPersonName());
                    item.setSex(gridPeople.getSex());
                    if(StringUtils.isNotBlank(gridPeople.getWgCode())){
                        item.setWgName(gridRegionService.getWgName(gridPeople.getWgCode()));
                    }
                    if (StringUtils.isNotBlank(gridPeople.getRklxCode())) {
                        item.setRklxValue(bsCommonService.getName(gridPeople.getRklxCode()));
                    }
                    companyPeopleExtList.add(item);
                }
            }
        }
        return AjaxResult.success(companyPeopleExtList);
    }

    /**
     * 企业/商铺走访日志信息
     * @param id
     * @return
     */
    @GetMapping("/interview/list")
    public AjaxResult companyInterviewList(@RequestParam(value = "id") String id){
        GridInterviewExample ex = new GridInterviewExample();
        GridInterviewExample.Criteria ca = ex.createCriteria();
        ca.andCidEqualTo(id);
        ex.setOrderByClause(" interview_time desc, create_time desc ");
        List<GridInterview> list = gridInterviewService.selectByExample(ex);
        return AjaxResult.success(list);
    }

    /**
     * 商铺点位
     * @param wgCode
     * @param name
     * @return
     */
    @GetMapping("/shop/list")
    public AjaxResult shopList(String wgCode, String name){
        List<SimpleGridShopItem> gridShops = gridShopService.getAllShopPointList(wgCode, name);
        return AjaxResult.success(gridShops);
    }

    /**
     * 网格点位
     * @param wgCode
     * @param name
     * @param type 1 基础网格，2专属网格 3经济地块
     * @return
     */
    @GetMapping("/region/list")
    public AjaxResult regionList(@RequestParam("type")String type, String wgCode, String name){
        GridRegionExample wgsExample = new GridRegionExample();
        GridRegionExample.Criteria criteria = wgsExample.createCriteria();
        criteria.andIsValidEqualTo("1");
        criteria.andWgTypeEqualTo("1");
        if(StringUtils.isNotBlank(wgCode)){
            criteria.andWgCodeLike(wgCode +"%");
        }
        if(StringUtils.isNotBlank(name)){
            criteria.andWgNameLike("%"+name+"%");
        }
        if("1".equals(type)){
            criteria.andLevelEqualTo("3");
            criteria.andYlzd2NotEqualTo("1");
        }else if("2".equals(type)){
            criteria.andLevelEqualTo("3");
            criteria.andYlzd2EqualTo("1");
        }else{
            criteria.andLevelEqualTo("4");
        }
        criteria.andWgCentreCoordinateIsNotNull();
        criteria.andWgCentreCoordinateNotEqualTo("");
        List<GridRegion> gridRegionList = gridRegionService.selectByExample(wgsExample);
        List<GridRegionExtInfo> infoList = BeanCopyUtil.bathToBean(gridRegionList, GridRegionExtInfo.class);
        if(!CollectionUtils.isEmpty(infoList)){
            infoList.forEach(e ->{
                if(org.apache.commons.lang3.StringUtils.isNotBlank(e.getWgCoordinate())){
                    String point = "MULTILINESTRING((" + e.getWgCoordinate().replaceAll("\\|"," ")+"))";
                    e.setWgCoordinate(point);
                }
                if(StringUtils.isNotBlank(e.getWgCentreCoordinate()) && e.getWgCentreCoordinate().contains("|")){
                    String longitude = e.getWgCentreCoordinate().substring(0, e.getWgCentreCoordinate().indexOf("|"));
                    String latitude = e.getWgCentreCoordinate().substring(e.getWgCentreCoordinate().indexOf("|")+1);
                    e.setLongitude(longitude);
                    e.setLatitude(latitude);
                    String point = e.getWgCentreCoordinate().replaceAll("\\|"," ");
                    e.setWgCentreCoordinate(point);
                }
            });
        }
        return AjaxResult.success(infoList);
    }

    /**
     * 商铺详情
     * @param id
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/shop/{id}")
    public AjaxResult getShopById(@PathVariable("id") Long id) throws Exception {
        GridShop gridShop = gridShopService.getGridShopById(id);
        //前端不支持对象套对象，附件不需要，返回null即可
        gridShop.setOtherappAttachments(null);
        return AjaxResult.success(gridShop);
    }

    //商铺人员列表
    @GetMapping(value = "/listGridShopPeople")
    public AjaxResult ListGridPeople(@RequestParam(value = "shopId") Long shopId) {
        GridShopStaffExample shopStaffExample = new GridShopStaffExample();
        GridShopStaffExample.Criteria criteria = shopStaffExample.createCriteria();
        criteria.andShopIdEqualTo(shopId);
        criteria.andValidEqualTo(Byte.valueOf("1"));
        List<GridShopStaff> wsShopStaffs = gridShopStaffService.selectByExample(shopStaffExample);
        List<CommonPeopleItem> itemList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(wsShopStaffs)){
            for(GridShopStaff people : wsShopStaffs){
                CommonPeopleItem item = new CommonPeopleItem();
                GridPeople gridPeople = gridPeopleService.selectByPrimaryKey(people.getPeopleId());
                if(gridPeople != null){
                    item.setName(gridPeople.getPersonName());
                    item.setSex(gridPeople.getSex());
                    if(StringUtils.isNotBlank(gridPeople.getWgCode())){
                        item.setWgName(gridRegionService.getWgName(gridPeople.getWgCode()));
                    }
                    if (StringUtils.isNotBlank(gridPeople.getRklxCode())) {
                        item.setRklxValue(bsCommonService.getName(gridPeople.getRklxCode()));
                    }
                    itemList.add(item);
                }
            }
        }
        return AjaxResult.success(itemList);
    }

    /**
     * 地块详情
     * @param landId
     * @param year
     * @return
     */
    @GetMapping("/land/detail")
    public AjaxResult landDetail(String landId, String year){
        GridRegion gridRegion = gridRegionService.selectByPrimaryKey(landId);
        if(gridRegion == null){
            return AjaxResult.error("地块不存在");
        }
        LandDetail detail = new LandDetail();
        detail.setLandId(landId);
        detail.setName(gridRegion.getWgName());
        detail.setArea(gridRegion.getWgArea());
        detail.setPurpose(gridRegion.getWgPurpose());
        List<GridCompanyLandExt> wsCompanyLandExtList = gridCompanyLandExtMapper.getList(null, landId, null);
        if (!org.springframework.util.CollectionUtils.isEmpty(wsCompanyLandExtList)) {
            //年度亩均税收总数
            Map<String, Object> saleAndTaxAndPerMuCountMap = wsCompanyEconomyInfoExtMapper.sumSaleAndTaxAndPerMu(wsCompanyLandExtList.stream().map(GridCompanyLandExt::getCompanyId).collect(Collectors.toList()), year);
            if(!saleAndTaxAndPerMuCountMap.isEmpty()){
                detail.setTax(saleAndTaxAndPerMuCountMap.get("perMuCount").toString());
            }
        }
        return AjaxResult.success(detail);
    }

    /**
     * 关联集团地块
     * @param landId
     * @return
     */
    @GetMapping("/land/group/list")
    public AjaxResult landGroupList(String landId){
        GridGroupLandExample example = new GridGroupLandExample();
        GridGroupLandExample.Criteria criteria = example.createCriteria();
        criteria.andLandIdEqualTo(landId);
        List<GridGroupLand> gridGroupLandList = gridGroupLandService.selectByExample(example);
        if(CollectionUtils.isNotEmpty(gridGroupLandList)){
            // 默认地块只能绑定在一个集团下
            GridGroupLand wsGroupLand = gridGroupLandList.get(0);
            GridGroupLandExample wsGroupLandExample1 = new GridGroupLandExample();
            wsGroupLandExample1.createCriteria().andGroupIdEqualTo(wsGroupLand.getGroupId());
            List<GridGroupLand> groupLands = gridGroupLandService.selectByExample(wsGroupLandExample1);
            if (!CollectionUtils.isEmpty(groupLands)) {
                List<String> landIds = new ArrayList<>();
                for (GridGroupLand wsGroupLand1 : groupLands) {
                    if (!landId.equals(wsGroupLand1.getLandId())) {
                        landIds.add(wsGroupLand1.getLandId());
                    }
                }
                if (!CollectionUtils.isEmpty(landIds)) {
                    GridRegionExample bsWgxxbExample = new GridRegionExample();
                    bsWgxxbExample.createCriteria().andIdIn(landIds).andIsValidEqualTo("1");
                    List<GridRegion> bsWgxxbs = gridRegionService.selectByExample(bsWgxxbExample);
                    return AjaxResult.success(bsWgxxbs);
                }
            }
        }
        return AjaxResult.success(new ArrayList<>());
    }

    /**
     * 地块关联企业
     * @param landId
     * @return
     */
    @GetMapping("/land/company/list")
    public AjaxResult landCompanyList(String landId, String year){
        GridRegion region = gridRegionService.selectByPrimaryKey(landId);
        if (region == null) {
            throw new RuntimeException("查询失败：未找到对应地块");
        }
        if(StringUtils.isBlank(year)){
            LocalDate localDate = LocalDate.now();
            year = String.valueOf(localDate.getYear());
        }
        List<GridCompanyLandWithEcoExt> exts = new ArrayList<>();
        List<GridCompanyLandExt> wsCompanyLandExtList = wsCompanyLandExtMapper.getList(null, region.getId(),  null);
        if (!CollectionUtils.isEmpty(wsCompanyLandExtList)) {
            List<String> companyIds = new ArrayList<>();
            for (GridCompanyLandExt wsCompanyLandExt : wsCompanyLandExtList) {
                companyIds.add(wsCompanyLandExt.getCompanyId());
                GridCompanyLandWithEcoExt wsCompanyLandWithEcoExt = BeanCopyUtil.toBean(wsCompanyLandExt, GridCompanyLandWithEcoExt.class);
                exts.add(wsCompanyLandWithEcoExt);
            }
            GridCompanyEconomyInfoExample wsCompanyEconomyInfoExample = new GridCompanyEconomyInfoExample();
            wsCompanyEconomyInfoExample.createCriteria().andCompanyIdIn(companyIds).andIsValidEqualTo("1").andYearEqualTo(year);
            List<GridCompanyEconomyInfo> wsCompanyEconomyInfos = wsCompanyEconomyInfoMapper.selectByExample(wsCompanyEconomyInfoExample);
            if (!CollectionUtils.isEmpty(wsCompanyEconomyInfos)) {
                for (GridCompanyLandWithEcoExt ext : exts) {
                    for (GridCompanyEconomyInfo info : wsCompanyEconomyInfos) {
                        if (ext.getCompanyId().equals(info.getCompanyId())) {
                            ext.setPerMu(info.getPerMu());
                            ext.setSale(info.getSale());
                            ext.setTax(info.getTax());
                            break;
                        }
                    }
                }
            }
        }
        return AjaxResult.success(exts);
    }

    @GetMapping("/regionDetail")
    public AjaxResult regionDetail(String wgCode){
        GridRegion region = gridRegionService.getWgByCode(wgCode);
        GridBasicInfo basicInfo = new GridBasicInfo();
        basicInfo.setWgCode(wgCode);
        basicInfo.setWgName(region.getWgName());
        GridRegionUserExample example = new GridRegionUserExample();
        GridRegionUserExample.Criteria criteria = example.createCriteria();
        criteria.andIsValidEqualTo("1");
        criteria.andWgIdEqualTo(wgCode);
        GridRegionUser regionUser = gridRegionUserService.selectFirstByExample(example);
        if(regionUser != null){
            SysUser sysUser = sysUserService.selectUserById(regionUser.getUserId());
            if(sysUser != null){
                basicInfo.setRegionUserName(sysUser.getNickName());
                basicInfo.setUserPhone(sysUser.getPhonenumber());
            }
        }
        return AjaxResult.success(basicInfo);
    }

    /**
     * @param type 1企业 2商铺 3住宅 4人口
     * @param wgCode
     * @return
     */
    @GetMapping("/region/obj/list")
    public AjaxResult regionObjList(@RequestParam("type")String type, @RequestParam("wgCode")String wgCode){
        if("1".equals(type)){
            GridCompanyExample example = new GridCompanyExample();
            GridCompanyExample.Criteria criteria = example.createCriteria();
            criteria.andIsValidEqualTo(Byte.valueOf("1"));
            criteria.andWgCodeEqualTo(wgCode);
            List<GridCompany> list = gridCompanyService.selectByExample(example);
            List<GridCompanyExt> itemList = BeanCopyUtil.bathToBean(list, GridCompanyExt.class);
            if(CollectionUtils.isNotEmpty(itemList)){
                itemList.forEach( e ->{
                    if(StringUtils.isNotBlank(e.getQylxCode())){
                        e.setQylxValue(bsCommonService.getName(e.getQylxCode()));
                    }
                });
            }
            return AjaxResult.success(itemList);
        }else if("2".equals(type)){
            GridShopExample example = new GridShopExample();
            GridShopExample.Criteria criteria = example.createCriteria();
            criteria.andValidEqualTo(Byte.valueOf("1"));
            criteria.andWgCodeEqualTo(wgCode);
            List<GridShop> shopList = gridShopService.selectByExample(example);
            return AjaxResult.success(shopList);
        }else if("3".equals(type)){
            GridHouseExample example = new GridHouseExample();
            GridHouseExample.Criteria criteria = example.createCriteria();
            criteria.andIsValidEqualTo(Byte.valueOf("1"));
            criteria.andWgCodeEqualTo(wgCode);
            List<GridHouse> list = gridHouseService.selectByExample(example);
            List<GridHouseExt> itemList = BeanCopyUtil.bathToBean(list, GridHouseExt.class);
            if(CollectionUtils.isNotEmpty(itemList)){
                itemList.forEach( e ->{
                    if(StringUtils.isNotBlank(e.getFwlxCode())){
                        e.setFwlxValue(bsCommonService.getName(e.getFwlxCode()));
                    }
                });
            }
            return AjaxResult.success(itemList);
        }else{
            GridPeopleExample example = new GridPeopleExample();
            GridPeopleExample.Criteria criteria = example.createCriteria();
            criteria.andIsValidEqualTo(Byte.valueOf("1"));
            criteria.andWgCodeEqualTo(wgCode);
            List<GridPeople> list = gridPeopleService.selectByExample(example);
            List<GridPeopleExt> itemList = BeanCopyUtil.bathToBean(list, GridPeopleExt.class);
            if(CollectionUtils.isNotEmpty(itemList)){
                itemList.forEach( e ->{
                    if(StringUtils.isNotBlank(e.getRklxCode())){
                        e.setRklxValue(bsCommonService.getName(e.getRklxCode()));
                    }
                });
            }
            return AjaxResult.success(itemList);
        }
    }

    /**
     * 企业点位
     * @param wgCode
     * @param name
     * @return
     */
    @GetMapping("/companyPointList")
    public AjaxResult companyPointList(@RequestParam(value = "wgCode")String wgCode,
                                       @RequestParam(value = "name", required = false) String name){
        return AjaxResult.success(gridCompanyService.companyPointList(wgCode, name));
    }

    /**
     * 子集网格
     * @param wgCode
     * @return
     */
    @GetMapping("/getChildGridRegion")
    public AjaxResult getChildGridRegion(@RequestParam(value = "wgCode")String wgCode){
        return AjaxResult.success(gridRegionService.getChildGridRegion(wgCode));
    }
}
