package com.ssm.manage.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.config.RestTemplateConfig;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.AESUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.BaseDao;
import com.ssm.manage.dto.PlatformCouponDto;
import com.ssm.manage.dto.StoreWechatDto;
import com.ssm.manage.entity.*;
import com.ssm.manage.mapper.PlatformCouponMapper;
import com.ssm.manage.mapper.UseProjectMapper;
import com.ssm.manage.mapper.UseStoreMapper;
import com.ssm.manage.query.*;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.StaffResponse;
import com.ssm.manage.service.PlatformCouponService;
import com.ssm.manage.service.PushMessageService;
import com.ssm.manage.service.SsmBaseStoreService;
import com.ssm.manage.service.SsmUploadFilesService;
import com.ssm.manage.utils.*;
import com.ssm.util.RedisClient;
import com.ssm.wxpay.sdk.WXPayConstants;
import com.ssm.wxpay.sdk.WXPayUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;


/**
 * (PlatformCoupon)表服务实现类
 *
 * @author makejava
 * @since 2022-06-11 14:58:52
 */
@Service("platformCouponService")
public class PlatformCouponServiceImpl extends BaseServiceImpl<PlatformCoupon> implements PlatformCouponService {

    @Autowired
    private PlatformCouponMapper platformCouponMapper;
    @Autowired
    private RedisClient<StaffResponse> templateRedisClient;
    @Autowired
    private UseStoreMapper useStoreMapper;
    @Autowired
    private UseProjectMapper useProjectMapper;
    @Autowired
    private SsmUploadFilesService ssmUploadFilesService;
    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;
    @Autowired
    private PushMessageService pushMessageService;

    // 开发者密码(AppSecret)
    private static String AppSecret = "9ed5097e93b5a0e909dbe2b347d068ac";
    // 开发者ID(AppID)
    private static String AppId = "wx3c108aae98b1433c";
    // 消息模板ID
    private static String TemplateId = "LGNr1hdreDtKcmgN6-950KOQ_DLl-odczwqNMMPlkpY";

    public static final String APPID = "wx094b8c7fb88ba28d"; //申请小程序的AppId

    public static final Integer MCH_ID = 1627685754; //商户号ID

    public static final String APP_SECRET = "2777bb81ea8a1afbb112c07529041d2f"; //生成的AppSecret

    // 网页授权接口
    private final static String GetAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
    // 发送模板消息接口
    private final static String SendTempMessage = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
    //获取手机号链接
    private final static String GetPhone = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN";

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return
     */
    @Override
    public PlatformCoupon queryById(Serializable id) {

        Long aLong = Long.valueOf((String) id);
        PlatformCoupon platformCoupon = platformCouponMapper.selectByPrimaryKey(aLong);
        UseProject useProject = new UseProject();
        UseStore useStore = new UseStore();
        //查询优惠券确认文件
        UploadFilesRequest uploadFilesRequest = new UploadFilesRequest();
        uploadFilesRequest.setDocId(platformCoupon.getId());
        uploadFilesRequest.setDocNum(platformCoupon.getCouponNum());
        uploadFilesRequest.setDocType(Constant.doc_type_platform_coupon);
        List<UploadFiles> filesList = ssmUploadFilesService.selectList(uploadFilesRequest);
//            //设置返回List
        platformCoupon.setFileLists(filesList);
//            refundRechargeResponse.setEntities(entities);
//            refundRechargeResponse.setFileLists(filesList);
        useProject.setCouponId(platformCoupon.getId());
        useProject.setCouponNum(platformCoupon.getCouponNum());
        useProject.setCouponName(platformCoupon.getCouponName());
        List<UseProject> useProjects = useProjectMapper.queryAll(useProject);
        platformCoupon.setUseProjects(useProjects);
        useStore.setCouponId(platformCoupon.getId());
        useStore.setCouponNum(platformCoupon.getCouponNum());
        useStore.setCouponName(platformCoupon.getCouponName());
        List<UseStore> useStores = useStoreMapper.queryAll(useStore);
        platformCoupon.setUseStores(useStores);
        return platformCoupon;
    }

    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageInfo<PlatformCoupon> queryByPage(PlatformCouponDto dto) {
        Example example = new Example(PlatformCoupon.class);
        Example.Criteria criteria = example.createCriteria();

        if (null != dto.getCouponName()) {//优惠卷名称
            criteria.andLike("couponName", "%" + dto.getCouponName() + "%");
        }
        if (null != dto.getStoreName()) {//创建门店名称
            criteria.andLike("storeName", "%" + dto.getStoreName() + "%");
        }
        if (null != dto.getCouponNum()) {//优惠卷编码
            criteria.andLike("couponNum", "%" + dto.getCouponNum() + "%");
        }
        if (null != dto.getJudge()) {
            if (dto.getJudge() == 1) {
                List<Integer> integers = Arrays.asList(5, 6, 7, 8, 9, 10, 11, 13, 14);
                criteria.andIn("state", integers);
            }
        }


        PageHelper.startPage(dto.getPageNum(), dto.getPageSize(), dto.getOrderAndSort());
        List<PlatformCoupon> list = platformCouponMapper.selectByExample(example);
        UseProject useProject = new UseProject();
        UseStore useStore = new UseStore();
        for (PlatformCoupon platformCoupon : list) {
            //查询优惠券确认文件
            UploadFilesRequest uploadFilesRequest = new UploadFilesRequest();
            uploadFilesRequest.setDocId(platformCoupon.getId());
            uploadFilesRequest.setDocNum(platformCoupon.getCouponNum());
            uploadFilesRequest.setDocType(Constant.doc_type_platform_coupon);
            List<UploadFiles> filesList = ssmUploadFilesService.selectList(uploadFilesRequest);
            uploadFilesRequest.setDocType(Constant.doc_type_platform_huizhi);
            List<UploadFiles> filesList_huizhi = ssmUploadFilesService.selectList(uploadFilesRequest);
            for (UploadFiles uploadFiles:
            filesList_huizhi) {
                filesList.add(uploadFiles);
            }
//            //设置返回List
            platformCoupon.setFileLists(filesList);
//            refundRechargeResponse.setEntities(entities);
//            refundRechargeResponse.setFileLists(filesList);
            useProject.setCouponId(platformCoupon.getId());
            useProject.setCouponNum(platformCoupon.getCouponNum());
            useProject.setCouponName(platformCoupon.getCouponName());
            List<UseProject> useProjects = useProjectMapper.queryAll(useProject);
            platformCoupon.setUseProjects(useProjects);
            useStore.setCouponId(platformCoupon.getId());
            useStore.setCouponNum(platformCoupon.getCouponNum());
            useStore.setCouponName(platformCoupon.getCouponName());
            List<UseStore> useStores = useStoreMapper.queryAll(useStore);
            platformCoupon.setUseStores(useStores);
        }

        Example examples = new Example(PlatformCoupon.class);
        Example.Criteria criterias = examples.createCriteria();

        if (null != dto.getCouponName()) {
            criterias.andLike("couponName", "%" + dto.getCouponName() + "%");
        }
        if (null != dto.getStoreName()) {
            criterias.andLike("storeName", "%" + dto.getStoreName() + "%");
        }
        if (null != dto.getCouponNum()) {
            criterias.andLike("couponNum", "%" + dto.getCouponNum() + "%");
        }
        if (null != dto.getJudge()) {
            if (dto.getJudge() == 1) {
                List<Integer> integers = Arrays.asList(5, 6, 7, 8, 9, 10, 11, 13, 14);
                criteria.andIn("state", integers);
            }
        }

        int size = platformCouponMapper.selectByExample(examples).size();

        PageInfo<PlatformCoupon> pageInfo = new PageInfo<>(list);
        pageInfo.setTotal(size);
        return pageInfo;

    }

    /**
     * 新增
     *
     * @param platformCoupon
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int add(PlatformCouponRequest platformCoupon, String key, List<UploadFiles> uploadFilesInfo) throws SmsException {

        Long refundId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        StaffResponse staffResponse = templateRedisClient.get(getKey(key));
        String substring = getString();
        platformCoupon.setInputName(staffResponse.getStaffName());
        platformCoupon.setInputNum(staffResponse.getStaffNum());
        platformCoupon.setId(refundId);
        platformCoupon.setCouponNum(substring);
        platformCoupon.setState(0);
        //创建人信息
//        platformCoupon.setInputId(staffResponse.getStaffNum());
        platformCoupon.setInputNum(staffResponse.getStaffNum());
        platformCoupon.setInputName(staffResponse.getStaffName());
        platformCoupon.setInputPhone(staffResponse.getMobilePhone());
        platformCoupon.setInputDate(new Date());
        //创建门店信息
        platformCoupon.setStoreId(staffResponse.getStoreId());
//        platformCoupon.setStoreNum(staffResponse.getStoreName());
        platformCoupon.setStoreName(staffResponse.getStoreName());
        platformCoupon.setOpenId(InstanceVariables.getOpenid());
        //多个门店
        if (null != platformCoupon.getUseStoreList()) {
            for (String s : platformCoupon.getUseStoreList()) {
                Long refundId1 = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
                UseStore useStore = useStoreMapper.selectStore(s);
                useStore.setId(refundId1);
                useStore.setCouponId(refundId);
                useStore.setCouponNum(platformCoupon.getCouponNum());
                useStore.setCouponName(platformCoupon.getCouponName());
                useStoreMapper.insert(useStore);
            }
        }
        //多个项目
        if (null != platformCoupon.getProjectList()) {
            for (Long s : platformCoupon.getProjectList()) {
                UseProject useProject = useProjectMapper.selectProject(s);
                Long refundId1 = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
                useProject.setId(refundId1);
                useProject.setCouponId(refundId);
                useProject.setCouponNum(platformCoupon.getCouponNum());
                useProject.setCouponName(platformCoupon.getCouponName());
                useProjectMapper.insert(useProject);
            }
        }
        //新增图片
        if (null != uploadFilesInfo) {
            for (UploadFiles uploadFiles : uploadFilesInfo) {
                uploadFiles.setDocId(refundId);
                uploadFiles.setDocNum(platformCoupon.getCouponNum());
                uploadFiles.setDocType(Constant.doc_type_platform_huizhi);
                ssmUploadFilesService.add(uploadFiles);
            }
        }

        PlatformCoupon platformCoupon1 = new PlatformCoupon();
        BeanUtils.copyProperties(platformCoupon, platformCoupon1);

        InstanceVariables.setOpenid(null);
        InstanceVariables.setDate(null);

        return platformCouponMapper.insert(platformCoupon1);
    }

    /**
     * 生成随机编码
     *
     * @return
     */
    private String getString() {
        //生成随机优惠券编码
        int i = UUID.randomUUID().toString().hashCode();
        if (i < 0) {
            i = -i;
        }
        String substring = String.format("%010d", i).substring(0, 10);
        return substring;
    }

    public String getKey(String phone) {
        String key = "";
        if (StringUtils.isNotBlank(phone)) {
            key = Constant.staffKey + phone;
        }
        return key;
    }

    /**
     * 编辑
     *
     * @param platformCoupon
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int edit(PlatformCouponRequest platformCoupon, String key, List<UploadFiles> uploadFilesInfo) throws SmsException {
//        //增量
//        if (null!=platformCoupon.getCouponNumber()){
//            platformCouponMapper.incremental(platformCoupon);
//        }

        if (platformCouponMapper.selectByPrimaryKey(platformCoupon).getState() == 5) {//打款待审不能修改
            throw new SmsException(ResponseCode.MSG, "打款待审中不能修改！");
        }
        //多个门店
        if (null != platformCoupon.getUseStoreList()) {
            for (String useStore : platformCoupon.getUseStoreList()) {
                useStoreMapper.deleteuseStore(useStore, platformCoupon);
            }
            for (String s : platformCoupon.getUseStoreList()) {
                Long refundId1 = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
                UseStore useStore = useStoreMapper.selectStore(s);
                useStore.setId(refundId1);
                useStore.setCouponId(platformCoupon.getId());
                useStore.setCouponNum(platformCoupon.getCouponNum());
                useStore.setCouponName(platformCoupon.getCouponName());
                useStoreMapper.insert(useStore);
            }
        }

        //多个项目
        if (null != platformCoupon.getProjectList()) {
            for (Long useProject : platformCoupon.getProjectList()) {
                useProjectMapper.deleteuseProject(useProject, platformCoupon);
            }
            for (Long s : platformCoupon.getProjectList()) {
                UseProject useProject = useProjectMapper.selectProject(s);
                Long refundId1 = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
                useProject.setId(refundId1);
                useProject.setCouponId(platformCoupon.getId());
                useProject.setCouponNum(platformCoupon.getCouponNum());
                useProject.setCouponName(platformCoupon.getCouponName());
                useProjectMapper.insert(useProject);
            }
        }

        //修改图片

        if (null != uploadFilesInfo) {

//            List<UploadFiles> fileLists = platformCoupon.getFileLists();

//            if (null!=fileLists){
//                for (UploadFiles fileList : fileLists) {
//
//                }
//            }

//            UploadFiles uploadFiles1 = new UploadFiles();
//            uploadFiles1.setDocId(platformCoupon.getCloseId());
//            uploadFiles1.setDocNum(platformCoupon.getCouponNum());
//            uploadFiles1.setDocType(Constant.doc_type_platform_coupon);
            for (UploadFiles uploadFiles : uploadFilesInfo) {
                UploadFiles uploadFiles1 = new UploadFiles();
                uploadFiles1.setDocId(platformCoupon.getId());
                uploadFiles1.setDocNum(platformCoupon.getCouponNum());
                uploadFiles1.setDocType(Constant.doc_type_platform_coupon);
                ssmUploadFilesService.delete(uploadFiles1);
                uploadFiles.setDocId(platformCoupon.getId());
                uploadFiles.setDocNum(platformCoupon.getCouponNum());
                uploadFiles.setDocType(Constant.doc_type_platform_coupon);
                ssmUploadFilesService.add(uploadFiles);
            }
        }
        PlatformCoupon platformCoupon1 = new PlatformCoupon();
        BeanUtils.copyProperties(platformCoupon, platformCoupon1);
        return platformCouponMapper.updateByPrimaryKeySelective(platformCoupon1);
    }

    /**
     * 根据主键删除
     *
     * @param id 主键
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int delete(Serializable id) {
        return platformCouponMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int audit(PlatformCouponRequest platformCoupon, String key) throws SmsException {
        if (platformCoupon.getState() == 2 || platformCoupon.getState() > 4) {
            throw new SmsException(ResponseCode.MSG, "门店与平台正在审核无法进行操作！");
        }
        StaffResponse staffResponse = templateRedisClient.get(getKey(key));
        PlatformCoupon platformCoupon1 = new PlatformCoupon();
        BeanUtils.copyProperties(platformCoupon, platformCoupon1);
        return platformCouponMapper.audit(platformCoupon1);
    }

    @Override
    public int newCheck(PlatformCoupon platformCoupon, String key) throws SmsException {

        StaffResponse staffResponse = templateRedisClient.get(getKey(key));

        return getInvalid(platformCoupon);
    }

    @Override
    public int shopCheck(PlatformCouponRequest platformCoupon, String key) throws SmsException {
//        if (platformCoupon.getState()<1){
//            throw new SmsException(ResponseCode.MSG,"优惠券未送审无法审核！");
//        }
        StaffResponse staffResponse = templateRedisClient.get(getKey(key));
        if (platformCoupon.getState() == 3) {//审核门店
            platformCoupon.setStoreAuditId(staffResponse.getStoreId());
            platformCoupon.setStoreAuditName(staffResponse.getStoreName());
            platformCoupon.setStoreAuditDate(new Date());
        } else if (platformCoupon.getState() == 4) {//反审核门店
            PlatformCoupon platformCoupon1 = platformCouponMapper.selectByPrimaryKey(platformCoupon);
            if (platformCoupon1.getState() == 5) {
                throw new SmsException(ResponseCode.MSG, "打款待审中不能反审核！");
            }
            platformCoupon.setStoreAuditeeId(staffResponse.getStoreId());
            platformCoupon.setStoreAuditeeName(staffResponse.getStoreName());
            platformCoupon.setStoreAuditeeDate(new Date());
        } else if (platformCoupon.getState() == 12) {
            PlatformCoupon platformCoupon1 = platformCouponMapper.selectByPrimaryKey(platformCoupon);
            if (platformCoupon1.getState() > 5 && platformCoupon1.getState() < 11) {
                throw new SmsException(ResponseCode.MSG, "平台操作中无法退款！");
            }
            platformCoupon.setStoreAuditeeId(staffResponse.getStoreId());
            platformCoupon.setStoreAuditeeName(staffResponse.getStoreName());
            platformCoupon.setStoreAuditeeDate(new Date());
        }

        PlatformCoupon platformCoupon1 = new PlatformCoupon();
        BeanUtils.copyProperties(platformCoupon, platformCoupon1);
        return getInvalid(platformCoupon1);
    }

    @Autowired
    private StoreWechatServiceImpl storeWechatService;

    @Override
    public int platformCheck(PlatformCouponRequest platformCoupon, String key) throws SmsException {
        if (platformCoupon.getState() < 5) {
            throw new SmsException(ResponseCode.MSG, "未打款，请通知制卷方打款！");
        }
        StaffResponse staffResponse = templateRedisClient.get(getKey(key));
        if (platformCoupon.getState() == 6) {
//            platformCoupon.setPlatformAuditNum(staffResponse.getStaffNum());
//            platformCoupon.setPlatformAuditName(staffResponse.getStaffName());
            platformCoupon.setPlatformAuditDate(new Date());
        } else if (platformCoupon.getState() == 7) {
//            platformCoupon.setPlatformAuditeeNum(staffResponse.getStaffNum());
//            platformCoupon.setPlatformAuditeeName(staffResponse.getStaffName());
            platformCoupon.setPlatformAuditeeDate(new Date());
        }

//        if (platformCoupon.getState()==8){
////            String at ;
////            String url  = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
////            String date;
////            String result = Util.post(url,date);
//            PlatformCoupon platformCoupon1 = queryById(platformCoupon.getId());
//            sendEnterTemplateMessage(platformCoupon1.getCouponName(),
//                    platformCoupon1.getCouponNum(), String.valueOf(new Date()),"o615O41Cw9B1GMFBFpzocNKGrjP0","");
//        }
        if (platformCoupon.getState() == 8) {


            PlatformCoupon platformCoupon1 = platformCouponMapper.selectByPrimaryKey(platformCoupon.getId());

            StoreRequest storeRequest = new StoreRequest();
            storeRequest.setId(platformCoupon1.getStoreId());
            List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
            List<BaseStores> collect = pagesorganizations.stream().filter(baseStores -> null == baseStores.getParentId()).collect(Collectors.toList());
            StoreWechatDto storeWechatDto = new StoreWechatDto();
            storeWechatDto.setStoreId(collect.get(0).getId());
            storeWechatDto.setPageNum(1);
            storeWechatDto.setPageSize(10);

            PageInfo<StoreWechat> storeWechatPageInfo = storeWechatService.queryByPage(storeWechatDto);
            List<StoreWechat> list = storeWechatPageInfo.getList();
            StoreWechat storeWechat = null;
            if (list.isEmpty()){
                storeWechat= list.get(0);
            }

            AlarmParamsDTO alarmParamsDTO = new AlarmParamsDTO();
            alarmParamsDTO.setFirst(platformCoupon1.getCouponName() + "优惠券领取信息提醒");
            alarmParamsDTO.setKeyword1(platformCoupon1.getCouponName());
            alarmParamsDTO.setKeyword2(String.valueOf(new Date()));
            alarmParamsDTO.setKeyword3(platformCoupon1.getCouponNum());
//            +"www.baidu.com"
            alarmParamsDTO.setRemark("点击领取属于您的优惠劵");
            alarmParamsDTO.setOpenId(platformCoupon1.getOpenId());

//            sendEnterTemplateMessage(platformCoupon1.getCouponName(),
//                    platformCoupon1.getCouponNum(), String.valueOf(new Date()),"o615O41Cw9B1GMFBFpzocNKGrjP0","www.baidu.com");

            pushMessageService.pushMessage(alarmParamsDTO, platformCoupon1.getId(),storeWechat);
        }


        PlatformCoupon platformCoupon1 = new PlatformCoupon();
        BeanUtils.copyProperties(platformCoupon, platformCoupon1);
        return getInvalid(platformCoupon1);
    }

    /**
     * //     * 推送模板消息
     * //     * @param couponName 优惠券名称
     * //     * @param couponNum 优惠券编码
     * //     * @param enterTime 发布时间
     * //     * @param openId    推送用户OpenId （注意，是OpenId）
     * //     * @param templateUrl 跳转Url
     */
    public void sendEnterTemplateMessage(String couponName, String couponNum, String enterTime, String openId, String templateUrl) {
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, TemplateData> data = new HashMap<>();
            TemplateData first = new TemplateData();
            TemplateData keyword1 = new TemplateData();
            TemplateData keyword2 = new TemplateData();
            TemplateData keyword3 = new TemplateData();
            TemplateData remark = new TemplateData();
            first.setColor("#328392");
            first.setValue(couponName + "优惠券领取信息提醒");
            keyword3.setColor("#328392");
            keyword3.setValue(couponNum);
            keyword1.setColor("#328392");
            keyword1.setValue(couponName);
            keyword2.setColor("#328392");
            keyword2.setValue(enterTime);//发布时间
            remark.setColor("#328392");
            // 有模板模板跳转链接，则推送消息可点击
            remark.setValue("点击领取属于您的优惠劵" + (StringUtils.isBlank(templateUrl) ? "" : "点击领取属于您的优惠劵。"));
            data.put("first", first);
            data.put("keyword1", keyword1);
            data.put("keyword2", keyword2);
            data.put("keyword3", keyword3);
            data.put("remark", remark);
            WxTemplate template = new WxTemplate();
            // 推送用户OpenId
            template.setTouser(openId);
            // 消息模板ID
            template.setTemplate_id(TemplateId);
            // 有模板模板跳转链接，则推送消息可点击
            if (!StringUtils.isBlank(templateUrl)) template.setUrl(templateUrl);
            template.setData(data);
            System.out.println("模板消息推送:" + template.toString());
            // 获取 AccessToken
            String accessToken = null;
            try {
                accessToken = getAccessToken();
            } catch (Exception e) {
                e.printStackTrace();
            }
            template.setAppid(AppId);
            String message = sendPostMessage(SendTempMessage.replace("ACCESS_TOKEN", accessToken), template);
            result.put("code", 1);
            result.put("message", message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println((String.valueOf(result)));
    }

    /**
     * Post 请求发送数据
     *
     * @param url
     * @param dataMap
     * @return
     */
    private static String sendPostMessage(String url, Object dataMap) {
        String data = new String();
        // 创建HttpClient实例
        HttpClient client = HttpClientBuilder.create().build();
        // 根据URL创建HttpPost实例
        HttpPost post = new HttpPost(url);
        try {
            // 构造post参数
            StringEntity s = new StringEntity(JSON.toJSONString(dataMap), "UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            // 发送请求，得到响应体
            HttpResponse response = client.execute(post);
            // 判断是否正常返回
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 解析数据
                HttpEntity resEntity = response.getEntity();
                data = EntityUtils.toString(resEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.getConnectionManager().shutdown();
        }
        return data;
    }

    /**
     * 获取AccessToken
     *
     * @return
     * @throws Exception
     */
    private static String getAccessToken() throws Exception {
        String requestUrl = GetAccessTokenUrl.replace("APPID", AppId).replace("SECRET", AppSecret);
        HttpClient client = HttpClientBuilder.create().build();
        String accessToken = null;
        String errcode = null;
        String errmsg = null;
        try {
            HttpGet httpget = new HttpGet(requestUrl);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = client.execute(httpget, responseHandler);
            JSONObject OpenidJSONO = JSONObject.parseObject(response);
            errcode = String.valueOf(OpenidJSONO.get("errcode"));
            errmsg = String.valueOf(OpenidJSONO.get("errmsg"));
            accessToken = String.valueOf(OpenidJSONO.get("access_token"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.getConnectionManager().shutdown();
        }
        if (!StringUtils.isBlank(errcode) && !errcode.equals("null"))
            throw new Exception(errmsg);
        return accessToken;
    }

    @Override
    public int moneyReceipt(PlatformCouponRequest platformCoupon, String key, List<UploadFiles> uploadFilesInfo) throws SmsException {
        if (platformCoupon.getState() == 5) {
            //新增图片
            if (null != uploadFilesInfo) {
                for (UploadFiles uploadFiles : uploadFilesInfo) {
                    uploadFiles.setDocId(platformCoupon.getId());
                    uploadFiles.setDocNum(platformCoupon.getCouponNum());
                    uploadFiles.setDocType(Constant.doc_type_platform_coupon);
                    ssmUploadFilesService.add(uploadFiles);
                }
            }
            PlatformCoupon platformCoupon1 = new PlatformCoupon();
            BeanUtils.copyProperties(platformCoupon, platformCoupon1);
            platformCouponMapper.updateByPrimaryKeySelective(platformCoupon1);
        }


        return 1;
    }

    @Override
    public List<PlatformCoupon> shareDiscounts(PlatformCouponDto dto) {
        Example example = new Example(PlatformCoupon.class);
        Example.Criteria criteria = example.createCriteria();
        Example example1 = new Example(UseStore.class);
        Example.Criteria criteria1 = example.createCriteria();

        if (null != dto.getStoreNum()) {
            criteria1.andEqualTo("storeNum", dto.getStoreNum());
        }

        List<UseStore> useStores = useStoreMapper.selectByExample(example1);

        List<PlatformCoupon> list = platformCouponMapper.selectByExample(example);
        UseProject useProject = new UseProject();
        for (PlatformCoupon platformCoupon : list) {
            if (platformCoupon.getSuitableStore() == 1) {
                long count = useStores.stream().filter(useStore -> useStore.getCouponNum() == platformCoupon.getCouponNum()).count();
                if (count == 0) {
                    list.remove(platformCoupon);
                }
            }
//            if (new Date() < platformCoupon.getEndDate()){//有效期内
//
//            }
            if (platformCoupon.getSuitableProject() == 1) {
                useProject.setCouponId(platformCoupon.getId());
                useProject.setCouponNum(platformCoupon.getCouponNum());
                useProject.setCouponName(platformCoupon.getCouponName());
                List<UseProject> useProjects = useProjectMapper.queryAll(useProject);
                platformCoupon.setUseProjects(useProjects);
            }
        }

        return list;
    }

    @Override
    public void thePublic(HttpServletRequest request, HttpServletResponse response, String key) throws Exception {

        StaffResponse staffResponse = templateRedisClient.get(getKey(key));


        //查询对应id拿到手机号和appid和秘钥


        //生成图片//包含删除图片
//        WxHelper.makeQRcodeByPhone(staffResponse.getMobilePhone(),session);


        String push = "qr/1657010489390.jpg";

        ExcelUtils.downloadExcelTemplate(push, "1657010489390", request, response);

    }

    @Override
    public void thePublic(HttpServletRequest request, HttpServletResponse response, String key, HttpSession session) throws Exception {

        StaffResponse staffResponse = templateRedisClient.get(getKey(key));


        //查询对应id拿到手机号和appid和秘钥


        //生成图片//包含删除图片
        WxHelper.makeQRcodeByPhone(AESUtils.decrypt(staffResponse.getMobilePhone()),session);


        String push = "qr/1657010489390.jpg";

        ExcelUtils.downloadExcelTemplate(push, "1657010489390", request, response);

    }

    @Override
    public List<String> obtainOpenid(HttpServletRequest request, HttpServletResponse response) {

        ArrayList<String> objects = new ArrayList<>();
        objects.add(0, InstanceVariables.getOpenid());
        objects.add(1, String.valueOf(InstanceVariables.getDate()));

        return objects;
    }

    @Autowired
    private RestTemplateConfig restTemplateConfig;

    @Override
    public String obtainPhone(String accessToken, String code) {

//        org.springframework.http.HttpEntity<Map<String, String>> mapHttpEntity = new org.springframework.http.HttpEntity<>();
        Map<String, String> param = new HashMap<>();

        param.put("code", code);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", "application/json");
        org.springframework.http.HttpEntity<Map<String, String>> httpEntity = new org.springframework.http.HttpEntity<Map<String, String>>(param, headers);
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
        ResponseEntity<String> postResponseEntity = restTemplateConfig.restTemplate().postForEntity(url, httpEntity, String.class);
        System.out.println(postResponseEntity.getBody());
        Map postMap = JSONObject.parseObject(postResponseEntity.getBody(), Map.class);
        if (!StringUtils.isEmpty(String.valueOf(postMap.get("errcode")))) {
            String errcode = postMap.get("errcode").toString();
            if (errcode.equals("-1")) {
                return "系统繁忙，请稍后重试";
            }
            if (errcode.equals("40029")) {
                return "code不存在或已过期，请重试";
            }
            if (errcode.equals("40013")) {
                return "不合法AppId";
            }
            if (errcode.equals("0")) {
                Map<String,String> phone_info = (Map<String, String>) postMap.get("phone_info");
                String s = phone_info.get("phoneNumber");

                return s;
            }
        }
        return String.valueOf(postMap);

    }

    private int getInvalid(PlatformCoupon platformCoupon) {
        int i = 0;
        //审核或者作废
        if (null != platformCoupon.getState()) {
            i = platformCouponMapper.updateByPrimaryKeySelective(platformCoupon);
        }
        return i;
    }

    @Override
    public BaseDao<PlatformCoupon> getDao() {
        return null;
    }

    /*
    *
    * --------------------------分隔------------------------------
    *
    * */

    /*
    * 微信支付下单信息
    * */
    @Override
    public String generateUniPayXml(String openId ,String ipAddress, String money){
        //double money = 0.01;   //转换为分，向上取整
        
        Map<String,String> map=new HashMap<>();
        map.put("appid", APPID); //小程序id
        map.put("mch_id", String.valueOf(MCH_ID));  //商户号
        map.put("nonce_str",UUID.randomUUID().toString().replaceAll("-",""));   //随机字符串
        map.put("body", "微信支付测试");    //商品描述
        map.put("out_trade_no", UUID.randomUUID().toString().replaceAll("-",""));    //商户订单号
        map.put("total_fee",money); //标价金额, 订单总金额单位为分
        map.put("spbill_create_ip",ipAddress);   //终端IP
        map.put("notify_url", "/platformCoupon/fallback");//通知地址
        map.put("trade_type","JSAPI");//交易类型
        map.put("openid", openId);//用户标识,trade_type=JSAPI 时此参数必传

        String xml = null;
        try {
            //WXPayUtil.generateSignedXml进行一次签名
            xml = WXPayUtil.generateSignedXml(map, WXPayConstants.KEY,WXPayConstants.SignType.MD5);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("--------------"+xml);
        return xml;
    }

    /*
    * 二次签名
    * */
    @Override
    public Map<String, String> secondSign(Map<String, String> unifiedOrderMap){
        Map<String,String> map=new HashMap<>();
        map.put("appId", WXPayConstants.APPID);
        map.put("timeStamp",String.valueOf(System.currentTimeMillis()/1000));
        map.put("nonceStr",unifiedOrderMap.get("nonce_str"));
        map.put("package","prepay_id="+unifiedOrderMap.get("prepay_id"));
        map.put("signType", WXPayConstants.MD5);

        String sign = null;
        try {
            sign = WXPayUtil.generateSignature(map, WXPayConstants.KEY,WXPayConstants.SignType.MD5);
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("paySign",sign);
        map.put("prePackage",unifiedOrderMap.get("prepay_id"));

        return map;
    }

}