package com.bweb.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.ForbbidenTime;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.IDGenerator;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.HuiLianTongConfig;
import com.hai.config.HuiLianTongUnionCardConfig;
import com.hai.config.QianZhuConfig;
import com.hai.config.WxOrderConfig;
import com.hai.entity.*;
import com.hai.model.OrderRefundModel;
import com.hai.model.ResponseData;
import com.hai.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/3/26 23:08
 */
@Controller
@RequestMapping(value = "/test")
@Api(value = "订单接口")
public class HighTestController {

    private static Logger log = LoggerFactory.getLogger(HighTestController.class);


    @Resource
    private OutRechargeOrderService outRechargeOrderService;

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private HighUserService highUserService;


    @Resource
    private HighOilCardService oilCardService;

    @Resource
    private ApiProductService apiProductService;

    @Resource
    private BsRechargeCodeService rechargeCodeService;

    @Resource
    private OutRechargePriceService rechargePriceService;

    @RequestMapping(value = "/kfcRefund", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "KFC退款")
    public ResponseData kfcRefund(@RequestParam(name = "orderNo", required = true) String orderNo,HttpServletRequest request) {
        try {
            OrderRefundModel orderRefundModel = null;
            if (StringUtils.isNotBlank(orderNo)) {
                // 查询订单
                HighOrder order = highOrderService.getOrderByOrderNo(orderNo);
                // 订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消   6.退款中   7.拒绝退款
                if (order != null && order.getOrderStatus() == 2) {
                    orderRefundModel = WxOrderConfig.orderToRefund(order.getPaySerialNo(), order.getPayRealPrice(), "1609882817", order.getPayRealPrice());
                    if(orderRefundModel.getResult_code().equals("SUCCESS")) {
                        for (HighChildOrder childOrder : order.getHighChildOrderList()) {
                            childOrder.setChildOrdeStatus(4);
                        }
                        order.setOrderStatus(4);
                        order.setRefundTime(new Date());
                        order.setRefundPrice(order.getPayRealPrice());
                        highOrderService.updateOrder(order);
                        return ResponseMsgUtil.success(orderRefundModel);
                    }
                }
            }
            return ResponseMsgUtil.success(orderRefundModel);

        } catch (Exception e) {
            log.error("HighUserCardController --> oilCardRefund() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/oilCardRefund", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "油卡退款")
    public ResponseData oilCardRefund(@RequestParam(name = "orderNo", required = true) String orderNo,HttpServletRequest request) {
        try {

            oilCardService.refund(orderNo);
            return ResponseMsgUtil.success("");

        } catch (Exception e) {
            log.error("HighUserCardController --> oilCardRefund() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/resolveResponse",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "解析")
    public ResponseData resolveResponse(
            @RequestParam(name = "data", required = false) String data
    ) {
        try {
            JSONObject cardInfoObject = HuiLianTongUnionCardConfig.resolveResponse(data);
            return ResponseMsgUtil.success(cardInfoObject);

        } catch (Exception e) {
            log.error("getUserByTelephone",e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/consumption",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "工会卡重新发起充值")
    public ResponseData consumption(
            @RequestParam(name = "orderNo", required = false) String orderNo
    ) {
        try {

            OutRechargeOrder order = outRechargeOrderService.findByOrderNo(orderNo);

            String goodsDesc = "重新充值";
            String tranDesc = order.getRechargeContent() + "重新充值" + order.getPayRealPrice() + "元";
            String instCode = "11101527";
            String businessType = "hisen_consume";

            String orderNoPost = "AGAIN" + DateUtil.date2String(new Date(), "yyyyMMddHHmmss") + IDGenerator.nextId(5);

            // 工会卡支付
            JSONObject consumption = HuiLianTongUnionCardConfig.consumption(orderNoPost, order.getLaborUnionCard(), order.getPayRealPrice(), businessType, instCode, goodsDesc, tranDesc);

            JSONObject cardInfoObject = HuiLianTongUnionCardConfig.resolveResponse(consumption.getString("data"));
            return ResponseMsgUtil.success(cardInfoObject);

        } catch (Exception e) {
            log.error("getUserByTelephone",e);
            return ResponseMsgUtil.exception(e);
        }
    }




    @RequestMapping(value = "/getHuiLianTongCardConsume", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询汇联通工会卡消费记录")
    public ResponseData getHuiLianTongCardConsume(@RequestParam(name = "businessType", required = true) String businessType,
                                                  @RequestParam(name = "cardNo", required = true) String cardNo,
                                                  @RequestParam(name = "sdate", required = true) Long sdate,
                                                  @RequestParam(name = "edate", required = true) Long edate,
                                                  @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                                  @RequestParam(name = "pageSize", required = true) Integer pageSize,
                                                  HttpServletRequest request) {
        try {


            JSONObject consumptionRecord = HuiLianTongUnionCardConfig.queryConsumptionRecordByBusiness(businessType, cardNo, sdate, edate, pageNum, pageSize);
            if (StringUtils.isBlank(consumptionRecord.getString("data"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQUEST_ERROR, "");
            }

            JSONArray array = HuiLianTongUnionCardConfig.resolveResponse(consumptionRecord.getString("data")).getJSONArray("records");
//
//            String s = "HFR1";
//            String s1 = "AGAIN1";
//
//            List<JSONObject> list = new ArrayList<>();
//
//
//            for (Object data : array) {
//                JSONObject dataObject = (JSONObject) data;
//                if (!StringUtils.contains(dataObject.getString("orderNo"),s) && !StringUtils.contains(dataObject.getString("orderNo"),s1)) {
//                    list.add(dataObject);
//                }
//


            return ResponseMsgUtil.success(array);

        } catch (Exception e) {
            log.error("HighUserCardController --> getHuiLianTongCardConsume() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/orderToRefund", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "积分充值退款")
    public ResponseData orderToRefund(@RequestParam(name = "orderId", required = true) Long orderId ,HttpServletRequest request) {
        try {
            HighOrder highOrder = highOrderService.getOrderById(orderId);
            // 微信退款
            OrderRefundModel orderRefundModel = WxOrderConfig.orderToRefund(highOrder.getPaySerialNo(), highOrder.getPayRealPrice(), highOrder.getPayRealPrice());
            if(orderRefundModel.getResult_code().equals("SUCCESS")) {
                for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {
                    childOrder.setChildOrdeStatus(4);
                }
                highOrder.setOrderStatus(4);
                highOrder.setRefundTime(new Date());
                highOrder.setRefundPrice(highOrder.getPayRealPrice());
                highOrderService.updateOrder(highOrder);
            }
            if (highUserService.findGoldRepeat(3 , highOrder.getId())) {
                String remark = "订单" + highOrder.getOrderNo() + "退款积分：" +  highOrder.getPayRealPrice().multiply(BigDecimal.valueOf(100)).intValue();
                highUserService.goldHandle(highOrder.getMemId(), highOrder.getPayRealPrice().multiply(BigDecimal.valueOf(100)).intValue(), 2, 3, highOrder.getId() , remark);
            }else {
                log.error("orderToPay error!", "已有退款记录");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "已有退款记录");
            }
            return ResponseMsgUtil.success(orderRefundModel);

        } catch (Exception e) {
            log.error("HighOrderController --> orderToRefund() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/orderToRefundByHlt", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "汇联通充值退款")
    public ResponseData orderToRefundByHlt(@RequestParam(name = "orderId", required = true) Long orderId ,HttpServletRequest request) {
        try {
            HighOrder highOrder = highOrderService.getOrderById(orderId);
            // 微信退款
            OrderRefundModel orderRefundModel = WxOrderConfig.orderToRefund(highOrder.getPaySerialNo(), highOrder.getPayRealPrice(), WxOrderConfig.MCH_ID_1619676214 , highOrder.getPayRealPrice());
            if(orderRefundModel.getResult_code().equals("SUCCESS")) {
                for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {
                    childOrder.setChildOrdeStatus(4);
                }
                highOrder.setOrderStatus(4);
                highOrder.setRefundTime(new Date());
                highOrder.setRefundPrice(highOrder.getPayRealPrice());
                highOrderService.updateOrder(highOrder);
            }
            return ResponseMsgUtil.success(orderRefundModel);

        } catch (Exception e) {
            log.error("HighOrderController --> orderToRefund() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/rechargeOrderToRefund", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "话费退款")
    public ResponseData rechargeOrderToRefund(
            @RequestParam(name = "orderId", required = true) Long orderId) {
        try {
            outRechargeOrderService.rechargeOrderToRefund(orderId);

            return ResponseMsgUtil.success("退款成功");

        } catch (Exception e) {
            log.error("HighOrderController --> unionStagingPay() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getStarbucksProducts", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "更新星巴克商品")
    public ResponseData getStarbucksProducts(HttpServletRequest request) {
        try {

            JSONObject jsonObject = QianZhuConfig.getStarbucksProducts(1 , 200);

            JSONObject object = jsonObject.getJSONObject("data");
            JSONArray array = object.getJSONArray("items");
              for (Object data : array) {
                JSONObject dataObject = (JSONObject) data;

                ApiStarbucksProducts starbucksProducts = apiProductService.findStarbucksProductsByGoodsId(dataObject.getLong("id"));

                if (dataObject.getInteger("shelfStatus") == 5) {
                    if (starbucksProducts == null) {
                        starbucksProducts = new ApiStarbucksProducts();
                    }
                    starbucksProducts.setCategoryName(dataObject.getString("categoryName"));
                    starbucksProducts.setCream(dataObject.getString("cream"));
                    starbucksProducts.setCupSize(dataObject.getString("cupSize"));
                    starbucksProducts.setDefaultImage(dataObject.getString("defaultImage"));
                    starbucksProducts.setDes(dataObject.getString("des"));
                    starbucksProducts.setEspresso(dataObject.getString("espresso"));
                    starbucksProducts.setMarketGrandePrice(dataObject.getBigDecimal("marketGrandePrice"));
                    starbucksProducts.setMarketTallPrice(dataObject.getBigDecimal("marketTallPrice"));
                    starbucksProducts.setMarketVentiPrice(dataObject.getBigDecimal("marketVentiPrice"));
                    starbucksProducts.setSalesGrandePrice(dataObject.getBigDecimal("salesGrandePrice"));
                    starbucksProducts.setSalesTallPrice(dataObject.getBigDecimal("salesTallPrice"));
                    starbucksProducts.setSalesVentiPrice(dataObject.getBigDecimal("salesVentiPrice"));
                    starbucksProducts.setMilk(dataObject.getString("milk"));
                    starbucksProducts.setMilkBubble(dataObject.getString("milkBubble"));
                    starbucksProducts.setName(dataObject.getString("name"));
                    starbucksProducts.setTemperature(dataObject.getString("temperature"));
                    if (starbucksProducts.getId() == null) {
                        starbucksProducts.setCreateTime(new Date());
                        starbucksProducts.setOperatorId(9999L);
                        starbucksProducts.setOperatorName("系统生成");
                        starbucksProducts.setStatus(100);
                        starbucksProducts.setGoodsId(dataObject.getLong("id"));
                        apiProductService.insertStarbucksProducts(starbucksProducts);
                    } else {
                        starbucksProducts.setUpdateTime(new Date());
                        apiProductService.updateStarbucksProducts(starbucksProducts);
                    }
                }
            }
            return ResponseMsgUtil.success("商品生成成功");

        } catch (Exception e) {
            log.error("HighUserCardController --> oilCardRefund() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/getKfcStore", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询肯德基门店")
    public ResponseData getKfcStore(HttpServletRequest request) {
        try {

            JSONObject jsonObject = QianZhuConfig.getKfcStore();

            JSONArray object = jsonObject.getJSONArray("data");
            for (Object data : object) {
                JSONObject dataObject = (JSONObject) data;
                Map<String, Object> mapStore = new HashMap<>();
                mapStore.put("storeCode" , dataObject.getString("storeCode"));
                ApiKfcStores apiKfcStores = apiProductService.findKfcStores(mapStore);

                if (apiKfcStores == null) {
                    apiKfcStores = new ApiKfcStores();
                }
                apiKfcStores.setProvinceCode(dataObject.getString("provinceCode"));
                apiKfcStores.setProvinceName(dataObject.getString("provinceName"));
                apiKfcStores.setCityCode(dataObject.getString("cityCode"));
                apiKfcStores.setCityName(dataObject.getString("cityName"));
                apiKfcStores.setCityNameFirstLetter(dataObject.getString("cityNameFirstLetter"));
                apiKfcStores.setKfcCityId(dataObject.getInteger("kfcCityId"));
                apiKfcStores.setKfcCityCode(dataObject.getString("kfcCityCode"));
                apiKfcStores.setStoreName(dataObject.getString("storeName"));
                apiKfcStores.setStoreCode(dataObject.getString("storeCode"));
                apiKfcStores.setLon(dataObject.getString("lon"));
                apiKfcStores.setLat(dataObject.getString("lat"));
                apiKfcStores.setAddress(dataObject.getString("address"));
                apiKfcStores.setStartTime(dataObject.getString("startTime"));
                apiKfcStores.setEndTime(dataObject.getString("endTime"));
                apiKfcStores.setStoreStatus(dataObject.getInteger("storeStatus"));
                apiKfcStores.setShelfStatus(dataObject.getInteger("shelfStatus"));

                if (apiKfcStores.getId() == null) {
                    apiKfcStores.setCreateTime(new Date());
                    apiKfcStores.setOperatorId(9999L);
                    apiKfcStores.setOperatorName("系统生成");
                    apiKfcStores.setStatus(100);
                    apiProductService.insertKfcStore(apiKfcStores);
                } else {
                    apiKfcStores.setUpdateTime(new Date());
                    apiProductService.updateKfcStore(apiKfcStores);
                }
            }
            return ResponseMsgUtil.success("生成成功");

        } catch (Exception e) {
            log.error("HighUserCardController --> oilCardRefund() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/insertCity", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "插入城市")
    public ResponseData insertCity(HttpServletRequest request) {
        try {

            JSONObject jsonObject = QianZhuConfig.getAllCities();

            JSONArray object = jsonObject.getJSONArray("data");
            for (Object data : object) {
                JSONObject dataObject = (JSONObject) data;

                ApiCity apiCity = new ApiCity();

                apiCity.setCityInitial(dataObject.getString("cityInitial"));
                apiCity.setCityCode(dataObject.getString("cityCode"));
                apiCity.setCityName(dataObject.getString("cityName"));
                apiCity.setProvinceCode(dataObject.getString("provinceCode"));
                apiCity.setProvinceName(dataObject.getString("provinceName"));
                apiCity.setCreateTime(new Date());
                apiCity.setUpdateTime(new Date());
                apiCity.setOperatorId(9999L);
                apiCity.setOperatorName("系统生成");
                apiCity.setStatus(100);
                apiProductService.insertCity(apiCity);
            }
            return ResponseMsgUtil.success("生成成功");

        } catch (Exception e) {
            log.error("HighUserCardController --> oilCardRefund() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/updatePrice", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "更新价格")
    public ResponseData updatePrice() {
        try {

            List<OutRechargePrice> list = rechargePriceService.getListRechargePrice(new HashMap<>());

            for (OutRechargePrice rechargePrice : list) {
                BsRechargeCode rechargeCode = new BsRechargeCode();

                if (rechargePrice.getGoodsId() != null) {
                    rechargeCode.setStatus(100);
                    rechargeCode.setUpdateTime(new Date());
                    rechargeCode.setCreateTime(new Date());
                    rechargeCode.setGoodsId(rechargePrice.getGoodsId().toString());
                    rechargeCode.setOperatorName("系统自动更新");
                    rechargeCode.setType(1);
                    rechargeCode.setSourceId(rechargePrice.getId().toString());
                    rechargeCode.setRechargePlatform(2);
                    rechargeCodeService.insertRechargeCode(rechargeCode);
                }

            }

            return ResponseMsgUtil.success("生成成功");

        } catch (Exception e) {
            log.error("HighUserCardController --> oilCardRefund() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/test", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "测试")
    public ResponseData test(@RequestBody JSONObject object) {
        try {


            return ResponseMsgUtil.success(HuiLianTongConfig.test(object));

        } catch (Exception e) {
            log.error("HighOrderController --> unionStagingPay() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/下单", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "支付")
    public ResponseData insertV2() {
        try {

            String orderNo = "HF2022080818504922206";
            JSONObject object = QianZhuConfig.insertV2("PLM100024", orderNo, "15585850137");
            object.put("orderNo", orderNo);
            return ResponseMsgUtil.success(object);
        } catch (Exception e) {
            log.error("HighOrderController --> getBackendToken() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
