package com.ruoyi.system.service.grid.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.bean.BeanCopyUtil;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.grid.ext.GridGroupExt;
import com.ruoyi.system.domain.grid.ext.GridGroupLandExt;
import com.ruoyi.system.listener.MyBaseService;
import com.ruoyi.system.mapper.grid.GridGroupLandExtMapper;
import com.ruoyi.system.mapper.grid.GridGroupLandMapper;
import com.ruoyi.system.mapper.grid.GridGroupMapper;
import com.ruoyi.system.mapper.grid.GridRegionMapper;
import com.ruoyi.system.service.BaseServiceImpl;
import com.ruoyi.system.service.grid.GridGroupLandService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yaoqiang
 * @date 2023-04-20 16:09
 * @desc GridGroupLandService实现
 */
@Service
@MyBaseService
public class GridGroupLandServiceImpl extends BaseServiceImpl<GridGroupLandMapper, GridGroupLand, GridGroupLandExample> implements GridGroupLandService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GridGroupLandServiceImpl.class);

    @Autowired
    GridGroupMapper gridGroupMapper;

    @Autowired
    GridGroupLandMapper gridGroupLandMapper;

    @Autowired
    GridGroupLandExtMapper gridGroupLandExtMapper;

    @Autowired
    GridRegionMapper gridRegionMapper;

    @Override
    public PageInfo<GridGroupExt> page(Integer pageNo, Integer pageSize, String groupName) {
        PageHelper.startPage(pageNo, pageSize);
        GridGroupExample wsGroupExample = new GridGroupExample();
        GridGroupExample.Criteria criteria = wsGroupExample.createCriteria();
        if (StringUtils.isNotBlank(groupName)) {
            criteria.andGroupNameLike("%" + groupName + "%");
        }
        wsGroupExample.setOrderByClause("create_time desc");
        PageInfo<GridGroup> pageInfo = new PageInfo<>(gridGroupMapper.selectByExample(wsGroupExample));
        List<GridGroup> wsGroupList = pageInfo.getList();
        List<GridGroupExt> wsGroupExtList = BeanCopyUtil.bathToBean(wsGroupList, GridGroupExt.class);
        List<String> groupIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(wsGroupExtList)) {
            for (GridGroupExt wsGroupExt : wsGroupExtList) {
                groupIds.add(wsGroupExt.getId());
            }
            List<GridGroupLandExt> wsGroupLandExtList = gridGroupLandExtMapper.getByGroupIds(groupIds);
            Map<String, List<GridGroupLandExt>> wsGroupLandExtListMap = wsGroupLandExtList.stream().collect(Collectors.groupingBy(GridGroupLandExt::getGroupId));
            for (GridGroupExt wsGroupExt : wsGroupExtList) {
                List<GridGroupLandExt> wsGroupLandExts = wsGroupLandExtListMap.get(wsGroupExt.getId());
                List<String> landIds = new ArrayList<>();
                List<String> landNames = new ArrayList<>();
                String landAreaTotal = "0";
                List<Map<String, String>> relatedCompanyList = new ArrayList<>();
                if (CollectionUtils.isEmpty(wsGroupLandExts)) {
                    wsGroupLandExts = new ArrayList<>();
                }
                for (GridGroupLandExt wsGroupLandExt : wsGroupLandExts) {
                    landIds.add(wsGroupLandExt.getLandId());
                    landNames.add(wsGroupLandExt.getLandName());
                }
                wsGroupExt.setLandIds(landIds);
                wsGroupExt.setLandNames(landNames);
                wsGroupExt.setGridGroupLandExtList(wsGroupLandExts);


                if (!CollectionUtils.isEmpty(landIds)) {
                    //集团地块总面积
                    landAreaTotal = sumlandAreaTotal(landIds);
                    //地块下属关联企业
                    relatedCompanyList = getRelatedCompanyList(landIds);
                }
                wsGroupExt.setLandAreaTotal(landAreaTotal);
                wsGroupExt.setRelatedCompanyList(relatedCompanyList);

                //地块下属关联企业数量
                wsGroupExt.setRelatedCompanyCount(String.valueOf(relatedCompanyList.size()));
            }

        }
        PageInfo<GridGroupExt> result = BeanCopyUtil.toBean(pageInfo, PageInfo.class);
        result.setList(wsGroupExtList);
        return result;
    }

    @Override
    @Transactional
    public AjaxResult saveOrUpdate(GridGroupExt wsGroupExt) {
        Validator.validateNotEmpty(wsGroupExt.getGroupName(), "集团名称为空");
        Validator.validateNotEmpty(wsGroupExt.getLandIds(), "地块id信息为空");

        GridGroupLandExample wsGroupLandExample = new GridGroupLandExample();
        GridGroupLandExample.Criteria wsGroupLandExampleCriteria = wsGroupLandExample.createCriteria();
        wsGroupLandExampleCriteria.andLandIdIn(wsGroupExt.getLandIds());
        List<GridGroupLand> wsGroupLandList = gridGroupLandMapper.selectByExample(wsGroupLandExample);

        if (StringUtils.isBlank(wsGroupExt.getId())) {
            //集团名称校验重复
            GridGroupExample wsGroupExample = new GridGroupExample();
            GridGroupExample.Criteria wsGroupExampleCriteria = wsGroupExample.createCriteria();
            wsGroupExampleCriteria.andGroupNameEqualTo(wsGroupExt.getGroupName());
            List<GridGroup> wsGroupList = gridGroupMapper.selectByExample(wsGroupExample);
            if (!CollectionUtils.isEmpty(wsGroupList)) {
                return AjaxResult.error(400, "集团已存在");
            }

            //所选地块已被其他集团绑定
            if (!CollectionUtils.isEmpty(wsGroupLandList)) {
                return AjaxResult.error(400, "所选地块已被其他集团绑定");
            }

            String groupId = IdUtil.fastSimpleUUID();
            wsGroupExt.setId(groupId);
            GridGroup wsGroup = new GridGroup();
            wsGroup.setId(groupId);
            wsGroup.setGroupName(wsGroupExt.getGroupName());
            wsGroup.setCreateTime(DateUtil.formatDateTime(new Date()));
            gridGroupMapper.insertSelective(wsGroup);

            //新的集团地块关联
            for (String landId : wsGroupExt.getLandIds()) {
                GridGroupLand wsGroupLand = new GridGroupLand();
                wsGroupLand.setId(IdUtil.fastSimpleUUID());
                wsGroupLand.setGroupId(groupId);
                wsGroupLand.setLandId(landId);
                wsGroupLand.setCreateTime(DateUtil.formatDateTime(new Date()));
                gridGroupLandMapper.insertSelective(wsGroupLand);
            }

        } else {
            //集团名称校验重复
            GridGroupExample wsGroupExample = new GridGroupExample();
            GridGroupExample.Criteria criteria = wsGroupExample.createCriteria();
            criteria.andGroupNameEqualTo(wsGroupExt.getGroupName());
            criteria.andIdNotEqualTo(wsGroupExt.getId());
            List<GridGroup> wsGroupList = gridGroupMapper.selectByExample(wsGroupExample);
            if (!CollectionUtils.isEmpty(wsGroupList)) {
                return AjaxResult.error(400, "集团已存在");
            }

            //所选地块已被其他集团绑定
            wsGroupLandExampleCriteria.andGroupIdNotEqualTo(wsGroupExt.getId());
            List<GridGroupLand> wsGroupLandList2 = gridGroupLandMapper.selectByExample(wsGroupLandExample);
            if (!CollectionUtils.isEmpty(wsGroupLandList2)) {
                return AjaxResult.error(400, "所选地块已被其他集团绑定");
            }

            //更新集团
            GridGroup wsGroup = new GridGroup();
            wsGroup.setId(wsGroupExt.getId());
            wsGroup.setGroupName(wsGroupExt.getGroupName());
            wsGroup.setIsValid(wsGroupExt.getIsValid());
            gridGroupMapper.updateByPrimaryKeySelective(wsGroup);

            //删除原有的集团地块关联
            GridGroupLandExample wsGroupLandExample2 = new GridGroupLandExample();
            GridGroupLandExample.Criteria wsGroupLandExample2Criteria = wsGroupLandExample2.createCriteria();
            wsGroupLandExample2Criteria.andGroupIdEqualTo(wsGroupExt.getId());
            gridGroupLandMapper.deleteByExample(wsGroupLandExample2);

            //新的集团地块关联
            for (String landId : wsGroupExt.getLandIds()) {
                GridGroupLand wsGroupLand = new GridGroupLand();
                wsGroupLand.setId(IdUtil.fastSimpleUUID());
                wsGroupLand.setGroupId(wsGroupExt.getId());
                wsGroupLand.setLandId(landId);
                wsGroupLand.setCreateTime(DateUtil.formatDateTime(new Date()));
                gridGroupLandMapper.insertSelective(wsGroupLand);
            }
        }
        return AjaxResult.success("success", wsGroupExt.getId());
    }

    @Override
    @Transactional
    public void delete(String groupId) {
        Validator.validateNotEmpty(groupId, "集团id为空");

        //删除集团
        gridGroupMapper.deleteByPrimaryKey(groupId);

        //删除集团关联地块
        GridGroupLandExample wsGroupLandExample = new GridGroupLandExample();
        GridGroupLandExample.Criteria criteria2 = wsGroupLandExample.createCriteria();
        criteria2.andGroupIdEqualTo(groupId);
        gridGroupLandMapper.deleteByExample(wsGroupLandExample);
    }

    @Override
    public GridGroupExt detail(String groupId) {
        Validator.validateNotEmpty(groupId, "集团id为空");
        GridGroup wsGroup = gridGroupMapper.selectByPrimaryKey(groupId);
        GridGroupExt wsGroupExt = BeanCopyUtil.toBean(wsGroup, GridGroupExt.class);
        List<GridGroupLandExt> wsGroupLandExtList = gridGroupLandExtMapper.getByGroupId(groupId);
        List<String> landIdList = new ArrayList<>();
        List<String> landNameList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(wsGroupLandExtList)) {
            for (GridGroupLandExt wsGroupLandExt : wsGroupLandExtList) {
                landIdList.add(wsGroupLandExt.getLandId());
                landNameList.add(wsGroupLandExt.getLandName());
            }
        }
        wsGroupExt.setLandIds(landIdList);
        wsGroupExt.setLandNames(landNameList);
        wsGroupExt.setGridGroupLandExtList(wsGroupLandExtList);

        //集团地块总面积
        String landAreaTotal = sumlandAreaTotal(landIdList);
        wsGroupExt.setLandAreaTotal(landAreaTotal);

        //地块下属关联企业
        List<Map<String, String>> relatedCompanyList = getRelatedCompanyList(landIdList);
        wsGroupExt.setRelatedCompanyList(relatedCompanyList);

        //地块下属关联企业数量
        wsGroupExt.setRelatedCompanyCount(String.valueOf(relatedCompanyList.size()));
        return wsGroupExt;
    }

    @Override
    public String sumlandAreaTotal(List<String> landIds) {
        GridRegionExample example = new GridRegionExample();
        GridRegionExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(landIds);
        List<GridRegion> regionList = gridRegionMapper.selectByExample(example);
        BigDecimal landAreaTotal = new BigDecimal("0");
        if (!CollectionUtils.isEmpty(regionList)) {
            for (GridRegion region : regionList) {
                if (StringUtils.isNotBlank(region.getWgArea())) {
                    landAreaTotal = landAreaTotal.add(new BigDecimal(region.getWgArea()));
                }
            }
        }
        return landAreaTotal.toString();
    }

    @Override
    public List<Map<String, String>> getRelatedCompanyList(List<String> landIds) {
        List<Map<String, String>> relatedCompanyList = gridGroupLandExtMapper.getRelatedCompanyList(landIds);
        return relatedCompanyList;
    }

    @Override
    public List<Map<String, String>> permuSortList(String year) {
        if (StringUtils.isBlank(year)) {
            year = String.valueOf(DateUtil.thisYear());
        }
        List<Map<String, String>> permuSortList = gridGroupLandExtMapper.getPermuSortList(year);
        return permuSortList;
    }
}
