package com.winsun.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.bean.*;
import com.winsun.mapper.*;
import com.winsun.utils.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 兑换券校检
 *
 * @Author: xiangli
 * @Date:
 */
@Slf4j
@RestController
@RequestMapping("/yxtCard") //
public class YxtCardController extends BaseController {

    @Autowired
    private YxtCouponMapper yxtCouponMapper;
    @Autowired
    private YxtAddressMapper yxtAddressMapper;
    @Autowired
    private YxtOrderMapper yxtOrderMapper;
    @Autowired
    private YxtSalesLimitMapper yxtSalesLimitMapper;
    @Autowired
    private YxtOrderDetailMapper yxtOrderDetailMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    private final double price = 0.1;

    /**
     * 进入院线通兑换券销售界面
     *
     * @return
     */
    @RequestMapping(value = "/getCardCount", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseData<Map<String, Object>> getCardCount() {

        Wrapper<YxtCoupon> yxtCouponWrapper = new EntityWrapper<>();
        yxtCouponWrapper.eq("state", 1);
        yxtCouponWrapper.eq("shelf_state", 1);
        Integer cardNum = yxtCouponMapper.selectCount(yxtCouponWrapper);
        Wrapper<YxtCoupon> yxtCouponWrapper1 = new EntityWrapper<>();
        yxtCouponWrapper1.eq("state", 2);
        Integer salesNum = yxtCouponMapper.selectCount(yxtCouponWrapper1);
        Map<String, Object> map = new Hashtable<>();
        map.put("cardNum", cardNum);
        map.put("salesNum", salesNum);
        map.put("price", price);
        return ResponseData.success(map);
    }

    /**
     * 测试时使用
     *
     * @param request
     * @param response
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/weixinAuthorizati", method = {RequestMethod.GET, RequestMethod.POST})
    public void weixinAuthorization(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String requestURL = request.getContextPath();
        log.info(requestURL);
        String redirect_uri = "http://167460x6b0.51mypc.cn/ciop/forgerpw/callBackLogin";
        String redirect_uri2 = "http://167460x6b0.51mypc.cn/dist/#/yxt/pay?userId=6399";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?";
        url += "appid=" + WxConfig.APPID;
        url += "&redirect_uri=" + URLEncoder.encode(redirect_uri2, "UTF-8");//此处和微信回调用的域名相同
        url += "&response_type=code&scope=snsapi_userinfo&state=frommenu#wechat_redirect";

        try {
            response.sendRedirect(url);
        } catch (Exception e) {
            log.error("微信授权异常" + e.getMessage(), e);
        }
    }

    /**
     * 进入院线通实体票下单界面
     *
     * @return
     */
    @RequestMapping(value = "/enterPay", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseData<Map<String, Object>> enterPay(String code) throws Exception {

        Map<String, Object> objectMap = new HashMap<>();
        String openIdt = "";
        String result = WxInterfacesUtil.getAccess_tokenByCode(code);
        Object object = redisTemplate.opsForValue().get("openid");
        if (object != null) {
            openIdt = object.toString();
        }
        if (StringUtils.isNotBlank(result)) {
            JSONObject obj = JSONObject.fromObject(result);
            redisTemplate.opsForValue().set("access_token", obj.get("access_token"), 120, TimeUnit.MINUTES);
            String openId = String.valueOf(obj.get("openid"));
            // code重复使用时，从session拿出第一次保存openId赋予openId
            if ("null".equals(openId) && !"null".equals(openIdt)) {
                openId = openIdt;
            }
            // code重复使用时，openId为"null"，不更新session
            if (!"null".equals(openId)) {
                redisTemplate.opsForValue().set("openid", openId);//设置不过期
                //redisTemplate.opsForValue().set("openid", openId, 1200, TimeUnit.MINUTES);
            }
            objectMap.put("openId", openId);
            log.info("openId:" + openId);
        }

        if (!"null".equals(openIdt)) {
            objectMap.put("openId", openIdt);
        }
        return ResponseData.success(objectMap);
    }


    /**
     * 支付界面初始化
     */
    @RequestMapping(value = "getJsapiSign", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseData<Map<String, Object>> getJsapiSign(HttpServletRequest request) {
        // 加密参数
        String url = "http://" + request.getServerName() + request.getRequestURI();
        String access_token = "";
        Object obj = redisTemplate.opsForValue().get("access_token");
        Map<String, Object> objectMap = null;
        try {
            if (obj != null) {
                access_token = obj.toString();
            }
            objectMap = new WxInterfacesUtil().getJspaiSign(url, access_token);
            objectMap.put("appid", WxConfig.APPID);
            return ResponseData.success(objectMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseData.error("");
    }

    /**
     * 下单新增订单
     *
     * @return
     */
    @RequestMapping(value = "/addYxtOrder", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseData<Map<String, Object>> addYxtOrder(@RequestParam("order") String order) {

        Map<String, Object> objectMap = new Hashtable<>();
        YxtOrder yxtOrderTemp = new YxtOrder();
        List<YxtCoupon> coupIds = new ArrayList<>();
        List<YxtOrderDetail> detailList = new ArrayList<>();
        String msg = "";
        try {
            //目前可购买兑换券数量
            int totalNums = returnCardNum();
            YxtOrder yxtOrder = JSON.parseObject(order, YxtOrder.class);
            String orderNum = "YXT0018" + ProduceIdUtil.getId();
            yxtOrder.setOrderNum(orderNum);
            yxtOrder.setUnitPrice(price);
            Integer goodsNum = yxtOrder.getGoodsNum();
            redisTemplate.opsForValue().set("goodsNum", goodsNum.toString(), 30, TimeUnit.MINUTES);
            String orderType = yxtOrder.getOrderType();
            if (orderType.equals("实体订单")) {
                //快递状态(0:无须快递,1待寄出:,2:寄出,3:已寄出)
                yxtOrder.setExpressState(1);
                Integer addressId = yxtOrder.getAddressId();
                if (StringUtils.isBlank(addressId.toString())) {
                    return ResponseData.error("地址不能为空！！！");
                }
            }
            yxtOrder.setUpdateDate(new Date());
            // 一个学校一个月累计购买数为300
            Object object = redisTemplate.opsForValue().get("openid");//设置不过期
            String openId = (object != null) ? object.toString() : "oLLfr0_XJc2mcaRqRl3sOQ7GwmVw";//临时测试用
            Wrapper<YxtSalesLimit> salesLimitWrapper = new EntityWrapper<>();
            salesLimitWrapper.eq(StringUtils.isNotBlank(openId), "open_id", openId);
            YxtSalesLimit salesLimit = yxtSalesLimitMapper.selectList(salesLimitWrapper).get(0);
            int dayNum = 0;

            if (null != salesLimit && null != salesLimit.getSalesNum()) {
                dayNum = salesLimit.getSalesNum();
            }
            Integer num0 = yxtOrderMapper.insert(yxtOrder);
            yxtOrderTemp = getYxtOrder(yxtOrder.getUserId(), yxtOrder.getOrderNum());
            redisTemplate.opsForValue().set("yxtOrderId", yxtOrderTemp.getId().toString(), 30, TimeUnit.MINUTES);
            Integer residuNum = 5 - dayNum;
            if ("实体订单".equals(orderType)) {
                // 快递订单不需分配兑换券账号和密码，由快递寄出
                if (num0 == 1) {
                    objectMap.put("yxtOrder", yxtOrderTemp);
                    return ResponseData.success(objectMap);
                }
            } else {
                if (null != yxtOrderTemp) {
                    if ((dayNum + goodsNum) > 5) {
                        yxtOrderMapper.deleteById(yxtOrderTemp.getId());
                        return ResponseData.error("每人每天限购5张，目前可购买数量为" + residuNum + "！");
                    } else {
                        if (totalNums < goodsNum && "电子订单".equals(orderType)) {
                            yxtOrderMapper.deleteById(yxtOrderTemp.getId());
                            return ResponseData.error("可购买的兑换券数量不足，目前兑换券数量为" + totalNums + ";请刷新下单界面，重新购买！");
                        }
                    }
                    Wrapper<YxtCoupon> couponWrapper = new EntityWrapper<>();
                    couponWrapper.eq("state", "1");
                    couponWrapper.eq("shelf_state", "1");
                    List<YxtCoupon> couponList = yxtCouponMapper.selectList(couponWrapper);
                    int count = goodsNum;
                    for (YxtCoupon yxtCoupon : couponList) {
                        coupIds.add(yxtCoupon);
                        count--;
                        if (count == 0) {
                            break;
                        }
                    }
                    List<YxtCoupon> yxtCoupons = new ArrayList<>();
                    int num1 = 0;
                    int count0 = 0;
                    for (YxtCoupon coup : coupIds) {
                        count0++;
                        if (count0 > totalNums) {
                            break;
                        }
                        yxtCoupons.add(coup);
                        YxtOrderDetail detail = new YxtOrderDetail();
                        detail.setYxtId(coup.getId());
                        detail.setOrderId(yxtOrderTemp.getId());
                        detailList.add(detail);
                        num1 += yxtOrderDetailMapper.insert(detail);
                    }
                    // 添加兑换券到订单详情后，更新兑换券状态，不允许再次购买
                    if (num1 == goodsNum) {
                        //清空
                        while (redisTemplate.opsForList().size("yxtCouponList") > 0) {
                            redisTemplate.opsForList().leftPop("yxtCouponList");
                        }
                        //存储
                        redisTemplate.opsForList().rightPushAll("yxtCouponList", yxtCoupons);
                        for (YxtCoupon coup : yxtCoupons) {
                            Wrapper<YxtCoupon> yxtCouponWrapper = new EntityWrapper<>();
                            yxtCouponWrapper.eq("id", coup.getId());
                            YxtCoupon yxtCoupon = new YxtCoupon();
                            yxtCoupon.setState(3);
                            yxtCouponMapper.update(yxtCoupon, yxtCouponWrapper);
                        }
                        objectMap.put("yxtCoupons", yxtCoupons);
                    } else {
                        msg = "添加订单详情失败";
                    }
                } else {
                    msg = "获取新增订单的信息失败";
                }
                if (num0 == 1) {
                    objectMap.put("yxtOrder", yxtOrderTemp);
                    return ResponseData.success(objectMap);
                } else {
                    msg = "院线通下单失败！！！";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            yxtOrderMapper.deleteById(yxtOrderTemp.getId());
        }
        return ResponseData.error(msg);
    }

    /**
     * 发起支付
     *
     * @param orderNum
     * @param totalPrice
     */
    @RequestMapping(value = "/activePay", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseData<Map<String, Object>> activePay(
            @RequestParam("orderNum") String orderNum,
            @RequestParam("totalPrice") Double totalPrice,
            @RequestParam("openId") String openId) {
        int totalPrice0 = (int) (totalPrice * 100);
        String nonceStr = Sha1Util.getNonceStr();

        // 统一下单请求参数
        PayRequest payRequest = new PayRequest();
        payRequest.setAppid(WxConfig.APPID);
        payRequest.setMch_id(WxConfig.MAC_ID);
        payRequest.setNonce_str(nonceStr);
        payRequest.setSign("sign");
        payRequest.setBody("yuan_xian_tong");
        payRequest.setOut_trade_no(orderNum);
        payRequest.setTotal_fee(Integer.toString(totalPrice0));
        payRequest.setSpbill_create_ip("219.128.144.210");
        payRequest.setNotify_url(WxConfig.NOTIFY_URL);
        payRequest.setTrade_type("JSAPI");
        //payRequest.setOpenid("o22lhwRZP2zbXff7UHH3J8oqH8A0");//临时测试用
        log.info("pay——openid:" + openId);
        payRequest.setOpenid(openId);

        // 统一下单加密参数
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        parameters.put("appid", payRequest.getAppid());
        parameters.put("mch_id", payRequest.getMch_id());
        parameters.put("nonce_str", payRequest.getNonce_str());
        parameters.put("body", payRequest.getBody());
        parameters.put("out_trade_no", payRequest.getOut_trade_no());
        parameters.put("total_fee", payRequest.getTotal_fee());
        parameters.put("spbill_create_ip", payRequest.getSpbill_create_ip());
        parameters.put("notify_url", payRequest.getNotify_url());
        parameters.put("trade_type", payRequest.getTrade_type());
        parameters.put("openid", payRequest.getOpenid());

        String sign = WXPayUtil.createSign("UTF-8", parameters);
        payRequest.setSign(sign);

        try {
            Map<String, Object> map = ConvertMapBean.bean2map(payRequest);
            String xmlStr = WXPayUtil.map2Xmlstring(map);
            String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            String result = HTTPSClient.sendPostXml(url, xmlStr);
            log.info(result);
            Map<String, Object> resultMap = WXPayUtil.xmlString2Map(result);

            long timeStamp = System.currentTimeMillis();
            nonceStr = Sha1Util.getNonceStr();

            // 加密参数
            String packages = "prepay_id=" + resultMap.get("prepay_id").toString();
            SortedMap<Object, Object> secretParams = new TreeMap<Object, Object>();
            secretParams.put("timeStamp", timeStamp);
            secretParams.put("nonceStr", nonceStr);
            secretParams.put("package", packages);
            secretParams.put("appId", WxConfig.APPID);
            secretParams.put("signType", "MD5");
            String secretSign = WXPayUtil.createSign("UTF-8", secretParams);

            // 获取签名
//			String params = "appid=wxfc18f5186b729d15&timestamp="+timeStamp+"&noncestr="+nonceStr+"&package="+resultMap.get("prepay_id")+"&signtype=MD5";
//			MessageDigest crypt = MessageDigest.getInstance("MD5");
//			crypt.reset();
//			crypt.update(params.getBytes("UTF-8"));
//			String signature = WxInterfacesUtil.byteToHex(crypt.digest());

            Map<String, Object> jsonObject = new Hashtable<>();
            jsonObject.put("appId", WxConfig.APPID);
            jsonObject.put("timeStamp", timeStamp);
            jsonObject.put("nonceStr", nonceStr);
            jsonObject.put("package", packages);
            jsonObject.put("signType", "MD5");
            jsonObject.put("sign", secretSign);
            return ResponseData.success(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
        }
        //预支付信息生成失败后回滚
        String orderId = redisTemplate.opsForValue().get("yxtOrderId").toString();
        if (StringUtils.isNotBlank(orderId)) {
            yxtOrderMapper.deleteById(Integer.valueOf(orderId));
        }
        if (StringUtils.isNotBlank(orderId)) {
            Wrapper<YxtOrderDetail> detailWrapper = new EntityWrapper<>();
            detailWrapper.eq("order_id", Integer.valueOf(orderId));
            detailWrapper.eq("is_del", 0);
            detailWrapper.orderBy("id", false);
            List<YxtOrderDetail> details = yxtOrderDetailMapper.selectList(detailWrapper);
            Integer count = Integer.valueOf(redisTemplate.opsForValue().get("goodsNum").toString());
            for (YxtOrderDetail detail1 : details) {
                yxtOrderDetailMapper.deleteById(detail1.getId());
                count--;
                if (count == 0) {
                    break;
                }
            }
        }
        //取出
        List<YxtCoupon> yxtCouponList = redisTemplate.opsForList().range("yxtCouponList", 0, -1);
        log.info(">>>>>>>>>>>>>>>list = {}", yxtCouponList.toString());
        Iterator<YxtCoupon> it = yxtCouponList.iterator();
        while (it.hasNext()) {
            YxtCoupon p = it.next();
            Wrapper<YxtCoupon> yxtCouponWrapper = new EntityWrapper<>();
            yxtCouponWrapper.eq("id", p.getId());
            YxtCoupon coupon = new YxtCoupon();
            coupon.setState(1);
            yxtCouponMapper.update(coupon, yxtCouponWrapper);
        }
        return ResponseData.error("预支付信息生成失败！！！");
    }

    /**
     * 半个小时后取消订单
     *
     * @param orderNum
     * @return
     */
    @RequestMapping(value = "cancelOrder", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseData<Map<String, Object>> cancelOrder(@RequestParam("orderNum") String orderNum) {
        try {
            Wrapper<YxtOrder> orderWrapper = new EntityWrapper<>();
            orderWrapper.eq("order_num", orderNum);
            YxtOrder yxtOrder = new YxtOrder();
            yxtOrder.setDelFlag(1);
            yxtOrder.setState(4);
            int result = yxtOrderMapper.update(yxtOrder, orderWrapper);
            if (result > 0) {
                Wrapper<YxtOrderDetail> detailWrapper = new EntityWrapper<>();
                detailWrapper.eq("order_id", orderNum);
                List<YxtOrderDetail> list = yxtOrderDetailMapper.selectList(detailWrapper);
                List<Integer> couponIds = new ArrayList<>();
                List<Integer> detailIds = new ArrayList<>();
                if (list.size() > 0) {
                    for (YxtOrderDetail detail : list) {
                        couponIds.add(detail.getYxtId());
                        detailIds.add(detail.getId());
                    }
                }
                YxtOrderDetail orderDetail = new YxtOrderDetail();
                orderDetail.setIsDel(1);
                Wrapper<YxtOrderDetail> orderDetailWrapper = new EntityWrapper<>();
                orderDetailWrapper.in("id", detailIds);
                yxtOrderDetailMapper.update(orderDetail, orderDetailWrapper);
                //修改院线通卡的状态
                YxtCoupon coupon = new YxtCoupon();
                coupon.setState(1);
                Wrapper<YxtCoupon> couponWrapper = new EntityWrapper<>();
                couponWrapper.eq("state", 1);
                couponWrapper.in("id", couponIds);
                yxtCouponMapper.update(coupon, couponWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.error("取消订单失败！！！");
        }
        return ResponseData.success();
    }

    /**
     * 进入付款成功界面
     *
     * @return
     */
    @RequestMapping(value = "enterPaySuccess", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseData<Map<String, Object>> enterPaySuccess(
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam("orderNum") String orderNum, @RequestParam("totalPrice") Double totalPrice) {

        //new YxtWxPayController().payNotify(response,request);
        Map<String, Object> objectMap = new HashMap<>();
        Wrapper<YxtOrder> orderWrapper = new EntityWrapper<>();
        orderWrapper.eq("order_num", orderNum);
        orderWrapper.eq("state", 2);
        List<YxtOrder> orderList = yxtOrderMapper.selectList(orderWrapper);
        List<Integer> couponIds = new ArrayList<>();
        if (orderList.size() > 0) {
            Wrapper<YxtOrderDetail> detailWrapper = new EntityWrapper<>();
            detailWrapper.eq("order_id", orderList.get(0).getId());
            List<YxtOrderDetail> detailList = yxtOrderDetailMapper.selectList(detailWrapper);
            for (YxtOrderDetail orderDetail : detailList) {
                couponIds.add(orderDetail.getYxtId());
            }
        }
        Wrapper<YxtCoupon> couponWrapper = new EntityWrapper<>();
        couponWrapper.in("id", couponIds);
        List<YxtCoupon> cardList = yxtCouponMapper.selectList(couponWrapper);

        objectMap.put("orderNum", orderNum);
        objectMap.put("totalPrice", totalPrice);
        objectMap.put("cardList", cardList);

        return ResponseData.success(objectMap);

    }

    /**
     * 获取院线通订单列表
     *
     * @return
     */
    @RequestMapping(value = "getYxtOrderList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseData<List<YxtOrder>> getYxtOrderList(@RequestParam("userId") String userId) {
        Wrapper<YxtOrder> orderWrapper = new EntityWrapper<>();
        orderWrapper.eq(StringUtils.isNotBlank(userId), "user_id", userId);
        orderWrapper.orderBy("updateDate", false);
        List<YxtOrder> list = yxtOrderMapper.selectList(orderWrapper);

        return ResponseData.success(list);
    }

    /**
     * 获取院线通订单详情
     *
     * @return
     */
    @RequestMapping(value = "getYxtOrderDetail", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseData<Map<String, Object>> getYxtOrderDetail(@RequestParam("orderNum") String orderNum) {
        Map<String, Object> objectMap = new HashMap<>();
        if (StringUtils.isBlank(orderNum)) {
            return ResponseData.error("订单号不能为空！！！");
        }
        try {
            Wrapper<YxtOrder> orderWrapper = new EntityWrapper<>();
            orderWrapper.eq("order_num", orderNum);
            YxtOrder order = yxtOrderMapper.selectList(orderWrapper).get(0);
            objectMap.put("order", order);
            if (order.getOrderType().equals("电子订单")) {
                Wrapper<YxtOrderDetail> detailWrapper = new EntityWrapper<>();
                detailWrapper.eq("order_id", order.getId());
                List<YxtOrderDetail> detail = yxtOrderDetailMapper.selectList(detailWrapper);
                List<Integer> cuponList = new ArrayList<>();
                for (YxtOrderDetail orderDetail : detail) {
                    cuponList.add(orderDetail.getYxtId());
                }
                Wrapper<YxtCoupon> couponWrapper = new EntityWrapper<>();
                couponWrapper.eq("state", 2);
                couponWrapper.in("id", cuponList);
                List<YxtCoupon> cardList = yxtCouponMapper.selectList(couponWrapper);
                objectMap.put("cardList", cardList);
            } else {
                SysUser sysUser = sysUserMapper.selectById(order.getUserId());
                objectMap.put("sysUser", sysUser);
                if (StringUtils.isNotBlank(order.getAddressId().toString())) {
                    YxtAddress address = yxtAddressMapper.selectById(order.getAddressId());
                    objectMap.put("address", address);
                }
            }

            objectMap.put("price", price);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseData.success(objectMap);
    }

    /**
     * 获取用户地址
     *
     * @return
     */
    @RequestMapping(value = "/getUserAddress", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseData<List<YxtAddress>> getUserAddress(@RequestParam("userId") String userId, @RequestParam("addressId") String addressId) {
        Wrapper<YxtAddress> wrapper = new EntityWrapper<>();
        if (StringUtils.isNotBlank(addressId)) {
            wrapper.eq(StringUtils.isNotBlank(userId), "id", addressId);
        } else {
            wrapper.eq("user_id", userId);
        }
        List<YxtAddress> list = yxtAddressMapper.selectList(wrapper);
        return ResponseData.success(list);
    }

    /**
     * 添加用户地址
     *
     * @return
     */
    @RequestMapping(value = "/addAddress", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseData<List<YxtAddress>> addAddress(@RequestParam("address") String address) {
        HashMap hashMap = JSON.parseObject(address, HashMap.class);
        YxtAddress yxtAddress = new YxtAddress();
        String userId = hashMap.get("userId").toString();
        yxtAddress.setUserId(userId);
        String consignee = hashMap.get("consignee").toString();
        if (StringUtils.isBlank(consignee)) {
            return ResponseData.error("收货人不能为空！！！");
        }
        yxtAddress.setConsignee(consignee);
        String phone = hashMap.get("phone").toString();
        if (StringUtils.isBlank(phone)) {
            return ResponseData.error("联系电话不能为空！！！");
        }
        yxtAddress.setPhone(phone);
        String area = hashMap.get("area").toString();
        if (StringUtils.isBlank(area)) {
            return ResponseData.error("地址不能为空！！！");
        }
        yxtAddress.setArea(area);
        yxtAddress.setDetailAddress(hashMap.get("detailAddress").toString());
        yxtAddress.setUpdateDate(new Date());
        Integer num = yxtAddressMapper.insert(yxtAddress);
        if (num == 1) {
            return ResponseData.success();
        }
        return ResponseData.error("新增地址失败！！！");
    }


    // 返回目前可购买兑换券数量
    public int returnCardNum() {
        Wrapper<YxtCoupon> couponWrapper = new EntityWrapper<>();
        couponWrapper.eq("state", "1");
        couponWrapper.eq("shelf_state", "1");
        List<YxtCoupon> list = yxtCouponMapper.selectList(couponWrapper);
        return list.size() > 0 ? list.size() : 0;
    }

    //返回院线通订单信息
    public YxtOrder getYxtOrder(String userId, String orderNum) {
        Wrapper<YxtOrder> orderWrapper1 = new EntityWrapper<>();
        orderWrapper1.eq("user_id", userId);
        orderWrapper1.eq("order_num", orderNum);
        orderWrapper1.orderBy("id", false);
        YxtOrder order1 = yxtOrderMapper.selectList(orderWrapper1).get(0);
        return order1;
    }

}
