package org.jeecg.modules.service.impl;

import com.aliyun.oss.common.utils.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.bean.CommentBean;
import org.jeecg.bean.ProjectBean;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.config.shiro.ShiroRealm;
import org.jeecg.modules.bean.*;
import org.jeecg.modules.hanHaiMember.entity.HanHaiMember;
import org.jeecg.modules.hanHaiMember.service.IHanHaiMemberService;
import org.jeecg.modules.msgAddress.entity.MsgAddress;
import org.jeecg.modules.msgAddress.service.IMsgAddressService;
import org.jeecg.modules.msgBanner.entity.MsgBanner;
import org.jeecg.modules.msgBanner.service.IMsgBannerService;
import org.jeecg.modules.msgBelece.entity.MsgBelece;
import org.jeecg.modules.msgBelece.service.IMsgBeleceService;
import org.jeecg.modules.msgCity.entity.MsgCity;
import org.jeecg.modules.msgCity.service.IMsgCityService;
import org.jeecg.modules.msgCollect.entity.MsgCollect;
import org.jeecg.modules.msgCollect.service.IMsgCollectService;
import org.jeecg.modules.msgConfig.entity.MsgConfig;
import org.jeecg.modules.msgConfig.service.IMsgConfigService;
import org.jeecg.modules.msgCoupon.entity.MsgCoupon;
import org.jeecg.modules.msgCoupon.service.IMsgCouponService;
import org.jeecg.modules.msgDistributor.entity.MsgDistributor;
import org.jeecg.modules.msgDistributor.service.IMsgDistributorService;
import org.jeecg.modules.msgEvaluate.entity.MsgEvaluate;
import org.jeecg.modules.msgEvaluate.service.IMsgEvaluateService;
import org.jeecg.modules.msgOrder.entity.MsgOrder;
import org.jeecg.modules.msgOrder.service.IMsgOrderService;
import org.jeecg.modules.msgPackage.entity.MsgPackage;
import org.jeecg.modules.msgPackage.service.IMsgPackageService;
import org.jeecg.modules.msgShop.entity.MsgShop;
import org.jeecg.modules.msgShop.service.IMsgShopService;
import org.jeecg.modules.msgShopConfig.entity.MsgShopConfig;
import org.jeecg.modules.msgShopConfig.service.IMsgShopConfigService;
import org.jeecg.modules.msgTechnician.entity.MsgTechnician;
import org.jeecg.modules.msgTechnician.service.IMsgTechnicianService;
import org.jeecg.modules.msgTer.entity.MsgTer;
import org.jeecg.modules.msgTer.service.IMsgTerService;
import org.jeecg.modules.msgWater.entity.MsgWater;
import org.jeecg.modules.msgWater.service.IMsgWaterService;
import org.jeecg.modules.pay.MpWxPayService;
import org.jeecg.modules.service.ApiLoginService;
import org.jeecg.modules.service.UserVipApiService;
import org.jeecg.modules.utils.SmsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;


@Slf4j
@Service
public class UserVipApiServiceImpl implements UserVipApiService {

    //获取banner信息列表
    @Resource
    private IMsgBannerService msgBannerService;
    //获取项目信息列表
    @Resource
    private IMsgShopService msgShopService;
    //获取技师信息列表
    @Resource
    private IMsgTechnicianService msgTechnicianService;
    //获取订单信息列表
    @Resource
    private IMsgOrderService msgOrderService;
    //获取优惠券信息列表
    @Resource
    private IMsgCouponService msgCouponService;
    //获取地址信息列表
    @Resource
    private IMsgAddressService msgAddressService;
    //获取钱包信息列表
    @Resource
    private IMsgPackageService msgPackageService;
    //微信公众号授权等了
    @Resource
    private ApiLoginService apiLoginService;
    //修改用户信息
    @Resource
    private IHanHaiMemberService memberService;
    //缓存记录
    @Resource
    private RedisUtil redisUtil;
    //权限验证
    @Resource
    private ShiroRealm shiroRealm;

    @Autowired
    private MpWxPayService mpWxPayService;
    //钱包
    @Resource
    private IMsgBeleceService beanleceService;
    //提现记录
    @Resource
    private IMsgWaterService msgWaterService;
    //获取配置信息
    @Resource
    private IMsgConfigService configService;
    //获取评论
    @Resource
    private IMsgEvaluateService eventService;
    //获取项目所配置的技师
    @Resource
    private IMsgShopConfigService shopConfigService;
    //技师入驻
    @Resource
    private IMsgTerService msgTerService;
    //获取开放城市
    @Resource
    private IMsgCityService cityService;
    //收藏接口
    @Resource
    private IMsgCollectService msgCollectService;
    //商户入驻
    @Resource
    private IMsgDistributorService msgDistributorService;
    //获取技师项目配置数据
    @Resource
    private IMsgShopConfigService msgShopConfigService;




    //微信公众号授权登录
    @Override
    public Result<?> wxOfficialLogin(OfficialLoginBean bean){
        LoginReq req = new LoginReq();
        req.setCode(bean.getCode());
        req.setHeadimgurl(bean.getHeadimgurl());
        req.setOpenid(bean.getOpenid());
        req.setNickName(bean.getNickName());
        req.setVid(bean.getVid());
        return apiLoginService.officialLogin(req);
    }




    //首页-获取banner
    @Override
    public Result<?> getBanner() {
        List<MsgBanner> list = msgBannerService.list();
        return Result.ok(list);
    }


    //首页-获取项目列表
    @Override
    public Result<?> getProjectList(ProjectBean bean) {
        //分页
        IPage<MsgShop> pageList = msgShopService.page(new Page<MsgShop>(bean.getPageNo(), bean.getPageSize()),
                new QueryWrapper<MsgShop>().lambda().orderByDesc(MsgShop::getSort));

        if(StringUtils.isNotBlank(bean.getTitle())){
            pageList = msgShopService.page(new Page<MsgShop>(bean.getPageNo(), bean.getPageSize()),
                    new QueryWrapper<MsgShop>().lambda().like(MsgShop::getTitle, bean.getTitle()).orderByDesc(MsgShop::getSort));
        }
        return Result.ok(pageList);
    }



    //首页-详情-获取项目详情-根据项目标识
    @Override
    public Result<?> getProjectDetail(String id,TechnicianPageBean pageBean){
        Map map = new HashMap();
        if(StringUtils.isBlank(id)){
            return Result.error("项目标识不能为空");
        }
        MsgShop byId = msgShopService.getById(id);
        map.put("details",byId);
        //根据项目所配置的信息查询技师列表
        List<MsgShopConfig> list = shopConfigService.lambdaQuery().eq(MsgShopConfig::getShopId, id)
                .eq(MsgShopConfig::getIsDelete, "Y")
                .list();
        //根据配置循环得出出技师列表带分页
        List<MsgTechnician> shop = new ArrayList<>();
        for (MsgShopConfig msgShopConfig : list) {
            MsgTechnician byId1 = msgTechnicianService.getById(msgShopConfig.getTenId());
            if(StringUtils.isNotBlank(pageBean.getCounty())){
                if(pageBean.getCounty().equals(byId1.getMsgCityId())){
                    shop.add(byId1);
                }

            }else{
                shop.add(byId1);
            }

        }
        map.put("tenPageList",shop);
        return Result.ok(map);
    }


    //技师-获取技师列表-带分页搜索
    @Override
    public Result<?> getTechnicianList(TechnicianPageBean pageBean) {
        Page<MsgTechnician> page = new Page<MsgTechnician>(pageBean.getPageNo(), pageBean.getPageSize());
        IPage<MsgTechnician> pageList = msgTechnicianService
                .lambdaQuery()
                .isNotNull(MsgTechnician::getUserId)
                .page(page);
        if(!StringUtils.isBlank(pageBean.getTitle())){
            pageList = msgTechnicianService
                    .lambdaQuery()
                    .like(MsgTechnician::getTitle, pageBean.getTitle())
                    .isNotNull(MsgTechnician::getUserId)
                    .page(page);
        }
        if(!StringUtils.isBlank(pageBean.getCounty())){
            pageList = msgTechnicianService
                    .lambdaQuery()
                    .eq(MsgTechnician::getMsgCityId, pageBean.getCounty())
                    .isNotNull(MsgTechnician::getUserId)
                    .page(page);
        }

        return Result.ok(pageList);
    }



    //技师-获取技师详情
    @Override
    public Result<?> getTechnicianDetail(String token,String id){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(StringUtils.isBlank(id)){
            return Result.error("技师标识不能为空");
        }
        MsgTechnician byId = msgTechnicianService.getById(id);
        //查询项目列表数据
//        List<MsgShop> list = msgShopService.lambdaQuery()
//                .list();
        MsgTechnician technician = msgTechnicianService.lambdaQuery()
                .eq(MsgTechnician::getUserId, hanHaiMember.getId())
                .one();
        //技师不能为空
        if(technician==null){
            return Result.error("技师不存在");
        }
        List<MsgShopConfig> list = msgShopConfigService.lambdaQuery()
                .eq(MsgShopConfig::getTenId, technician.getId())
                .eq(MsgShopConfig::getIsDelete, "Y")
                .list();
        List<MsgShop> listShop = new ArrayList<>();
//        if(list.size()==1){
//            MsgShop msgShop = msgShopService.getById(list.get(0).getShopId());
//            listShop.add(msgShop);
//        }else{
            for (MsgShopConfig s:list) {
                MsgShopConfig msgShopConfig = s;
                msgShopConfig.setShopObject(msgShopService.getById(s.getShopId()));


                MsgShop msgShop = msgShopService.getById(s.getShopId());
                listShop.add(msgShop);
            }
//        }







        Map map = new HashMap();
        map.put("msgTechnician", byId);
        map.put("list",listShop);

        //查询是否已收藏技师
        MsgCollect one = msgCollectService.lambdaQuery().eq(MsgCollect::getTenId, byId.getId()).eq(MsgCollect::getUserId, hanHaiMember.getId()).one();
        if(one == null){
            map.put("collect", 0);
        }else{
            map.put("collect", 1); //已收藏
        }
        return Result.ok(map);
    }


    //订单-获取订单列表-带分页搜索
    @Override
    public Result<?> getOrderList(String token,OrderPageBean pageBean) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null) {
            return Result.error("用户信息失效");
        }


        Page<MsgOrder> page = new Page<MsgOrder>(pageBean.getPageNo(), pageBean.getPageSize());
        IPage<MsgOrder> pageList = msgOrderService
                .lambdaQuery()
                .eq(MsgOrder::getUserId, hanHaiMember.getId())
                .isNotNull(MsgOrder::getAddressId)
                .orderByDesc(MsgOrder::getCreateTime)
                .page(page);
        if(pageBean.getState()==-1){
            pageList = msgOrderService
                    .lambdaQuery()
                    .eq(MsgOrder::getUserId, hanHaiMember.getId())
                    .isNotNull(MsgOrder::getAddressId)
                    .orderByDesc(MsgOrder::getCreateTime)
                    .page(page);
        }else{
            pageList = msgOrderService
                    .lambdaQuery()
                    .eq(MsgOrder::getUserId, hanHaiMember.getId())
                    .isNotNull(MsgOrder::getAddressId)
                    .eq(MsgOrder::getState, pageBean.getState())
                    .orderByDesc(MsgOrder::getCreateTime)
                    .page(page);
        }

        return Result.ok(pageList);
    }

    //订单-获取订单详情
    @Override
    public Result<?> getOrderDetail(String token,String id){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息失效");
        }
        if(StringUtils.isBlank(id)){
            return Result.error("订单标识不能为空");
        }
        Map map = new HashMap();
        MsgOrder msgOrder = msgOrderService.getById(id);
        //根据订单中的项目标识获得项目信息
        MsgShop msgShop = msgShopService.getById(msgOrder.getProjectId());
        //根据订单中的技师标识获取技师信息
        MsgTechnician msgTechnician = msgTechnicianService.getById(msgOrder.getTechnicianId());
        //根据订单中的地址标识获取地址
        MsgAddress msgAddress = msgAddressService.getById(msgOrder.getAddressId());
        map.put("msgOrder", msgOrder);
        map.put("msgShop", msgShop);
        map.put("msgTechnician", msgTechnician);
        //根据订单中的优惠券标识获取优惠券信息
        MsgCoupon msgCoupon = msgCouponService.getById(msgOrder.getCouponId());
        map.put("coupon",msgCoupon);
        return Result.ok(map);
    }

    //我的-获取优惠券列表信息
    @Override
    public Result<?> getCouponList(String token,CouponPageBean pageBean) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息失效");
        }
        //查询当前用户过期的优惠券修改优惠券状态
        msgCouponService.lambdaUpdate()
                .eq(MsgCoupon::getUserId, hanHaiMember.getId())
                .lt(MsgCoupon::getEndTime, new Date())
                .set(MsgCoupon::getState, 2)
                .update();


        Page<MsgCoupon> page = new Page<MsgCoupon>(pageBean.getPageNo(), pageBean.getPageSize());
        IPage<MsgCoupon> pageList = msgCouponService
                .lambdaQuery()
                .eq(MsgCoupon::getUserId, hanHaiMember.getId())
                .page(page);

        if(pageBean.getState() == null){
            pageList = msgCouponService
                    .lambdaQuery()
                    .eq(MsgCoupon::getUserId, hanHaiMember.getId())
                    .page(page);
        }else{
            pageList = msgCouponService
                    .lambdaQuery()
                    .eq(MsgCoupon::getUserId, hanHaiMember.getId())
                    .eq(MsgCoupon::getState, pageBean.getState())
                    .page(page);
        }
        return Result.ok(pageList);
    }

    //我的-获取地址信息列表
    @Override
    public Result<?> getAddressList(String token,AddressPageBean pageBean) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息失效");
        }
        Page<MsgAddress> page = new Page<MsgAddress>(pageBean.getPageNo(), pageBean.getPageSize());
        IPage<MsgAddress> pageList = msgAddressService
                .lambdaQuery()
                .eq(MsgAddress::getUserId, hanHaiMember.getId())
                .page(page);
        return Result.ok(pageList);
    }

    //我的-获取地址信详情
    @Override
    public Result<?> getAddressDetail(String token,String id){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息失效");
        }
        if(StringUtils.isBlank(id)){
            return Result.error("地址标识不能为空");
        }
        return Result.ok(msgAddressService.getById(id));
    }


    //我的-钱包-获取充值套餐列表信息
    @Override
    public Result<?> getRechargeList() {
        List<MsgPackage> list = msgPackageService.list();
        return Result.ok(list);
    }


    //我的-获取客服信息
    @Override
    public Result<?> getCustomerService() {
        return Result.ok("17373110849");
    }


    //我的-增加或修改地址信息
    @Override
    public Result<?> addOrUpdateAddress(MsgAddress msgAddress,String token) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);

        //查询改用户是否有默认地址
        List<MsgAddress> list = msgAddressService.lambdaQuery()
                .eq(MsgAddress::getUserId, hanHaiMember.getId())
                .eq(MsgAddress::getDefaultId, "1")
                .list();
        if(list.size() > 0 && msgAddress.getDefaultId().equals("1")){
            for (MsgAddress msgAddress1 : list) {
                msgAddress1.setDefaultId("0");
                msgAddressService.updateById(msgAddress1);
            }
        }
        //如果当前设置默认地址


        if(StringUtils.isBlank(msgAddress.getId())){
            msgAddress.setUserId(hanHaiMember.getId());
            msgAddressService.save(msgAddress);
        }else{
            MsgAddress byId = msgAddressService.getById(msgAddress.getId());
            if(byId == null){
                return Result.error("当前地址不存在无法修改");
            }
            msgAddressService.updateById(msgAddress);
        }


        return Result.ok("成功");
    }

    //我的-删除地址信息
    @Override
    public Result<?> deleteAddress(String id,String token) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息失效");
        }
        if(StringUtils.isBlank(id)){
            return Result.error("地址标识不能为空");
        }
        msgAddressService.removeById(id);
        return Result.ok();
    }

    //我的-增加或修改技师入驻信息
    @Override
    public Result<?> addOrUpdateMsgTer(MsgTer msgTer, String token) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息失效");
        }
        if(StringUtils.isBlank(msgTer.getId())){
            msgTer.setUserId(hanHaiMember.getId());
            msgTerService.save(msgTer);
        }else{
            MsgTer byId = msgTerService.getById(msgTer.getId());
            if(byId == null){
                return Result.error("当前技师不存在无法修改");
            }
            msgTerService.updateById(msgTer);
        }
        return Result.ok();
    }

    //我的-增加分销商入驻信息
    @Override
    public Result<?> addOrUpdateShop(MsgDistributor bean, String token) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息失效");
        }
        if(StringUtils.isBlank(bean.getId())){
            msgDistributorService.save(bean);
        }else{
            msgDistributorService.updateById(bean);
        }
        return Result.ok();
    }


    //我的-修改用户信息
    @Override
    public Result<?> updateUser(HanHaiMember member,String token) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息失效");
        }
        if(StringUtils.isBlank(member.getId())){
            return Result.error("用户标识不能为空");
        }
        memberService.updateById(member);
        return Result.ok();
    }


    /**
     * 微信支付
     * @param token
     * @param req
     * @return
     */
    @Override
    public Result<?> createPayOrder(String token, RechargeReq req){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
//        MsgOrder byId = msgOrderService.getById(req.getId());
//        if(byId == null){
//            return Result.error(500,"创建失败");
//        }
//        BigDecimal multiply = byId.getMoney().multiply(new BigDecimal(100).setScale(0, BigDecimal.ROUND_UP));

        BigDecimal multiply = new BigDecimal(0.01).setScale(0, BigDecimal.ROUND_UP);
        String s = multiply.toString();
        int i1 = Double.valueOf(s).intValue();
        Object appOrder = mpWxPayService.createOrder(
                "购买测试",
                "127.0.0.1",
                System.currentTimeMillis()+"",
                i1,
                System.currentTimeMillis()+"",
                hanHaiMember.getOfficialOpenid(),
                "{}");

        return Result.OK("创建成功",appOrder);
    }


    /**
     * 微信支付 -- 支付回调
     * @param requestBody
     * @return
     */
    @Override
    public Object createWxNotify(String requestBody){
        log.info("进入订单支付回回调-----------------------------");
        WxPayOrderNotifyResult notify = mpWxPayService.notify(requestBody);
        log.info(notify.toString());
        String outTradeNo = notify.getOutTradeNo();
        log.info("订单标识"+outTradeNo);
        //开始处理业务逻辑
        MsgOrder byId = msgOrderService.getById(outTradeNo);
        log.info("订单数据{}",byId);
        if(byId!=null){
            if(byId.getState()==0){
                //修改订单状态
                byId.setState(1);
                byId.setUpdateTime(new Date());
                msgOrderService.updateById(byId);

                //根据订单优惠券标识修改优惠券使用状态
                if(StringUtils.isNotBlank(byId.getCouponId())){
                    MsgCoupon msgCoupon = msgCouponService.getById(byId.getCouponId());
                    if(msgCoupon!=null){
                        msgCoupon.setState(1);
                        msgCouponService.updateById(msgCoupon);
                    }
                }

                //增加流水
                MsgWater wallet = new MsgWater();
                wallet.setMoney(byId.getMoney().add(byId.getTemp()));
                wallet.setTitle("微信支付订单");
                wallet.setType(2);
                wallet.setUserId(byId.getUserId());
                wallet.setState(1);
                wallet.setCreateTime(new Date());
                msgWaterService.save(wallet);

                //根据订单关联技师信息查询当前技师信息
                MsgTechnician msgTechnician = msgTechnicianService.getById(byId.getTechnicianId());

                this.sendSms(msgTechnician);

                //根据技师信息中的用户标识查询用户电话
                HanHaiMember byId1 = memberService.getById(msgTechnician.getUserId());


                this.onlineCall(byId1.getPhone());


            }
        }
        return null;
    }


    //语音电话拨打  -- 来订单
    public void onlineCall(String  phone){



        try {
            String appId = "61ZhAwDm";
            String appKey = "22JncSVX";
            String mobile = phone;
            String templateId = "1275466558320451584";


            String urlParameters = "appId=" + appId +
                    "&appKey=" + appKey +
                    "&mobile=" + mobile +
                    "&templateId=" + templateId;

            URL url = new URL("https://api.253.com/open/notify/batch-voice-notify");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(urlParameters.length()));
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            os.write(urlParameters.getBytes());
            os.flush();
            os.close();

            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
            br.close();

            System.out.println("Response: " + response.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }






    //发送短信提现技师
    public void sendSms(MsgTechnician msgTechnician){
        //查询配置列表中的配置的电话
        MsgConfig msgConfig = configService.lambdaQuery().eq(MsgConfig::getName, "phone").one();

        //查询当前技师是否是测试技师
        if(msgTechnician.getIsTest().equals("1")){
            //发送短信给运营号
            SmsClient.sendMsg2(msgConfig.getContent(),msgTechnician.getTitle());
        }else{
            //根据技师中的用户标识查询用户信息
            HanHaiMember hanHaiMember = memberService.lambdaQuery().eq(HanHaiMember::getId, msgTechnician.getUserId()).one();
            //发送短信给技师
            SmsClient.sendMsg2(hanHaiMember.getPhone(),msgTechnician.getTitle());
        }

    }

    // 临时二维码
    private final static String QR_SCENE = "QR_SCENE";
    // 永久二维码
    private final static String QR_LIMIT_SCENE = "QR_LIMIT_SCENE";
    // 永久二维码(字符串)
    private final static String QR_LIMIT_STR_SCENE = "QR_LIMIT_STR_SCENE";
    // 创建二维码
    private String create_ticket_path = "https://api.weixin.qq.com/cgi-bin/qrcode/create";
    // 通过ticket换取二维码
    private String showqrcode_path = "https://mp.weixin.qq.com/cgi-bin/showqrcode";

    /**
     * 展示二维码
     */
    @Override
    public Result<?> getShowQrcode()  {
        WinXinEntity winXinEntity = WeiXinUnitl.getWinXinEntity(create_ticket_path);
        String s = showQrcode(winXinEntity.getTicket());
        try{
            WeiXinResult weiXinResult = showQrcode(winXinEntity.getTicket(), "E:\\iamge\123.jpg");
        }catch (Exception e){
            e.printStackTrace();
        }

        return Result.OK("查询成功",s);
    }


    /**
     * 创建临时带参数二维码
     * @param accessToken
     * @expireSeconds 该二维码有效时间，以秒为单位。 最大不超过2592000（即30天），此字段如果不填，则默认有效期为30秒。
     * @param sceneId 场景Id
     * @return
     */

    public String createTempTicket(String accessToken, String expireSeconds, int sceneId) {

        WeiXinQRCode wxQRCode = null;

        TreeMap<String,String> params = new TreeMap<String,String>();
        params.put("access_token", accessToken);
        Map<String,Integer> intMap = new HashMap<String,Integer>();
        intMap.put("scene_id",sceneId);
        Map<String,Map<String,Integer>> mapMap = new HashMap<String,Map<String,Integer>>();
        mapMap.put("scene", intMap);
        //
        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("expire_seconds", expireSeconds);
        paramsMap.put("action_name", QR_SCENE);
        paramsMap.put("action_info", mapMap);
        String data = new Gson().toJson(paramsMap);
        data = HttpRequestUtil.HttpsDefaultExecute(HttpRequestUtil.POST_METHOD,create_ticket_path,params,data);
        try {
            wxQRCode = new Gson().fromJson(data, WeiXinQRCode.class);
        } catch (JsonSyntaxException e) {
            wxQRCode = null;
            e.printStackTrace();
        }
        return wxQRCode==null?null:wxQRCode.getTicket();

    }

    /**
     * 创建永久二维码(数字)
     * @param accessToken
     * @param sceneId 场景Id
     * @return
     */

    public String createForeverTicket(String accessToken, int sceneId) {

        TreeMap<String,String> params = new TreeMap<String,String>();
        params.put("access_token", accessToken);
        //output data
        Map<String,Integer> intMap = new HashMap<String,Integer>();
        intMap.put("scene_id",sceneId);
        Map<String,Map<String,Integer>> mapMap = new HashMap<String,Map<String,Integer>>();
        mapMap.put("scene", intMap);
        //
        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("action_name", QR_LIMIT_SCENE);
        paramsMap.put("action_info", mapMap);
        String data = new Gson().toJson(paramsMap);
        data =  HttpRequestUtil.HttpsDefaultExecute(HttpRequestUtil.POST_METHOD,create_ticket_path,params,data);
        WeiXinQRCode wxQRCode = null;
        try {
            wxQRCode = new Gson().fromJson(data, WeiXinQRCode.class);
        } catch (JsonSyntaxException e) {
            wxQRCode = null;
            e.printStackTrace();
        }
        return wxQRCode==null?null:wxQRCode.getTicket();
    }

    /**
     * 创建永久二维码(字符串)
     *
     * @param accessToken
     * @param sceneStr 场景str
     * @return
     */
    public String createForeverStrTicket(String accessToken, String sceneStr){
        TreeMap<String,String> params = new TreeMap<String,String>();
        params.put("access_token", accessToken);
        //output data
        Map<String,String> intMap = new HashMap<>();
        intMap.put("scene_str",sceneStr);
        Map<String,Map<String,String>> mapMap = new HashMap<String,Map<String,String>>();
        mapMap.put("scene", intMap);

        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("action_name", QR_LIMIT_STR_SCENE);
        paramsMap.put("action_info", mapMap);
        String data = new Gson().toJson(paramsMap);
        data =  HttpRequestUtil.HttpsDefaultExecute(HttpRequestUtil.POST_METHOD,create_ticket_path,params,data);
        WeiXinQRCode wxQRCode = null;
        try {
            wxQRCode = new Gson().fromJson(data, WeiXinQRCode.class);
        } catch (JsonSyntaxException e) {
            wxQRCode = null;
        }
        return wxQRCode==null?null:wxQRCode.getTicket();
    }


    /**
     * 获取二维码ticket后，通过ticket换取二维码图片展示
     * @param ticket
     * @return
     */
    public String showQrcode(String ticket){
        Map<String,String> params = new TreeMap<String,String>();
        params.put("ticket", HttpRequestUtil.urlEncode(ticket, HttpRequestUtil.DEFAULT_CHARSET));
        try {
            showqrcode_path = HttpRequestUtil.setParmas(params,showqrcode_path,"");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return showqrcode_path;
    }

    /**
     * 获取二维码ticket后，通过ticket换取二维码图片
     * @param ticket
     * @param savePath  保存的路径,例如 F:\\test\test.jpg
     * @return      Result.success = true 表示下载图片下载成功
     */
    public WeiXinResult showQrcode(String ticket, String savePath) throws Exception{
        TreeMap<String,String> params = new TreeMap<String,String>();
        params.put("ticket", HttpRequestUtil.urlEncode(ticket, HttpRequestUtil.DEFAULT_CHARSET));
        WeiXinResult result = HttpRequestUtil.downMeaterMetod(params,HttpRequestUtil.GET_METHOD,showqrcode_path,savePath);
        return result;
    }



    //钱包提现
    @Override
    public Result<?> walletWithdraw(String token, BigDecimal price) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息异常");
        }
        MsgBelece belece = beanleceService.lambdaQuery().eq(MsgBelece::getUserId, hanHaiMember.getId()).one();
        if(belece == null){
            return Result.error("用户钱包不存在");
        }
        if(belece.getMoney().compareTo(price) < 0){
            return Result.error("余额不足");
        }
        if(belece.getMoney().compareTo(new BigDecimal(1)) < 0){
            return Result.error("提现最低1元");
        }
        //减去用户钱包额度
        if(beanleceService.lambdaUpdate().eq(MsgBelece::getUserId, hanHaiMember.getId()).set(MsgBelece::getMoney, belece.getMoney().subtract(price)).update()){
            //添加提现记录
            MsgWater walletWallet = new MsgWater();
            walletWallet.setUserId(hanHaiMember.getId());
            walletWallet.setCreateTime(new Date());
            walletWallet.setType(0);
            walletWallet.setMoney(price);
            walletWallet.setTitle("提现");
            if(msgWaterService.save(walletWallet)){
                //提现成功
                return Result.ok();
            }
        }
        return Result.ok();
    }



    //获取配置信息
    @Override
    public Result<?> getConfig() {
        return Result.ok(configService.list());
    }

    //获取评论信息的接口
    @Override
    public Result<?> getCommentList(String token, CommentBean bean) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息失效");
        }
        //技师标识不能为空
        if(bean.getTenantId() == null){
            return Result.error("技师标识不能为空");
        }
//        //项目标识不能为空
//        if(bean.getProjectId() == null){
//            return Result.error("项目标识不能为空");
//        }
        //类型不能为空
        if(bean.getType() == null){
            return Result.error("类型不能为空");
        }
        //评论区分不能为空
        if(bean.getFraction() == null){
            return Result.error("评论区分不能为空");
        }
        List<MsgEvaluate> list = eventService
                .lambdaQuery()
                .eq(MsgEvaluate::getUserId, hanHaiMember.getId())
                .eq(MsgEvaluate::getType, 0)
//                .eq(MsgEvaluate::getShopId, bean.getProjectId())
                .eq(MsgEvaluate::getTerId, bean.getTenantId())
                .eq(MsgEvaluate::getFraction, bean.getFraction())
                .orderByDesc(MsgEvaluate::getCreateTime)
                .list();
        if(bean.getType() != null){
            list = eventService
                    .lambdaQuery()
                    .eq(MsgEvaluate::getUserId, hanHaiMember.getId())
                    .eq(MsgEvaluate::getType, bean.getType())
//                    .eq(MsgEvaluate::getShopId, bean.getProjectId())
                    .eq(MsgEvaluate::getFraction, bean.getFraction())
                    .eq(MsgEvaluate::getTerId, bean.getTenantId())
                    .orderByDesc(MsgEvaluate::getCreateTime)
                    .list();
        }

        return Result.ok(list);
    }

    //我的-获取个人信息接口
    @Override
    public Result<?> getUserInfo(String token) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        //获取钱包信息
        if(hanHaiMember == null){
            return Result.error("用户信息异常");
        }
        if(hanHaiMember.getId() != null){
            MsgBelece msgBelece = beanleceService.lambdaQuery().eq(MsgBelece::getUserId, hanHaiMember.getId()).one();
            if(msgBelece != null){
                hanHaiMember.setPrice(msgBelece.getMoney());
            }
        }
        return Result.ok(hanHaiMember);
    }


    //获取分销代理流水信息
    @Override
    public Result<?> getAgentFlow(String token,MsgWaterBean bean) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息异常");
        }
        if(StringUtils.isEmpty(bean.getType())){
            return Result.error("类型不能为空");
        }

        Page<MsgWater> page = new Page<MsgWater>(bean.getPageNo(), bean.getPageSize());
        IPage<MsgWater> pageList = msgWaterService
                .lambdaQuery()
                .eq(MsgWater::getType,bean.getType())
                .eq(MsgWater::getUserId,hanHaiMember.getId())
                .orderByDesc(MsgWater::getCreateTime)
                .page(page);

        //如果是充值
        if(bean.getType().equals("0")){
            pageList = msgWaterService
                    .lambdaQuery()
                    .eq(MsgWater::getType,bean.getType())
                    .eq(MsgWater::getState,1)
                    .eq(MsgWater::getUserId,hanHaiMember.getId())
                    .orderByDesc(MsgWater::getCreateTime)
                    .page(page);

        }


        //查询当前钱包
        MsgBelece msgBelece = beanleceService.lambdaQuery().eq(MsgBelece::getUserId, hanHaiMember.getId()).one();
        Map map = new HashMap();
        map.put("pageList",pageList);
        if(msgBelece == null){
            map.put("use_money",0);
        }else{
            map.put("use_money",msgBelece.getMoney());
        }
        map.put("lei_give", 0);
        map.put("lei_set",0);

        return Result.ok(map);
    }



    //获取当前开放区域的接口
    @Override
    public Result<?> getCurrentArea(){
        List<MsgCity> list =cityService.list();
        return Result.ok(list);
    }


}
