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

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.bean.BeanCopyUtil;
import com.ruoyi.common.zqt.ZQTConcurrencyHelper;
import com.ruoyi.common.zqt.ZQTImportExcelUtil;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.grid.enums.GridCompanyEcoInfoEnum;
import com.ruoyi.system.domain.grid.enums.GridCompanyEconomyPerMuResultEnum;
import com.ruoyi.system.domain.grid.ext.*;
import com.ruoyi.system.listener.MyBaseService;
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.BaseServiceImpl;
import com.ruoyi.system.service.grid.GridCompanyEconomyInfoService;
import com.ruoyi.system.service.grid.GridCompanyService;
import com.ruoyi.system.service.grid.GridGroupLandService;
import com.ruoyi.system.service.grid.GridRegionService;
import com.ruoyi.system.service.other.BsCommonService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author Cesar
 * @date ${cTime}
 * @desc GridCompanyEconomyInfoService实现
 */
@Service
@MyBaseService
public class GridCompanyEconomyInfoServiceImpl extends BaseServiceImpl<GridCompanyEconomyInfoMapper, GridCompanyEconomyInfo, GridCompanyEconomyInfoExample> implements GridCompanyEconomyInfoService {

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

    @Autowired
    GridCompanyEconomyInfoMapper gridCompanyEconomyInfoMapper;
    @Autowired
    GridCompanyEconomyInfoExtMapper gridCompanyEconomyInfoExtMapper;
    @Autowired
    GridCompanyLandExtMapper gridCompanyLandExtMapper;
    @Autowired
    GridCompanyService gridCompanyService;
    @Autowired
    GridRegionService gridRegionService;

    @Autowired
    GridGroupLandService gridGroupLandService;

    @Autowired
    BsCommonService bsCommonService;

    @Override
    public List<GridCompanyEconomyInfo> listEconomyInfos(String companyId, String year) {
        GridCompanyEconomyInfoExample example = new GridCompanyEconomyInfoExample();
        GridCompanyEconomyInfoExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(companyId)) {
            criteria.andCompanyIdEqualTo(companyId);
        }
        if (StringUtils.isNotBlank(year)) {
            criteria.andYearEqualTo(year);
        }
        criteria.andIsValidEqualTo("1");
        example.setOrderByClause(" year desc ");
        List<GridCompanyEconomyInfo> res = gridCompanyEconomyInfoMapper.selectByExample(example);
        for (GridCompanyEconomyInfo info : res) {
            info.setSales(Arrays.asList(info.getYearSales().substring(1, info.getYearSales().length()-1).split(",")));
            info.setTaxes(Arrays.asList(info.getYearTaxes().substring(1, info.getYearTaxes().length()-1).split(",")));
        }
        return res;
    }

    @Override
    public PageInfo<GridCompanyEcoInfoBean> pageEconomyInfos(Integer pageNo, Integer pageSize, String year,String qylxCode, String companyKeyword, String orderValue, String orderType) {
        int currIndex = (pageNo - 1) * pageSize;
        PageInfo<GridCompanyEcoInfoBean> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(pageNo);
        pageInfo.setPageSize(pageSize);
        List<GridCompanyEcoInfoBean> infos = gridCompanyEconomyInfoExtMapper.pageInfoList(orderType, orderValue, companyKeyword, year, qylxCode, currIndex, pageSize);
        pageInfo.setList(infos);
        pageInfo.setTotal(gridCompanyEconomyInfoExtMapper.countPageNum(companyKeyword, year, qylxCode));
        return pageInfo;
    }

    @Override
    public GridCompanyEconomyInfo detail(String id) {
        return gridCompanyEconomyInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public void save(GridCompanyEconomyInfoExt economyInfo) {
        if (StringUtils.isBlank(economyInfo.getCompanyId())
                || StringUtils.isBlank(economyInfo.getYear())
                || economyInfo.getSale() == null
                || economyInfo.getTax() == null
                || economyInfo.getPerMu() == null) {
            throw new RuntimeException("保存失败：缺少必要参数");
        }
        GridCompanyEconomyInfoExample example = new GridCompanyEconomyInfoExample();
        example.createCriteria().andYearEqualTo(economyInfo.getYear()).andCompanyIdEqualTo(economyInfo.getCompanyId()).andIsValidEqualTo("1");
        example.setOrderByClause(" create_time desc ");
        List<GridCompanyEconomyInfo> economyInfos = gridCompanyEconomyInfoMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(economyInfos)) {
            economyInfo.setId(UUID.randomUUID().toString());
            economyInfo.setIsValid("1");
            economyInfo.setCreateTime(DateUtils.getTime());
            gridCompanyEconomyInfoMapper.insert(economyInfo);
        } else {
            GridCompanyEconomyInfo oldEconomyInfo = economyInfos.get(0);
            oldEconomyInfo.setTax(economyInfo.getTax());
            oldEconomyInfo.setSale(economyInfo.getSale());
            oldEconomyInfo.setPerMu(economyInfo.getPerMu());
            gridCompanyEconomyInfoMapper.updateByPrimaryKey(oldEconomyInfo);
        }
    }

    @Override
    public boolean checkIsExist(String year, String companyId) {
        GridCompanyEconomyInfoExample example = new GridCompanyEconomyInfoExample();
        example.createCriteria().andYearEqualTo(year).andCompanyIdEqualTo(companyId).andIsValidEqualTo("1");
        return gridCompanyEconomyInfoMapper.countByExample(example) > 0;
    }

    @Override
    public AjaxResult importExcel(MultipartFile file) {

        if (file == null) {
            return AjaxResult.error(400, "文件不存在");
        }
        StringBuilder msg = new StringBuilder();
        Workbook workbook = null;
        try {
            String fileName = file.getOriginalFilename();
            InputStream is = file.getInputStream();
            if ("xls".equals(ZQTImportExcelUtil.getPostFix(fileName))) {
                workbook = new HSSFWorkbook(is);
            } else if ("xlsx".equals(ZQTImportExcelUtil.getPostFix(fileName))) {
                workbook = new XSSFWorkbook(is);
            } else {
                return AjaxResult.error(400, "文件格式不正确");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            msg.append(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            msg.append(e.getMessage());
            return AjaxResult.error(400, "系统错误" + msg);
        }

        List<GridCompanyEconomyInfoImportExt> list = new ArrayList<>();

        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i); //读取工作表
            if (sheet == null) //空判断
                continue;
            for (int j = 1; j <= sheet.getLastRowNum(); j++) {
                Row row = sheet.getRow(j); //读取每行
                if (row.getCell(0) != null) {
                    GridCompanyEconomyInfoImportExt ce = new GridCompanyEconomyInfoImportExt();
                    ce.setCreditCode(ZQTImportExcelUtil.getValue(row.getCell(0)));
                    ce.setCompanyName(ZQTImportExcelUtil.getValue(row.getCell(1)));
                    ce.setYear(ZQTImportExcelUtil.getValue(row.getCell(2)));
                    ce.setPerMuStr(ZQTImportExcelUtil.getValue(row.getCell(3)));
                    ce.setTaxStr(ZQTImportExcelUtil.getValue(row.getCell(4)));
                    ce.setSaleStr(ZQTImportExcelUtil.getValue(row.getCell(5)));
                    list.add(ce);
                }
            }
        }

        if (StringUtils.isBlank(msg)) {
            int records = 0;
            int temp = 0;
            for (int i = 0; i < list.size(); i++) {
                GridCompanyEconomyInfoImportExt ce = list.get(i);
                try {
                    StringBuilder recordMsg = new StringBuilder();
                    if (StringUtils.isBlank(ce.getCreditCode())) {
                        recordMsg.append("统一社会信用代码不能为空；");
                    }
                    if (StringUtils.isBlank(ce.getYear())) {
                        recordMsg.append("年度数据不能为空；");
                    }
                    if (StringUtils.isBlank(ce.getPerMuStr())) {
                        recordMsg.append("亩均经济不能为空；");
                    }
                    if (StringUtils.isBlank(ce.getTaxStr())) {
                        recordMsg.append("年度税收不能为空；");
                    }
                    if (StringUtils.isBlank(ce.getSaleStr())) {
                        recordMsg.append("年度销售不能为空；");
                    }
                    List<GridCompany> companyList = gridCompanyService.selectGridCompanyByCreditCode(ce.getCreditCode(), null);
                    if (CollectionUtils.isEmpty(companyList)) {
                        recordMsg.append("企业信息错误，找不到对应企业；");
                    }
                    if (StringUtils.isNotBlank(recordMsg)) {
                        msg.append("第").append(i + 1).append("行数据导入出错:" + recordMsg);
                        continue;
                    }
                    GridCompanyEconomyInfoExt wsCompanyEconomyInfo = new GridCompanyEconomyInfoExt();
                    wsCompanyEconomyInfo.setCompanyId(companyList.get(0).getId());
                    wsCompanyEconomyInfo.setYear(ce.getYear());
                    wsCompanyEconomyInfo.setPerMu(new BigDecimal(ce.getPerMuStr()));
                    wsCompanyEconomyInfo.setTax(new BigDecimal(ce.getTaxStr()));
                    wsCompanyEconomyInfo.setSale(new BigDecimal(ce.getSaleStr()));
                    wsCompanyEconomyInfo.setCover(true);
                    this.save(wsCompanyEconomyInfo);
                    records++;
                } catch (Exception e) {
                    e.printStackTrace();
                    msg.append("第").append(i + 1).append("行数据导入出错:" + e.getMessage());
                }
            }
            msg.append("导入").append(records).append("条数据");
            return AjaxResult.success("success", msg.toString());//返回成功信息
        }
        return AjaxResult.error(400, msg.toString());
    }

    @Override
    public void delete(String id) {
        GridCompanyEconomyInfo wsCompanyEconomyInfo = gridCompanyEconomyInfoMapper.selectByPrimaryKey(id);
        if (wsCompanyEconomyInfo == null) {
            throw new RuntimeException("删除失败：找不到对应的经济信息");
        }
        wsCompanyEconomyInfo.setIsValid("0");
        gridCompanyEconomyInfoMapper.updateByPrimaryKey(wsCompanyEconomyInfo);
    }

    @Override
    public Map perMuCount(String year) {
        Map<String, Object> result = new HashMap<>();
        List<GridCompanyEconomyInfoPerMuBean> beans = gridCompanyEconomyInfoExtMapper.countPerMu(year, null);
        if (CollectionUtils.isEmpty(beans)) {
            for (GridCompanyEconomyPerMuResultEnum enums : GridCompanyEconomyPerMuResultEnum.values()) {
                GridCompanyEconomyInfoPerMuCountBean countBean = new GridCompanyEconomyInfoPerMuCountBean(0, enums.getCode(), enums.getValue());
                result.put(enums.getCode(), countBean);
            }
            return result;
        }
        List<GridCompanyEconomyInfoPerMuBean> ZERO_TO_ONE_BEANS = new ArrayList<>();
        List<GridCompanyEconomyInfoPerMuBean> ONE_TO_THREE_BEANS = new ArrayList<>();
        List<GridCompanyEconomyInfoPerMuBean> OVER_THREE_BEANS = new ArrayList<>();
        BigDecimal oneNum = new BigDecimal("1.00");
        BigDecimal threeNum = new BigDecimal("3.00");
        for (GridCompanyEconomyInfoPerMuBean bean : beans) {
            if (bean.getAllPerMu().compareTo(oneNum) < 0) {
                ZERO_TO_ONE_BEANS.add(bean);
            } else if (bean.getAllPerMu().compareTo(threeNum) <= 0) {
                ONE_TO_THREE_BEANS.add(bean);
            } else {
                OVER_THREE_BEANS.add(bean);
            }
        }
        GridCompanyEconomyInfoPerMuCountBean ZERO_TO_ONE_BEAN = new GridCompanyEconomyInfoPerMuCountBean(ZERO_TO_ONE_BEANS.size(), GridCompanyEconomyPerMuResultEnum.ZERO_TO_ONE.getCode(), GridCompanyEconomyPerMuResultEnum.ZERO_TO_ONE.getValue(), ZERO_TO_ONE_BEANS);
        GridCompanyEconomyInfoPerMuCountBean ONE_TO_THREE_BEAN = new GridCompanyEconomyInfoPerMuCountBean(ONE_TO_THREE_BEANS.size(), GridCompanyEconomyPerMuResultEnum.ONE_TO_THREE.getCode(), GridCompanyEconomyPerMuResultEnum.ONE_TO_THREE.getValue(), ONE_TO_THREE_BEANS);
        GridCompanyEconomyInfoPerMuCountBean OVER_THREE_BEAN = new GridCompanyEconomyInfoPerMuCountBean(OVER_THREE_BEANS.size(), GridCompanyEconomyPerMuResultEnum.OVER_THREE.getCode(), GridCompanyEconomyPerMuResultEnum.OVER_THREE.getValue(), OVER_THREE_BEANS);
        result.put(GridCompanyEconomyPerMuResultEnum.ZERO_TO_ONE.getCode(), ZERO_TO_ONE_BEAN);
        result.put(GridCompanyEconomyPerMuResultEnum.ONE_TO_THREE.getCode(), ONE_TO_THREE_BEAN);
        result.put(GridCompanyEconomyPerMuResultEnum.OVER_THREE.getCode(), OVER_THREE_BEAN);
        return result;
    }

    @Override
    public List<GridCompanyEconomyPermuItem> listPerMuByYear(String year) {
        List<GridCompanyEconomyPermuItem> list = new ArrayList<>();
        List<GridCompanyEconomyInfoPerMuBean> beans = gridCompanyEconomyInfoExtMapper.countPerMu(year, null);
        if (CollectionUtils.isEmpty(beans)) {
            for (GridCompanyEconomyPerMuResultEnum enums : GridCompanyEconomyPerMuResultEnum.values()) {
                GridCompanyEconomyPermuItem countBean = new GridCompanyEconomyPermuItem(enums.getCode(), enums.getValue(), 0);
                list.add(countBean);
            }
            return list;
        }
        List<GridCompanyEconomyInfoPerMuBean> ZERO_TO_ONE_BEANS = new ArrayList<>();
        List<GridCompanyEconomyInfoPerMuBean> ONE_TO_THREE_BEANS = new ArrayList<>();
        List<GridCompanyEconomyInfoPerMuBean> OVER_THREE_BEANS = new ArrayList<>();
        BigDecimal oneNum = new BigDecimal("1.00");
        BigDecimal threeNum = new BigDecimal("3.00");
        for (GridCompanyEconomyInfoPerMuBean bean : beans) {
            if (bean.getAllPerMu().compareTo(oneNum) < 0) {
                ZERO_TO_ONE_BEANS.add(bean);
            } else if (bean.getAllPerMu().compareTo(threeNum) <= 0) {
                ONE_TO_THREE_BEANS.add(bean);
            } else {
                OVER_THREE_BEANS.add(bean);
            }
        }
        GridCompanyEconomyPermuItem ZERO_TO_ONE_BEAN = new GridCompanyEconomyPermuItem(GridCompanyEconomyPerMuResultEnum.ZERO_TO_ONE.getCode(), GridCompanyEconomyPerMuResultEnum.ZERO_TO_ONE.getValue(),ZERO_TO_ONE_BEANS.size());
        GridCompanyEconomyPermuItem ONE_TO_THREE_BEAN = new GridCompanyEconomyPermuItem(GridCompanyEconomyPerMuResultEnum.ONE_TO_THREE.getCode(), GridCompanyEconomyPerMuResultEnum.ONE_TO_THREE.getValue(), ONE_TO_THREE_BEANS.size());
        GridCompanyEconomyPermuItem OVER_THREE_BEAN = new GridCompanyEconomyPermuItem(GridCompanyEconomyPerMuResultEnum.OVER_THREE.getCode(), GridCompanyEconomyPerMuResultEnum.OVER_THREE.getValue(), OVER_THREE_BEANS.size());
        list.add(ZERO_TO_ONE_BEAN);
        list.add(ONE_TO_THREE_BEAN);
        list.add(OVER_THREE_BEAN);
        return list;
    }

    @Override
    public List<GridCompanyEconomyInfoSaleBean> saleCount(String year) {
        return gridCompanyEconomyInfoExtMapper.countSale(year);
    }

    @Override
    public List<GridCompanyEconomyInfoSaleBean> taxCount(String year) {
        return gridCompanyEconomyInfoExtMapper.countTax(year);
    }

    @Override
    public GridCompanyLandInfoBean loadCompanyLandInfo(String landId, String year) {
        GridRegion region = gridRegionService.selectByPrimaryKey(landId);
        if (region == null) {
            throw new RuntimeException("查询失败：未找到对应地块");
        }
        GridCompanyLandInfoBean infoBean = BeanCopyUtil.toBean(region, GridCompanyLandInfoBean.class);
        // 关联集团地块
        List<Runnable> runnables = new ArrayList<>();
        runnables.add(() -> {
            GridGroupLandExample wsGroupLandExample = new GridGroupLandExample();
            wsGroupLandExample.createCriteria().andLandIdEqualTo(landId);
            List<GridGroupLand> wsGroupLands = gridGroupLandService.selectByExample(wsGroupLandExample);
            if (!CollectionUtils.isEmpty(wsGroupLands)) {
                // 默认地块只能绑定在一个集团下
                GridGroupLand wsGroupLand = wsGroupLands.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 example = new GridRegionExample();
                        example.createCriteria().andIdIn(landIds).andIsValidEqualTo("1");
                        List<GridRegion> regionList = gridRegionService.selectByExample(example);
                        infoBean.setLinkLands(regionList);
                    }
                }
            }
        });

        // 地块下企业
        runnables.add(() -> {
            List<GridCompanyLandWithEcoExt> exts = new ArrayList<>();
            List<GridCompanyLandExt> wsCompanyLandExtList = gridCompanyLandExtMapper.getList(null, infoBean.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 = gridCompanyEconomyInfoMapper.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;
                            }
                        }
                    }
                }
            }
            infoBean.setCompanyLandExts(exts);
        });
        runnables.add(() -> {
            List<GridCompanyEconomyInfoPerMuBean> beans = gridCompanyEconomyInfoExtMapper.countPerMu(year, infoBean.getId());
            if (!CollectionUtils.isEmpty(beans)) {
                infoBean.setPerMu(beans.get(0).getAllPerMu());
            }
        });
        if (StringUtils.isNotBlank(infoBean.getWgPurpose())) {
            runnables.add(() -> {
                String purposeName = bsCommonService.getName(infoBean.getWgPurpose());
                infoBean.setWgPurposeName(purposeName);
            });
        }
        ZQTConcurrencyHelper.doMutli(runnables);
        if (!CollectionUtils.isEmpty(infoBean.getCompanyLandExts()) && infoBean.getPerMu() != null) {
            BigDecimal perMu = infoBean.getPerMu();
            BigDecimal companyNum = new BigDecimal(infoBean.getCompanyLandExts().size() + "");
            BigDecimal nPerMu = perMu.divide(companyNum, 2, BigDecimal.ROUND_HALF_UP);
            infoBean.setPerMu(nPerMu);
        }

        return infoBean;
    }

    @Override
    public List<GridCompanyEcoInfoBean>  loadCompanyEcoInfos(String type, String year, String searchName) {
        if (GridCompanyEcoInfoEnum.getByCode(type) == null || (!GridCompanyEcoInfoEnum.SHARE_AREA_TYPE.getCode().equals(type) && StringUtils.isBlank(year))) {
            throw new RuntimeException("查询失败：缺少必要参数");
        }
        if (!GridCompanyEcoInfoEnum.SHARE_AREA_TYPE.getCode().equals(type)) {
            return gridCompanyEconomyInfoExtMapper.selectCompanyEcoInfoList(type, year, searchName, null, null);
        } else {
            return gridCompanyEconomyInfoExtMapper.selectCompanyAreaInfoList(searchName, null, null);
        }
    }
}
