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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.DesensitizedUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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.common.zqt.ZQTPageUtil;
import com.ruoyi.common.zqt.ZQTPoiUtil;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.grid.ext.GridPeopleExt;
import com.ruoyi.system.domain.grid.vo.GridShopSearchParam;
import com.ruoyi.system.domain.grid.vo.GridStatistic;
import com.ruoyi.system.domain.grid.vo.SimpleGridShopItem;
import com.ruoyi.system.domain.other.BsCommon;
import com.ruoyi.system.domain.other.BsCommonExample;
import com.ruoyi.system.domain.publicservice.TOtherappAttachment;
import com.ruoyi.system.domain.publicservice.TOtherappAttachmentExample;
import com.ruoyi.system.domain.system.enums.AttachEnums;
import com.ruoyi.system.domain.visit.enums.VisitTypeEnum;
import com.ruoyi.system.domain.visit.ext.VisitFreeInterviewExt;
import com.ruoyi.system.listener.MyBaseService;
import com.ruoyi.system.mapper.grid.GridShopMapper;
import com.ruoyi.system.mapper.publicservice.TOtherappAttachmentMapper;
import com.ruoyi.system.service.BaseServiceImpl;
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.visit.VisitFreeInterviewService;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
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 org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Cesar
 * @date ${cTime}
 * @desc GridShopService实现
 */
@Service
@MyBaseService
public class GridShopServiceImpl extends BaseServiceImpl<GridShopMapper, GridShop, GridShopExample> implements GridShopService {

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

    @Autowired
    GridShopMapper gridShopMapper;

    @Autowired
    GridShopStaffService gridShopStaffService;

    @Autowired
    TOtherappAttachmentMapper tOtherappAttachmentService;

    @Autowired
    GridPeopleService gridPeopleService;

    @Autowired
    BsCommonService bsCommonService;

    @Autowired
    GridRegionService gridRegionService;

    @Autowired
    private GridWgLogService gridWgLogService;

    @Autowired
    private GridRegionUserService gridRegionUserService;

    @Autowired
    private VisitFreeInterviewService visitFreeInterviewService;

    @Autowired
    private ISysUserService sysUserService;

    private static String shopCode = "spjylx";

    @Override
    @Transactional
    public AjaxResult addGridShop(GridShop wsShop) {
        Validator.validateNotEmpty(wsShop.getShopName(), "商铺名称为空");

        GridShopExample shopExample = new GridShopExample();
        GridShopExample.Criteria criteria = shopExample.createCriteria();
        criteria.andShopTypeEqualTo(wsShop.getShopType());
        criteria.andShopNameEqualTo(wsShop.getShopName());
        criteria.andValidEqualTo(Byte.valueOf("1"));
        Long count = gridShopMapper.countByExample(shopExample);

        if (count > 0) {
            return AjaxResult.error(400, "该商铺名称及商铺类型已存在商铺库中");
        }

        gridShopMapper.insertSelective(wsShop);

        if (!CollectionUtils.isEmpty(wsShop.getOtherappAttachments())) {
            for (TOtherappAttachment attachment : wsShop.getOtherappAttachments()) {

                attachment.setAttachType(AttachEnums.AttachType.SHOP.name());
                attachment.setBusinessId(wsShop.getId().toString());
                tOtherappAttachmentService.insertSelective(attachment);
            }
        }

        // 日志
        GridWgLog wsWgLog = new GridWgLog();
        wsWgLog.setCreateId(wsShop.getCreateBy());
        SysUser sysUser = sysUserService.selectUserById(wsShop.getCreateBy());
        wsWgLog.setCreateName(sysUser != null ? sysUser.getNickName() : "");
        wsWgLog.setCreateWgCode(wsShop.getWgCode());
        wsWgLog.setObjectName(wsShop.getShopName());
        wsWgLog.setType("4");
        wsWgLog.setOperate("insert");
        wsWgLog.setObjectId(wsShop.getId().toString());
        gridWgLogService.add(wsWgLog);

        return AjaxResult.success(wsShop.getId());
    }

    @Override
    @Transactional
    public AjaxResult updateGridShop(GridShop wsShop) {
        Validator.validateNotEmpty(wsShop.getId(), "商铺Id为空");
        Validator.validateNotEmpty(wsShop.getShopName(), "商铺名称为空");
        Validator.validateNotEmpty(wsShop.getShopType(), "商铺类型为空");

        // 对比字段
        List<String> contentList = new ArrayList<>();
        GridShop origin = this.selectByPrimaryKey(wsShop.getId());

        if ((StringUtils.isNotBlank(origin.getShopName()) && !origin.getShopName().equals(wsShop.getShopName()))
                || (StringUtils.isBlank(origin.getShopName()) && StringUtils.isNotBlank(wsShop.getShopName()))) {
            contentList.add("商铺名称");
        }

        if ((StringUtils.isNotBlank(origin.getShopOwner()) && !origin.getShopOwner().equals(wsShop.getShopOwner()))
                || (StringUtils.isBlank(origin.getShopOwner()) && StringUtils.isNotBlank(wsShop.getShopOwner()))) {
            contentList.add("经营负责人");
        }

        if ((StringUtils.isNotBlank(origin.getShopPhone()) && !origin.getShopPhone().equals(wsShop.getShopPhone()))
                || (StringUtils.isBlank(origin.getShopPhone()) && StringUtils.isNotBlank(wsShop.getShopPhone()))) {
            contentList.add("联系方式");
        }

        if ((StringUtils.isNotBlank(origin.getShopAddress()) && !origin.getShopAddress().equals(wsShop.getShopAddress()))
                || (StringUtils.isBlank(origin.getShopAddress()) && StringUtils.isNotBlank(wsShop.getShopAddress()))) {
            contentList.add("位置");
        }

        if ((StringUtils.isNotBlank(origin.getShopType()) && !origin.getShopType().equals(wsShop.getShopType()))
                || (StringUtils.isBlank(origin.getShopType()) && StringUtils.isNotBlank(wsShop.getShopType()))) {
            contentList.add("类型");
        }

        if ((StringUtils.isNotBlank(origin.getBelongArea()) && !origin.getBelongArea().equals(wsShop.getBelongArea()))
                || (StringUtils.isBlank(origin.getBelongArea()) && StringUtils.isNotBlank(wsShop.getBelongArea()))) {
            contentList.add("所属地块");
        } else if ((StringUtils.isNotBlank(origin.getWgCode()) && !origin.getWgCode().equals(wsShop.getWgCode()))
                || (StringUtils.isBlank(origin.getWgCode()) && StringUtils.isNotBlank(wsShop.getWgCode()))) {
            contentList.add("所属地块code");
        }

        if ((StringUtils.isNotBlank(origin.getLongitude()) && !origin.getLongitude().equals(wsShop.getLongitude()))
                || (StringUtils.isBlank(origin.getLongitude()) && StringUtils.isNotBlank(wsShop.getLongitude()))) {
            contentList.add("定位地址经度");
        } else if ((StringUtils.isNotBlank(origin.getLatitude()) && !origin.getLatitude().equals(wsShop.getLatitude()))
                || (StringUtils.isBlank(origin.getLatitude()) && StringUtils.isNotBlank(wsShop.getLatitude()))) {
            contentList.add("定位地址纬度");
        }

        if ((StringUtils.isNotBlank(origin.getLicenseCode()) && !origin.getLicenseCode().equals(wsShop.getLicenseCode()))
                || (StringUtils.isBlank(origin.getLicenseCode()) && StringUtils.isNotBlank(wsShop.getLicenseCode()))) {
            contentList.add("营业执照编码");
        }

        int result = gridShopMapper.updateByPrimaryKeySelective(wsShop);

        TOtherappAttachmentExample attachmentExample = new TOtherappAttachmentExample();
        TOtherappAttachmentExample.Criteria criteria = attachmentExample.createCriteria();
        criteria.andAttachTypeEqualTo(AttachEnums.AttachType.SHOP.name());
        criteria.andBusinessIdEqualTo(wsShop.getId().toString());
        tOtherappAttachmentService.deleteByExample(attachmentExample);
        if (!CollectionUtils.isEmpty(wsShop.getOtherappAttachments())) {
            for (TOtherappAttachment attachment : wsShop.getOtherappAttachments()) {
                attachment.setAttachType(AttachEnums.AttachType.SHOP.name());
                attachment.setBusinessId(wsShop.getId().toString());
                tOtherappAttachmentService.insertSelective(attachment);
            }
        }

        //更新走访
        if(!CollectionUtils.isEmpty(contentList)){
            SysUser sysUser = sysUserService.selectUserById(wsShop.getUpdateBy());
            VisitFreeInterviewExt visitFreeInterviewExt = new VisitFreeInterviewExt();
            visitFreeInterviewExt.setWgCode(wsShop.getWgCode());
            visitFreeInterviewExt.setWgValue(gridRegionService.getWgName(wsShop.getWgCode()));
            GridRegionUser gridRegionUser = gridRegionUserService.selectByUserId(sysUser.getUserId());
            visitFreeInterviewExt.setWgyCode(gridRegionUser == null?"":gridRegionUser.getWgId());
            visitFreeInterviewExt.setWgyName(sysUser != null ? sysUser.getNickName() : "");
            visitFreeInterviewExt.setInterviewTime(DateUtil.formatDateTime(new Date()));
            visitFreeInterviewExt.setType("2");
            visitFreeInterviewExt.setContent("完成商铺基本信息更新,更新字段："+StringUtils.join(contentList, ","));
            visitFreeInterviewExt.setObjId(wsShop.getId().toString());
            visitFreeInterviewExt.setAddress(wsShop.getShopAddress());
            visitFreeInterviewExt.setInterviewTime(DateUtil.formatDate(new Date()));
            visitFreeInterviewExt.setActualTime(DateUtil.formatDateTime(new Date()));
            visitFreeInterviewExt.setObjName(wsShop.getShopName());
            visitFreeInterviewExt.setObjType(wsShop.getShopType());
            String objectName = bsCommonService.getName(wsShop.getShopType());
            visitFreeInterviewExt.setObjTypeName(objectName);
            visitFreeInterviewExt.setObjUserName(wsShop.getShopOwner());
            visitFreeInterviewExt.setLatitude(wsShop.getLatitude());
            visitFreeInterviewExt.setLongitude(wsShop.getLongitude());
            visitFreeInterviewExt.setObjNumber(wsShop.getLicenseCode());
            visitFreeInterviewExt.setVisitType(VisitTypeEnum.UPDATE_VISIT.getCode());
            visitFreeInterviewService.addVisitFreeInterview(visitFreeInterviewExt);

            // 日志
            GridWgLog wsWgLog = new GridWgLog();
            wsWgLog.setCreateId(wsShop.getUpdateBy());
            wsWgLog.setCreateName(sysUser != null ? sysUser.getNickName() : "");
            wsWgLog.setCreateWgCode(wsShop.getWgCode());
            wsWgLog.setObjectName(wsShop.getShopName());
            wsWgLog.setType("4");
            wsWgLog.setOperate("update");
            wsWgLog.setContent(StringUtils.join(contentList, ","));
            wsWgLog.setObjectId(wsShop.getId().toString());
            gridWgLogService.add(wsWgLog);
        }

        return AjaxResult.success(result);
    }

    @Override
    public GridShop getGridShopById(Long id) {

        Validator.validateNotEmpty(id, "商铺Id为空");

        GridShop wsShop = gridShopMapper.selectByPrimaryKey(id);

        Validator.validateNotEmpty(wsShop, "商铺不存在");

        wsShop.setShopTypeName(StringUtils.isEmpty(wsShop.getShopType()) ? "" : bsCommonService.getName(wsShop.getShopType()));
        wsShop.setBelongArea(StringUtils.isEmpty(wsShop.getWgCode()) ? "" : gridRegionService.getWgName(wsShop.getWgCode()));

        TOtherappAttachmentExample attachmentExample = new TOtherappAttachmentExample();
        TOtherappAttachmentExample.Criteria criteriaShop = attachmentExample.createCriteria();
        criteriaShop.andBusinessIdEqualTo(id.toString());
        criteriaShop.andAttachTypeEqualTo(AttachEnums.AttachType.SHOP.name());
        criteriaShop.andValidEqualTo(Byte.valueOf("1"));
        List<TOtherappAttachment> otherappAttachments = tOtherappAttachmentService.selectByExample(attachmentExample);
        wsShop.setOtherappAttachments(CollectionUtils.isEmpty(otherappAttachments)?null:otherappAttachments);

        if (!StringUtils.isEmpty(wsShop.getWgCode())) {
            GridRegion wg = gridRegionService.getWgOtherCode(wsShop.getWgCode());
            if (wg != null) {
                wsShop.setWgOtherCode(wg.getWgCode());
                wsShop.setWgOtherCodeValue(wg.getWgName());
            }
        }
        return wsShop;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult batchRemove(Long[] ids) {
        int count = 0;

        if (null == ids || ids.length <= 0) {
            return AjaxResult.error(400, "商铺id未传");
        }

        for (Long id : ids) {
            GridShopStaffExample shopStaffExample = new GridShopStaffExample();
            GridShopStaffExample.Criteria criteria = shopStaffExample.createCriteria();
            criteria.andShopIdEqualTo(id);
            int staffCount = gridShopStaffService.countByExample(shopStaffExample);

            if (staffCount > 0) {
                return AjaxResult.error(400, "商铺已存在员工信息绑定关系，不可删除，如需删除此商铺，请先解绑对应关系");
            }

            TOtherappAttachmentExample attachmentExample = new TOtherappAttachmentExample();
            TOtherappAttachmentExample.Criteria criteriaShop = attachmentExample.createCriteria();
            criteriaShop.andBusinessIdEqualTo(id.toString());
            criteriaShop.andAttachTypeEqualTo(AttachEnums.AttachType.SHOP.name());
            long attatchCount = tOtherappAttachmentService.countByExample(attachmentExample);

            if (attatchCount > 0) {
                return AjaxResult.error(400, "商铺已存在证照信息绑定关系，不可删除，如需删除此商铺，请先解绑对应关系");
            }

            GridShop wsShop = this.selectByPrimaryKey(id);
            wsShop.setValid(Byte.valueOf("0"));
            this.updateByPrimaryKeySelective(wsShop);
        }
        return AjaxResult.success(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addWsStaff(List<GridShopStaff> wsShopStaffs) {
        int result = 0;
        GridShopStaffExample shopStaffExample = new GridShopStaffExample();
        GridShopStaffExample.Criteria criteria = shopStaffExample.createCriteria();

        for (GridShopStaff shopStaff : wsShopStaffs) {
            Validator.validateNotEmpty(shopStaff.getPeopleId(), "商铺绑定人员id未传");
            Validator.validateNotEmpty(shopStaff.getShopId(), "商铺id未传");

            criteria.andPeopleIdEqualTo(shopStaff.getPeopleId());
            criteria.andShopIdEqualTo(shopStaff.getShopId());
            int count = gridShopStaffService.countByExample(shopStaffExample);

            if (count > 0) {
                return AjaxResult.error(400, "该人员已绑定该商铺");
            }

            result = gridShopStaffService.insertSelective(shopStaff);

            // 日志
            SysUser sysUser = sysUserService.selectUserById(shopStaff.getCreateBy());
            GridShop gridShop = this.selectByPrimaryKey(shopStaff.getShopId());
            GridWgLog wsWgLog = new GridWgLog();
            wsWgLog.setCreateId(shopStaff.getCreateBy());
            wsWgLog.setCreateName(sysUser != null ? sysUser.getNickName() : "");
            wsWgLog.setCreateWgCode(gridShop.getWgCode());
            wsWgLog.setObjectName(gridShop.getShopName());
            wsWgLog.setBindName(gridPeopleService.selectByPrimaryKey(shopStaff.getPeopleId()).getPersonName());
            wsWgLog.setType("4");
            wsWgLog.setOperate("bind");
            wsWgLog.setObjectId(shopStaff.getStaffId().toString());
            gridWgLogService.add(wsWgLog);
        }

        return AjaxResult.success(result);
    }

    @Override
    public int deleteShopStaff(Long[] ids) {
        GridShopStaffExample shopStaffExample = new GridShopStaffExample();
        GridShopStaffExample.Criteria criteria = shopStaffExample.createCriteria();
        criteria.andStaffIdIn(Arrays.asList(ids));
        return gridShopStaffService.deleteByExample(shopStaffExample);
    }

    @Override
    public AjaxResult ListGridPeople(int pageNum, int pageSize, 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);

        if (CollectionUtils.isEmpty(wsShopStaffs)) {
            return AjaxResult.success(new PageInfo<>());
        }

        Map<String, Long> staffIdMap = wsShopStaffs.stream().collect(Collectors.toMap(GridShopStaff::getPeopleId, GridShopStaff::getStaffId));

        List<String> peopleIds = wsShopStaffs.stream().map(o -> o.getPeopleId()).collect(Collectors.toList());

        GridPeopleExample wsPeopleExample = new GridPeopleExample();
        GridPeopleExample.Criteria criteriaPeople = wsPeopleExample.createCriteria();
        criteriaPeople.andIdIn(peopleIds);
        criteriaPeople.andIsValidEqualTo(Byte.valueOf("1"));

        wsPeopleExample.setOrderByClause(" create_time desc, person_name ");
        List<GridPeople> wsPeoples = gridPeopleService.selectByExample(wsPeopleExample);

        List<GridPeopleExt> peopleExtList = BeanCopyUtil.bathToBean(wsPeoples, GridPeopleExt.class);

        if (!CollectionUtils.isEmpty(peopleExtList)) {
            Map<String, String> regionMap = gridRegionService.getGridRegionMap().stream().collect(Collectors.toMap(GridRegion::getWgCode, GridRegion::getWgName));
            Map<String, String> commonMap = bsCommonService.getBsCommonMap().stream().collect(Collectors.toMap(BsCommon::getCode, BsCommon::getName));

            for (GridPeopleExt wsPeopleExt : peopleExtList) {
                gridPeopleService.dealPeopleExt(regionMap, commonMap, wsPeopleExt);
                if (staffIdMap.containsKey(wsPeopleExt.getId())) {
                    wsPeopleExt.setStaffId(staffIdMap.get(wsPeopleExt.getId()));
                }
                wsPeopleExt.setIdCard(DesensitizedUtil.idCardNum(wsPeopleExt.getIdCard(), 6, 4));
                wsPeopleExt.setPhone(DesensitizedUtil.mobilePhone(wsPeopleExt.getPhone()));
            }
        }

        PageInfo<GridPeopleExt> pageInfo = new PageInfo<>(ZQTPageUtil.buildPage(peopleExtList, pageNum, pageSize));
        return AjaxResult.success(pageInfo);
    }

    @Override
    public AjaxResult ListGridShop(GridShop wsShop) {
        PageHelper.startPage(wsShop.getPageNum(), wsShop.getPageSize());
        GridShopSearchParam param = new GridShopSearchParam();
        if(StringUtils.isNotBlank(wsShop.getWgCode())){
            param.setWgCodeLikes(Arrays.asList(wsShop.getWgCode().split(",")));
        }
        param.setShopType(wsShop.getShopType());
        param.setShopName(wsShop.getShopName());
        param.setBelongArea(wsShop.getBelongArea());
        List<GridShop> wsShopList = gridShopMapper.listByParam(param);

        if(!CollectionUtils.isEmpty(wsShopList)){
            //获取所有商铺经营类型
            BsCommonExample typeEx = new BsCommonExample();
            BsCommonExample.Criteria typeCa = typeEx.createCriteria();
            typeCa.andCodeLike(shopCode + "%");
            typeCa.andIsValidEqualTo("1");
            List<BsCommon> bsCommons = bsCommonService.selectByExample(typeEx);
            Map<String, String> typeMap = bsCommons.stream().collect(Collectors.toMap(BsCommon::getCode, BsCommon::getName));
            Map<String, String> regionMap =gridRegionService.getMapByWgCodes(wsShopList.stream().map(GridShop::getWgCode).collect(Collectors.toList()));
            for (GridShop wsShopTemp : wsShopList) {
                wsShopTemp.setShopTypeName(typeMap.get(wsShopTemp.getShopType()));
                wsShopTemp.setBelongArea(regionMap.get(wsShopTemp.getWgCode()));
                GridRegion wg = gridRegionService.getWgOtherCode(wsShopTemp.getWgCode());
                if (wg != null) {
                    wsShopTemp.setWgOtherCode(wg.getWgCode());
                    wsShopTemp.setWgOtherCodeValue(wg.getWgName());
                }
            }
        }
        PageInfo<GridShop> pageInfo = new PageInfo<>(wsShopList);
        return AjaxResult.success(pageInfo);
    }

    @Override
    @Transactional
    public AjaxResult dealImportExcel(MultipartFile file, String createBy) {
        List<GridShop> list = new ArrayList<>();

        //根据file的文件名后缀获取对应的Workbook工作簿对象
        Workbook wb = null;
        try {
            wb = ZQTPoiUtil.createWorkbook(file);
        } catch (IOException e) {
            throw new RuntimeException("解析excel失败");
        }

        GridRegionExample regionExample = new GridRegionExample();
        GridRegionExample.Criteria criteria = regionExample.createCriteria();
        criteria.andIsValidEqualTo("1");
        List<GridRegion> regionList = gridRegionService.selectByExample(regionExample);

        Map<String, String> regionMap = regionList.stream()
                .collect(Collectors.toMap(GridRegion::getWgName, GridRegion::getWgCode, (v1, v2) -> v1));

        BsCommonExample typeEx = new BsCommonExample();
        BsCommonExample.Criteria typeCa = typeEx.createCriteria();
        typeCa.andCodeLike(shopCode + "%");
        typeCa.andIsValidEqualTo("1");
        List<BsCommon> bsCommons = bsCommonService.selectByExample(typeEx);

        Map<String, String> typeMap = bsCommons.stream().collect(Collectors.toMap(BsCommon::getName, BsCommon::getCode));

        StringBuilder sb = new StringBuilder();
        //获取Excel文档中的第一个表单
        Sheet sht0 = wb.getSheetAt(0);

        int rowNum = 0;
        //对Sheet中的每一行进行迭代
        for (int i = 0; i <= sht0.getLastRowNum(); i++) {
            Row r = sht0.getRow(i);
            if (r.getRowNum() < 1) {
                continue;
            }

            if (r.getCell(1) != null) {
                GridShop wsShop = new GridShop();

                wsShop.setShopName(ZQTPoiUtil.getCellValue(r.getCell(0)));
                wsShop.setShopTypeName(ZQTPoiUtil.getCellValue(r.getCell(1)));
                wsShop.setLicenseCode(ZQTPoiUtil.getCellValue(r.getCell(2)));
                wsShop.setBelongArea(ZQTPoiUtil.getCellValue(r.getCell(3)));
                wsShop.setShopOwner(ZQTPoiUtil.getCellValue(r.getCell(4)));
                wsShop.setShopPhone(ZQTPoiUtil.getCellValue(r.getCell(5)));
                wsShop.setShopAddress(ZQTPoiUtil.getCellValue(r.getCell(6)));
                wsShop.setCreateBy(createBy);

                rowNum = r.getRowNum() + 1;
                if (StringUtils.isEmpty(wsShop.getShopName())) {
                    sb.append("第" + rowNum + "行商铺名称不能为空;" + "\n");
                }

                if (StringUtils.isEmpty(wsShop.getShopTypeName())) {
                    sb.append("第" + rowNum + "行商铺类型不能为空;" + "\n");
                }

                if (StringUtils.isEmpty(wsShop.getBelongArea())) {
                    sb.append("第" + rowNum + "行所属地块不能为空;" + "\n");
                }

                if (!regionMap.containsKey(wsShop.getBelongArea())) {
                    sb.append("第" + rowNum + "行未找到对应网格;" + "\n");
                } else {
                    wsShop.setWgCode(regionMap.get(wsShop.getBelongArea()));
                }

                if (!typeMap.containsKey(wsShop.getShopTypeName())) {
                    sb.append("第" + rowNum + "行未找到对应商铺类型;" + "\n");
                } else {
                    wsShop.setShopType(typeMap.get(wsShop.getShopTypeName()));
                }

                list.add(wsShop);
            }
        }

        if (!StringUtils.isEmpty(sb.toString())) {
            return AjaxResult.error(400, sb.toString());
        }

        for (GridShop wsShop : list) {
            gridShopMapper.insertSelective(wsShop);
        }

        return AjaxResult.success("导入成功");
    }

    @Override
    public List<Map<String, Object>> countGridShop(String wgCode) {
        List<String> wgCodes = new ArrayList<>();
        if(StringUtils.isNotBlank(wgCode)){
            wgCodes = Arrays.asList(wgCode.split(","));
        }
        return gridShopMapper.countGridShop(wgCodes);
    }

    @Override
    public List<GridStatistic> countGridShopFive(String wgCode) {
        List<Map<String, Object>> list = gridShopMapper.countGridShop(Arrays.asList(wgCode));

        List<GridStatistic> result = new ArrayList<>();

        Integer total = 0;

        for (Map<String, Object> mapTemp : list) {
            total = total + Integer.parseInt(mapTemp.get("number").toString());
            result.add(new GridStatistic(mapTemp.get("name") + "", mapTemp.get("number") + ""));
        }

        result = result.stream().sorted(Comparator.comparing(GridStatistic::getNum, Comparator.reverseOrder())).collect(Collectors.toList());

        List<GridStatistic> temp = new ArrayList<>();
        if (!CollectionUtils.isEmpty(result) && result.size() >= 5) {
            temp = result.subList(0, 4);

            int otherNum = 0;
            for (GridStatistic wsStatistic : result.subList(4, result.size())) {
                otherNum = otherNum + Integer.parseInt(wsStatistic.getNum());
            }
            GridStatistic other = new GridStatistic();
            other.setName("其它");
            other.setNum(otherNum + "");
            temp.add(other);
        }
        temp.add(new GridStatistic("总计", total.toString()));
        return temp;
    }

    @Override
    public int countAll(String wgCode) {
        GridShopSearchParam param = new GridShopSearchParam();
        if(StringUtils.isNotBlank(wgCode)){
            param.setWgCodeLikes(Arrays.asList(wgCode.split(",")));
        }
        return gridShopMapper.countByParam(param);
    }

    @Override
    public List<Map<String, Object>> countGridShopByGrid() {
        return gridShopMapper.countGridShopByGrid();
    }

    @Override
    public HashMap<String, BigDecimal> GridShopTypeStatistic(String wgCode) {

//        HashMap<String, BigDecimal> result = new HashMap<>();
//
//        List<Map<String, Object>> list = gridShopMapper.countGridShop(Lists.newArrayList(wgCode));
//
//        BigDecimal allCount = new BigDecimal(this.countAll(wgCode));
//
//        if (allCount.compareTo(new BigDecimal(0)) <= 0) {
//            return result;
//        }
//
//        Iterator<Map<String, Object>> iterator = list.iterator();
//        while (iterator.hasNext()) {
//            Map<String, Object> map = iterator.next();
//
//            BigDecimal percent = new BigDecimal("" + map.get("number")).divide(allCount, 3, BigDecimal.ROUND_HALF_UP);
//            result.put(map.get("name") + "", percent);
//        }
//
//        return result;
        return null;
    }

    @Override
    public List<GridStatistic> countGridShopGrid(String wgCode) {

        List<GridStatistic> wsStatistics = new ArrayList<>();

        List<Map<String, Object>> gridMap = gridShopMapper.countGridShopByGrid();

        Iterator<Map<String, Object>> iterator = gridMap.iterator();
        while (iterator.hasNext()) {
            Map<String, Object> map = iterator.next();

            GridStatistic wsStatistic = new GridStatistic();
            wsStatistic.setNum(map.get("number") + "");
            wsStatistic.setName(map.get("name") + "");
            wsStatistics.add(wsStatistic);
        }
        return wsStatistics;
    }

    @Override
    public List<GridShop> getAllShopList(GridShopSearchParam param) {
        return gridShopMapper.listByParam(param);
    }

    @Override
    public List<SimpleGridShopItem> getAllShopPointList(String wgCode, String name) {
        return gridShopMapper.listShopPoint(wgCode, name);
    }
}
