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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.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.enums.GridCompanyLevelEnum;
import com.ruoyi.system.domain.grid.ext.GridCompanyExt;
import com.ruoyi.system.domain.grid.vo.GridCompanySearchParam;
import com.ruoyi.system.domain.grid.vo.SimpleGridCompanyItem;
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.GridCompanyMapper;
import com.ruoyi.system.mapper.grid.GridRegionMapper;
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.stream.Collectors;

/**
 * @author Cesar
 * @date ${cTime}
 * @desc GridCompanyService实现
 */
@Service
@MyBaseService
public class GridCompanyServiceImpl extends BaseServiceImpl<GridCompanyMapper, GridCompany, GridCompanyExample> implements GridCompanyService {

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

    @Autowired
    GridCompanyMapper gridCompanyMapper;
    @Autowired
    BsCommonService bsCommonService;
    @Autowired
    GridRegionService gridRegionService;
    @Autowired
    GridCompanyPeopleService gridCompanyPeopleService;
    @Autowired
    GridCompanyEconomyService gridCompanyEconomyService;
    @Autowired
    private GridPeopleService gridPeopleService;
    @Autowired
    private GridWgLogService gridWgLogService;
    @Autowired
    private GridRegionUserService gridRegionUserService;
    @Autowired
    private VisitFreeInterviewService visitFreeInterviewService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private GridRegionMapper gridRegionMapper;

    @Override
    public PageInfo page(GridCompany wsCompany, String value) {
        GridCompanySearchParam param = new GridCompanySearchParam();
        if(StringUtils.isNotBlank(wsCompany.getWgCode())){
            param.setWgCodeLikes(Arrays.asList(wsCompany.getWgCode()));
        }
        param.setValue(value);
        param.setCreditCode(wsCompany.getCreditCode());
        param.setQylxCode(wsCompany.getQylxCode());
        param.setIsClosed(wsCompany.getIsClosed());
        param.setIsUnowned(wsCompany.getIsUnowned());
        param.setOrderCondition(" create_time desc, company_name ");
        List<GridCompany> companyList = gridCompanyMapper.listByParam(param);

        List<GridCompanyExt> companyExtList = BeanCopyUtil.bathToBean(companyList, GridCompanyExt.class);
        PageInfo<GridCompanyExt> pageInfo = ZQTPageUtil.build(companyList, companyExtList);
        if(CollectionUtils.isNotEmpty(pageInfo.getList())){
            Map<String, String> regionMap = gridRegionService.getMapByWgCodes(companyList.stream().map(GridCompany::getWgCode).collect(Collectors.toList()));
            Map<String, String> commonMap = bsCommonService.getMapByCodes(companyExtList.stream().map(GridCompany::getQylxCode).collect(Collectors.toList()));
            for(GridCompanyExt c : pageInfo.getList()){
                this.dealGridCompanyExt(regionMap, commonMap, c);
            }
        }

        return pageInfo;
    }

    @Override
    @Transactional
    public AjaxResult add(GridCompany wsCompany) {
        Validator.validateNotEmpty(wsCompany.getCompanyName(), "企业名称为空");
        Validator.validateNotEmpty(wsCompany.getCreditCode(), "企业统一社会信用代码为空");
        if (this.countByCompanyNameOrCreditCode(wsCompany.getCompanyName(), null, null) > 0) {
            return AjaxResult.error(400, "该企业名称已在企业库中");
        }
        if (this.countByCompanyNameOrCreditCode(null, wsCompany.getCreditCode(), null) > 0) {
            return AjaxResult.error(400, "该企业统一社会信用代码已在企业库中");
        }
        wsCompany.setId(IdUtil.fastSimpleUUID());
        wsCompany.setCreateTime(DateUtil.formatDateTime(new Date()));
        gridCompanyMapper.insertSelective(wsCompany);

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

    @Override
    @Transactional
    public AjaxResult edit(GridCompany wsCompany) {
        Validator.validateNotEmpty(wsCompany.getId(), "id is empty");
        Validator.validateNotEmpty(wsCompany.getCompanyName(), "企业名称为空");
        Validator.validateNotEmpty(wsCompany.getCreditCode(), "企业统一社会信用代码为空");
        if (this.countByCompanyNameOrCreditCode(wsCompany.getCompanyName(), null, wsCompany.getId()) > 0) {
            return AjaxResult.error(400, "该企业名称已在企业库中");
        }
        if (this.countByCompanyNameOrCreditCode(null, wsCompany.getCreditCode(), wsCompany.getId()) > 0) {
            return AjaxResult.error(400, "该企业统一社会信用代码已在企业库中");
        }
        wsCompany.setUpdateTime(DateUtil.formatDateTime(new Date()));

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

        if ((StringUtils.isNotBlank(origin.getCompanyName()) && !origin.getCompanyName().equals(wsCompany.getCompanyName()))
                || (StringUtils.isBlank(origin.getCompanyName()) && StringUtils.isNotBlank(wsCompany.getCompanyName()))) {
            contentList.add("企业名称");
        }

        if ((StringUtils.isNotBlank(origin.getQylxCode()) && !origin.getQylxCode().equals(wsCompany.getQylxCode()))
                || (StringUtils.isBlank(origin.getQylxCode()) && StringUtils.isNotBlank(wsCompany.getQylxCode()))) {
            contentList.add("企业类型");
        }

        if ((StringUtils.isNotBlank(origin.getCreditCode()) && !origin.getCreditCode().equals(wsCompany.getCreditCode()))
                || (StringUtils.isBlank(origin.getCreditCode()) && StringUtils.isNotBlank(wsCompany.getCreditCode()))) {
            contentList.add("统一社会信用代码");
        }

        if ((StringUtils.isNotBlank(origin.getLawPerson()) && !origin.getLawPerson().equals(wsCompany.getLawPerson()))
                || (StringUtils.isBlank(origin.getLawPerson()) && StringUtils.isNotBlank(wsCompany.getLawPerson()))) {
            contentList.add("法定代表人");
        }

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

        if ((StringUtils.isNotBlank(origin.getAddress()) && !origin.getAddress().equals(wsCompany.getAddress()))
                || (StringUtils.isBlank(origin.getAddress()) && StringUtils.isNotBlank(wsCompany.getAddress()))) {
            contentList.add("企业位置");
        }

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

        if ((StringUtils.isNotBlank(origin.getArea()) && !origin.getArea().equals(wsCompany.getArea()))
                || (StringUtils.isBlank(origin.getArea()) && StringUtils.isNotBlank(wsCompany.getArea()))) {
            contentList.add("宗地面积");
        }

        if ((StringUtils.isNotBlank(origin.getIsFactory()) && !origin.getIsFactory().equals(wsCompany.getIsFactory()))
                || (StringUtils.isBlank(origin.getIsFactory()) && StringUtils.isNotBlank(wsCompany.getIsFactory()))) {
            contentList.add("是否厂中厂");
        }

        if ((StringUtils.isNotBlank(origin.getIsLive()) && !origin.getIsLive().equals(wsCompany.getIsLive()))
                || (StringUtils.isBlank(origin.getIsLive()) && StringUtils.isNotBlank(wsCompany.getIsLive()))) {
            contentList.add("是否住人");
        }

        if ((StringUtils.isNotBlank(origin.getEmployeeNum()) && !origin.getEmployeeNum().equals(wsCompany.getEmployeeNum()))
                || (StringUtils.isBlank(origin.getEmployeeNum()) && StringUtils.isNotBlank(wsCompany.getEmployeeNum()))) {
            contentList.add("员工数");
        }
        if ((StringUtils.isNotBlank(origin.getLevel()) && !origin.getLevel().equals(wsCompany.getLevel()))
                || (StringUtils.isBlank(origin.getLevel()) && StringUtils.isNotBlank(wsCompany.getLevel()))) {
            contentList.add("企业等级");
        }

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


        gridCompanyMapper.updateByPrimaryKeySelective(wsCompany);

        SysUser sysUser = sysUserService.selectUserById(wsCompany.getUpdateId());
        //更新走访
        if(CollectionUtils.isNotEmpty(contentList)){
            VisitFreeInterviewExt visitFreeInterviewExt = new VisitFreeInterviewExt();
            visitFreeInterviewExt.setWgCode(wsCompany.getWgCode());
            visitFreeInterviewExt.setWgValue(gridRegionService.getWgName(wsCompany.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("1");
            visitFreeInterviewExt.setContent("完成企业基本信息更新，更新字段：" + StringUtils.join(contentList, ","));
            visitFreeInterviewExt.setObjId(wsCompany.getId());
            visitFreeInterviewExt.setAddress(wsCompany.getAddress());
            visitFreeInterviewExt.setInterviewTime(DateUtil.formatDate(new Date()));
            visitFreeInterviewExt.setActualTime(DateUtil.formatDateTime(new Date()));
            visitFreeInterviewExt.setObjName(wsCompany.getCompanyName());
            visitFreeInterviewExt.setObjType(wsCompany.getQylxCode());
            String objectName = bsCommonService.getName(wsCompany.getQylxCode());
            visitFreeInterviewExt.setObjTypeName(objectName);
            visitFreeInterviewExt.setObjUserName(wsCompany.getLawPerson());
            visitFreeInterviewExt.setObjNumber(wsCompany.getCreditCode());
            visitFreeInterviewExt.setLongitude(wsCompany.getLongitude());
            visitFreeInterviewExt.setLatitude(wsCompany.getLatitude());
            visitFreeInterviewExt.setVisitType(VisitTypeEnum.UPDATE_VISIT.getCode());
            visitFreeInterviewService.addVisitFreeInterview(visitFreeInterviewExt);

            // 日志
            GridWgLog wsWgLog = new GridWgLog();
            wsWgLog.setCreateId(wsCompany.getUpdateId());
            wsWgLog.setCreateName(sysUser != null ? sysUser.getUserName() : "");
            wsWgLog.setCreateWgCode(wsCompany.getWgCode());
            wsWgLog.setObjectName(wsCompany.getCompanyName());
            wsWgLog.setType("3");
            wsWgLog.setOperate("update");
            wsWgLog.setContent(StringUtils.join(contentList, ","));
            wsWgLog.setObjectId(wsCompany.getId());
            gridWgLogService.add(wsWgLog);
        }

        return AjaxResult.success();
    }

    @Override
    public AjaxResult detail(String id) {
        GridCompany wsCompany = this.selectByPrimaryKey(id);
        wsCompany.setEmployeeNum(String.valueOf(gridCompanyPeopleService.countEmployeeNum(id, null)));
        GridCompanyExt wsCompanyExt = BeanCopyUtil.toBean(wsCompany, GridCompanyExt.class);
        if (wsCompanyExt != null) {
            if (Byte.valueOf("1").equals(wsCompanyExt.getIsValid())) {
                this.selectGridCompanyExt(wsCompanyExt);
            } else {
                return AjaxResult.success(null);
            }
        }
        return AjaxResult.success(wsCompanyExt);
    }

    @Override
    public AjaxResult delete(String id) {
        // 是否存在关联人口
        GridCompanyPeopleExample ex = new GridCompanyPeopleExample();
        GridCompanyPeopleExample.Criteria ca = ex.createCriteria();
        ca.andCompanyIdEqualTo(id);
        int a = gridCompanyPeopleService.countByExample(ex);
        if (a > 0) {
            return AjaxResult.error(400, "企业已存在人员绑定关系，不可删除，如需删除此企业，请先解绑对应关系");
        }
        // 删除企业
        GridCompany wsCompany = this.selectByPrimaryKey(id);
        wsCompany.setIsValid(Byte.valueOf("0"));
        this.updateByPrimaryKeySelective(wsCompany);
        return AjaxResult.success(null);
    }

    @Override
    public AjaxResult detailByCreditCode(String creditCode) {
        GridCompanyExample ex = new GridCompanyExample();
        GridCompanyExample.Criteria ca = ex.createCriteria();
        ca.andIsValidEqualTo(Byte.valueOf("1"));
        ca.andCreditCodeEqualTo(creditCode);
        GridCompany wsCompany = this.selectFirstByExample(ex);
        GridCompanyExt wsCompanyExt = BeanCopyUtil.toBean(wsCompany, GridCompanyExt.class);
        if (wsCompanyExt != null) {
            wsCompany.setEmployeeNum(String.valueOf(gridCompanyPeopleService.countEmployeeNum(wsCompany.getId(), null)));
            this.selectGridCompanyExt(wsCompanyExt);
        }
        return AjaxResult.success(wsCompanyExt);
    }

    @Override
    public List<GridCompany> otherCompany(String creditCode, String wgCode) {
        GridCompanyExample ex = new GridCompanyExample();
        GridCompanyExample.Criteria ca = ex.createCriteria();
        ca.andIsValidEqualTo(Byte.valueOf("1"));
        ca.andCreditCodeNotEqualTo(creditCode);
        ca.andWgCodeEqualTo(wgCode);
        ex.setOrderByClause(" create_time desc, company_name ");
        return this.selectByExample(ex);
    }

    @Override
    public List<GridCompanyEconomy> economy(String creditCode, String belongTime) {
        GridCompanyEconomyExample ex = new GridCompanyEconomyExample();
        GridCompanyEconomyExample.Criteria ca = ex.createCriteria();
        ca.andCreditCodeEqualTo(creditCode);
        if (StringUtils.isNotBlank(belongTime)) {
            ca.andBelongTimeLike(belongTime + "%");
        }
        ex.setOrderByClause(" belong_time desc ");
        return gridCompanyEconomyService.selectByExample(ex);
    }

    @Override
    @Transactional
    public AjaxResult companyBindPeople(GridCompanyPeople wsCompanyPeople) {
        GridCompany wsCompany = this.selectByPrimaryKey(wsCompanyPeople.getCompanyId());
        List<GridCompanyPeople> companyPeopleList = gridCompanyPeopleService.selectGridCompanyPeopleByCompanyId(wsCompanyPeople.getCompanyId(), wsCompany.getCreditCode(), wsCompanyPeople.getPeopleId());
        if (companyPeopleList.size() > 0) {
            return AjaxResult.error(400, "该人员已绑定该企业");
        }
        wsCompanyPeople.setCreditCode(wsCompany.getCreditCode());
        wsCompanyPeople.setId(IdUtil.fastSimpleUUID());
        wsCompanyPeople.setCreateTime(DateUtil.formatDateTime(new Date()));
        gridCompanyPeopleService.insertSelective(wsCompanyPeople);

        SysUser sysUser = sysUserService.selectUserById(wsCompanyPeople.getCreateId());
        // 日志
        GridWgLog wsWgLog = new GridWgLog();
        wsWgLog.setCreateId(wsCompanyPeople.getCreateId());
        wsWgLog.setCreateName(sysUser != null ? sysUser.getNickName() : "");
        wsWgLog.setCreateWgCode(wsCompany.getWgCode());
        wsWgLog.setObjectName(this.selectByPrimaryKey(wsCompanyPeople.getCompanyId()).getCompanyName());
        wsWgLog.setBindName(gridPeopleService.selectByPrimaryKey(wsCompanyPeople.getPeopleId()).getPersonName());
        wsWgLog.setType("3");
        wsWgLog.setOperate("bind");
        wsWgLog.setObjectId(wsCompany.getId());
        gridWgLogService.add(wsWgLog);

        return AjaxResult.success(null);
    }

    @Override
    public int countByCompanyNameOrCreditCode(String companyName, String creditCode, String id) {
        GridCompanyExample ex = new GridCompanyExample();
        GridCompanyExample.Criteria ca = ex.createCriteria();
        ca.andIsValidEqualTo(Byte.valueOf("1"));
        if (StringUtils.isNotBlank(companyName)) {
            ca.andCompanyNameEqualTo(companyName);
        }
        if (StringUtils.isNotBlank(creditCode)) {
            ca.andCreditCodeEqualTo(creditCode);
        }
        if (StringUtils.isNotBlank(id)) {
            ca.andIdNotEqualTo(id);
        }
        return this.countByExample(ex);
    }

    @Override
    public GridCompanyExt selectGridCompanyExt(GridCompanyExt wsCompanyExt) {

        String wgType = gridRegionMapper.getWgTypeByWgCode(wsCompanyExt.getWgCode());
        Map<String, String> wgxxbMap = gridRegionService.getGridRegionMapByWgType(wgType).stream().collect(Collectors.toMap(GridRegion::getWgCode, GridRegion::getWgName));
        Map<String, String> commonMap = bsCommonService.getBsCommonMap().stream().collect(Collectors.toMap(BsCommon::getCode, BsCommon::getName));

        this.dealGridCompanyExt(wgxxbMap, commonMap, wsCompanyExt);

        return wsCompanyExt;
    }

    @Override
    public GridCompanyExt dealGridCompanyExt(Map<String, String> wgxxbMap, Map<String, String> commonMap, GridCompanyExt wsCompanyExt) {
        if (StringUtils.isNotBlank(wsCompanyExt.getWgCode())) {
            wsCompanyExt.setWgValue(wgxxbMap.get(wsCompanyExt.getWgCode()));
            GridRegion wg = gridRegionService.getWgOtherCode(wsCompanyExt.getWgCode());
            if (wg != null) {
                wsCompanyExt.setWgOtherCode(wg.getWgCode());
                wsCompanyExt.setWgOtherCodeValue(wg.getWgName());
            }
        }
        if (StringUtils.isNotBlank(wsCompanyExt.getQylxCode())) {
            wsCompanyExt.setQylxValue(commonMap.get(wsCompanyExt.getQylxCode()));
        }
        if(StringUtils.isNotBlank(wsCompanyExt.getLevel())){
            GridCompanyLevelEnum companyLevelEnum = GridCompanyLevelEnum.getByCode(wsCompanyExt.getLevel());
            wsCompanyExt.setLevelValue(companyLevelEnum.getValue());
        }
        // wsCompanyExt.setPhone(DesensitizedUtil.mobilePhone(wsCompanyExt.getPhone()));
        wsCompanyExt.setEmployeeNum(String.valueOf(gridCompanyPeopleService.countEmployeeNum(wsCompanyExt.getId(), null)));
        return wsCompanyExt;
    }

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

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

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

    @Override
    public List<GridCompany> selectGridCompanyByCreditCode(String creditCode, String companyName) {
        GridCompanyExample ex = new GridCompanyExample();
        GridCompanyExample.Criteria ca = ex.createCriteria();
        ca.andIsValidEqualTo(Byte.valueOf("1"));
        if (StringUtils.isNotBlank(creditCode)) {
            ca.andCreditCodeEqualTo(creditCode);
        }
        if (StringUtils.isNotBlank(companyName)) {
            ca.andCompanyNameEqualTo(companyName);
        }
        return this.selectByExample(ex);
    }

    @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<GridCompany> 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) {
                    GridCompany ce = new GridCompany();
                    ce.setCreditCode(ZQTImportExcelUtil.getValue(row.getCell(0)));
                    ce.setCompanyName(ZQTImportExcelUtil.getValue(row.getCell(1)));
                    ce.setQylxCode(commonMap.get(ZQTImportExcelUtil.getValue(row.getCell(2))));
                    ce.setWgCode(regionMap.get(ZQTImportExcelUtil.getValue(row.getCell(3))));
                    ce.setLawPerson(ZQTImportExcelUtil.getValue(row.getCell(4)));
                    ce.setPhone(ZQTImportExcelUtil.getValue(row.getCell(5)));
                    ce.setAddress(ZQTImportExcelUtil.getValue(row.getCell(6)));
                    ce.setArea(ZQTImportExcelUtil.getValue(row.getCell(7)));
                    ce.setIsFactory(ZQTImportExcelUtil.getValue(row.getCell(8)));
                    ce.setIsLive(ZQTImportExcelUtil.getValue(row.getCell(9)));
                    list.add(ce);
                }
            }
        }

        if (StringUtils.isBlank(msg)) {
            int records = 0;
            int temp = 0;
            try {
                for (GridCompany ce : list) {
                    List<GridCompany> companyList = this.selectGridCompanyByCreditCode(ce.getCreditCode(), null);
                    if (companyList.isEmpty()) {
                        ce.setId(IdUtil.fastSimpleUUID());
                        ce.setCreateId(createId);
                        ce.setCreateTime(DateUtil.formatDateTime(new Date()));
                        temp = this.insertSelective(ce);
                    } else {
                        ce.setId(companyList.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<GridCompany> selectCompanyForDoubleRandomLimit() {

        PageHelper.startPage(1, 1000);
        GridCompanyExample ex = new GridCompanyExample();
        GridCompanyExample.Criteria ca = ex.createCriteria();
        ca.andIsValidEqualTo(Byte.valueOf("1"));
        ca.andIsClosedEqualTo(Byte.valueOf("1"));
        ca.andWgCodeIsNotNull();
        return gridCompanyMapper.selectByExample(ex);
    }

    @Override
    public List<GridCompany> selectByRandom(int companyNum, String chooseCompanyType) {
        return gridCompanyMapper.selectByRandom(companyNum, chooseCompanyType);
    }

    @Override
    public List<GridCompany> getAllCompanyList(GridCompanySearchParam param) {
        return gridCompanyMapper.listByParam(param);
    }

    @Override
    public List<SimpleGridCompanyItem> companyPointList(String wgCode, String name) {
        return gridCompanyMapper.simplePointList(wgCode, name);
    }

}
