package com.kiisoo.ic.store.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kiisoo.aegis.common.faces.util.HttpUtil;
import com.kiisoo.ic.common.utils.ExcelUtils;
import com.kiisoo.ic.common.utils.MD5FileUtil;
import com.kiisoo.ic.customer.entity.OpSellerCustomerRelation;
import com.kiisoo.ic.customer.mapper.OpSellerCustomerRelationDOMapper;
import com.kiisoo.ic.department.entity.DepartmentDO;
import com.kiisoo.ic.department.mapper.PrivilageDepartmentDOMapper;
import com.kiisoo.ic.domain.service.PrivilageDomainService;
import com.kiisoo.ic.employee.entity.EmployeeDO;
import com.kiisoo.ic.employee.entity.ImportErrorDTO;
import com.kiisoo.ic.employee.mapper.PrivilageCpUserDOMapper;
import com.kiisoo.ic.employee.service.EmployeeService;
import com.kiisoo.ic.generalize.entity.PrivilageOrganizational;
import com.kiisoo.ic.generalize.service.RetailCompanyService;
import com.kiisoo.ic.generalize.mapper.RetailCompanyMapper;
import com.kiisoo.ic.store.bean.BsdShareCodeResponse;
import com.kiisoo.ic.store.bean.PoiStoreStaffDTO;
import com.kiisoo.ic.store.entity.PoiStore;
import com.kiisoo.ic.store.entity.PoiStoreStaff;
import com.kiisoo.ic.store.entity.StoreUserDTO;
import com.kiisoo.ic.store.mapper.PoiStoreDOMapper;
import com.kiisoo.ic.store.mapper.PoiStoreStaffDOMapper;
import com.kiisoo.ic.store.mapper.PrivilageCpUserStoreDOMapper;
import com.kiisoo.ic.utils.ZipUtils;
import org.apache.commons.collections.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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

import static com.kiisoo.ic.employee.constant.Constants.ADD_CP_CODE_BINDED;
import static com.kiisoo.ic.store.constant.Constants.*;

/**
 * @Description: 门店号管理service
 * @Auther: yechenhao
 * @Date: 2020/4/9 18:27
 * @Version: v1
 */
@Service
public class StoreEmployeeService {

    @Autowired
    private PoiStoreDOMapper poiStoreDOMapper;

    @Autowired
    private PrivilageCpUserStoreDOMapper privilageCpUserStoreDOMapper;

    @Autowired
    private PrivilageCpUserDOMapper privilageCpUserDOMapper;

    @Autowired
    private PoiStoreStaffDOMapper poiStoreStaffDOMapper;

    @Autowired
    private PrivilageDepartmentDOMapper departmentDOMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private PrivilageDomainService privilageDomainService;
    @Autowired
    private OpSellerCustomerRelationDOMapper opSellerCustomerRelationDOMapper;

    @Autowired
    private RetailCompanyMapper retailCompanyMapper;

    @Autowired
    private RetailCompanyService retailCompanyService;
    /**
     * 查询门店号
     * @param storeId 门店id
     * @param regionId 区域id
     */
    public PageInfo<StoreUserDTO> listStoreUser(Long userId ,Long storeId, Long regionId,Long companyId, Integer pageNum, Integer pageSize,String code) {
        Map<String,Object> result = new HashMap<>();
        List<PoiStore> poiStores = null;
        List<Long> shopIds = new ArrayList<>();
        if (storeId != null){
            shopIds.add(storeId);
        }else if(StringUtils.isNotBlank(code)){
            List<PoiStore>  store =  poiStoreDOMapper.selectShopByNameOrCode(code);
            shopIds = store.stream().map(i -> i.getId()).collect(Collectors.toList());
            List<Long> userAllShops = privilageDomainService.listUserDatePermission(userId);
            shopIds.retainAll(userAllShops);
        }else if(regionId != null){
            shopIds = privilageDomainService.listUserDatePermission(userId);
            //有区域就查区域店铺
            List<PoiStore> stores = poiStoreDOMapper.selectRegionShop(regionId);
            shopIds = stores.stream().map(i -> i.getId()).collect(Collectors.toList());
            List<Long> userAllShops = privilageDomainService.listUserDatePermission(userId);
            shopIds.retainAll(userAllShops);
        }else if(companyId != null){
            //如果有公司则查公司店铺
            List<PoiStore> shops = retailCompanyService.selectShopByCompany(companyId);
            shopIds = shops.stream().map(p -> p.getId()).collect(Collectors.toList());
            List<Long> userAllShops = privilageDomainService.listUserDatePermission(userId);
            shopIds.retainAll(userAllShops);
        }else{
            //查询用户权限店铺
            shopIds = new ArrayList<>(privilageDomainService.listUserDatePermission(userId));
        }
        PageHelper.startPage(pageNum, pageSize);
        List<StoreUserDTO> cpUserStoreDO = privilageCpUserStoreDOMapper.selectCpUserByShops(shopIds);
        if (CollectionUtils.isNotEmpty(cpUserStoreDO)){
            int orderNum = (pageNum -1) * pageSize;
            for(StoreUserDTO cpUserStore : cpUserStoreDO) {
                //设置序号
                cpUserStore.setOrderNum(++orderNum);
                //查询店铺绑定的企业微信
                PoiStore poiStore =  poiStoreDOMapper.selectById(cpUserStore.getId());
                if (null != poiStore){
                    cpUserStore.setName(poiStore.getName());
                    cpUserStore.setCode(poiStore.getCode());
                }
                //查询导购数目
                List<Long> shops = Arrays.asList(cpUserStore.getId());
                List<PoiStoreStaffDTO> sellerList =  poiStoreStaffDOMapper.selectSellersByShopIds(shops);
                  int staffNum = 0;
                if (null != sellerList && sellerList.size() > 0){
                    staffNum = sellerList.size();
                }
                cpUserStore.setStaffNum(staffNum);
                //客户数
                QueryWrapper<OpSellerCustomerRelation> wrapper2 = new QueryWrapper<>();
                wrapper2.eq("store_id",cpUserStore.getId());
                wrapper2.eq("type",1);
                List<OpSellerCustomerRelation> opRelations = opSellerCustomerRelationDOMapper.selectList(wrapper2);
                long count = opRelations.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
                cpUserStore.setCustomerNum((int)count);
            }
        }
        return new PageInfo<>(cpUserStoreDO) ;
    }


    /**
     * 批量下载店铺二维码
     * @param response
     */
    public void downloadStoreUserCode(HttpServletResponse response) throws IOException {
        //查询所有公司
        List<PrivilageOrganizational> privilageOrganizationals = retailCompanyMapper.selectList(null);
        if (CollectionUtils.isNotEmpty(privilageOrganizationals)){
            //根文件夹用于存放公司
            String fileUrl = "门店码-"+UUID.randomUUID().toString().replace("-", "");
            File file = new File(fileUrl);
            file.mkdir();
            // 生成的ZIP文件名
            String strZipName = "store_qrCode_"+ fileUrl +".zip";
            FileOutputStream out = new FileOutputStream(new File(strZipName));

            //遍历零售公司
            for (PrivilageOrganizational privilageOrganizational:privilageOrganizationals) {
                if (privilageOrganizational == null || privilageOrganizational.getId() == null){
                    continue;
                }

                //创建零售公司文件夹
                File complayFile = new File(file.getPath()+"/"+privilageOrganizational.getName());
                complayFile.mkdir();
                //查询店铺
                List<PoiStore> poiStores = poiStoreDOMapper.selectShopByCompany(privilageOrganizational.getId());
                if (CollectionUtils.isNotEmpty(poiStores)){
                    //遍历店铺查询门店码url
                    for (PoiStore poiStore:poiStores){
                        String url = poiStoreDOMapper.selectStoreQrCode(poiStore.getId());
                        if (StringUtils.isBlank(url)){
                            continue;
                        }
                        //下载图片
                        BufferedInputStream in = new BufferedInputStream(employeeService.getInputStream(url));
                        //字节流转图片对象
                        Image bi = ImageIO.read(in);
                        //构建图片流
                        BufferedImage tag = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
                        //绘制改变尺寸后的图
                        tag.getGraphics().drawImage(bi, 0, 0, 300, 300, null);
                        //输出流
                        BufferedOutputStream image = new BufferedOutputStream(new FileOutputStream(complayFile.getPath() +"/" +poiStore.getCode() + ".png"));

                        ImageIO.write(tag, "PNG", image);

                        in.close();
                        image.close();
                    }
                }
            }

            //将根文件转换为zip文件
            ZipUtils.toZip(file.getPath(),out,true);

            //将文件输入到response
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            File zipFile = new File(strZipName);
            FileInputStream inStream = new FileInputStream(zipFile);
            int lenNew;
            while ((lenNew = inStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, lenNew);
            }
            //删除文件，清理空间
            file.delete();
            zipFile.delete();
        }
    }
    /**
     * 批量下载店铺二维码
     * @param response
     */
    public void downloadStoreUserCodeFromBSD(HttpServletResponse response) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //查询所有公司
        QueryWrapper<PrivilageOrganizational> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",1).eq("type",1).eq("level",2);
        List<PrivilageOrganizational> privilageOrganizationals = retailCompanyMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(privilageOrganizationals)){
            //根文件夹用于存放公司
            String fileUrl = "门店码-"+UUID.randomUUID().toString().replace("-", "");
            File file = new File(fileUrl);
            file.mkdir();
            // 生成的ZIP文件名
            String strZipName = "store_qrCode_"+ fileUrl +".zip";
            FileOutputStream out = new FileOutputStream(new File(strZipName));

            //遍历零售公司
            for (PrivilageOrganizational privilageOrganizational:privilageOrganizationals) {
                if (privilageOrganizational == null || privilageOrganizational.getId() == null){
                    continue;
                }

                //创建零售公司文件夹
                File complayFile = new File(file.getPath()+"/"+privilageOrganizational.getName());
                complayFile.mkdir();
                //查询客户
                QueryWrapper<PrivilageOrganizational> customerWrap = new QueryWrapper<>();
                customerWrap.eq("status",1).eq("type",1).eq("level",3).eq("parent_id",privilageOrganizational.getId());
                List<PrivilageOrganizational> customerList = retailCompanyMapper.selectList(customerWrap);
                if (CollectionUtils.isNotEmpty(customerList)){
                    List<Long> customerIds = customerList.stream().map(i -> i.getId()).collect(Collectors.toList());
                    //查询店铺
                    List<PoiStore> poiStores = poiStoreDOMapper.selectShopByCustomerIds(customerIds);
                    if (CollectionUtils.isNotEmpty(poiStores)){
                        //遍历店铺查询门店码url
                        for (PoiStore poiStore:poiStores){
                            String cpUserId = privilageCpUserStoreDOMapper.selectCpUserIdByStoreId(poiStore.getId());
                            if (StringUtils.isBlank(cpUserId)){
                                continue;
                            }
                            Map<String,Object> params = new HashMap<>();
                            params.put("userId",cpUserId);
                            params.put("type",0);
                            params.put("storeNo",poiStore.getCode());
                            String get = HttpUtil.get("http://vtest.bsd.cn/BSD_WXAPP/qyWechat/getShareQRcode?token=BOSIDENG" + MD5FileUtil.getMD5String(sdf.format(new Date())), params);
                            JSONObject saveAccountInputJSON = JSONObject.parseObject(get);
                            BsdShareCodeResponse bsdResponse = saveAccountInputJSON.toJavaObject(BsdShareCodeResponse.class);

                            String url = bsdResponse.getData();
                            if (StringUtils.isBlank(url)){
                                continue;
                            }
                            //下载图片
                            BufferedInputStream in = new BufferedInputStream(employeeService.getInputStream(url));
                            //字节流转图片对象
                            Image bi = ImageIO.read(in);
                            //构建图片流
                            BufferedImage tag = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
                            //绘制改变尺寸后的图
                            tag.getGraphics().drawImage(bi, 0, 0, 300, 300, null);
                            //输出流
                            BufferedOutputStream image = new BufferedOutputStream(new FileOutputStream(complayFile.getPath() +"/" +poiStore.getCode() + ".png"));

                            ImageIO.write(tag, "PNG", image);

                            in.close();
                            image.close();
                        }
                    }
                }
            }

            //将根文件转换为zip文件
            ZipUtils.toZip(file.getPath(),out,true);

            //将文件输入到response
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            File zipFile = new File(strZipName);
            FileInputStream inStream = new FileInputStream(zipFile);
            int lenNew;
            while ((lenNew = inStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, lenNew);
            }
            //删除文件，清理空间
            file.delete();
            zipFile.delete();
        }
    }
    /**
     * 批量下载店铺导购吗
     * @param response
     */
    public void downloadStoreStaffCode(HttpServletResponse response) throws IOException {
        //查询所有公司
        List<PrivilageOrganizational> privilageOrganizationals = retailCompanyMapper.selectList(null);
        if (CollectionUtils.isNotEmpty(privilageOrganizationals)){
            //根文件夹用于存放公司
            String fileUrl = "导购码-"+UUID.randomUUID().toString().replace("-", "");
            File file = new File(fileUrl);
            file.mkdir();
            // 生成的ZIP文件名
            String strZipName = "store_qrCode_"+ fileUrl +".zip";
            FileOutputStream out = new FileOutputStream(new File(strZipName));

            //遍历零售公司
            for (PrivilageOrganizational privilageOrganizational:privilageOrganizationals) {
                if (privilageOrganizational == null || privilageOrganizational.getId() == null){
                    continue;
                }

                //创建零售公司文件夹
                File complayFile = new File(file.getPath()+"/"+privilageOrganizational.getName());
                complayFile.mkdir();
                //查询店铺
                List<PoiStore> poiStores = poiStoreDOMapper.selectShopByCompany(privilageOrganizational.getId());
                if (CollectionUtils.isNotEmpty(poiStores)){
                    //遍历店铺查询门店码url
                    for (PoiStore poiStore:poiStores){
                        //创建零售公司文件夹
                        File storeFile = new File(complayFile.getPath()+"/"+poiStore.getName());
                        storeFile.mkdir();

                        QueryWrapper<PoiStoreStaff> staffQr = new QueryWrapper();
                        staffQr.eq(DATABASE_STORE_ID_KEY,poiStore.getId());
                        staffQr.eq(DATABASE_TYPE_KEY,TYPE_STAFF_SELLER);
                        List<PoiStoreStaff> poiStoreStaffs = poiStoreStaffDOMapper.selectList(staffQr);
                        if (CollectionUtils.isNotEmpty(poiStoreStaffs)){
                            for (PoiStoreStaff poiStoreStaff:poiStoreStaffs){
                                String url = poiStoreStaff.getEpWechatQrCode();
                                if (StringUtils.isBlank(url)){
                                    continue;
                                }
                                //下载图片
                                BufferedInputStream in = new BufferedInputStream(employeeService.getInputStream(url));
                                //字节流转图片对象
                                Image bi = ImageIO.read(in);
                                //构建图片流
                                BufferedImage tag = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
                                //绘制改变尺寸后的图
                                tag.getGraphics().drawImage(bi, 0, 0, 300, 300, null);
                                //输出流
                                BufferedOutputStream image = new BufferedOutputStream(new FileOutputStream(storeFile.getPath() +"/" +poiStoreStaff.getStaffCode() + ".png"));

                                ImageIO.write(tag, "PNG", image);

                                in.close();
                                image.close();
                            }
                        }
                    }
                }
            }

            //将根文件转换为zip文件
            ZipUtils.toZip(file.getPath(),out,true);

            //将文件输入到response
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            File zipFile = new File(strZipName);
            FileInputStream inStream = new FileInputStream(zipFile);
            int lenNew;
            while ((lenNew = inStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, lenNew);
            }
            //删除文件，清理空间
            file.delete();
            zipFile.delete();
        }
    }
    /**
     * 批量下载店铺导购吗
     * @param response
     */
    public void downloadStoreStaffCodeFromBSD(HttpServletResponse response) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //查询所有公司
        List<PrivilageOrganizational> privilageOrganizationals = retailCompanyMapper.selectList(null);
        if (CollectionUtils.isNotEmpty(privilageOrganizationals)){
            //根文件夹用于存放公司
            String fileUrl = "导购码-"+UUID.randomUUID().toString().replace("-", "");
            File file = new File(fileUrl);
            file.mkdir();
            // 生成的ZIP文件名
            String strZipName = "store_qrCode_"+ fileUrl +".zip";
            FileOutputStream out = new FileOutputStream(new File(strZipName));

            //遍历零售公司
            for (PrivilageOrganizational privilageOrganizational:privilageOrganizationals) {
                if (privilageOrganizational == null || privilageOrganizational.getId() == null){
                    continue;
                }

                //创建零售公司文件夹
                File complayFile = new File(file.getPath()+"/"+privilageOrganizational.getName());
                complayFile.mkdir();
                QueryWrapper<PrivilageOrganizational> customerWrap = new QueryWrapper<>();
                customerWrap.eq("status",1).eq("type",1).eq("level",3).eq("parent_id",privilageOrganizational.getId());
                List<PrivilageOrganizational> customerList = retailCompanyMapper.selectList(customerWrap);
                if (CollectionUtils.isNotEmpty(customerList)) {
                    List<Long> customerIds = customerList.stream().map(i -> i.getId()).collect(Collectors.toList());
                    //查询店铺
                    List<PoiStore> poiStores = poiStoreDOMapper.selectShopByCustomerIds(customerIds);
                    if (CollectionUtils.isNotEmpty(poiStores)){
                        //遍历店铺查询门店码url
                        for (PoiStore poiStore:poiStores){
                            //创建零售公司文件夹
                            File storeFile = new File(complayFile.getPath()+"/"+poiStore.getName());
                            storeFile.mkdir();

                            QueryWrapper<PoiStoreStaff> staffQr = new QueryWrapper();
                            staffQr.eq(DATABASE_STORE_ID_KEY,poiStore.getId());
                            staffQr.eq(DATABASE_TYPE_KEY,TYPE_STAFF_SELLER);
                            List<PoiStoreStaff> poiStoreStaffs = poiStoreStaffDOMapper.selectList(staffQr);
                            if (CollectionUtils.isNotEmpty(poiStoreStaffs)){
                                for (PoiStoreStaff poiStoreStaff:poiStoreStaffs){
                                    String cpUserId = privilageCpUserStoreDOMapper.selectCpUserIdByStoreId(poiStore.getId());
                                    if (StringUtils.isBlank(cpUserId)){
                                        continue;
                                    }
                                    Map<String,Object> params = new HashMap<>();
                                    params.put("userId",cpUserId);
                                    params.put("type",1);
                                    params.put("state",poiStoreStaff.getStaffCode());
                                    params.put("storeNo",poiStore.getCode());
                                    String get = HttpUtil.get("http://vtest.bsd.cn/BSD_WXAPP/qyWechat/getShareQRcode?token=BOSIDENG" + MD5FileUtil.getMD5String(sdf.format(new Date())), params);
                                    JSONObject saveAccountInputJSON = JSONObject.parseObject(get);
                                    BsdShareCodeResponse bsdResponse = saveAccountInputJSON.toJavaObject(BsdShareCodeResponse.class);

                                    String url = bsdResponse.getData();
                                    if (StringUtils.isBlank(url)){
                                        continue;
                                    }

                                    //下载图片
                                    BufferedInputStream in = new BufferedInputStream(employeeService.getInputStream(url));
                                    //字节流转图片对象
                                    Image bi = ImageIO.read(in);
                                    //构建图片流
                                    BufferedImage tag = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
                                    //绘制改变尺寸后的图
                                    tag.getGraphics().drawImage(bi, 0, 0, 300, 300, null);
                                    //输出流
                                    BufferedOutputStream image = new BufferedOutputStream(new FileOutputStream(storeFile.getPath() +"/" +poiStoreStaff.getStaffCode() + ".png"));

                                    ImageIO.write(tag, "PNG", image);

                                    in.close();
                                    image.close();
                                }
                            }
                        }
                    }
                }

            }

            //将根文件转换为zip文件
            ZipUtils.toZip(file.getPath(),out,true);

            //将文件输入到response
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            File zipFile = new File(strZipName);
            FileInputStream inStream = new FileInputStream(zipFile);
            int lenNew;
            while ((lenNew = inStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, lenNew);
            }
            //删除文件，清理空间
            file.delete();
            zipFile.delete();
        }
    }

    /**
     * 导入excel门店号
     * @param file excel文件
     * @return
     * @throws Exception
     */
    public List<ImportErrorDTO> importShopEmpByExcel(MultipartFile file) throws Exception {
        List<ImportErrorDTO> results = new ArrayList<>();
        if (file != null) {
            if (!file.isEmpty()) {
                //获取文件名
                String fileName = file.getOriginalFilename();
                InputStream fileInput = file.getInputStream();
                // 根据后缀创建EXCEL对象
                Workbook book;
                if (ExcelUtils.isExcel2007(fileName)) {
                    book = new XSSFWorkbook(fileInput);
                } else {
                    book = new HSSFWorkbook(fileInput);
                }

                // 得到第一个sheet
                Sheet sheet = book.getSheetAt(0);
                // 得到Excel的行数
                int totalRows = sheet.getPhysicalNumberOfRows();

                // 循环Excel行数,获取数据
                for (int r = 1; r < totalRows; r++) {
                    Row dataRow = sheet.getRow(r);
                    if (dataRow == null) {
                        continue;
                    }
                    addRowInfo(dataRow,results,r);
                }
            }
        }
        return results;
    }

    /**
     * Excel导入门店号-添加行信息
     * @param dataRow 行对象
     * @param results 错误信息集合
     * @param row 行数
     * @throws Exception
     */
    private void addRowInfo(Row dataRow,List<ImportErrorDTO> results,Integer row) throws Exception {
        //初始化导购对象
        EmployeeDO employeeDO = new EmployeeDO();
        //获取店铺名和店铺code
        String shopName = dataRow.getCell(0).getStringCellValue();
        if (StringUtils.isBlank(shopName)){
            getReason(row,"未填写店铺名",results);
            return;
        }
        String shopCode = dataRow.getCell(1).getStringCellValue();
        if (StringUtils.isBlank(shopCode)){
            getReason(row,"未填写店铺Code",results);
            return;
        }
        //查询店铺信息
        QueryWrapper<PoiStore> storeParams = new QueryWrapper<>();
        storeParams.eq(DATABASE_NAME_KEY,shopName);
        storeParams.eq(DATABASE_CODE_KEY,shopCode);
        PoiStore poiStore = poiStoreDOMapper.selectOne(storeParams);
        if (poiStore == null){
            getReason(row,"未找到店铺",results);
            return;
        }
        employeeDO.setStoreId(poiStore.getId());
        //获取企业微信账号（user_id）
        String cpUserId = dataRow.getCell(2).getStringCellValue();
        if (StringUtils.isBlank(cpUserId)){
            getReason(row,"未填写账号",results);
            return;
        }
        employeeDO.setUserId(cpUserId);

        //获取企业微信别名
        String align = dataRow.getCell(3).getStringCellValue();
        employeeDO.setAlias(align);

        //获取部门信息
        String departmentName = dataRow.getCell(4).getStringCellValue();
        if (StringUtils.isBlank(departmentName)){
            getReason(row,"未填写部门",results);
            return;
        }
        QueryWrapper<DepartmentDO> depParams = new QueryWrapper<DepartmentDO>();
        depParams.eq(DATABASE_NAME_KEY,departmentName);
        DepartmentDO departmentDO = departmentDOMapper.selectOne(depParams);
        if (departmentDO == null){
            getReason(row,"未找到部门",results);
            return;
        }
        Long[] depIds = new Long[1];
        depIds[0] = departmentDO.getId();
        employeeDO.setDepartIds(depIds);

        String mobile = dataRow.getCell(5).getStringCellValue();
        if (StringUtils.isBlank(mobile)){
            getReason(row,"未填写手机号",results);
            return;
        }
        employeeDO.setMobile(mobile);

        String returnCode = employeeService.addUser(employeeDO);
        if (returnCode.contains(ADD_CP_CODE_BINDED)){
            String[] split = returnCode.split("&");
            getReason(row,"该账号已绑定【"+ split[1] +"】店铺",results);
        }
    }

    /**
     * 添加错误原因
     * @param row 行数
     * @param reason 原因
     * @param results 错误集合
     */
    private void getReason(Integer row,String reason,List<ImportErrorDTO> results){
        ImportErrorDTO importErrorDTO = new ImportErrorDTO();
        importErrorDTO.setRow(row);
        reason = "第"+ row + "行导入失败，原因："+reason;
        importErrorDTO.setReason(reason);
        results.add(importErrorDTO);
    }
}
