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.system.domain.grid.*;
import com.ruoyi.system.domain.grid.ext.GridCompanyLandExt;
import com.ruoyi.system.domain.grid.vo.GridEconomyPerMuItem;
import com.ruoyi.system.domain.other.BsCommon;
import com.ruoyi.system.listener.MyBaseService;
import com.ruoyi.system.mapper.grid.*;
import com.ruoyi.system.service.BaseServiceImpl;
import com.ruoyi.system.service.grid.GridCompanyLandService;
import com.ruoyi.system.service.other.BsCommonService;
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.*;

/**
 * @author yaoqiang
 * @date 2023-04-20 16:09
 * @desc GridCompanyLandService实现
 */
@Service
@MyBaseService
public class GridCompanyLandServiceImpl extends BaseServiceImpl<GridCompanyLandMapper, GridCompanyLand, GridCompanyLandExample> implements GridCompanyLandService {

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

    @Autowired
    GridCompanyLandMapper gridCompanyLandMapper;

    @Autowired
    GridCompanyLandExtMapper gridCompanyLandExtMapper;

    @Autowired
    GridRegionMapper gridRegionMapper;

    @Autowired
    GridGroupMapper gridGroupMapper;

    @Autowired
    GridCompanyEconomyInfoExtMapper wsCompanyEconomyInfoExtMapper;

    @Autowired
    BsCommonService bsCommonService;

    @Override
    public PageInfo<GridCompanyLandExt> page(Integer pageNo, Integer pageSize, String companyId, String landId, String landPurpose) {
        PageHelper.startPage(pageNo, pageSize);
        PageInfo<GridCompanyLandExt> pageInfo = new PageInfo<>(gridCompanyLandExtMapper.getList(companyId, landId, landPurpose));
        return pageInfo;
    }

    @Override
    @Transactional
    public AjaxResult saveOrUpdate(GridCompanyLand wsCompanyLand) {
        Validator.validateNotEmpty(wsCompanyLand.getCompanyId(), "企业id为空");
        Validator.validateNotEmpty(wsCompanyLand.getLandId(), "地块id为空");
        try {
            new BigDecimal(wsCompanyLand.getShareArea());
        } catch (Exception e) {
            throw new RuntimeException("分摊面积只能是数字或小数");
        }
        //分摊面积不可超过地块的总面积
        GridRegion region = gridRegionMapper.selectByPrimaryKey(wsCompanyLand.getLandId());
        if (StringUtils.isNotBlank(wsCompanyLand.getShareArea())
                && StringUtils.isNotBlank(region.getWgArea())
                && new BigDecimal(wsCompanyLand.getShareArea()).compareTo(new BigDecimal(region.getWgArea())) > 0) {
            return AjaxResult.error(400, "分摊面积不可超过地块的总面积");
        }
        if (StringUtils.isBlank(wsCompanyLand.getId())) {
            List<GridCompanyLandExt> wsCompanyLandExtList = gridCompanyLandExtMapper.getList(wsCompanyLand.getCompanyId(), wsCompanyLand.getLandId(), null);
            if (!CollectionUtils.isEmpty(wsCompanyLandExtList)) {
                return AjaxResult.error(400, "该企业已绑定该地块");
            }
            wsCompanyLand.setId(IdUtil.fastSimpleUUID());
            wsCompanyLand.setCreateTime(DateUtil.formatDateTime(new Date()));
            gridCompanyLandMapper.insertSelective(wsCompanyLand);
        } else {
            GridCompanyLandExample wsCompanyLandExample = new GridCompanyLandExample();
            GridCompanyLandExample.Criteria criteria = wsCompanyLandExample.createCriteria();
            criteria.andCompanyIdEqualTo(wsCompanyLand.getCompanyId());
            criteria.andLandIdEqualTo(wsCompanyLand.getLandId());
            criteria.andIdNotEqualTo(wsCompanyLand.getId());
            criteria.andIsValidEqualTo("1");
            List<GridCompanyLand> wsCompanyLandList = gridCompanyLandMapper.selectByExample(wsCompanyLandExample);
            if (!CollectionUtils.isEmpty(wsCompanyLandList)) {
                return AjaxResult.error(400, "该企业已绑定该地块");
            }
            gridCompanyLandMapper.updateByPrimaryKeySelective(wsCompanyLand);
        }
        return AjaxResult.success("success", wsCompanyLand.getId());
    }

    @Override
    @Transactional
    public void delete(String id) {
        Validator.validateNotEmpty(id, "id为空");
        GridCompanyLand wsCompanyLand = new GridCompanyLand();
        wsCompanyLand.setId(id);
        wsCompanyLand.setIsValid("0");
        gridCompanyLandMapper.updateByPrimaryKeySelective(wsCompanyLand);
    }

    @Override
    public GridCompanyLandExt detail(String id) {
        Validator.validateNotEmpty(id, "id为空");
        return gridCompanyLandExtMapper.getById(id);
    }

    @Override
    public Map<String, String> infoStatistic(String year) {
        if (StringUtils.isBlank(year)) {
            year = String.valueOf(DateUtil.thisYear());
        }
        Map<String, String> result = new HashMap<>();
        // 总的经济地块数量
        long landCount = 0;
        GridRegionExample bsWgxxbExample = new GridRegionExample();
        GridRegionExample.Criteria bsWgxxbExampleCriteria = bsWgxxbExample.createCriteria();
        bsWgxxbExampleCriteria.andWgTypeEqualTo("4");
        bsWgxxbExampleCriteria.andLevelEqualTo("3");
        landCount = gridRegionMapper.countByExample(bsWgxxbExample);

        //对应的企业数
        long companyCount = 0;
        Set<String> companyIdSet = new HashSet<>();
        List<GridCompanyLandExt> wsCompanyLandExtList = gridCompanyLandExtMapper.getList(null, null, null);
        if (!CollectionUtils.isEmpty(wsCompanyLandExtList)) {
            for (GridCompanyLandExt wsCompanyLandExt : wsCompanyLandExtList) {
                companyIdSet.add(wsCompanyLandExt.getCompanyId());
            }
            companyCount = companyIdSet.size();
        }
        //对应的集团数
        long groupCount = 0;
        GridGroupExample wsGroupExample = new GridGroupExample();
        GridGroupExample.Criteria wsGroupExampleCriteria = wsGroupExample.createCriteria();
        wsGroupExampleCriteria.andIsValidEqualTo("1");
        groupCount = gridGroupMapper.countByExample(wsGroupExample);


        //年度亩均税收总数
        Map<String, Object> saleAndTaxAndPerMuCountMap = wsCompanyEconomyInfoExtMapper.sumSaleAndTaxAndPerMu(new ArrayList<>(companyIdSet), year);

        // 年度销售总数
        String saleCount = saleAndTaxAndPerMuCountMap != null && saleAndTaxAndPerMuCountMap.get("saleCount") != null ? String.valueOf(saleAndTaxAndPerMuCountMap.get("saleCount")) : "0";
        // 年度税收总数
        String taxCount = saleAndTaxAndPerMuCountMap != null && saleAndTaxAndPerMuCountMap.get("taxCount") != null ? String.valueOf(saleAndTaxAndPerMuCountMap.get("taxCount")) : "0";
        // 年度亩均税收总数
        String perMuCount = saleAndTaxAndPerMuCountMap != null && saleAndTaxAndPerMuCountMap.get("perMuCount") != null ? String.valueOf(saleAndTaxAndPerMuCountMap.get("perMuCount")) : "0";

        result.put("landCount", String.valueOf(landCount));
        result.put("companyCount", String.valueOf(companyCount));
        result.put("groupCount", String.valueOf(groupCount));
        result.put("saleCount", saleCount);
        result.put("taxCount", taxCount);
        result.put("perMuCount", perMuCount);
        return result;
    }

    @Override
    public Map<String, String> leaseStatistic() {
        Map<String, String> result = new HashMap<>();
        List<BsCommon> bsCommonList = bsCommonService.getWgdxList("zlgx");
        if (!CollectionUtils.isEmpty(bsCommonList)) {
            for (BsCommon bsCommon : bsCommonList) {
                int zlgxCount = gridCompanyLandExtMapper.countByZlgx(bsCommon.getCode());
                result.put(bsCommon.getCode(), String.valueOf(zlgxCount));
            }
        }
        return result;
    }

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