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.KiisooException;
import com.kiisoo.ic.common.utils.ExcelUtils;
import com.kiisoo.ic.common.utils.MD5FileUtil;
import com.kiisoo.ic.common.utils.httpClientUtil.HttpClientUtil;
import com.kiisoo.ic.constants.Constants;
import com.kiisoo.ic.customer.entity.OpSellerCustomerRelation;
import com.kiisoo.ic.customer.mapper.OpSellerCustomerRelationDOMapper;
import com.kiisoo.ic.customer.service.CustomerViewService;
import com.kiisoo.ic.department.entity.DepartmentDO;
import com.kiisoo.ic.department.mapper.PrivilageDepartmentDOMapper;
import com.kiisoo.ic.domain.entity.PrivilageDomainDO;
import com.kiisoo.ic.domain.entity.PrivilageDomainEntityDO;
import com.kiisoo.ic.domain.mapper.PrivilageDomainDOMapper;
import com.kiisoo.ic.domain.mapper.PrivilageDomainEntityDOMapper;
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.entity.PoiStoreStaffDO;
import com.kiisoo.ic.employee.entity.PrivilageCpUserDO;
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.entity.PrivilageOrganizationalDomain;
import com.kiisoo.ic.generalize.mapper.PrivilageOrganizationalDomainMapper;
import com.kiisoo.ic.generalize.mapper.RetailCompanyMapper;
import com.kiisoo.ic.generalize.service.RetailCompanyService;
import com.kiisoo.ic.store.bean.*;
import com.kiisoo.ic.store.entity.PoiStore;
import com.kiisoo.ic.store.entity.PoiStoreStaff;
import com.kiisoo.ic.store.entity.PrivilageCpUserStoreDO;
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.system.bean.SaveAccountInput;
import com.kiisoo.ic.system.entity.PrivilageRoleDO;
import com.kiisoo.ic.system.entity.PrivilageUserDO;
import com.kiisoo.ic.system.enums.RoleEnum;
import com.kiisoo.ic.system.mapper.PrivilageRoleDOMapper;
import com.kiisoo.ic.system.mapper.PrivilageUserDOMapper;
import com.kiisoo.ic.system.service.PrivilageAccountService;
import com.kiisoo.ic.utils.ZipUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
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.List;
import java.util.*;
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
@Slf4j
public class StoreEmployeeService {

    @Autowired
    private PoiStoreDOMapper poiStoreDOMapper;

    @Autowired
    private PrivilageCpUserStoreDOMapper privilageCpUserStoreDOMapper;
    @Autowired
    private PrivilageAccountService privilageAccountService;
    @Autowired
    private PrivilageRoleDOMapper privilageRoleDOMapper;

    @Autowired
    private PrivilageDomainEntityDOMapper privilageDomainEntityDOMapper;

    @Autowired
    private RetailCompanyMapper retailCompanyMapper;

    @Autowired
    private PrivilageCpUserDOMapper privilageCpUserDOMapper;

    @Autowired
    private PoiStoreStaffDOMapper poiStoreStaffDOMapper;

    @Autowired
    private PoiStoreStaffService poiStoreStaffService;

    @Autowired
    private PrivilageDepartmentDOMapper departmentDOMapper;

    @Autowired
    private EmployeeService employeeService;

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

    /**
     * 组织表
     */
    @Autowired
    private RetailCompanyService retailCompanyService;

    /**
     * 客户数据概览service
     */
    @Autowired
    private CustomerViewService customerViewService;

    /**
     * 组织和域的关系表
     */
    @Autowired
    private PrivilageOrganizationalDomainMapper privilageOrganizationalDomainMapper;

    /**
     * 域
     */
    @Autowired
    private PrivilageDomainDOMapper privilageDomainDOMapper;

    /**
     * 用户
     */
    @Autowired
    private PrivilageUserDOMapper privilageUserDOMapper;


    @Value("${bsd.qrCode}")
    private String qrCodeBsdUrl;

    @Value("${bsd.cancelQrCode}")
    private String cancelQrCode;

    /**
     * 推广管理-列表，查询门店号
     *
     * @param userId      用户ID
     * @param storeId     店铺ID
     * @param bigRegionId 大区ID
     * @param companyId   公司ID
     * @param pageNum     页码
     * @param pageSize
     * @param code
     * @return
     * @throws Exception
     */
    public PageInfo<StoreUserDTO> listStoreUser(Long userId, Long storeId, Long bigRegionId, Long companyId, Integer pageNum, Integer pageSize, String code) throws Exception {
        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 (companyId != null) {
            shopIds = new ArrayList<>(customerViewService.getCompanyShop(companyId, userId));
            List<Long> userAllShops = privilageDomainService.listUserDatePermission(userId);
            shopIds.retainAll(userAllShops);
        } else if (bigRegionId != null) {
            shopIds = new ArrayList<>(customerViewService.getCompanyShop(bigRegionId, userId));
            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());
                }
                //客户orgId
                Long customerId = privilageDomainEntityDOMapper.selectDomainIdByShopEntity(cpUserStore.getId());

                if (customerId != null) {
                    PrivilageOrganizational customer = retailCompanyMapper.selectById(customerId);
                    PrivilageOrganizational company = retailCompanyMapper.selectById(customer.getParentId());
                    PrivilageOrganizational region = retailCompanyMapper.selectById(company.getParentId());

                    cpUserStore.setCompanyName(company.getName());
                    cpUserStore.setCompanyCode(company.getCode());
                    cpUserStore.setRegionName(region.getName());
                }


                String qrCodeAction = cpUserStore.getQrCodeAction();
                if (StringUtils.isBlank(qrCodeAction)) {
                    try {
                        qrCodeAction = getQrCodeFromBSD(cpUserStore.getCpUserId(), BSD_REQ_QRCODE_TYPE_STORE, "0", cpUserStore.getCode());
                        cpUserStore.setQrCodeAction(qrCodeAction);
                        PrivilageCpUserDO update = new PrivilageCpUserDO();
                        update.setId(cpUserStore.getUserId());
                        update.setQrCode(qrCodeAction);
                        privilageCpUserDOMapper.updateById(update);
                    } catch (Exception e) {
                        log.error("生成二维码失败:cpuserid-" + cpUserStore.getCpUserId(), e);
                    }
                }

                //查询导购数目
                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());
                List<OpSellerCustomerRelation> opRelations = opSellerCustomerRelationDOMapper.selectList(wrapper2);
                long count = opRelations.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
                cpUserStore.setCustomerNum((int) count);
            }
        }
        return new PageInfo<>(cpUserStoreDO);
    }


    /**
     * 获取波司登二维码
     *
     * @param cpUserId
     * @param type
     * @param state
     * @param storeNo
     * @return
     * @throws Exception
     */
    public String getQrCodeFromBSD(String cpUserId, String type, String state, String storeNo) throws Exception {
        String url = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> params = new HashMap<>();
        params.put("userId", cpUserId);
        params.put("type", type);
        params.put("state", state);
        params.put("storeNo", storeNo);
        String message = HttpClientUtil.httpPost(qrCodeBsdUrl + MD5FileUtil.getMD5String("BOSIDENG" + sdf.format(new Date())), JSONObject.toJSONString(params)).getMessage();
        log.info("cpUserId="+cpUserId + "type=" + type + "state=" + state + "storeNo=" + storeNo + "getQrCodeFromBSD " + message);
        JSONObject qrCodeJson = JSONObject.parseObject(message);
        BsdShareCodeResponse bsdResponse = qrCodeJson.toJavaObject(BsdShareCodeResponse.class);
        if (bsdResponse.getSuccess() && StringUtils.isNotBlank(bsdResponse.getData())) {
            url = bsdResponse.getData();
        } else {
          log.error("cpUserId="+cpUserId + "type=" + type + "state=" + state + "storeNo=" + storeNo + "getQrCodeFromBSD 二维码生成失败 " + message);
        }
        return url;
    }


    /**
     * 获取波司登二维码
     *
     * @param cpUserId
     * @param type
     * @param state
     * @param storeNo
     * @return
     * @throws Exception
     */
    public BsdShareCodeResponse getQrCodeFromBSDNew(String cpUserId, String type, String state, String storeNo) throws Exception {
        String url = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> params = new HashMap<>();
        params.put("userId", cpUserId);
        params.put("type", type);
        params.put("state", state);
        params.put("storeNo", storeNo);
        String message = HttpClientUtil.httpPost(qrCodeBsdUrl + MD5FileUtil.getMD5String("BOSIDENG" + sdf.format(new Date())), JSONObject.toJSONString(params)).getMessage();
        JSONObject qrCodeJson = JSONObject.parseObject(message);
        BsdShareCodeResponse bsdResponse = qrCodeJson.toJavaObject(BsdShareCodeResponse.class);
        return bsdResponse;
    }


    /**
     * 批量下载店铺二维码
     *
     * @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();
        }
    }

    /**
     * 批量下载店铺二维码
     */
    public void downloadStoreUserCodeFromBSD(HttpServletResponse response) throws Exception {
        File zipFile = new File("store_qrCode.zip");
        if (zipFile.exists()) {
            zipFile.delete();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //查询所有公司
        QueryWrapper<PrivilageOrganizational> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1).eq("type", 2).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.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", 2).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;
                            }
                            QueryWrapper<PrivilageCpUserDO> userQw = new QueryWrapper<>();
                            userQw.eq("cp_user_id", cpUserId).last("limit 1");
                            PrivilageCpUserDO privilageCpUserDO = privilageCpUserDOMapper.selectOne(userQw);

                            String url = "";
                            if (privilageCpUserDO != null) {
                                url = privilageCpUserDO.getQrCode();
                            }
                            if (StringUtils.isBlank(url)) {
                                try {
                                    url = getQrCodeFromBSD(cpUserId, BSD_REQ_QRCODE_TYPE_STORE, "0", poiStore.getCode());
                                    privilageCpUserDO.setQrCode(url);
                                    int update = privilageCpUserDOMapper.updateById(privilageCpUserDO);
                                } catch (Exception e) {
                                    log.error("生成二维码失败:cpuserid-" + cpUserId, e);
                                    continue;
                                }
                            }
                            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);

            //删除文件，清理空间
            deleteDir(file.getAbsolutePath());
            System.out.println("门店码生成成功");

            //将文件输入到response
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            FileInputStream inStream = new FileInputStream(zipFile);
            int lenNew;
            while ((lenNew = inStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, lenNew);
            }
            outputStream.flush();
            outputStream.close();
            zipFile.delete();
        }
    }

    /**
     * 批量下载店铺二维码
     *
     * @param response
     */
    public void exportStoreExcel(HttpServletResponse response, Long userId, Long regionId, Long companyId, Long storeId, String code) throws Exception {
        List<StoreUserDTO> results = new ArrayList<>();
        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 (companyId != null) {
            shopIds = new ArrayList<>(customerViewService.getCompanyShop(companyId, userId));
            List<Long> userAllShops = privilageDomainService.listUserDatePermission(userId);
            shopIds.retainAll(userAllShops);
        } else if (regionId != null) {
            shopIds = new ArrayList<>(customerViewService.getCompanyShop(regionId, userId));
            List<Long> userAllShops = privilageDomainService.listUserDatePermission(userId);
            shopIds.retainAll(userAllShops);
        } else {
            //查询用户权限店铺
            shopIds = new ArrayList<>(privilageDomainService.listUserDatePermission(userId));
        }
        long s = System.currentTimeMillis();
        System.out.println(s);
        List<StoreUserDTO> cpUserStoreDO = privilageCpUserStoreDOMapper.selectCpUserByShops(shopIds);
        if (CollectionUtils.isNotEmpty(cpUserStoreDO)) {
            int orderNum = 0;
            for (StoreUserDTO cpUserStore : cpUserStoreDO) {
                //设置序号
                cpUserStore.setOrderNum(++orderNum);
                //客户orgId
                Long customerId = privilageDomainEntityDOMapper.selectDomainIdByShopEntity(cpUserStore.getId());

                if (customerId != null) {
                    PrivilageOrganizational customer = retailCompanyMapper.selectById(customerId);
                    PrivilageOrganizational company = retailCompanyMapper.selectById(customer.getParentId());
                    PrivilageOrganizational region = retailCompanyMapper.selectById(company.getParentId());

                    cpUserStore.setCompanyName(company.getName());
                    cpUserStore.setCompanyCode(company.getCode());
                    cpUserStore.setRegionName(region.getName());
                }

//                String qrCodeAction = cpUserStore.getQrCodeAction();
//                if (StringUtils.isBlank(qrCodeAction)){
//                    qrCodeAction = getQrCodeFromBSD(cpUserStore.getCpUserId(),BSD_REQ_QRCODE_TYPE_STORE,"0",cpUserStore.getCode());
//                    cpUserStore.setQrCodeAction(qrCodeAction);
//                    PrivilageCpUserDO update = new PrivilageCpUserDO();
//                    update.setId(cpUserStore.getUserId());
//                    update.setQrCode(qrCodeAction);
//                    privilageCpUserDOMapper.updateById(update);
//                }

                //查询导购数目
                List<Long> shops = Arrays.asList(cpUserStore.getId());
                Integer staffNum = poiStoreStaffDOMapper.selectSellersByShopIdsCount(shops);
                cpUserStore.setStaffNum(staffNum);
                //客户数
                QueryWrapper<OpSellerCustomerRelation> wrapper2 = new QueryWrapper<>();
                wrapper2.eq("store_id", cpUserStore.getId());
                Integer opRelations = opSellerCustomerRelationDOMapper.selectCount(wrapper2);
//                long count = opRelations.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
                cpUserStore.setCustomerNum(opRelations);

                results.add(cpUserStore);
            }
        }

        System.out.println(s - System.currentTimeMillis());

        if (CollectionUtils.isNotEmpty(results)) {
            createStoreUserExcel(results, response);
        }

        System.out.println(s - System.currentTimeMillis());

    }

    public void createStoreUserExcel(List<StoreUserDTO> results, HttpServletResponse response) throws IOException {
        String[] headNames = new String[]{"序号", "店铺名", "店铺编号", "门店企业号", "大区名", "零售公司", "零售公司编号", "员工数", "客户数"};
        HSSFWorkbook ws = new HSSFWorkbook();
        Sheet hssfSheet = ws.createSheet("推广管理");
        HSSFCellStyle cellStyle = ws.createCellStyle();
        cellStyle.setWrapText(true);//设置自动换行
        int isAdd = 0;
        //设置列名
        if (null != headNames && headNames.length > 0) {

            Row row = hssfSheet.createRow(isAdd++);
            for (int i = 0; i < headNames.length; i++) {

                String name = headNames[i];
                Cell cell = row.createCell(i);
                cell.setCellValue(name);
            }
        }

        for (int i = 0; i < results.size(); i++) {
            //创造行
            Row row = hssfSheet.createRow(isAdd++);
            StoreUserDTO cpUserExcelDTO = results.get(i);
            Cell orderCell = row.createCell(0);
            orderCell.setCellValue(i + 1 + "");
            Cell reginCell = row.createCell(1);
            reginCell.setCellValue(cpUserExcelDTO.getName());
            Cell companyNameCell = row.createCell(2);
            companyNameCell.setCellValue(cpUserExcelDTO.getCode());
            Cell companyCodeCell = row.createCell(3);
            companyCodeCell.setCellValue(cpUserExcelDTO.getCpUserId());
            Cell storeNameCell = row.createCell(4);
            storeNameCell.setCellValue(cpUserExcelDTO.getRegionName());
            Cell storeCodeCell = row.createCell(5);
            storeCodeCell.setCellValue(cpUserExcelDTO.getCompanyName());
            Cell cpUserIdCell = row.createCell(6);
            cpUserIdCell.setCellValue(cpUserExcelDTO.getCompanyCode());
            Cell nameCell = row.createCell(7);
            nameCell.setCellValue(cpUserExcelDTO.getStaffNum());
            Cell aliasCell = row.createCell(8);
            aliasCell.setCellValue(cpUserExcelDTO.getCustomerNum());
        }
        OutputStream output = response.getOutputStream();
        response.setHeader("Content-disposition", "attachment; filename=store.xls");
        response.setContentType("application/vnd.ms-excel");
        ws.write(output);
        ws.close();
    }


    /**
     * 批量下载店铺导购吗
     */
    public void downloadStoreStaffCodeFromBSD(HttpServletResponse response) throws Exception {
        File zipFile = new File("seller_qrCode.zip");
        if (zipFile.exists()) {
            zipFile.delete();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //查询所有公司
        //查询所有公司
        QueryWrapper<PrivilageOrganizational> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1).eq("type", 2).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 = "seller_qrCode.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", 2).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;
                                    }
                                    String url = poiStoreStaff.getEpWechatQrCode();
                                    if (StringUtils.isBlank(url)) {
                                        try {
                                            if (poiStoreStaff.getType() == 1L){
                                                url = getQrCodeFromBSD(poiStoreStaff.getStaffCode(), BSD_REQ_QRCODE_TYPE_SELLER, poiStoreStaff.getStaffCode(), poiStore.getCode());
                                            }else{
                                                url = getQrCodeFromBSD(cpUserId, BSD_REQ_QRCODE_TYPE_SELLER, poiStoreStaff.getStaffCode(), poiStore.getCode());
                                            }
                                            poiStoreStaff.setEpWechatQrCode(url);
                                            poiStoreStaffDOMapper.updateById(poiStoreStaff);
                                        } catch (Exception e) {
                                            log.error("生成二维码失败:cpuserid-" + cpUserId + "--staffCode-" + poiStoreStaff.getStaffCode(), e);
                                            continue;
                                        }
                                    }
                                    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);

            //删除文件，清理空间
            deleteDir(file.getAbsolutePath());
            System.out.println("导购码生成成功");

            //将文件输入到response
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            FileInputStream inStream = new FileInputStream(zipFile);
            int lenNew;
            while ((lenNew = inStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, lenNew);
            }
            outputStream.flush();
            outputStream.close();
            zipFile.delete();
        }
    }

    /**
     * 迭代删除文件夹
     * @param dirPath 文件夹路径
     */
    public static void deleteDir(String dirPath)
    {
        File file = new File(dirPath);
        if(file.isFile())
        {
            file.delete();
        }else
        {
            File[] files = file.listFiles();
            if(files == null)
            {
                file.delete();
            }else
            {
                for (int i = 0; i < files.length; i++)
                {
                    deleteDir(files[i].getAbsolutePath());
                }
                file.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 file excel文件
     * @return
     * @throws Exception
     */
    public List<ImportErrorDTO> importShopStaffByExcel(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;
                    }
                    addRowStaffInfo(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);
        }
    }

    /**
     * Excel导入门店员工-添加行信息
     *
     * @param dataRow 行对象
     * @param results 错误信息集合
     * @param row     行数
     * @throws Exception
     */
    private void addRowStaffInfo(Row dataRow, List<ImportErrorDTO> results, Integer row) throws Exception {
        //初始化导购对象
        com.kiisoo.ic.store.entity.PoiStoreStaffVO poiStoreStaffVO = new com.kiisoo.ic.store.entity.PoiStoreStaffVO();
        //店铺code
        dataRow.getCell(0).setCellType(CellType.STRING);
        String shopCode = dataRow.getCell(0).getStringCellValue();
        if (StringUtils.isBlank(shopCode)) {
            getReason(row, "未填写店铺Code", results);
            return;
        }
        //查询店铺信息
        QueryWrapper<PoiStore> storeParams = new QueryWrapper<>();
        storeParams.eq(DATABASE_CODE_KEY, shopCode).last("limit 1");
        PoiStore poiStore = poiStoreDOMapper.selectOne(storeParams);
        if (poiStore == null) {
            getReason(row, "未找到店铺", results);
            return;
        }
        poiStoreStaffVO.setStoreId(poiStore.getId());

        //获取员工名
        dataRow.getCell(1).setCellType(CellType.STRING);
        String name = dataRow.getCell(1).getStringCellValue();
        if (StringUtils.isBlank(name)) {
            getReason(row, "未填写推广人员名称", results);
            return;
        }
        poiStoreStaffVO.setName(name);

        dataRow.getCell(2).setCellType(CellType.STRING);
        String mobile = dataRow.getCell(2).getStringCellValue();
        if (StringUtils.isBlank(mobile)) {
            getReason(row, "未填写手机号", results);
            return;
        }
        poiStoreStaffVO.setMobil(mobile);

        dataRow.getCell(3).setCellType(CellType.STRING);
        String staffCode = dataRow.getCell(3).getStringCellValue();
        if (StringUtils.isBlank(staffCode)) {
            getReason(row, "未填写工号", results);
            return;
        }
        poiStoreStaffVO.setStaffCode(staffCode);

        dataRow.getCell(4).setCellType(CellType.STRING);
        String roleCode = dataRow.getCell(4).getStringCellValue();
        if (StringUtils.isBlank(roleCode)) {
            getReason(row, "未填写角色", results);
            return;
        }
        poiStoreStaffVO.setRole(roleCode);

        if ("DZ-DIANZHANG".equals(roleCode)) {
            poiStoreStaffVO.setType(1L);
        }else{
            poiStoreStaffVO.setType(4L);
        }

        String returnCode = poiStoreStaffService.addStaff(poiStoreStaffVO);
        switch (returnCode){
            case "0001":
                getReason(row, "新增失败，请联系管理员", results);
                return;
            case "0002":
                getReason(row, "该员工已存在", results);
                return;
            case "0003":
                getReason(row, "该手机号已存在", results);
                return;
            case "0004":
                getReason(row, "该账号已存在", results);
                return;
            default:
                return;
        }
    }

    /**
     * 添加错误原因
     *
     * @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);
    }


    /**
     * 作废波司登分享二维码
     *
     * @param cpUserId 用户ID
     * @param state    场景
     * @return 返回是否成功
     * @throws Exception 异常
     * @author dexiang.jiang
     * @date 2020/05/05 17:24
     */
    public boolean cancelQrCodeFromBSD(String cpUserId, String state) {
        String url = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> params = new HashMap<>();
        params.put("userId", cpUserId);
        params.put("state", state);
        String message = HttpClientUtil.httpPost(cancelQrCode + MD5FileUtil.getMD5String("BOSIDENG" + sdf.format(new Date())), JSONObject.toJSONString(params)).getMessage();
        JSONObject qrCodeJson = JSONObject.parseObject(message);
        log.error("cpUserId="+cpUserId + "state=" + state + "cancelQrCodeFromBSD" + message);
        BsdShareCodeResponse bsdResponse = qrCodeJson.toJavaObject(BsdShareCodeResponse.class);
        if (null == bsdResponse) {
            return false;
        }
        return bsdResponse.getSuccess();
    }

    /**
     * 作废波司登分享二维码
     *
     * @param cpUserId 用户ID
     * @param state    场景
     * @return 返回是否成功
     * @throws Exception 异常
     * @author dexiang.jiang
     * @date 2020/05/05 17:24
     */
    public String cancelQrCodeFromBSDNew(String cpUserId, String state) {
        String url = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> params = new HashMap<>();
        params.put("userId", cpUserId);
        params.put("state", state);
        String message = HttpClientUtil.httpPost(cancelQrCode + MD5FileUtil.getMD5String("BOSIDENG" + sdf.format(new Date())), JSONObject.toJSONString(params)).getMessage();
        log.error("cpUserId="+cpUserId + "state=" + state + "cancelQrCodeFromBSD" + message);
        return message;
    }

    /**
     * 添加组织 大区
     *
     * @param name 名称
     * @param code 编码
     * @author dexiang.jiang
     * @date 2020/05/20 14:57
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean addOrganizationalByRegion(String name, String code) throws KiisooException {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("code", code);
        map.put("level", 1);
        List<PrivilageOrganizational> list = retailCompanyMapper.selectByMap(map);
        if (CollectionUtils.isNotEmpty(list) && list.size() > 0) {
            throw new KiisooException(Constants.MSG_ORGANIZATIONAL_HAS, Constants.CODE_ORGANIZATIONAL_HAS);
        }

        PrivilageOrganizational entity = new PrivilageOrganizational();
        entity.setName(name);
        entity.setCode(code);
        entity.setParentId(0L);
        entity.setLevel(1L);
        entity.setStatus(1L);
        entity.setType(1L);
        entity.setCreateBy(Constants.SYS_OPERATION);
        entity.setUpdateBy(Constants.SYS_OPERATION);
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        int b = retailCompanyMapper.insert(entity);

        return b > 0;
    }

    /**
     * 添加组织
     *
     * @param name 名称
     * @param code 编码
     * @author dexiang.jiang
     * @date 2020/05/20 14:57
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean addOrganizationalByCode(String name, String code, String parentCode, Long level) throws KiisooException {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("code", code);
        map.put("level", level);
        List<PrivilageOrganizational> list = retailCompanyMapper.selectByMap(map);
        if (CollectionUtils.isNotEmpty(list) && list.size() > 0) {
            throw new KiisooException(Constants.MSG_ORGANIZATIONAL_HAS, Constants.CODE_ORGANIZATIONAL_HAS);
        }

        Map<String, Object> cMap = new HashMap<>();
        cMap.put("code", parentCode);
        List<PrivilageOrganizational> companyList = retailCompanyMapper.selectByMap(cMap);
        if (CollectionUtils.isEmpty(companyList)) {
            throw new KiisooException(Constants.MSG_ORGANIZATIONAL_HAS, Constants.CODE_ORGANIZATIONAL_HAS);
        }

        PrivilageOrganizational item = companyList.get(0);

        PrivilageOrganizational entity = new PrivilageOrganizational();
        entity.setName(name);
        entity.setCode(code);
        entity.setParentId(item.getId());
        entity.setLevel(level);
        entity.setStatus(1L);
        entity.setType(1L);
        entity.setCreateBy(Constants.SYS_OPERATION);
        entity.setUpdateBy(Constants.SYS_OPERATION);
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        int b = retailCompanyMapper.insert(entity);

        if (level == 3) {
            //添加客户多了2步骤
            Map<String, Object> domainEntityMap = new HashMap<>();
            domainEntityMap.put("name", name);
            List<PrivilageDomainDO> domainList = privilageDomainDOMapper.selectByMap(domainEntityMap);
            if (domainList.size() > 1) {
                throw new KiisooException(Constants.MSG_DOMAIN_ENTITY_HAS, Constants.CODE_DOMAIN_ENTITY_HAS);
            }
            //添加域
            PrivilageDomainDO domainEntity = new PrivilageDomainDO();
            domainEntity.setName(name);
            domainEntity.setStatus(1);
            domainEntity.setCreateTime(new Date());
            domainEntity.setUpdateTime(new Date());
            domainEntity.setCreateBy(Constants.SYS_OPERATION);
            domainEntity.setUpdateBy(Constants.SYS_OPERATION);
            int b2 = privilageDomainDOMapper.insert(domainEntity);
            //添加域和组织的关系
            PrivilageOrganizationalDomain orgDomainEntity = new PrivilageOrganizationalDomain();
            orgDomainEntity.setOrgId(entity.getId());
            orgDomainEntity.setDomainId(domainEntity.getId());
            int b3 = privilageOrganizationalDomainMapper.insert(orgDomainEntity);
            return (b + b2 + b3) == 3;
        } else {
            return b > 0;
        }
    }
   /**
     * 添加组织
     * @param name 名称
     * @param alias 别名
     * @param cpUserId 账号
     * @param storeCode 店铺编码
     * @author yechenhao
     * @date 2020/05/20 14:57
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean addCpUserIdByCode(String name, String alias, String cpUserId, String storeCode)  throws KiisooException {
        //查询店铺code
        QueryWrapper<PoiStore> storeQw = new QueryWrapper<>();
        storeQw.eq("code",storeCode).last("limit 1");
        PoiStore poiStore = poiStoreDOMapper.selectOne(storeQw);
        if (poiStore == null){
            throw new KiisooException(Constants.MSG_STORE_NONE, Constants.CODE_STORE_NONE);
        }
        //查询账号是否存在
        QueryWrapper<PrivilageCpUserDO> cpUserQw = new QueryWrapper<>();
        cpUserQw.eq("cp_user_id",cpUserId).last("limit 1");
        PrivilageCpUserDO privilageCpUserDO = privilageCpUserDOMapper.selectOne(cpUserQw);
        PrivilageCpUserStoreDO privilageCpUserStoreDO;
        QueryWrapper<PrivilageCpUserStoreDO> cpUserRelationQwByStore = new QueryWrapper<>();
        cpUserRelationQwByStore.eq("store_id",poiStore.getId()).last("limit 1");
        privilageCpUserStoreDO = privilageCpUserStoreDOMapper.selectOne(cpUserRelationQwByStore);
//        if (privilageCpUserStoreDO != null){
//            throw new KiisooException(Constants.MSG_DOMAIN_ENTITY_HAS, Constants.CODE_DOMAIN_ENTITY_HAS);
//        }
        if (privilageCpUserDO != null){
            //查询关系是否存在
            QueryWrapper<PrivilageCpUserStoreDO> cpUserRelationQwByCpUser = new QueryWrapper<>();
            cpUserRelationQwByCpUser.eq("cp_user_id",privilageCpUserDO.getId()).last("limit 1");
            privilageCpUserStoreDO = privilageCpUserStoreDOMapper.selectOne(cpUserRelationQwByCpUser);
//            if (privilageCpUserStoreDO != null){
//                throw new KiisooException(Constants.MSG_DOMAIN_ENTITY_HAS, Constants.CODE_DOMAIN_ENTITY_HAS);
//            }
            privilageCpUserDO.setStatus(1);
            privilageCpUserDO.setName(name);
            privilageCpUserDO.setAlias(alias);
            privilageCpUserDO.setCpUserId(cpUserId);
            privilageCpUserDO.setMobile(cpUserId);
            privilageCpUserDO.setPosition("店长");
            privilageCpUserDOMapper.updateById(privilageCpUserDO);
        }else{
            privilageCpUserDO = new PrivilageCpUserDO();
            privilageCpUserDO.setStatus(1);
            privilageCpUserDO.setName(name);
            privilageCpUserDO.setAlias(alias);
            privilageCpUserDO.setCpUserId(cpUserId);
            privilageCpUserDO.setMobile(cpUserId);
            privilageCpUserDO.setPosition("店长");
            privilageCpUserDOMapper.insert(privilageCpUserDO);
        }

        if(null == privilageCpUserStoreDO){
            privilageCpUserStoreDO = new PrivilageCpUserStoreDO();
            privilageCpUserStoreDO.setStoreId(poiStore.getId());
            privilageCpUserStoreDO.setCpUserId(privilageCpUserDO.getId());
            int insert = privilageCpUserStoreDOMapper.insert(privilageCpUserStoreDO);
            if (insert == 0){
                throw new KiisooException(Constants.MSG_INSERT_ERROR, Constants.CODE_INSERT_ERROR);
            }
        }

        SaveAccountInput saveAccountInput = new SaveAccountInput();
        saveAccountInput.setAccount(cpUserId);
        saveAccountInput.setPassword(cpUserId);
        saveAccountInput.setMobil(cpUserId);
        QueryWrapper<PrivilageRoleDO> roleQw = new QueryWrapper<>();
        roleQw.eq("code", RoleEnum.ROLE_CODE_DZ.getRoleCode()).last("limit 1");
        PrivilageRoleDO privilageRoleDO = privilageRoleDOMapper.selectOne(roleQw);
        saveAccountInput.setRoleId(privilageRoleDO.getId());
        saveAccountInput.setConfirmPassword(cpUserId);
        saveAccountInput.setStaffCode(cpUserId);
        saveAccountInput.setUserName(name);
        saveAccountInput.setType(1L);
        saveAccountInput.setShopId(poiStore.getId());
        String saveReturnCode = privilageAccountService.saveAccount(saveAccountInput);
        if (!"0000".equals(saveReturnCode)){
            throw new KiisooException(Constants.MSG_INSERT_ERROR, Constants.CODE_INSERT_ERROR);
        }
        return true;
    }

    /**
     * 添加组织
     *
     * @param name 名称
     * @param code 编码
     * @author dexiang.jiang
     * @date 2020/05/20 14:57
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean addOrganizational(String name, String code, Long parentId, Long level) throws KiisooException {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("code", code);
        map.put("level", level);
        List<PrivilageOrganizational> list = retailCompanyMapper.selectByMap(map);
        if (CollectionUtils.isNotEmpty(list) && list.size() > 0) {
            throw new KiisooException(Constants.MSG_ORGANIZATIONAL_HAS, Constants.CODE_ORGANIZATIONAL_HAS);
        }

        PrivilageOrganizational entity = new PrivilageOrganizational();
        entity.setName(name);
        entity.setCode(code);
        entity.setParentId(parentId);
        entity.setLevel(level);
        entity.setStatus(1L);
        entity.setType(1L);
        entity.setCreateBy(Constants.SYS_OPERATION);
        entity.setUpdateBy(Constants.SYS_OPERATION);
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        int b = retailCompanyMapper.insert(entity);

        if (level == 3) {
            //添加客户多了2步骤
            Map<String, Object> domainEntityMap = new HashMap<>();
            domainEntityMap.put("name", name);
            List<PrivilageDomainDO> domainList = privilageDomainDOMapper.selectByMap(domainEntityMap);
            if (domainList.size() > 1) {
                throw new KiisooException(Constants.MSG_DOMAIN_ENTITY_HAS, Constants.CODE_DOMAIN_ENTITY_HAS);
            }
            //添加域
            PrivilageDomainDO domainEntity = new PrivilageDomainDO();
            domainEntity.setName(name);
            domainEntity.setStatus(1);
            domainEntity.setCreateTime(new Date());
            domainEntity.setUpdateTime(new Date());
            domainEntity.setCreateBy(Constants.SYS_OPERATION);
            domainEntity.setUpdateBy(Constants.SYS_OPERATION);
            int b2 = privilageDomainDOMapper.insert(domainEntity);
            //添加域和组织的关系
            PrivilageOrganizationalDomain orgDomainEntity = new PrivilageOrganizationalDomain();
            orgDomainEntity.setOrgId(entity.getId());
            orgDomainEntity.setDomainId(domainEntity.getId());
            int b3 = privilageOrganizationalDomainMapper.insert(orgDomainEntity);
            return (b + b2 + b3) == 3;
        } else {
            return b > 0;
        }
    }

    /**
     * 添加店铺
     *
     * @param poiStore 店铺对象
     * @return 返回 true成功  false失败
     * @throws KiisooException 异常
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean addStore(PoiStoreVO poiStore) throws KiisooException {

        Map<String, Object> map = new HashMap<>();
        map.put("code", poiStore.getCode());
        List<PoiStore> list = poiStoreDOMapper.selectByMap(map);
        if (CollectionUtils.isNotEmpty(list) && list.size() > 0) {
            throw new KiisooException(Constants.MSG_STORE_HAS, Constants.CODE_STORE_HAS);
        }

        int b = poiStoreDOMapper.insert(poiStore);

        //查看是否有客户
        QueryWrapper<PrivilageOrganizational> orgQw =  new QueryWrapper<>();
        orgQw.eq("name",poiStore.getCustomerName());
        orgQw.eq("code",poiStore.getCustomerCode());
        orgQw.eq("level",3L);
        PrivilageOrganizational parent = retailCompanyMapper.selectOne(orgQw);
        if (null == parent) {
            throw new KiisooException(Constants.MSG_ORGANIZATIONAL_NO, Constants.CODE_ORGANIZATIONAL_NO);
        }

        Map<String, Object> domainMap = new HashMap<>();
        domainMap.put("org_id", parent.getId());
        List<PrivilageOrganizationalDomain> domainList = privilageOrganizationalDomainMapper.selectByMap(domainMap);

        if (CollectionUtils.isEmpty(domainList)) {
            throw new KiisooException(Constants.MSG_ORGANIZATIONAL_NO, Constants.CODE_ORGANIZATIONAL_NO);
        }

        PrivilageOrganizationalDomain domain = domainList.get(0);

        //找到区域域
        Map<String, Object> domainEntityMap = new HashMap<>();
        domainEntityMap.put("entity_id", poiStore.getId());
        domainEntityMap.put("domain_id", domain.getDomainId());
        List<PrivilageDomainEntityDO> domainEntityList = privilageDomainEntityDOMapper.selectByMap(domainEntityMap);
        if (domainEntityList.size() > 0) {
            throw new KiisooException(Constants.MSG_DOMAIN_ENTITY_HAS, Constants.CODE_DOMAIN_ENTITY_HAS);
        }

        PrivilageDomainEntityDO privilageDomainEntityDO = new PrivilageDomainEntityDO();
        privilageDomainEntityDO.setDomainId(domain.getDomainId());
        privilageDomainEntityDO.setEntityId(poiStore.getId());
        privilageDomainEntityDO.setType(3);
        privilageDomainEntityDO.setCreateTime(new Date());
        privilageDomainEntityDO.setUpdateTime(new Date());
        privilageDomainEntityDO.setCreateBy(Constants.SYS_OPERATION);
        privilageDomainEntityDO.setUpdateBy(Constants.SYS_OPERATION);
        int b2 = privilageDomainEntityDOMapper.insert(privilageDomainEntityDO);

        return (b + b2) == 2;
    }


    /**
     * 添加店铺人员
     *
     * @param poiStoreStaffVO 店铺对象
     * @return 返回 true成功  false失败
     * @throws KiisooException 异常
     * @author dexiang.jiang
     * @date 2020/05/20 22:56
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean addStoreStaff(PoiStoreStaffVO poiStoreStaffVO) throws KiisooException {

        //查看店铺
        if (poiStoreStaffVO.getStoreCode() == null) {
            throw new KiisooException(Constants.MSG_STORE_NO, Constants.CODE_STORE_NO);
        }

        if (poiStoreStaffVO.getStaffCode() == null) {
            throw new KiisooException(Constants.MSG_STAFF_NO, Constants.CODE_STORE_NO);
        }

        PoiStore poiStore = new PoiStore();
        poiStore.setCode(poiStoreStaffVO.getStoreCode());
        PoiStore shop = poiStoreDOMapper.selectOne(new QueryWrapper<>(poiStore));
        if (null == shop) {
            throw new KiisooException(Constants.MSG_STORE_NO_HAS, Constants.CODE_STORE_NO_HAS);
        }

        //查看用户
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("mobil", poiStoreStaffVO.getStaffCode());
        List<PrivilageUserDO> userList = privilageUserDOMapper.selectByMap(userMap);

        if (userList.size() > 0) {
            throw new KiisooException(Constants.MSG_USER_HAS, Constants.CODE_USER_HAS);
        }

        PrivilageUserDO us = new PrivilageUserDO();
        us.setName(shop.getName());
        us.setMobil(poiStoreStaffVO.getMobil());
        us.setEmail("");
        us.setAddress("");
        us.setStatus(1);
        us.setAbbreviation(shop.getAbbreviation());
        us.setCreateTime(new Date());
        us.setUpdateTime(new Date());
        us.setCreateBy(Constants.SYS_OPERATION);
        us.setUpdateBy(Constants.SYS_OPERATION);
        int b = privilageUserDOMapper.insert(us);

        //店涨需要加staff
        PoiStoreStaff p = new PoiStoreStaff();
        p.setStoreId(shop.getId());
        p.setUserId(us.getId());
        p.setStoreCode(shop.getCode());
        p.setStaffCode(poiStoreStaffVO.getStaffCode());
        p.setType(1L);// 1、店长类型
        p.setStatus(1L);
        p.setCreateTime(new Date());
        p.setUpdateTime(new Date());

        Map<String, Object> staffMap = new HashMap<>();
        staffMap.put("store_code", p.getStoreCode());
        staffMap.put("staff_code", p.getStaffCode());
        staffMap.put("type", p.getType());
        staffMap.put("status", p.getStatus());
        List<PoiStoreStaff> staffList = poiStoreStaffDOMapper.selectByMap(staffMap);
        if (staffList.size() > 0) {
            throw new KiisooException(Constants.MSG_STORE_STAFF_HAS, Constants.CODE_STORE_STAFF_HAS);
        }

        int b2 = poiStoreStaffDOMapper.insert(p);

        //店长，需要绑定店铺cp
        //排重---根据企业微信账号查询是否存在用户
        PrivilageCpUserDO privilageCpUserDO = new PrivilageCpUserDO();
        privilageCpUserDO.setCpUserId(p.getStaffCode());
        privilageCpUserDO.setStatus(1);
        privilageCpUserDO.setMobile(p.getStaffCode());
        privilageCpUserDO.setName(poiStoreStaffVO.getStoreName());
        privilageCpUserDO.setAlias(poiStoreStaffVO.getStoreAlias());

        Map<String, Object> map = new HashMap<>();
        // 客户ID
        map.put("cp_user_id", p.getCustomerUserId());
        map.put("status", privilageCpUserDO.getStatus());
        List<PrivilageCpUserDO> list = privilageCpUserDOMapper.selectByMap(map);
        if (list.size() > 0) {
            throw new KiisooException(Constants.MSG_STORE_STAFF_HAS, Constants.CODE_STORE_STAFF_HAS);
        }

        int b3 = privilageCpUserDOMapper.insert(privilageCpUserDO);

        PrivilageCpUserStoreDO cpUserStore = new PrivilageCpUserStoreDO();
        cpUserStore.setStoreId(shop.getId());
        cpUserStore.setCpUserId(privilageCpUserDO.getId());
        int b4 = privilageCpUserStoreDOMapper.insert(cpUserStore);

        return (b + b2 + b3 + b4) == 4;
    }

    /**
     * 生成活动码
     * @param cpUserId 企业微信账号
     * @param storeCode 店铺编码
     * @param type 推广员:  1、导购 2、店铺 3、推广员
     * @param instanceId 活动实例id
     * @param promoterId 推广员ID 如果是导购， 对应导购的id, 如果是店铺 对应店铺id, 如果是推广员，对应推广员id
     * @return 返回 活动码地址、失败为空
     * @throws Exception 异常
     * @author dexiang.jiang
     * @date 2020/05/21 15:01
     */
    public String createActivityQrCode(String cpUserId, String storeCode,int type ,Long instanceId, Long promoterId) throws Exception {
        String state = Constants.ACTIVITY_QR_CODE_PREFIX + Constants.LINE + instanceId + Constants.LINE + type + Constants.LINE + promoterId;
        return getQrCodeFromBSD(cpUserId, BSD_REQ_QRCODE_TYPE_ACTIVITY, state, storeCode);
    }
}
