package com.zfire.mall.manager.logic.common;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zfire.mall.manager.bean.MainBean;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.admin.respDto.AdminWebsitDto;
import com.zfire.mall.manager.bean.direct.SysDictBean;
import com.zfire.mall.manager.bean.k3.K3CustomerBean;
import com.zfire.mall.manager.commonmapper.AdminMapper;
import com.zfire.mall.manager.commonmapper.manage.product.ProductUpdPriceBillReserveMapper;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.constant.SysDictConstant;
import com.zfire.mall.manager.enums.StatusEnum;
import com.zfire.mall.manager.enums.SysDictEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.admin.AdminWebsitLogic;
import com.zfire.mall.manager.logic.k3.K3CustomerLogic;
import com.zfire.mall.manager.logic.wallet.WalletLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.*;
import com.zfire.mall.manager.utils.ApplicationContextUtils;
import com.zfire.mall.manager.utils.CommonUtils;
import com.zfire.mall.manager.utils.RedisUtil;
import com.zfire.mall.manager.utils.oss.OSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommonLogic {

    @Value("${spring.profiles.active}")
    private String active;
    @Autowired
    OSSUtil ossUtil;

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AdminWebsitLogic adminWebsitLogic;
    @Autowired
    K3CustomerLogic k3CustomerLogic;
    @Autowired
    SysDictService sysDictService;
    @Autowired
    AdminCompanyService adminCompanyService;
    @Autowired
    CommonFileService commonFileService;
    @Autowired
    RegionService regionService;
    @Autowired
    AdminUserService adminUserService;
    @Autowired
    AdminUserWebsitRelaService adminUserWebsitRelaService;
    @Autowired
    ProductCategoryService productCategoryService;
    @Autowired
    ProductUpdPriceBillReserveMapper productUpdPriceBillReserveMapper;
    @Autowired
    WalletRebateSaleTypeService walletRebateSaleTypeService;
    @Autowired
    AdminUserCategoryRelaService adminUserCategoryRelaService;
    @Autowired
    OrderBaseService orderBaseService;

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    KingDeeCustomerService kingDeeCustomerService;
    @Autowired
    KingDeeCategoryService kingDeeCategoryService;
    @Autowired
    SaleTypeService saleTypeService;
    @Autowired
    WalletRebateService walletRebateService;
    @Autowired
    AdminModuleService adminModuleService;
    @Autowired
    OperatorLogService operatorLogService;
    @Autowired
    WalletLogic walletLogic;
    @Resource
    LbsAmapService lbsAmapService;


    public String getIp(){
        HttpServletRequest request = ApplicationContextUtils.getHttpServletRequest();
        String clientIP = ServletUtil.getClientIP(request, null);
        return clientIP;
    }

    public AdminUserCom getAdminUser(){
        HttpServletRequest request = ApplicationContextUtils.getHttpServletRequest();
        return this.getAdminUser(request,false);
    }

    public AdminUserCom getAdminUser(HttpServletRequest request){
        return this.getAdminUser(request,false);
    }



    public AdminUserCom getAdminUser(Boolean allServiceId){
        HttpServletRequest request = ApplicationContextUtils.getHttpServletRequest();
        return this.getAdminUser(request,allServiceId);
    }


    public AdminUserCom getAdminUser(HttpServletRequest request,Boolean allServiceId){
        String userId = CommonUtils.getUserId(request);
        return this.getAdminUser(userId,allServiceId,request);
    }


    /**
     * 获取帐号以及部门id集合
     */
    public AdminUserCom getAdminUser(String userId,Boolean allServiceId,HttpServletRequest request){
        //方便测试用
        if(userId == null && !active.equals("prd")){
            AdminUser admin = adminUserService.lambdaQuery().eq(AdminUser::getUserName, "admin").one();
            AdminUserCom adminUserCom = new AdminUserCom();
            redisUtil.set(Constant.SUPPLY_CHANGE_NUM+admin.getAdminUserId(),"1");
            BeanUtils.copyProperties(admin,adminUserCom);
            AdminCompany adminCompanyWechat = adminCompanyService.getById("1");
            adminUserCom.setLoginCompanyId(adminCompanyWechat.getAdminCompanyId());
            adminUserCom.setLoginCompanyName(adminCompanyWechat.getAdminCompanyName());
            adminUserCom.setUseOrgNumber("100");
            return adminUserCom;
        }
        String token = CommonUtils.getToken(request);
        if(!StringUtils.equals(token,"1111")) {
            String loginKey = Constant.RedisPrefix.TOKEN_MGR + token;
            AdminUserCom adminUserCom = (AdminUserCom) redisUtil.get(loginKey);
            if (adminUserCom != null) {
                return adminUserCom;
            }
        }
        AdminUser adminUser = adminUserService.getById(userId);
        if(adminUser == null || !adminUser.getStatus()){
            throw new RemoteServiceException("帐号不存在或已被禁用");
        }
        AdminUserCom adminUserCom = new AdminUserCom();
        BeanUtils.copyProperties(adminUser,adminUserCom);

        //财务
        adminUserCom.setIsCw(adminUserCom.getRoleName().equals(Constant.NOT_DEL_ROLE_NAME2));
        adminUserCom.setIsService(adminUserCom.getRoleName().equals(Constant.NOT_DEL_ROLE_YWY) || adminUserCom.getRoleName().equals(Constant.NOT_DEL_SHANGYONG_ROLE_YWY));
        if (StrUtil.isNotBlank(adminUser.getRoleName()) ) {
            for (String str : Constant.NOT_DEL_ROLE_SPY) {
                if (adminUser.getRoleName().contains(str)) {
                    adminUserCom.setIsTradeExaminer(true);
                    break;
                } else {
                    adminUserCom.setIsTradeExaminer(false);
                }
            }
        }
        if (Objects.isNull(adminUserCom.getIsTradeExaminer())) {
            adminUserCom.setIsTradeExaminer(false);
        }
//        adminUserCom.setIsTradeExaminer(Constant.NOT_DEL_ROLE_SPY.contains(adminUserCom.getRoleName()));
        //部门帐号
        if(adminUserCom.getType() == 0){
            adminUserCom = this.websitAccount(adminUserCom, request);
        }

        //超管/平台帐号/企业主账号
        if(adminUserCom.getType() != 0){
            adminUserCom = this.companyAccount(adminUserCom);
        }

        // 经销商已绑定工程机
//        if (adminUser.getIsCustomer() && adminUser.getBindEngin()) {
//            List<AdminUserBindEngin> enginList = adminUserBindEnginService.lambdaQuery()
//                    .eq(AdminUserBindEngin::getAdminUserId, adminUser.getAdminUserId())
//                    .list();
//            if (CollectionUtils.isNotEmpty(enginList)) {
//                adminUserCom.setEnginUserIds(enginList.stream().map(AdminUserBindEngin::getEnginUserId).collect(Collectors.toList()));
//                adminUserCom.setBindEnginList(enginList);
//            }
//        }
        //查询所有下级业务员
        if(allServiceId && !adminUser.getIsCustomer()){
            //List<String> allAdminWebsitIds = adminWebsitLogic.getAllAdminWebsitIds(adminUserCom.getAdminWebsitId());
            //List<String> serviceIds = adminMapper.queryChildServiceId(allAdminWebsitIds,Constant.NOT_DEL_ROLE_YWY);
            //剔除掉自己部门
            List<String> serviceIds = adminMapper.queryChildServiceId(adminUserCom.getAdminWebsitIds(),null,adminUserCom.getAdminWebsitId());
            if(CollectionUtils.isEmpty(serviceIds)) {
                serviceIds = new ArrayList<>();
            }
            //添加自己
            serviceIds.add(adminUser.getAdminUserId());
            adminUserCom.setServiceIds(serviceIds);
        }
        //如果是子账号，根据主账号的权限拿业务员和仓库和品类权限
        String masterAdminUserId = adminUser.getAdminUserId();
        if(!adminUser.getIsMaster() && adminUser.getIsCustomer()){
            AdminUser masterAdminUser = adminUserService.lambdaQuery().eq(AdminUser::getIsMaster, true)
                    .eq(AdminUser::getCustomerId, adminUser.getCustomerId()).last("limit 1").one();
            if(masterAdminUser != null) {
                masterAdminUserId = masterAdminUser.getAdminUserId();
            }
        }
        adminUserCom.setMasterAdminUserId(masterAdminUserId);
        //查询该帐号拥有的品类权限
        List<AdminUserCategoryRela> list = adminUserCategoryRelaService.lambdaQuery().eq(AdminUserCategoryRela::getAdminUserId, masterAdminUserId).list();
        if(list.size() > 0){
            List<String> k3CategoryIds = list.stream().map(AdminUserCategoryRela::getK3CategoryId).collect(Collectors.toList());
            adminUserCom.setK3CategoryIds(k3CategoryIds);
            adminUserCom.setAdminUserCategoryRelas(list);
        }

        if(StringUtils.isNotEmpty(adminUserCom.getCustomerId())) {
            K3CustomerBean detail = k3CustomerLogic.detail(adminUserCom.getCustomerId());
            if (detail != null) {
                adminUserCom.setCustomerNumber(detail.getNumber());
                adminUserCom.setCustomerName(detail.getName());
                adminUserCom.setIsFront(detail.getIsFront());
                adminUserCom.setIsPick(detail.getIsPick());
                adminUserCom.setFrontPickType(detail.getFrontPickType());
            }
        }
        return adminUserCom;
    }


    public AdminUser getAdminUser(String userId){
        return adminUserService.getById(userId);
    }


    public void reloadAdminUserBean(AdminUserCom adminUserCom,HttpServletRequest request){
        String token = CommonUtils.getToken(request);
        String loginKey = Constant.RedisPrefix.TOKEN_MGR + token;
        redisUtil.set(loginKey,adminUserCom);
    }

    /**
     * 企业主帐号
     *  type = 1 企业主帐号
     */
    public AdminUserCom companyAccount(AdminUserCom adminUser){
        String adminUserId = adminUser.getAdminUserId();
        //查询该用户拥有的企业权限
        List<AdminCompany> list = adminMapper.queryAdminCompanyWechat(adminUserId);
        List<String> adminCompanyId = list.stream().map(AdminCompany::getAdminCompanyId).distinct().collect(Collectors.toList());
        List<String> useOrgNumbers = list.stream().map(AdminCompany::getUseOrgNumber).distinct().collect(Collectors.toList());
        adminUser.setAdminCompanyIds(adminCompanyId);
        adminUser.setUseOrgNumbers(useOrgNumbers);
        adminUser.setOnlyRead(adminCompanyId.size() > 1);
        if(adminCompanyId.size() == 1){
            AdminCompany adminCompany = list.get(0);
            adminUser.setLoginCompanyId(adminCompany.getAdminCompanyId());
            adminUser.setLoginCompanyName(adminCompany.getAdminCompanyName());
            adminUser.setUseOrgName(adminCompany.getUseOrgName());
            adminUser.setUseOrgNumber(adminCompany.getUseOrgNumber());
        }
        List<AdminUserWebsitRela> websitList = adminUserWebsitRelaService.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(adminCompanyId),AdminUserWebsitRela::getAdminCompanyId, adminCompanyId)
                .list();
        //查询该用户拥有的部门权限(企业帐号不需要)
        List<String> websitIds = websitList.stream().map(AdminUserWebsitRela::getAdminWebsitId).collect(Collectors.toList());

        if(websitIds.size() > 0) {
            adminUser.setAdminWebsitIds(websitIds);
            adminUser.setAdminWebsitId(websitIds.get(0));
            AdminWebsitDto detail = adminWebsitLogic.detail(websitIds.get(0));
            adminUser.setAdminWebsitName(detail.getName());
            adminUser.setAdminWebsit(detail);
        }
        return adminUser;

    }


    /**
     * 部门帐号
     */
    public AdminUserCom websitAccount(AdminUserCom adminUserCom,HttpServletRequest request){
        String userId = adminUserCom.getAdminUserId();
        List<AdminUserWebsitRela> websitList = adminUserWebsitRelaService.lambdaQuery().eq(AdminUserWebsitRela::getAdminUserId, userId).list();
        if(CollectionUtils.isEmpty(websitList)){
            throw new RemoteServiceException("暂无授权,请联系管理员");
        }
        List<String> adminWebsitIds = new ArrayList<>();
        if (adminUserCom.getChangeNum() == null || adminUserCom.getChangeNum().equals(1)) {
            adminWebsitIds = websitList.stream().map(AdminUserWebsitRela::getAdminWebsitId).distinct().collect(Collectors.toList());
            redisUtil.set(Constant.SUPPLY_CHANGE_NUM+adminUserCom.getAdminUserId(),"1");
        }else if (adminUserCom.getChangeNum().equals(2)){

            adminWebsitIds.add(Constant.GUANG_ZHOU_WEBSIT_ID);
            redisUtil.set(Constant.SUPPLY_CHANGE_NUM+adminUserCom.getAdminUserId(),"2");
        }else {
            adminWebsitIds.add(Constant.FO_SHAN_WEBSIT_ID);
            redisUtil.set(Constant.SUPPLY_CHANGE_NUM+adminUserCom.getAdminUserId(),"3");
        }

        List<String> adminCompanyIds = websitList.stream().map(AdminUserWebsitRela::getAdminCompanyId).distinct().collect(Collectors.toList());

        //根据所属部门查询所有下级部门
        List<String> allWebsitIds = new ArrayList<>();
        for(String adminWebsitId : adminWebsitIds){
            allWebsitIds.addAll(adminWebsitLogic.getAllAdminWebsitIds(adminWebsitId));
        }
        adminUserCom.setAdminCompanyIds(adminCompanyIds);
        adminUserCom.setAdminWebsitIds(allWebsitIds);
        //拥有多个企业主体的帐号只可以读，否则新增的数据不知道属于哪个主体
        // todo 这里需要登录的时候选择身份才可去除这个限制
        adminUserCom.setOnlyRead(adminCompanyIds.size() > 1);

        String loginCompanyId = "";
        String loginCompanyName = "";
        if(adminCompanyIds.size() == 1){
            loginCompanyId = websitList.get(0).getAdminCompanyId();
            AdminCompany adminCompany = adminCompanyService.getById(loginCompanyId);
            loginCompanyName = adminCompany.getAdminCompanyName();

            adminUserCom.setUseOrgName(adminCompany.getUseOrgName());
            adminUserCom.setUseOrgNumber(adminCompany.getUseOrgNumber());
            adminUserCom.setUseOrgNumbers(Arrays.asList(adminCompany.getUseOrgNumber()));
        }
        if(adminWebsitIds.size() > 0){
            AdminWebsitDto detail = adminWebsitLogic.detail(adminWebsitIds.get(0));
            adminUserCom.setAdminWebsitId(detail.getAdminWebsitId());
            adminUserCom.setAdminWebsitName(detail.getName());
            adminUserCom.setAdminWebsit(detail);
        }
        //获取当前登录人选用的企业微信身份
        //todo 保留登录时选择身份的支持
        if(StringUtils.isEmpty(loginCompanyId)){
            loginCompanyId = request.getHeader("loginCompanyId");
        }
        if(StringUtils.isEmpty(loginCompanyId)){
            loginCompanyId = request.getParameter("loginCompanyId");
        }
        if(StringUtils.isEmpty(loginCompanyName)){
            loginCompanyName = request.getHeader("loginCompanyName");
        }
        if(StringUtils.isEmpty(loginCompanyName)){
            loginCompanyName = request.getParameter("loginCompanyName");
        }

        if(StringUtils.isNotEmpty(loginCompanyId)) {

            if (!adminUserCom.getAdminCompanyIds().contains(loginCompanyId)) {
                throw new RemoteServiceException("暂无权限");
            }
            adminUserCom.setLoginCompanyId(loginCompanyId);
            adminUserCom.setLoginCompanyName(loginCompanyName);
        }
        return adminUserCom;
    }

    /**
     * 获取企业配置
     */
    public AdminCompany getAdminCompany(String companyWechatId){
        AdminCompany adminCompany = adminCompanyService.getById(companyWechatId);
        return adminCompany;
    }
    /**
     * 获取所有企业配置
     */
    public List<AdminCompany> getAdminCompanyList(){
        List<AdminCompany> list = adminCompanyService.list();
        return list;
    }


    /**
     * 附件归属绑定
     */
    public void bindFile(String objId,String objType,List<CommonFile> files){
        if(CollectionUtils.isEmpty(files)){
            return;
        }
        //先删除后绑定
        commonFileService.lambdaUpdate()
                .eq(CommonFile::getObjId,objId)
                .eq(CommonFile::getObjType,objType).remove();

        for(CommonFile file : files) {
            file.setObjId(objId);
            file.setObjType(objType);
        }
        commonFileService.saveBatch(files);
    }

    /**
     * 查询附件列表
     */
    public List<CommonFile> queryFileByObjId(String objId,String objType){
        return commonFileService.lambdaQuery()
                .eq(CommonFile::getObjId,objId)
                .eq(CommonFile::getObjType,objType)
                .orderByAsc(CommonFile::getCreateTime)
                .list();
    }

    /**
     * 查询附件列表
     */
    public List<String> queryFileUrlsByObjId(String objId,String objType){
        List<CommonFile> commonFiles = this.queryFileByObjId(objId, objType);
        if(commonFiles.size() == 0){
            return null;
        }
        return commonFiles.stream().map(CommonFile::getUrl).collect(Collectors.toList());
    }


    public Map<String, String> getOSSConfig() throws UnsupportedEncodingException {
        return ossUtil.getConfig();
    }

    public void getImg(String key, HttpServletResponse response) throws IOException {
        String url = ossUtil.getUrl(key);
        if(StringUtils.isNotEmpty(url)) {
            try {
                response.getOutputStream().write(getImageFromNetByUrl(url));
            }catch(Exception e){
                log.error("生成图片失败"+e.getMessage());
            }
        }
    }

    public String getFile(String key, HttpServletResponse response) throws IOException {
        String url = ossUtil.getUrlWw(key);
        return url;
    }

    public  byte[] getImageFromNetByUrl(String strUrl) {
        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            log.error("生成图片失败"+e.getMessage());
        }
        return null;
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    /**
     * 上传附件
     * @return
     * @throws IOException
     */
//    public CommonFile uploadFile( MultipartFile file) throws IOException, RemoteServiceException {
//
//        if (file == null || file.isEmpty()) {
//            return null;
//        }
//        String uploadFilePath = file.getOriginalFilename().replaceAll("\\\\", "/");
//        String uploadFileName = uploadFilePath.substring(
//                uploadFilePath.lastIndexOf('/') + 1, uploadFilePath.lastIndexOf('.'));
//        String uploadFileSuffix = uploadFilePath.substring(uploadFilePath.lastIndexOf('.') + 1, uploadFilePath.length());
//        long currentTime = System.currentTimeMillis();
//        BufferedOutputStream bufferedOutputStream = null;
//
//        //限制大小为10m
//        if (file.getSize() > 1024 * 1024 * 30) {
//            throw new RemoteServiceException("文件大小超出限制");
//        }
//
//        try {
//            String filePath = OSSUtil.OSS_TYPE_PIC + currentTime + UUID.randomUUID().toString() + "." + uploadFileSuffix;
//            if (!OSSUtil.uploadFile(filePath, file.getBytes())) {
//                throw new RemoteServiceException("文件同步oss失败");
//            }
//            String ossUrl = OSSUtil.accessUrl + filePath;
//
//            CommonFile commonFile = new CommonFile();
//            commonFile.setUrl(ossUrl);
//            commonFile.setName(uploadFileName);
//            commonFile.setFileType(uploadFileSuffix);
//            commonFile.setFileSize(BigDecimal.valueOf(file.getSize()));
//            commonFile.setCreateTime(new Date());
//            commonFileService.save(commonFile);
//            return commonFile;
//        } finally {
//            if (bufferedOutputStream != null) {
//                bufferedOutputStream.close();
//            }
//        }
//    }


    public List<Region> queryRegionList(Long pid){
        return regionService.lambdaQuery().eq(Region::getPid,pid).list();
    }

    public InputStream getFileInputStreamByUrl(String strUrl) {
        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据
            return inStream;
        } catch (Exception e) {
            log.error("生成附件失败"+e.getMessage());
        }
        return null;
    }

    /**
     * 字典列表
     */
    public List<SysDict> getSysDictList(String type) {
        if(StringUtils.isEmpty(type)){
            throw new RemoteServiceException("参数异常");
        }
        if(StringUtils.equals(type,SysDictEnum.PRODUCT_TYPE.toString())){
            List<ProductCategory> list = productCategoryService.lambdaQuery().list();

            List<SysDict> sysDicts = new ArrayList<>();
            for(ProductCategory productCategory : list){
                SysDict sysDict = new SysDict();
                sysDict.setDictCode(productCategory.getProductCategoryNumber());
                sysDict.setDictValue(productCategory.getProductCategoryName());
                sysDicts.add(sysDict);
            }
            return sysDicts;
        }
        return sysDictService.lambdaQuery()
                .eq(StringUtils.isNotBlank(type),SysDict::getDictType, type)
                .list();
    }

    /**
     * 品类map
     */
    public Map<String,String> getProductTypeMap(){
        List<SysDict> sysDictList = this.getSysDictList(SysDictEnum.PRODUCT_TYPE.toString());
        Map<String,String> map = new HashMap<>();
        for(SysDict sysDict : sysDictList){
            map.put(sysDict.getDictCode(),sysDict.getDictValue());
        }
        return map;
    }


    /**
     * 生成订单号
     * @param start 1开头零售 2开头政策 3家
     * @param orderType 订单类型
     * @param length 一般13 位
     * @return
     */
    public  String generateNo(String start, String orderType,int length) {
        String dayFmt = DateUtil.format(new Date(), "yyMMdd");
        String tNumKey = Constant.RedisPrefix.ORDER_NUM + orderType + dayFmt;
        StringBuffer number = new StringBuffer();
        number.append(start);
        number.append(dayFmt);
        int ramainLen = length - number.toString().length();
        //自增 填充位数
        Object value = redisUtil.incr(tNumKey, 1);
        redisUtil.expire(tNumKey, 24 * 60 * 60);
        number.append(String.format("%0" + ramainLen + "d", Integer.parseInt(value.toString())));
        return number.toString();
    }

    /**
     * 生成工程信息号
     * @param start
     * @param orderType 订单类型
     * @param length 一般 12 位
     * @return
     */
    public String generateInfoNo(String start, String orderType, int length) {
        Date curDate = new Date();
        String yearFmt = DateUtil.format(curDate, "yyyy");
        String yearMonthFmt = DateUtil.format(curDate, "yyMM");
        String tNumKey = Constant.RedisPrefix.INFO_ORDER_NUM + orderType + yearFmt;
        StringBuffer number = new StringBuffer();
        number.append(start);
        number.append(yearMonthFmt);
        int ramainLen = length - number.toString().length();
        //自增 填充位数
        Object value = redisUtil.incr(tNumKey, 1);
        redisUtil.expire(tNumKey, 375 * 24 * 60 * 60);
        number.append(String.format("%0" + ramainLen + "d", Integer.parseInt(value.toString())));
        return number.toString();
    }

    /**
     * 生成商用登录项目编号
     * @param orderType 订单类型
     * @param length 一般 8 位
     * @return
     */
    public String generateTradeLoginNo(String orderType, int length) {
        Date curDate = new Date();
        String yearFmt = DateUtil.format(curDate, "yyyy");
        String yearMonthFmt = DateUtil.format(curDate, "yy");
        String tNumKey = Constant.RedisPrefix.INFO_ORDER_NUM + orderType + yearFmt;
        StringBuffer number = new StringBuffer();
        number.append(yearMonthFmt);
        number.append("-");
        int ramainLen = length - number.toString().length();
        //自增 填充位数
        Object value = redisUtil.incr(tNumKey, 1);
        redisUtil.expire(tNumKey, 375 * 24 * 60 * 60);
        number.append(String.format("%0" + ramainLen + "d", Integer.parseInt(value.toString())));
        return number.toString();
    }


    /**
     * 根据物料id获取品类
     */
    public MainBean getMainBean(String materialId){
        MainBean mainBean = productUpdPriceBillReserveMapper.queryMain(materialId);
        return mainBean;
    }

    //检查返利类型钱包和销售类型是否匹配
    public Integer getRebateSaleTypeCount(String saleTypeId,String walletRebateId){
        Integer count = walletRebateSaleTypeService.lambdaQuery()
                .eq(WalletRebateSaleType::getSaleTypeId, saleTypeId)
                .eq(WalletRebateSaleType::getWalletRebateId, walletRebateId)
                .count();
        return count;
    }

    public void addSysDict(SysDict sysDict) {
        if (StringUtils.isBlank(sysDict.getDictType())) {
            throw new RemoteServiceException("字典类型不能为空");
        }
        if (StringUtils.isBlank(sysDict.getDictCode())) {
            throw new RemoteServiceException("字典名称不能为空");
        }
        if (StringUtils.isBlank(sysDict.getDictCode())) {
            throw new RemoteServiceException("字典值不能为空");
        }
        Integer count = sysDictService.lambdaQuery()
                .eq(SysDict::getDictType, sysDict.getDictType())
                .eq(SysDict::getDictCode, sysDict.getDictCode())
                .count();
        if (count > 0) {
            throw new RemoteServiceException(sysDict.getDictCode() + "重复存在");
        }
        sysDict.setSysDictId(IdWorker.getIdStr());
        sysDictService.save(sysDict);
    }

    public void updateSysDict(List<SysDict> sysDicts) {
        for (SysDict sysDict : sysDicts) {
            if (StringUtils.isBlank(sysDict.getSysDictId())) {
                throw new RemoteServiceException("字典id不能为空");
            }
            if (StringUtils.isBlank(sysDict.getDictType())) {
                throw new RemoteServiceException("字典类型不能为空");
            }
            if (StringUtils.isBlank(sysDict.getDictCode())) {
                throw new RemoteServiceException("字典名称不能为空");
            }
            if (StringUtils.isBlank(sysDict.getDictCode())) {
                throw new RemoteServiceException("字典值不能为空");
            }
            Integer count = sysDictService.lambdaQuery()
                    .eq(SysDict::getDictType, sysDict.getDictType())
                    .eq(SysDict::getDictCode, sysDict.getDictCode())
                    .ne(SysDict::getSysDictId, sysDict.getSysDictId())
                    .count();
            if (count > 0) {
                throw new RemoteServiceException(sysDict.getDictCode() + "重复存在");
            }
            sysDictService.updateById(sysDict);
        }
    }

    /**
     * 保存订单基础上表
     */
    public void addOrderBase(String orderId,String orderType){
        OrderBase orderBase = new OrderBase();
        orderBase.setOrderId(orderId);
        orderBase.setOrderType(orderType);
        orderBase.insert();
    }

    public List<SysDictBean> sysDictBeanList(String code) {
        //todo  判断拿到自己想要得值返回，默认返回字典表查值
        if(StringUtils.isEmpty(code)){
            throw new RemoteServiceException("参数异常");
        }
        List<SysDict> sysDicts = new ArrayList<>();
        if(StringUtils.equals(code,SysDictEnum.PRODUCT_TYPE.toString())){
            List<ProductCategory> list = productCategoryService.lambdaQuery().list();
            //保证有序
            LinkedHashMap<String, String> linkedHashMap = list.stream().collect(LinkedHashMap::new,(map, item) -> map.put(item.getProductCategoryNumber(), item.getProductCategoryName()),Map::putAll);
            return this.supplyDict(linkedHashMap);
        }else if(StringUtils.equals(code,SysDictConstant.K3_CATEGORY)){
            List<KingDeeCategory> list = kingDeeCategoryService.list();
            LinkedHashMap<String, String> linkedHashMap = list.stream().collect(LinkedHashMap::new,(map, item) -> map.put(item.getId(), item.getName()),Map::putAll);
            return this.supplyDict(linkedHashMap);
        }
        else if(StringUtils.equals(code,SysDictConstant.CUSTOMER)){
            List<KingDeeCustomer> list = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getForbidStatus, "A").list();
            LinkedHashMap<String, String> linkedHashMap = list.stream().collect(LinkedHashMap::new,(map, item) -> map.put(item.getNumber(), item.getName()),Map::putAll);
            return this.supplyDict(linkedHashMap);
        }else if(StringUtils.equals(code,SysDictConstant.SALE_TYPE)){
            List<SaleType> list = saleTypeService.lambdaQuery().eq(SaleType::getStatus, true).list();
            LinkedHashMap<String, String> linkedHashMap = list.stream().collect(LinkedHashMap::new,(map, item) -> map.put(item.getId(), item.getSaleName()),Map::putAll);
            return this.supplyDict(linkedHashMap);
        }else if(StringUtils.equals(code,SysDictConstant.WALLET_REBATE)){
            List<WalletRebate> list = walletRebateService.lambdaQuery().eq(WalletRebate::getStatus, true).list();
            LinkedHashMap<String, String> linkedHashMap = list.stream().collect(LinkedHashMap::new,(map, item) -> map.put(item.getWalletRebateId(), item.getName()),Map::putAll);
            return this.supplyDict(linkedHashMap);
        }else if(StringUtils.equals(code,SysDictConstant.WALLET)){
            List<KingDeeWallet> list = walletLogic.list(null);
            LinkedHashMap<String, String> linkedHashMap = list.stream().collect(LinkedHashMap::new,(map, item) -> map.put(item.getId(), item.getName()),Map::putAll);
            return this.supplyDict(linkedHashMap);
        }else if(StringUtils.equals(code,SysDictConstant.SERVICE)){
            List<AdminUser> list = adminUserService.lambdaQuery().eq(AdminUser::getIsService, true).eq(AdminUser::getStatus, true).list();
            LinkedHashMap<String, String> linkedHashMap = list.stream().collect(LinkedHashMap::new,(map, item) -> map.put(item.getAdminUserId(), item.getNickName()),Map::putAll);
            return this.supplyDict(linkedHashMap);
        }
        else {
            sysDicts = sysDictService.lambdaQuery().eq(SysDict::getDictType, code).select(SysDict::getDictCode, SysDict::getDictValue).list();
        }
        List<SysDictBean> sysDictBeans = BeanUtil.copyToList(sysDicts, SysDictBean.class);
        return sysDictBeans;
    }

    private List<SysDictBean> supplyDict(LinkedHashMap<String,String> map){
        List<SysDictBean> sysDictBeans = new ArrayList<>();
        for(String key : map.keySet()) {
            SysDictBean sysDictBean = new SysDictBean();
            sysDictBean.setDictCode(key);
            sysDictBean.setDictValue(map.get(key));
            sysDictBeans.add(sysDictBean);
        }
        return sysDictBeans;
    }


    public void saveLog(String id){
        this.saveLog(id, "编辑", "编辑");
    }

    public void saveLog(List<OperatorLog> operatorLogs){
        if(CollectionUtils.isEmpty(operatorLogs))
            return;
        operatorLogService.saveBatch(operatorLogs);
    }

    /**
     * 保存操作日志
     */
    public void saveLog(String id,String type,String content){
        OperatorLog operatorLog = this.supplyLog(id, type, content);
        operatorLog.insert();
    }

    public OperatorLog supplyLog(String id,String type,String content){
        HttpServletRequest request = ApplicationContextUtils.getHttpServletRequest();
        AdminUserCom adminUser = this.getAdminUser(request);
        //当前菜单ID
        String moduleId = request.getHeader("moduleId");
        AdminModule adminModule = adminModuleService.getById(moduleId);
        OperatorLog operatorLog = new OperatorLog();
        operatorLog.setObjId(id);
        if(adminModule != null) {
            operatorLog.setModuleName(adminModule.getModuleName());
        }
        operatorLog.setUserName(adminUser.getNickName()+"("+adminUser.getUserName()+")");
        operatorLog.setType(type);
        operatorLog.setContent(content);
        operatorLog.setIp(this.getIp());
        return operatorLog;
    }

    public List<LbsAmap> regionList(List<String> parentLbsId) {
        List<LbsAmap> list = lbsAmapService.lambdaQuery()
                .eq(LbsAmap::getStatus, StatusEnum.ON.getKey())
                .eq(org.springframework.util.CollectionUtils.isEmpty(parentLbsId),LbsAmap::getLevel,"province")
                .in(!org.springframework.util.CollectionUtils.isEmpty(parentLbsId), LbsAmap::getParentLbsId, parentLbsId)
                .list();
        return list;
    }

//    @Autowired
//    WalletLogic walletLogic;
//
//    @Transactional
//    public void test() throws InterruptedException {
//        walletLogic.addWalletAmount("1543930584064184323",BigDecimal.valueOf(100),"测试001","1",new Date(),"1",1);
//        walletLogic.addWalletAmount("1543930584064184323",BigDecimal.valueOf(200),"测试002","1",new Date(),"2",1);
//        walletLogic.addWalletAmount("1543930584064184323",BigDecimal.valueOf(300),"测试003","1",new Date(),"3",1);
//        walletLogic.addWalletAmount("1543930584064184323",BigDecimal.valueOf(400),"测试001","1",new Date(),"4",1);
//        walletLogic.addWalletAmount("1543930584064184323",BigDecimal.valueOf(500),"测试002","1",new Date(),"5",1);
//        walletLogic.addWalletAmount("1543930584064184323",BigDecimal.valueOf(600),"测试003","1",new Date(),"6",1);
//    }





}
