package com.ruoyi.web.controller.app.pay;


import com.jeequan.jeepay.util.JeepayKit;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.OrderCacheVo;
import com.ruoyi.system.service.*;
import com.ruoyi.web.controller.app.baidu.GsonUtils;
import com.sun.net.httpserver.Authenticator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;

@RestController
@RequestMapping("/wxPay")
public class PayBackController {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private ISysOrderService sysOrderService;

    @Autowired
    private ISysSourceService sysSourceService;

    @Autowired
    private IUserWorkService userWorkService;

    @Autowired
    private IDailySourceService dailySourceService;

    @Transactional
    @GetMapping("/wxRechargeCallback/{mchOrderNo}")
    public AjaxResult wxRechargeCallback(HttpServletRequest req, @PathVariable String mchOrderNo){
        System.out.println("调用回调, 订单号: "+mchOrderNo);
        System.out.println(redisCache.hasKey(mchOrderNo));

//        //--------------------------------------------旧版--------------------------------------------
//        String result = "failure";
//        try {
//            Map<String, Object> map = getParamsMap(req);
//            //获取私钥
//            String apikey = "";
//            //验签
//            if (chackSgin(map, apikey)) {
//                return result;
//            }
//            //订单号
//            String orderNumber = map.get("mchOrderNo").toString();
//            String cacheObject = redisCache.getCacheObject(orderNumber);
//        }
//        catch (Exception e){
//            return result;
//        }
//
//        return result;
//        //-------------------------------------------旧版end----------------------------------------------






        // 获取缓存中的订单信息
        List<OrderCacheVo> list = redisCache.getCacheObject(mchOrderNo);


        //--------------------------------------------------插入订单数据--------------------------------------------------------
        SysOrder sysOrder = new SysOrder();
        sysOrder.setOrderInfoId(mchOrderNo);
        sysOrder.setStatus("0");
        sysOrder.setCreateTime(DateUtils.getNowDate());
        sysOrder.setUserId(list.get(0).getUserId());
        sysOrder.setMoney(list.get(0).getMoney());
        sysOrder.setStartTime(list.get(0).getStartTime());
        sysOrder.setEndTime(list.get(0).getEndTime());
        sysOrder.setSourceId(list.get(0).getSourceId());
        sysOrder.setWay(list.get(0).getWay());

        // 插入系统订单表
        sysOrderService.insertSysOrder(sysOrder);
        //--------------------------------------------------插入订单数据 end-----------------------------------------------------

        SysOrder sysOrder1 = sysOrderService.selectSysOrderList(sysOrder).get(0);
        System.out.println("新订单id"+sysOrder1.getOrderId());



        for(OrderCacheVo orderCacheVo : list){
//            System.out.println(orderCacheVo);
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setOrderInfoId(mchOrderNo);
            orderInfo.setSourceId(orderCacheVo.getSourceId());
            orderInfo.setWorkId(orderCacheVo.getWorkId());

            // 订单初始状态 0, 下订单还未展示
            orderInfo.setStatus("0");
            // 插入订单详情表 order_info
            orderInfoService.insertOrderInfo(orderInfo);

            //----------------------------------------- 更新资源位表 sys_source----------------------------------------------

            // 获取资源位
            SysSource sysSource = sysSourceService.selectSysSourceBySourceId(orderCacheVo.getSourceId());
            // 购买次数+1
            sysSource.setbBought(sysSource.getbBought()+1);

            // 已购未展示
            sysSource.setSourceStatus("1");

            // 将LocalDate转换为ZonedDateTime，指定时区（例如系统默认时区）----------------看看要不要把时间转换成LocalDate
//            ZonedDateTime zoneStartTime = orderCacheVo.getStartTime().atStartOfDay(ZoneId.of("Asia/Shanghai"));

            // 设置资源位起止时间
            sysSource.setStartTime(orderCacheVo.getStartTime());
            sysSource.setEndTime(orderCacheVo.getEndTime());

            // 设置workId
            sysSource.setWorkId(orderCacheVo.getWorkId());
            sysSource.setOrderId(sysOrder1.getOrderId());



//            //---------- 更新资源位上的作品------这时应该不更新------------系统的定时任务更新-------
//            UserWork userWork = userWorkService.selectUserWorkByWorkId(orderCacheVo.getWorkId());
//            sysSource.setWorkAddress(userWork.getWorkAddress());
//            //------------更新资源位上的作品 end -------------------------------------------------------------

            // 更新资源位信息
            sysSourceService.updateSysSource(sysSource);

            // 删除缓存中资源位信息
            redisCache.deleteObject("order_"+orderCacheVo.getSourceId());



            //------------------------------------------更新资源位表 sys_source end------------------------------------------


            //---------------------------------------------20250401更新 不修改work_status的状态, 审核通过的直接过了-------------------------------------------------
            //------------------------------------------更新作品表 user_work 中的 work_status 为 2 以发表待审核----------------------------------
            UserWork userWork = userWorkService.selectUserWorkByWorkId(orderCacheVo.getWorkId());
            userWork.setPostTime(DateUtils.getNowDate());



            //------------------------------------ 更新作品状态 旧版--------------------------------------------------------------
            if(!userWork.getWorkStatus().equals("3")) {
                userWork.setWorkStatus("2");
            }
            userWork.setScenic(sysSource.getScenic());
            userWork.setCity(sysSource.getCity());
            userWork.setPart(sysSource.getPart());
            userWorkService.updateUserWork(userWork);

            //--------------------------------------更新作品状态 旧版end----------------------------------------------------------
            //------------------------------------------更新作品表 user_work 中的 work_status end-------------------------------

            //---------------------------------------daily_source 中 资源位 b_bought+1-----------------------------------------
            LocalDate now = LocalDate.now();
            DailySource dailySource = dailySourceService.getDailySourceBySourceIdAndDate(orderCacheVo.getSourceId(), now);
            if (dailySource != null){
                dailySource.setBought(dailySource.getBought()+1);
            }
            else{
                dailySource = new DailySource();
                dailySource.setSourceId(orderCacheVo.getSourceId());
                dailySource.setDate(now);

            }
            System.out.println(dailySource);

            //---------------------------------------daily_source 中 资源位 b_bought+1 end-------------------------------------

        }




        // 删除订单缓存数据
        redisCache.deleteObject(mchOrderNo);


        // 返回订单 order_id 和 订单详情的id,两者通过order_info_id关联.

        List<Long> orderInfoList = orderInfoService.getOrderInfoByOrderInfoId(mchOrderNo);


        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("orderId", sysOrder1.getOrderId());
        ajaxResult.put("id", orderInfoList);

        return ajaxResult;


    }

    private Boolean checkSign(Map<String, Object> map, String apikey) {
        Object sign = map.remove("sign");
        String reSign = JeepayKit.getSign(map, apikey);

        if (!Objects.equals(reSign, sign)) {
            return true;
        }
        return false;
    }

    private Map<String, Object> getParamsMap(HttpServletRequest req) {
        Map<String, String[]> requestMap = req.getParameterMap();
        Map<String, Object> paramsMap = new HashMap<>();
        requestMap.forEach((key, values) -> {
            String strs = "";
            for (String value : values) {
                strs = strs + value;
            }
            paramsMap.put(key, strs);
        });
        return paramsMap;
    }

}
