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 cn.hutool.core.util.IdcardUtil;
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.ZQTImportExcelUtil;
import com.ruoyi.common.zqt.ZQTPageUtil;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.grid.ext.GridCompanyPeopleExt;
import com.ruoyi.system.domain.grid.ext.GridHousePeopleExt;
import com.ruoyi.system.domain.grid.ext.GridPeopleExt;
import com.ruoyi.system.domain.grid.vo.GridPeopleSearchParam;
import com.ruoyi.system.domain.grid.vo.PeopleBindParam;
import com.ruoyi.system.domain.other.BsCommon;
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.GridPeopleMapper;
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.collections4.CollectionUtils;
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.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author Cesar
 * @date ${cTime}
 * @desc GridPeopleService实现
 */
@Service
@MyBaseService
public class GridPeopleServiceImpl extends BaseServiceImpl<GridPeopleMapper, GridPeople, GridPeopleExample> implements GridPeopleService {

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

    @Autowired
    GridPeopleMapper gridPeopleMapper;
    @Autowired
    private GridHouseService gridHouseService;
    @Autowired
    private GridHousePeopleService gridHousePeopleService;
    @Autowired
    private GridCompanyService gridCompanyService;
    @Autowired
    private GridCompanyPeopleService gridCompanyPeopleService;
    @Autowired
    private GridShopService gridShopService;
    @Autowired
    private GridShopStaffService gridShopStaffService;
    @Autowired
    private BsCommonService bsCommonService;
    @Autowired
    private GridRegionService gridRegionService;
    @Autowired
    private GridPendingPeopleService gridPendingPeopleService;
    @Autowired
    private GridWgLogService gridWgLogService;
    @Autowired
    private GridRegionUserService gridRegionUserService;
    @Autowired
    private VisitFreeInterviewService visitFreeInterviewService;
    @Autowired
    private ISysUserService sysUserService;

    @Override
    public PageInfo page(GridPeople wsPeople, String value) {
        GridPeopleSearchParam param = new GridPeopleSearchParam();
        param.setValue(value);
        if(StringUtils.isNotBlank(wsPeople.getWgCode())){
            param.setWgCodeLikes(Arrays.asList(wsPeople.getWgCode()));
        }
        param.setRklxCode(wsPeople.getRklxCode());
        param.setRkbqCode(wsPeople.getRkbqCode());
        param.setSex(wsPeople.getSex());
        List<GridPeople> peopleList = gridPeopleMapper.listByParam(param);
        List<GridPeopleExt> peopleExtList = BeanCopyUtil.bathToBean(peopleList, GridPeopleExt.class);
        PageInfo<GridPeopleExt> pageInfo = ZQTPageUtil.build(peopleList, peopleExtList);
        if(CollectionUtils.isNotEmpty(pageInfo.getList())){
            Map<String, String> regionMap = gridRegionService.getMapByWgCodes(pageInfo.getList().stream().map(GridPeopleExt::getWgCode).collect(Collectors.toList()));
            Map<String, String> commonMap = bsCommonService.getBsCommonMap().stream().collect(Collectors.toMap(BsCommon::getCode, BsCommon::getName));
            for (GridPeopleExt p : pageInfo.getList()) {
                this.dealPeopleExt(regionMap, commonMap, p);
            }
        }
        return pageInfo;
    }

    @Override
    @Transactional
    public AjaxResult add(GridPeople wsPeople) {
        Validator.validateNotEmpty(wsPeople.getIdCard(), "身份证号不能为空");
        String ID_18 = wsPeople.getIdCard();
        boolean valid = IdcardUtil.isValidCard(ID_18);
        if (!valid) {
            return AjaxResult.error(400, "该人员身份证信息不合法");
        }
        if (this.countByIdCardOrPhone(wsPeople.getIdCard(), null, null) > 0) {
            return AjaxResult.error(400, "该人员身份证信息已在人口信息库中");
        }
        if (StringUtils.isNotBlank(wsPeople.getPhone())) {
            if (!Pattern.matches("^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$", wsPeople.getPhone())) {
                return AjaxResult.error(400, "该人员手机号码不合法");
            }
            if (this.countByIdCardOrPhone(null, wsPeople.getPhone(), null) > 0) {
                return AjaxResult.error(400, "该人员手机号码已在人口信息库中");
            }
        }
//        if (StringUtils.isNotBlank(wsPeople.getBirthday())) {
//
//        } else {
//            wsPeople.setBirthday(IdcardUtil.getYearByIdCard(ID_18) + "-" + IdcardUtil.getMonthByIdCard(ID_18) + "-" + IdcardUtil.getDayByIdCard(ID_18));
//        }
        if (StringUtils.isBlank(wsPeople.getSex())) {
            wsPeople.setSex(IdcardUtil.getGenderByIdCard(ID_18) == 1 ? "男" : "女");
        }
        wsPeople.setId(IdUtil.fastSimpleUUID());
        wsPeople.setCreateTime(DateUtil.formatDateTime(new Date()));
        this.insertSelective(wsPeople);

        // 日志
        GridWgLog wsWgLog = new GridWgLog();
        wsWgLog.setCreateId(wsPeople.getCreateId());
        SysUser sysUser = sysUserService.selectUserById(wsPeople.getCreateId());
        wsWgLog.setCreateName(sysUser != null ? sysUser.getNickName() : "");
        wsWgLog.setCreateWgCode(wsPeople.getWgCode());
        wsWgLog.setObjectName(wsPeople.getPersonName());
        wsWgLog.setType("1");
        wsWgLog.setOperate("insert");
        wsWgLog.setObjectId(wsPeople.getId());
        gridWgLogService.add(wsWgLog);
        return AjaxResult.success("success", wsPeople.getId());
    }

    @Override
    @Transactional
    public AjaxResult edit(GridPeople wsPeople) {
        Validator.validateNotEmpty(wsPeople.getId(), "id is empty");
        Validator.validateNotEmpty(wsPeople.getIdCard(), "身份证号不能为空");
        String ID_18 = wsPeople.getIdCard();
        boolean valid = IdcardUtil.isValidCard(ID_18);
        if (!valid) {
            return AjaxResult.error(400, "该人员身份证信息不合法");
        }
        if (this.countByIdCardOrPhone(wsPeople.getIdCard(), null, wsPeople.getId()) > 0) {
            return AjaxResult.error(400, "该人员身份证信息已在人口信息库中");
        }
        if (StringUtils.isNotBlank(wsPeople.getPhone())) {
            if (!Pattern.matches("^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$", wsPeople.getPhone())) {
                return AjaxResult.error(400, "该人员手机号码不合法");
            }
            if (this.countByIdCardOrPhone(null, wsPeople.getPhone(), wsPeople.getId()) > 0) {
                return AjaxResult.error(400, "该人员手机号码已在人口信息库中");
            }
        }
        wsPeople.setUpdateTime(DateUtil.formatDateTime(new Date()));


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

        if ((StringUtils.isNotBlank(origin.getAvatar()) && !origin.getAvatar().equals(wsPeople.getAvatar()))
                || (StringUtils.isBlank(origin.getAvatar()) && StringUtils.isNotBlank(wsPeople.getAvatar()))) {
            contentList.add("头像");
        }

        if ((StringUtils.isNotBlank(origin.getPersonName()) && !origin.getPersonName().equals(wsPeople.getPersonName()))
                || (StringUtils.isBlank(origin.getPersonName()) && StringUtils.isNotBlank(wsPeople.getPersonName()))) {
            contentList.add("姓名");
        }

        if ((StringUtils.isNotBlank(origin.getIdCard()) && !origin.getIdCard().equals(wsPeople.getIdCard()))
                || (StringUtils.isBlank(origin.getIdCard()) && StringUtils.isNotBlank(wsPeople.getIdCard()))) {
            contentList.add("身份证号码");
        }

        if ((StringUtils.isNotBlank(origin.getSex()) && !origin.getSex().equals(wsPeople.getSex()))
                || (StringUtils.isBlank(origin.getSex()) && StringUtils.isNotBlank(wsPeople.getSex()))) {
            contentList.add("性别");
        }

        if ((StringUtils.isNotBlank(origin.getNativePlace()) && !origin.getNativePlace().equals(wsPeople.getNativePlace()))
                || (StringUtils.isBlank(origin.getNativePlace()) && StringUtils.isNotBlank(wsPeople.getNativePlace()))) {
            contentList.add("籍贯");
        }

        if ((StringUtils.isNotBlank(origin.getBirthday()) && !origin.getBirthday().equals(wsPeople.getBirthday()))
                || (StringUtils.isBlank(origin.getBirthday()) && StringUtils.isNotBlank(wsPeople.getBirthday()))) {
            contentList.add("出生日期");
        }

        if ((StringUtils.isNotBlank(origin.getRegisteredAddress()) && !origin.getRegisteredAddress().equals(wsPeople.getRegisteredAddress()))
                || (StringUtils.isBlank(origin.getRegisteredAddress()) && StringUtils.isNotBlank(wsPeople.getRegisteredAddress()))) {
            contentList.add("户籍地址");
        }

        if ((StringUtils.isNotBlank(origin.getMzCode()) && !origin.getMzCode().equals(wsPeople.getMzCode()))
                || (StringUtils.isBlank(origin.getMzCode()) && StringUtils.isNotBlank(wsPeople.getMzCode()))) {
            contentList.add("民族");
        }

        if ((StringUtils.isNotBlank(origin.getHyzkCode()) && !origin.getHyzkCode().equals(wsPeople.getHyzkCode()))
                || (StringUtils.isBlank(origin.getHyzkCode()) && StringUtils.isNotBlank(wsPeople.getHyzkCode()))) {
            contentList.add("婚姻状况");
        }

        if ((StringUtils.isNotBlank(origin.getWhcdCode()) && !origin.getWhcdCode().equals(wsPeople.getWhcdCode()))
                || (StringUtils.isBlank(origin.getWhcdCode()) && StringUtils.isNotBlank(wsPeople.getWhcdCode()))) {
            contentList.add("文化程度");
        }

        if ((StringUtils.isNotBlank(origin.getZzmmCode()) && !origin.getZzmmCode().equals(wsPeople.getZzmmCode()))
                || (StringUtils.isBlank(origin.getZzmmCode()) && StringUtils.isNotBlank(wsPeople.getZzmmCode()))) {
            contentList.add("政治面貌");
        }

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

        if ((StringUtils.isNotBlank(origin.getPhone()) && !origin.getPhone().equals(wsPeople.getPhone()))
                || (StringUtils.isBlank(origin.getPhone()) && StringUtils.isNotBlank(wsPeople.getPhone()))) {
            contentList.add("手机号码");
        }

        if ((StringUtils.isNotBlank(origin.getAddress()) && !origin.getAddress().equals(wsPeople.getAddress()))
                || (StringUtils.isBlank(origin.getAddress()) && StringUtils.isNotBlank(wsPeople.getAddress()))) {
            contentList.add("实际居住地址");
        }

        if ((StringUtils.isNotBlank(origin.getRklxCode()) && !origin.getRklxCode().equals(wsPeople.getRklxCode()))
                || (StringUtils.isBlank(origin.getRklxCode()) && StringUtils.isNotBlank(wsPeople.getRklxCode()))) {
            contentList.add("人口类型");
        }

        if ((StringUtils.isNotBlank(origin.getRkbqCode()) && !origin.getRkbqCode().equals(wsPeople.getRkbqCode()))
                || (StringUtils.isBlank(origin.getRkbqCode()) && StringUtils.isNotBlank(wsPeople.getRkbqCode()))) {
            contentList.add("人口标签");
        }

        this.updateByPrimaryKeySelective(wsPeople);

        //基本信息修改算一次更新走访
        if(CollectionUtils.isNotEmpty(contentList)){
            SysUser sysUser = sysUserService.selectUserById(wsPeople.getUpdateId());
            VisitFreeInterviewExt visitFreeInterviewExt = new VisitFreeInterviewExt();
            visitFreeInterviewExt.setWgCode(wsPeople.getWgCode());
            visitFreeInterviewExt.setWgValue(gridRegionService.getWgName(wsPeople.getWgCode()));
            GridRegionUser gridRegionUser = gridRegionUserService.selectByUserId(sysUser.getUserId());
            visitFreeInterviewExt.setWgyCode(gridRegionUser == null?"":gridRegionUser.getWgId());
            visitFreeInterviewExt.setWgyName(sysUser.getNickName());
            visitFreeInterviewExt.setInterviewTime(DateUtil.formatDateTime(new Date()));
            visitFreeInterviewExt.setType("4");
            visitFreeInterviewExt.setContent("完成人员基本信息更新，更新字段：" + StringUtils.join(contentList, ","));
            visitFreeInterviewExt.setObjId(wsPeople.getId());
            visitFreeInterviewExt.setAddress(wsPeople.getAddress());
            visitFreeInterviewExt.setInterviewTime(DateUtil.formatDate(new Date()));
            visitFreeInterviewExt.setActualTime(DateUtil.formatDateTime(new Date()));
            visitFreeInterviewExt.setObjName(wsPeople.getPersonName());
            visitFreeInterviewExt.setObjType(wsPeople.getRklxCode());
            String objectName = bsCommonService.getName(wsPeople.getRklxCode());
            visitFreeInterviewExt.setObjTypeName(objectName);
            visitFreeInterviewExt.setObjUserName(wsPeople.getPersonName());
            visitFreeInterviewExt.setVisitType(VisitTypeEnum.UPDATE_VISIT.getCode());
            visitFreeInterviewService.addVisitFreeInterview(visitFreeInterviewExt);

            // 日志
            GridWgLog wsWgLog = new GridWgLog();
            wsWgLog.setCreateId(wsPeople.getUpdateId());
            wsWgLog.setCreateName(sysUser != null ? sysUser.getNickName() : "");
            wsWgLog.setCreateWgCode(wsPeople.getWgCode());
            wsWgLog.setObjectName(wsPeople.getPersonName());
            wsWgLog.setType("1");
            wsWgLog.setOperate("update");
            wsWgLog.setContent(StringUtils.join(contentList, ","));
            wsWgLog.setObjectId(wsPeople.getId());
            gridWgLogService.add(wsWgLog);

        }

        return AjaxResult.success(null);
    }

    @Override
    public AjaxResult detail(String id) {
        GridPeople wsPeople = this.selectByPrimaryKey(id);
        GridPeopleExt wsPeopleExt = BeanCopyUtil.toBean(wsPeople, GridPeopleExt.class);
        if (wsPeopleExt != null) {
            if (Byte.valueOf("1").equals(wsPeopleExt.getIsValid())) {
                this.selectGridPeopleExt(wsPeopleExt);
            } else {
                return AjaxResult.success(null);
            }
        }
        return AjaxResult.success(wsPeopleExt);
    }

    @Override
    public AjaxResult delete(String id) {
        // 是否存在关联住宅
        GridHousePeopleExample ex = new GridHousePeopleExample();
        GridHousePeopleExample.Criteria ca = ex.createCriteria();
        ca.andPeopleIdEqualTo(id);
        int a = gridHousePeopleService.countByExample(ex);
        if (a > 0) {
            return AjaxResult.error(400, "人员已存在住宅绑定关系，不可删除，如需删除此人员，请先解绑对应关系");
        }
        // 是否存在关联企业
        GridCompanyPeopleExample ex1 = new GridCompanyPeopleExample();
        GridCompanyPeopleExample.Criteria ca1 = ex1.createCriteria();
        ca1.andPeopleIdEqualTo(id);
        int a1 = gridCompanyPeopleService.countByExample(ex1);
        if (a1 > 0) {
            return AjaxResult.error(400, "人员已存在企业绑定关系，不可删除，如需删除此人员，请先解绑对应关系");
        }
        // 是否存在关联商铺
        GridShopStaffExample ex2 = new GridShopStaffExample();
        GridShopStaffExample.Criteria ca2 = ex2.createCriteria();
        ca2.andPeopleIdEqualTo(id);
        ca2.andValidEqualTo(Byte.valueOf("1"));
        int a2 = gridShopStaffService.countByExample(ex2);
        if (a2 > 0) {
            return AjaxResult.error(400, "人员已存在商铺绑定关系，不可删除，如需删除此人员，请先解绑对应关系");
        }
        // 删除人口信息
        GridPeople wsPeople = this.selectByPrimaryKey(id);
        wsPeople.setIsValid(Byte.valueOf("0"));
        this.updateByPrimaryKeySelective(wsPeople);

        GridPendingPeopleExample ex3 = new GridPendingPeopleExample();
        GridPendingPeopleExample.Criteria ca3 = ex3.createCriteria();
        ca3.andIdCardEqualTo(wsPeople.getIdCard());
        gridPendingPeopleService.deleteByExample(ex3);
        return AjaxResult.success(null);
    }

    @Override
    public AjaxResult detailByIdCard(String idCard) {
        GridPeopleExample ex = new GridPeopleExample();
        GridPeopleExample.Criteria ca = ex.createCriteria();
        ca.andIdCardEqualTo(idCard);
        ca.andIsValidEqualTo(Byte.valueOf("1"));
        GridPeople wsPeople = this.selectFirstByExample(ex);
        GridPeopleExt wsPeopleExt = BeanCopyUtil.toBean(wsPeople, GridPeopleExt.class);
        if (wsPeopleExt != null) {
            this.selectGridPeopleExt(wsPeopleExt);
        }
        return AjaxResult.success(wsPeopleExt);
    }

    @Override
    public GridPeople detailByOpenId(String openId) {
        GridPeopleExample ex = new GridPeopleExample();
        GridPeopleExample.Criteria ca = ex.createCriteria();
        ca.andOpenIdEqualTo(openId);
        ca.andIsValidEqualTo(Byte.valueOf("1"));
        return this.selectFirstByExample(ex);
    }

    @Override
    public int countByIdCardOrPhone(String idCard, String phone, String id) {
        GridPeopleExample ex = new GridPeopleExample();
        GridPeopleExample.Criteria ca = ex.createCriteria();
        ca.andIsValidEqualTo(Byte.valueOf("1"));
        if (StringUtils.isNotBlank(idCard)) {
            ca.andIdCardEqualTo(idCard);
        }
        if (StringUtils.isNotBlank(phone)) {
            ca.andPhoneEqualTo(phone);
        }
        if (StringUtils.isNotBlank(id)) {
            ca.andIdNotEqualTo(id);
        }
        return this.countByExample(ex);
    }

    @Override
    public GridPeopleExt selectGridPeopleExt(GridPeopleExt wsPeopleExt) {

        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));

        this.dealPeopleExt(regionMap, commonMap, wsPeopleExt);

        return wsPeopleExt;
    }

    @Override
    public GridPeopleExt dealPeopleExt(Map<String, String> wgxxbMap, Map<String, String> commonMap, GridPeopleExt wsPeopleExt) {
        if (StringUtils.isNotBlank(wsPeopleExt.getMzCode())) {
            wsPeopleExt.setMzValue(commonMap.get(wsPeopleExt.getMzCode()));
        }

        if (StringUtils.isNotBlank(wsPeopleExt.getHyzkCode())) {
            wsPeopleExt.setHyzkValue(commonMap.get(wsPeopleExt.getHyzkCode()));
        }

        if (StringUtils.isNotBlank(wsPeopleExt.getWhcdCode())) {
            wsPeopleExt.setWhcdValue(commonMap.get(wsPeopleExt.getWhcdCode()));
        }

        if (StringUtils.isNotBlank(wsPeopleExt.getZzmmCode())) {
            wsPeopleExt.setZzmmValue(commonMap.get(wsPeopleExt.getZzmmCode()));
        }

        if (StringUtils.isNotBlank(wsPeopleExt.getWgCode())) {
            wsPeopleExt.setWgValue(wgxxbMap.get(wsPeopleExt.getWgCode()));
            GridRegion wg = gridRegionService.getWgOtherCode(wsPeopleExt.getWgCode());
            if (wg != null) {
                wsPeopleExt.setWgOtherCode(wg.getWgCode());
                wsPeopleExt.setWgOtherCodeValue(wg.getWgName());
            }
        }

        if (StringUtils.isNotBlank(wsPeopleExt.getRklxCode())) {
            wsPeopleExt.setRklxValue(commonMap.get(wsPeopleExt.getRklxCode()));
        }

        if (StringUtils.isNotBlank(wsPeopleExt.getRkbqCode())) {
            String[] rkbqArr = wsPeopleExt.getRkbqCode().split(",");
            List<String> rkbqList = new ArrayList<>();
            for (String rkbq : rkbqArr) {
                rkbqList.add(commonMap.get(rkbq));
            }
            wsPeopleExt.setRkbqValue(StringUtils.join(rkbqList.toArray(), ","));
        }

//        wsPeopleExt.setIdCard(DesensitizedUtil.idCardNum(wsPeopleExt.getIdCard(), 6, 4));
//        wsPeopleExt.setPhone(DesensitizedUtil.mobilePhone(wsPeopleExt.getPhone()));

        return wsPeopleExt;
    }

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

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

    @Override
    public Integer countSpecialPeople(String wgCode) {
        List<String> wgCodes = new ArrayList<>();
        if(StringUtils.isNotBlank(wgCode)){
            wgCodes = Arrays.asList(wgCode.split(","));
        }
        return gridPeopleMapper.countWsSpecialPeople(wgCodes);
    }

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

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

    @Override
    public List<Map<String, Object>> countGridPeopleRklxByGrid(String wgCode) {
        List<GridRegion> regionList = new ArrayList<>();
        if(StringUtils.isBlank(wgCode)){
            regionList = gridRegionService.getChildGridRegion(wgCode);
        }else{
            List<String> wgCodes = Arrays.asList(wgCode.split(","));
            for(String code : wgCodes){
                regionList.addAll(gridRegionService.getChildGridRegion(code));
            }
        }
        List<Map<String, Object>> mapList = gridPeopleMapper.countGridPeopleRklxByGrid(StringUtils.isBlank(wgCode)?new ArrayList<>(): Arrays.asList(wgCode.split(",")));
        List<Map<String, Object>> result = new ArrayList<>();
        for (GridRegion region : regionList) {
            Map<String, Object> obj = new HashMap<>();
            obj.put("name", region.getWgName());
            for (Map<String, Object> map : mapList) {
                if (region.getWgName().equals(map.get("name"))) {
                    if ("户籍人口".equals(map.get("type"))) {
                        obj.put("hjrkNum", map.get("number"));
                    }
                    if ("非户籍人口".equals(map.get("type"))) {
                        obj.put("fhjrkNum", map.get("number"));
                    }
                }
            }
            if (!obj.containsKey("hjrkNum")) {
                obj.put("hjrkNum", 0);
            }
            if (!obj.containsKey("fhjrkNum")) {
                obj.put("fhjrkNum", 0);
            }
            result.add(obj);
        }
        result.sort(Comparator.comparingInt((Map<String, Object> o) -> Integer.parseInt(String.valueOf(o.get("hjrkNum")))).reversed());
        if (result.size() > 6) {
            return result.subList(0, 6);
        }
        return result;
    }

    @Override
    public List<GridPeople> selectGridPeopleByIdCard(String idCard) {
        GridPeopleExample ex = new GridPeopleExample();
        GridPeopleExample.Criteria ca = ex.createCriteria();
        ca.andIdCardEqualTo(idCard);
        ca.andIsValidEqualTo(Byte.valueOf("1"));
        return this.selectByExample(ex);
    }

    @Override
    public AjaxResult peopleToHousePage(String peopleId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<GridHousePeople> housePeopleList = gridHousePeopleService.selectGridHousePeopleByHouseId(null, peopleId);
        List<GridHousePeopleExt> housePeopleExtList = BeanCopyUtil.bathToBean(housePeopleList, GridHousePeopleExt.class);
        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 (GridHousePeopleExt h : housePeopleExtList) {
            gridHousePeopleService.selectGridHousePeopleExt(regionMap, commonMap, h, true, false);
            // 查询住户
            List<GridHousePeople> housePeopleList1 = gridHousePeopleService.selectGridHousePeopleByHouseId(h.getHouseId(), null);
            List<GridHousePeopleExt> housePeopleExtList2 = BeanCopyUtil.bathToBean(housePeopleList1, GridHousePeopleExt.class);
            for (GridHousePeopleExt p : housePeopleExtList2) {
                gridHousePeopleService.selectGridHousePeopleExt(regionMap, commonMap, p, false, true);
            }
            h.getGridHouseExt().setCommonPeople(housePeopleExtList2.stream().map(GridHousePeopleExt::getGridPeopleExt).filter(o -> o != null).map(GridPeopleExt::getPersonName).collect(Collectors.joining(",")));
        }
        PageInfo<GridHousePeopleExt> pageInfo = ZQTPageUtil.build(housePeopleList, housePeopleExtList);
        return AjaxResult.success(pageInfo);
    }

    @Override
    public AjaxResult peopleToCompanyPage(String peopleId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<GridCompanyPeople> companyPeopleList = gridCompanyPeopleService.selectGridCompanyPeopleByCompanyId(null, null, peopleId);
        List<GridCompanyPeopleExt> companyPeopleExtList = BeanCopyUtil.bathToBean(companyPeopleList, GridCompanyPeopleExt.class);
        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 (GridCompanyPeopleExt c : companyPeopleExtList) {
            gridCompanyPeopleService.selectGridCompanyPeopleExt(regionMap, commonMap, c, true, false);
        }
        PageInfo<GridCompanyPeopleExt> pageInfo = ZQTPageUtil.build(companyPeopleList, companyPeopleExtList);
        return AjaxResult.success(pageInfo);
    }

    @Override
    public AjaxResult peopleToShopPage(String peopleId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<GridShopStaff> shopStaffList = gridShopStaffService.selecGridShopStaffByPeopleId(peopleId);
        List<Long> shopIds = shopStaffList.stream().map(GridShopStaff::getShopId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(shopIds)) {
            return AjaxResult.success(new PageInfo<>(shopIds));
        }
        GridShopExample ex = new GridShopExample();
        GridShopExample.Criteria ca = ex.createCriteria();
        ca.andIdIn(shopIds);
        ca.andValidEqualTo(Byte.valueOf("1"));
        List<GridShop> shopList = gridShopService.selectByExample(ex);
        if (CollectionUtils.isNotEmpty(shopList)) {
            Map<String, String> commonMap = bsCommonService.getBsCommonMap().stream().collect(Collectors.toMap(BsCommon::getCode, BsCommon::getName));
            Map<Long, Long> staffIdMap = shopStaffList.stream().collect(Collectors.toMap(GridShopStaff::getShopId, GridShopStaff::getStaffId));
            for (GridShop ws : shopList) {
                ws.setBelongArea(org.springframework.util.StringUtils.isEmpty(ws.getWgCode()) ? "" : gridRegionService.getWgName(ws.getWgCode()));

                if (staffIdMap.containsKey(ws.getId())) {
                    ws.setStaffId(staffIdMap.get(ws.getId()));
                }
                ws.setShopTypeName(commonMap.get(ws.getShopType()));
                // ws.setShopPhone(DesensitizedUtil.mobilePhone(ws.getShopPhone()));
            }
        }
        PageInfo<GridShop> pageInfo = new PageInfo<>(shopList);
        return AjaxResult.success(pageInfo);
    }

    @Override
    @Transactional
    public AjaxResult peopleBind(PeopleBindParam peopleBindParam) {
        AjaxResult result = new AjaxResult();
        String type = peopleBindParam.getType();
        String wgCode = "";
        if ("1".equals(type)) {
            GridHousePeople wsHousePeople = new GridHousePeople();
            wsHousePeople.setCreateId(peopleBindParam.getCreateId());
            wsHousePeople.setPeopleId(peopleBindParam.getPeopleId());
            wsHousePeople.setHouseId(String.valueOf(peopleBindParam.getId()));
            result = gridHouseService.houseBindPeople(wsHousePeople);
        } else if ("2".equals(type)) {
            GridCompanyPeople wsCompanyPeople = new GridCompanyPeople();
            wsCompanyPeople.setCreateId(peopleBindParam.getCreateId());
            wsCompanyPeople.setPeopleId(peopleBindParam.getPeopleId());
            wsCompanyPeople.setCompanyId(String.valueOf(peopleBindParam.getId()));
            result = gridCompanyService.companyBindPeople(wsCompanyPeople);
        } else if ("3".equals(type)) {
            GridShopStaff wsShopStaff = new GridShopStaff();
            wsShopStaff.setCreateBy(peopleBindParam.getCreateId());
            wsShopStaff.setPeopleId(peopleBindParam.getPeopleId());
            wsShopStaff.setShopId(Long.valueOf(String.valueOf(peopleBindParam.getId())));
            List<GridShopStaff> wsShopStaffList = Arrays.asList(wsShopStaff);
            result = gridShopService.addWsStaff(wsShopStaffList);
        }
        return result;
    }

    @Override
    public AjaxResult importExcel(MultipartFile file, String createId) {
        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);
        }

        Map<String, String> regionMap = gridRegionService.getGridRegionMap().stream().collect(Collectors.toMap(GridRegion::getWgName, GridRegion::getWgCode));
        Map<String, String> commonMap = bsCommonService.getBsCommonMap().stream().collect(Collectors.toMap(BsCommon::getName, BsCommon::getCode));
        List<GridPeople> 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) {
                    GridPeople ce = new GridPeople();
                    ce.setPersonName(ZQTImportExcelUtil.getValue(row.getCell(0)));
                    ce.setPhone(ZQTImportExcelUtil.getValue(row.getCell(1)));
                    ce.setIdCard(ZQTImportExcelUtil.getValue(row.getCell(2)));
                    ce.setSex(ZQTImportExcelUtil.getValue(row.getCell(3)));
                    ce.setNativePlace(ZQTImportExcelUtil.getValue(row.getCell(4)));
                    ce.setMzCode(commonMap.get(ZQTImportExcelUtil.getValue(row.getCell(5))));
                    ce.setHyzkCode(commonMap.get(ZQTImportExcelUtil.getValue(row.getCell(6))));
                    ce.setWhcdCode(commonMap.get(ZQTImportExcelUtil.getValue(row.getCell(7))));
                    ce.setZzmmCode(commonMap.get(ZQTImportExcelUtil.getValue(row.getCell(8))));
                    ce.setWgCode(regionMap.get(ZQTImportExcelUtil.getValue(row.getCell(9))));
                    if (StringUtils.isBlank(ZQTImportExcelUtil.getValue(row.getCell(10)))) {
                        ce.setRkbqCode(null);
                    } else {
                        String[] rkbqArr = ZQTImportExcelUtil.getValue(row.getCell(10)).trim().replaceAll("，", ",").split(",");
                        List<String> rkbqList = new ArrayList<>();
                        for (String rkbq : rkbqArr) {
                            if (!commonMap.containsKey(rkbq)) {
                                // msg.append("第").append(j).append("行人口标签:" + rkbq + "未找到对应人口标签Code;");
                            } else {
                                rkbqList.add(commonMap.get(rkbq));
                            }
                        }
                        ce.setRkbqCode(StringUtils.join(rkbqList.toArray(), ","));
                    }
                    ce.setRklxCode(commonMap.get(ZQTImportExcelUtil.getValue(row.getCell(11))));
                    list.add(ce);
                }
            }
        }

        if (StringUtils.isBlank(msg)) {
            int records = 0;
            int temp = 0;
            try {
                for (GridPeople ce : list) {
                    List<GridPeople> wsPeopleList = this.selectGridPeopleByIdCard(ce.getIdCard());
                    if (StringUtils.isBlank(ce.getIdCard()) || wsPeopleList.isEmpty()) {
                        ce.setId(IdUtil.fastSimpleUUID());
                        ce.setCreateId(createId);
                        ce.setCreateTime(DateUtil.formatDateTime(new Date()));
                        temp = this.insertSelective(ce);
                    } else {
                        ce.setId(wsPeopleList.get(0).getId());
                        ce.setUpdateId(createId);
                        ce.setUpdateTime(DateUtil.formatDateTime(new Date()));
                        temp = this.updateByPrimaryKeySelective(ce);
                    }
                    if (temp == 1) {
                        records++;
                    } else {
                        msg.append("第").append(records + 2).append("行数据导入出错:");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                msg.append(e.getMessage());
                return AjaxResult.error(400, msg.toString());
            }
            msg.append("共导入").append(records).append("条数据");
            return AjaxResult.success("success", msg.toString());//返回成功信息
        }
        return AjaxResult.error(400, msg.toString());
    }

    @Override
    public List<GridPeople> getAllPeople(GridPeopleSearchParam param) {
        return gridPeopleMapper.listByParam(param);
    }
}
