package com.platform.yijia.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.platform.yijia.pojo.*;
import com.platform.yijia.service.*;
import com.platform.yijia.utils.CodeMsg;
import com.platform.yijia.utils.FeiEPrinterUtil;
import com.platform.yijia.utils.ResultData;
import com.platform.yijia.utils.redis.RedisCacheUtil;
import com.platform.yijia.utils.weixinapp.WeiXinUserUtil;
import com.platform.yijia.utils.weixinapp.WxPushUtil;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/*
 * <Title> IntegralShoppingMallController </Title>
 * <Description> 油站积分商城模块 </Description>
 * @Author JK
 * @Date 2021年2月24日
 */
@Controller
@RequestMapping("/demo")
public class IntegralShoppingMallController {
    private static Logger logger =(Logger) LoggerFactory.getLogger(IntegralShoppingMallController.class);
    @Resource
    private IntegralWaresService integralWaresService;
    @Resource
    private IntegralOrderService integralOrderService;
    @Resource
    private CustomerPointsService customerPointsService;
    @Resource
    private StationService stationService;
    @Resource
    private CustomerPointsRecordService customerPointsRecordService;
    @Resource
    private RedisCacheUtil redisCacheUtil;
    @Resource
    private WxPushUtil wxPushUtil;
    @Resource
    private IntegralRuleService integralRuleService;
    @Resource
    private IntegralShopPicService integralShopPicService;
    @Resource
    private GzhNewsTemplateService gzhNewsTemplateService;

    //获取积分商城轮播图片
    @RequestMapping(value = "/getIntegralShopPicInfoList", method = RequestMethod.GET)
    @ResponseBody
    public String getIntegralShopPicInfoList(@RequestParam Integer stationId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(stationId !=null){
            IntegralShopPic integralShopPic = new IntegralShopPic();
            integralShopPic.setStationId(stationId);
            List<IntegralShopPic> integralShopPicList = integralShopPicService.getIntegralShopPicList(integralShopPic);
            resultData=ResultData.success(integralShopPicList);
        }else {
            resultData=ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    //获取油站积分商品详情信息
    @RequestMapping(value = "/getIntegralWaresInfo", method = RequestMethod.GET)
    @ResponseBody
    public String getIntegralWaresInfo(@RequestParam Integer id){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(id !=null){
            IntegralWares integralWares = new IntegralWares();
            integralWares.setId(id);
            IntegralWares integralWaresInfo = integralWaresService.getIntegralWaresInfo(integralWares);
            resultData=ResultData.success(integralWaresInfo);
        }else{
            resultData=ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }


    //获取油站积分商品信息
    @RequestMapping(value = "/getIntegralWaresInfoList", method = RequestMethod.GET)
    @ResponseBody
    public String getIntegralWaresInfoList(@RequestParam Integer stationId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(stationId !=null){
            IntegralWares integralWares = new IntegralWares();
            integralWares.setStationId(stationId);
            List<IntegralWares> integralWaresInfoList = integralWaresService.getIntegralWaresInfoList(integralWares);
            resultData=ResultData.success(integralWaresInfoList);
        }else{
            resultData=ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    //生成积分订单
    @RequestMapping(value = "/insertIntegralOrder", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public String insertIntegralOrder(@RequestBody IntegralOrder request){
        logger.info("生成订单所传递参数："+ request.toString());
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        IntegralOrder integralOrder = new IntegralOrder();      //积分订单
        IntegralWares integralWares = new IntegralWares();      //积分商品表
        CustomerPoints customerPoints = new CustomerPoints();       //客户积分表
        CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();     //客户积分记录

        if(StringUtils.isNotBlank(request.getCustomerName())){
            integralOrder.setCustomerName(request.getCustomerName());
            customerPointsRecord.setCustomerName(request.getCustomerName());
        }
        if(StringUtils.isNotBlank(request.getWaresName())){
            integralOrder.setWaresName(request.getWaresName());
        }
        if(request.getExchangeNum() != null){
            integralOrder.setExchangeNum(request.getExchangeNum());
        }
        if(request.getStationId() != null){
            integralOrder.setStationId(request.getStationId());
            customerPoints.setStationId(request.getStationId());
            customerPointsRecord.setStationId(request.getStationId());
        }
        if(request.getWaresId() !=null){
            integralOrder.setWaresId(request.getWaresId());
            integralWares.setId(request.getWaresId());
        }
        if(StringUtils.isNotBlank(request.getUnionId())){
            integralOrder.setUnionId(request.getUnionId());
            customerPoints.setUnionId(request.getUnionId());
            customerPointsRecord.setUnionId(request.getUnionId());
        }
        if(request.getIntegral() !=null){
            integralOrder.setIntegral(request.getIntegral());
            customerPointsRecord.setIntegral(request.getIntegral());
        }

        integralOrder.setStatus("1");   //订单状态

        //订单规则 时间+6位随机数
        Random random = new Random();
        String str="";
        for(int i=0; i<6; i++){
            str+=random.nextInt(10);
        }
        String integralOrderNo = System.nanoTime()+str;
        integralOrder.setIntegralOrderNo(integralOrderNo);
        integralOrder.setExchangeTime(new Date());

        String gzhAppId ="";
        String gzhAppSecret ="";
        String stationName = "";        //油站名称
        Map<String, String> m = stationService.getStationAppIdAndAppSecret(request.getStationId());
        if(m !=null && m.containsKey("stationName") && m.containsKey("gzhAppId") && m.containsKey("gzhAppSecret")){
            stationName = m.get("stationName");
            gzhAppId = m.get("gzhAppId");
            gzhAppSecret = m.get("gzhAppSecret");
            integralOrder.setStationName(stationName);
            customerPointsRecord.setStationName(stationName);
        }

        //更新商品已售数量
        List<IntegralWares> integralWaresInfoList = integralWaresService.getIntegralWaresInfoList(integralWares);
        if(integralWaresInfoList !=null && integralWaresInfoList.size() ==1 && integralWaresInfoList.get(0).getWaresCount() >0 && integralWaresInfoList.get(0).getWaresCount() >= request.getExchangeNum()){
            //更新用户积分
            String surplusPoints ="";   //剩余积分
            String orderSumIntegral ="";        //订单消费总积分
            CustomerPoints customerPointsInfo = customerPointsService.getCustomerPointsInfo(customerPoints);
            if(customerPointsInfo !=null){
                IntegralWares integralWaresInfo = integralWaresService.getIntegralWaresInfo(integralWares);
                //防止前台抓包修改价格做商品价格校验判断
                if(new BigDecimal(integralWaresInfo.getSaleIntegral().intValue()).equals(new BigDecimal(request.getIntegral()))){
                    BigDecimal multiply = new BigDecimal(request.getIntegral()).multiply(new BigDecimal(request.getExchangeNum())); //该订单总积分
                    orderSumIntegral = multiply.toString();
                    //用户剩余积分且大于订单积分
                    if(new BigDecimal(customerPointsInfo.getPoints()).compareTo(multiply) ==1){
                        BigDecimal points = new BigDecimal(customerPointsInfo.getPoints()).subtract(multiply);
                        customerPoints.setPoints(Integer.valueOf(points.toString()));
                        surplusPoints = points.toString();
                        //用户已消费积分累积
                        BigDecimal consumptionPoints = new BigDecimal(customerPointsInfo.getConsumptionPoints()).add(multiply);
                        customerPoints.setConsumptionPoints(Integer.valueOf(consumptionPoints.toString()));
                        customerPoints.setRecentConsumptionDate(new Date());
                        logger.info("用户已使用积分累计: "+ consumptionPoints.toString());
                        customerPointsService.updateCustomerPointsInfo(customerPoints);

                        integralWares.setWaresOutCount(integralWaresInfoList.get(0).getWaresOutCount()+1);
                        integralWares.setWaresCount(integralWaresInfoList.get(0).getWaresCount()-1);
                        logger.info("商品已售数量: "+ integralWares.toString());
                        integralWaresService.updateIntegralWaresInfo(integralWares);
                        //插入客户记录表
                        customerPointsRecord.setRecordType("-");    //客户积分表记录
                        customerPointsRecord.setCreateTime(new Date());
                        //插入客户积分记录
                        customerPointsRecordService.insertCustomerPointsRecordInfo(customerPointsRecord);

                        if(customerPointsInfo.getMobilePhone() !=null){     //用户手机号
                            integralOrder.setMobilePhone(customerPointsInfo.getMobilePhone());
                        }
                        integralOrder.setWaresPic(integralWaresInfo.getWaresPic());
                        integralOrder.setWaresDetail(integralWaresInfo.getWaresDetail());
                        boolean b = integralOrderService.insertIntegralOrder(integralOrder);
                        if (b){
                            //公众号积分消耗消息推送
                            List<WxMpTemplateData> wxMpTemplate = new ArrayList<>();
                            wxMpTemplate.add(new WxMpTemplateData("first","您好！您已成功在"+stationName+"完成积分商品兑换："));
                            wxMpTemplate.add(new WxMpTemplateData("keyword1", request.getCustomerName()));
                            wxMpTemplate.add(new WxMpTemplateData("keyword2", integralOrderNo));
                            wxMpTemplate.add(new WxMpTemplateData("keyword3", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
                            wxMpTemplate.add(new WxMpTemplateData("keyword4", request.getWaresName()+"   x "+ request.getExchangeNum()));
                            wxMpTemplate.add(new WxMpTemplateData("keyword5", orderSumIntegral));
                            wxMpTemplate.add(new WxMpTemplateData("remark",
                                    "截止至" + new SimpleDateFormat(" yyyy年MM月dd日HH时mm分").format(new Date())+"，您在"+stationName+"的积分值还剩余 "+surplusPoints+" 分"));
                            //String templateId = "9EWrreI-P8r4xDgoOcczC4jHt1v0HEjKzkgVRDzoNXA";  //积分兑换成功通知模板
                            GzhNewsTemplate gzhNewsTemplate = new GzhNewsTemplate();
                            gzhNewsTemplate.setStationId(request.getStationId());
                            gzhNewsTemplate.setTemplateType("2");
                            GzhNewsTemplate gzhNewsTemplateInfo = gzhNewsTemplateService.getGzhNewsTemplate(gzhNewsTemplate);
                            if(gzhNewsTemplateInfo !=null && gzhNewsTemplateInfo.getTemplateId() !=null){
                                wxPushUtil.push(gzhAppId, gzhAppSecret, gzhNewsTemplateInfo.getTemplateId(), request.getOpenId(), wxMpTemplate);
                                resultData=ResultData.success(CodeMsg.SUCCESS);
                            }
                            //打印机打印小票
                            List<Map<String, Object>> stationPrinterList = stationService.getStationPrinterList(request.getStationId());
                            if(stationPrinterList != null && stationPrinterList.get(0).get("integralPrintFlag").toString().equals("1")){
                                if(stationPrinterList.get(0).get("printerSn") !=null){
                                    String sn=stationPrinterList.get(0).get("printerSn").toString();
                                    String content1;
                                    content1 = "<CB>积分订单小票</CB><BR>";
                                    content1 += "订单号："+integralOrderNo+"  <BR>";
                                    content1 += "交易时间："+new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss").format(integralOrder.getExchangeTime())+" <BR>";
                                    content1 += "油站："+stationName+"  <BR>";
                                    content1 += "兑换商品："+integralOrder.getWaresName()+"  <BR>";
                                    content1 += "商品数量：x "+integralOrder.getExchangeNum()+"  <BR>";
                                    content1 += "消耗积分： "+orderSumIntegral+" 分<BR>";
                                    content1 += "剩余积分： "+surplusPoints+" 分<BR>";
                                    //content1 += "<BOLD><B>消耗积分： "+orderSumIntegral+" 分</B></BOLD><BR>";
                                    content1 += "客户昵称： "+integralOrder.getCustomerName()+"  <BR>";
                                    content1 += "<BR>";
                                    String printInfo = FeiEPrinterUtil.printReceipt(sn, content1);
                                    com.alibaba.fastjson.JSONObject jsonObject = JSONObject.parseObject(printInfo);
                                    if(jsonObject != null && jsonObject.getString("msg").equals("ok")){
                                        integralOrder.setPrinterStatus("1");
                                        integralOrderService.updateIntegralOrder(integralOrder);
                                    }
                                }
                            }
                        }else {
                            resultData=ResultData.error(CodeMsg.REQUEST_FAIL);
                        }
                    }else {
                        resultData=ResultData.error(CodeMsg.INTEGRAL_INSUFFICIENT);
                    }
                }else {
                    resultData=ResultData.error(CodeMsg.CHECK_DATA_ERROR);
                }
            }
        }else {
            resultData=ResultData.error(CodeMsg.WARSECOUNT_FAIL);
        }
        return gson.toJson(resultData);
    }

    //获取公众号消息模板
//    @RequestMapping(value = "/getGzhNewsTemplate", method = RequestMethod.GET)
//    @ResponseBody
//    public String getGzhNewsTemplate(@RequestParam Integer stationId, String templateType){
//        Gson gson =new Gson();
//        //返回结果集
//        ResultData resultData = null;
//        if(stationId !=null){
//            GzhNewsTemplate gzhNewsTemplate = new GzhNewsTemplate();
//            gzhNewsTemplate.setStationId(stationId);
//            gzhNewsTemplate.setTemplateType(templateType);
//            GzhNewsTemplate gzhNewsTemplate1 = gzhNewsTemplateService.getGzhNewsTemplate(gzhNewsTemplate);
//            resultData=ResultData.success(gzhNewsTemplate1);
//        }else {
//            resultData=ResultData.success(CodeMsg.REQUEST_FAIL);
//        }
//        return gson.toJson(resultData);
//    }

    //获取用户积分订单列表
    @RequestMapping(value = "/getUserIntegralOrderList", method = RequestMethod.GET)
    @ResponseBody
    public String getUserIntegralOrderList(@RequestParam String unionId, Integer stationId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(unionId !=null){
            IntegralOrder integralOrder = new IntegralOrder();
            integralOrder.setUnionId(unionId);
            integralOrder.setStationId(stationId);
            List<IntegralOrder> integralOrderList = integralOrderService.getUserIntegralOrderList(integralOrder);
            resultData=ResultData.success(integralOrderList);
        }else {
            resultData=ResultData.success(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    //获取客户积分信息
    @RequestMapping(value = "/getCustomerPointsInfo", method = RequestMethod.GET)
    @ResponseBody
    public String getCustomerPointsInfo(@RequestParam String unionId, Integer stationId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(unionId !=null){
            CustomerPoints customerPoints  =new CustomerPoints();
            customerPoints.setUnionId(unionId);
            customerPoints.setStationId(stationId);
            CustomerPoints customerPointsInfo = customerPointsService.getCustomerPointsInfo(customerPoints);
            resultData=ResultData.success(customerPointsInfo);
        }else {
            resultData=ResultData.success(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    //获取客户积分记录信息
    @RequestMapping(value = "/getCustomerPointsRecordList", method = RequestMethod.GET)
    @ResponseBody
    public String getCustomerPointsRecordList(@RequestParam String unionId, Integer stationId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(unionId !=null){
            CustomerPointsRecord customerPointsRecord  =new CustomerPointsRecord();
            customerPointsRecord.setUnionId(unionId);
            customerPointsRecord.setStationId(stationId);
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.MONTH, -6);
            Date time = c.getTime();
            customerPointsRecord.setCreateTime(time);
            List<CustomerPointsRecord> customerPointsRecordList = customerPointsRecordService.getCustomerPointsRecordList(customerPointsRecord);
            resultData=ResultData.success(customerPointsRecordList);
        }else {
            resultData=ResultData.success(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    //获取油站油品积分规则信息 根据油站ID和油品名称
    @RequestMapping(value = "/getIntegralRuleListByOilNameAndStationId", method = RequestMethod.GET)
    @ResponseBody
    public String getIntegralRuleList(@RequestParam Integer stationId, String oilName, String oilType){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(stationId !=null){
            IntegralRule integralRule = new IntegralRule();
            integralRule.setStationId(stationId);
            integralRule.setOilName(oilName);
            integralRule.setOilType(oilType);
            integralRule.setEmptyDate(new Date()); //有效期时间是否大于当前时间
            List<IntegralRule> integralRuleList = integralRuleService.getIntegralRule(integralRule);
            resultData=ResultData.success(integralRuleList);
        }else {
            resultData=ResultData.success(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    //获取油站积分规则信息 根据油站ID
    @RequestMapping(value = "/getIntegralRuleList", method = RequestMethod.GET)
    @ResponseBody
    public String getIntegralRuleList(@RequestParam Integer stationId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(stationId !=null){
            IntegralRule integralRule = new IntegralRule();
            integralRule.setStationId(stationId);
            integralRule.setEmptyDate(new Date()); //有效期时间是否大于当前时间
            List<IntegralRule> integralRuleList = integralRuleService.getIntegralRule(integralRule);
            resultData=ResultData.success(integralRuleList);
        }else {
            resultData=ResultData.success(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }


}
