package com.sqx.modules.timedtask.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.dao.UserMoneyDetailsDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.errand.dao.TbIndentDao;
import com.sqx.modules.errand.entity.TbIndent;
import com.sqx.modules.goods.dao.GoodsShopDao;
import com.sqx.modules.goods.entity.GoodsShop;
import com.sqx.modules.order.dao.AppOrderDao;
import com.sqx.modules.order.entity.TbOrder;
import com.sqx.modules.pay.controller.app.AliPayController;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.service.WxErrService;
import com.sqx.modules.utils.SenInfoCheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class AutoSendOrder {

    @Autowired
    private TbIndentDao tbIndentDao;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private AppOrderDao appOrderDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserMoneyDao userMoneyDao;
    @Autowired
    private WxErrService wxErrService;
    @Autowired
    private UserMoneyDetailsDao userMoneyDetailsDao;
    @Autowired
    private GoodsShopDao goodsShopDao;
    @Autowired
    private UserService userService;
    @Autowired
    private PayDetailsDao payDetailsDao;

    // //定时自动给骑手推单
    // @Scheduled(cron = "0 * * * * ?", zone = "Asia/Shanghai")
    // public void autoSendOrder(){
    //     CommonInfo three = commonInfoService.findOne(304);
    //     if("是".equals(three.getValue())){
    //         //查看所有支付以后两分钟后的订单（排除同城服务订单）
    //         CommonInfo two = commonInfoService.findOne(302);
    //         CommonInfo one = commonInfoService.findOne(303);
    //         CommonInfo four = commonInfoService.findOne(273);
    //         CommonInfo five = commonInfoService.findOne(310);
    //         Integer maxNum = Integer.parseInt(commonInfoService.findOne(342).getValue());
    //         Double cashDeposit = Double.valueOf(four.getValue());
    //         Double distance = Double.valueOf(one.getValue());
    //         String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    //         String date = getCurrentTime(Integer.valueOf(two.getValue()));
    //         List<TbIndent> tbIndents = tbIndentDao.selectSendOrder(date);
    //         //遍历这些订单，查出距离这些订单最近的骑手（骑手需要没有接单，且在订单位置xx米内）
    //         for(int i = 0;i<tbIndents.size();i++){
    //             GoodsShop goodsShop = goodsShopDao.selectById(tbIndents.get(i).getShopId());
    //                 try{
    //                     if("3".equals(tbIndents.get(i).getIndentType())&&"0".equals(tbIndents.get(i).getBuyType())){
    //                         //没有起点位置，只有终点位置。通过终点位置查距离内最近的骑手
    //                         Long userId = tbIndentDao.selectRiderByDictance(tbIndents.get(i).getUserLng(), tbIndents.get(i).getUserLat(),
    //                                 distance,cashDeposit,maxNum);
    //                         if(userId!=null){
    //                             tbIndentDao.indentReceiv(userId, tbIndents.get(i).getIndentNumber(), format,"4");
    //                             //自动推单以后，消息通知骑手
    //                             UserEntity userEntity = userDao.selectById(userId);
    //                             List<String> msgList=new ArrayList<>();
    //                             msgList.add("接单项目");
    //                             msgList.add(userEntity.getNickName());
    //                             msgList.add(format);
    //                             msgList.add("系统自动推单");
    //                             SenInfoCheckUtil.sendRiderMsg(userEntity.getRiderOpenId(),five.getValue(),msgList,4);
    //                             userService.pushToSingleRider("系统自动推单", "系统已为您自动派单，请及时前往派送！", userEntity.getRiderClientid());
    //                             userService.sendMsgDXB(userEntity.getPhone(), "autosend", 0);
    //                         }
    //                     }else {
    //                         if(goodsShop!=null&&goodsShop.getAutoSendOrder()!=null&&goodsShop.getAutoSendOrder()==0){
    //                             //有起点位置，通过起点位置查距离内最近的骑手
    //                             Long userId = tbIndentDao.selectRiderByDictance(tbIndents.get(i).getShopLng(), tbIndents.get(i).getShopLat(),
    //                                     distance, cashDeposit,maxNum);
    //                             if(userId!=null){
    //                                 tbIndentDao.indentReceiv(userId, tbIndents.get(i).getIndentNumber(), format,"3");
    //                      //           tbIndentDao.indentReceiving(userId, tbIndents.get(i).getIndentNumber(), format);
    //                                 //自动推单以后，消息通知骑手
    //                                 UserEntity userEntity = userDao.selectById(userId);
    //                                 List<String> msgList=new ArrayList<>();
    //                                 msgList.add("接单项目");
    //                                 msgList.add(userEntity.getNickName());
    //                                 msgList.add(format);
    //                                 msgList.add("系统自动推单");
    //                                 SenInfoCheckUtil.sendRiderMsg(userEntity.getRiderOpenId(),five.getValue(),msgList,4);
    //                                 userService.pushToSingleRider("系统自动推单", "系统已为您自动派单，请及时前往派送！", userEntity.getRiderClientid());
    //                                 userService.sendMsgDXB(userEntity.getPhone(), "autosend", 0);
    //                             }
    //                         }
    //                     }
    //                 }catch (Exception e){
    //                     e.printStackTrace();
    //                     log.error("定时任务自动退单异常，异常订单id:"+tbIndents.get(i).getIndentId()+"，异常："+e.getMessage(),e);
    //                 }
    //             }
    //         }
    // }

    //定时取消商家长时间未接单的订单
 //   @Scheduled(cron = "0 * * * * ?", zone = "Asia/Shanghai")
    public void autoCancelOrder(){
        String overTime = getCurrentTime(5);
        List<TbOrder> tbOrderList = appOrderDao.selectOverTimeOrder(overTime);
        cancelOrder(tbOrderList);
    }

    @Transactional
    public void cancelOrder(List<TbOrder> tbOrderList){
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        for(int i = 0;i<tbOrderList.size();i++) {
            TbOrder tbOrder = tbOrderList.get(i);
            UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
            //已支付判断支付方式

            if (tbOrder.getPayType() == 2) {
                //余额支付，直接退还钱包
                userMoneyDao.updateMayMoney(1, tbOrder.getUserId(), tbOrder.getPayMoney().doubleValue());
            } else if(tbOrder.getPayType()==1){
                PayDetails payDetails = payDetailsDao.selectByOrderId(tbOrder.getOrderNumber());
                boolean b = wxErrService.wxRefund(payDetails);
                if(!b){
                    continue;
                }
            }else{
                PayDetails payDetails = payDetailsDao.selectByOrderId(tbOrder.getOrderNumber());
                String code = AliPayController.alipayRefund(payDetails);
                if(StringUtils.isNotBlank(code)){
                    log.error(code);
                    JSONObject jsonObject = JSON.parseObject(code);
                    JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                    String code1 = alipay_trade_refund_response.getString("code");
                    if(!"10000".equals(code1)){
                        continue;
                    }
                }else{
                    continue;
                }
            }
            tbOrder.setStatus(5);
            appOrderDao.updateById(tbOrder);
            //添加退款记录
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(tbOrder.getUserId());
            userMoneyDetails.setTitle("退款");
            userMoneyDetails.setType(1);
            userMoneyDetails.setState(2);
            userMoneyDetails.setMoney(tbOrder.getPayMoney());
            userMoneyDetails.setContent("因商家规定时间内未接单，系统已自动为您取消订单，退款到账："+tbOrder.getPayMoney()+"元，退款按原路返回");
            userMoneyDetails.setCreateTime(format);
            userMoneyDetailsDao.insert(userMoneyDetails);
            //设置小程序消息推送
            CommonInfo one = commonInfoService.findOne(266);
            List<String> msgList=new ArrayList<>();
            msgList.add(tbOrder.getOrderNumber());
            msgList.add("取消订单");
            msgList.add(tbOrder.getPayMoney().toString());
            msgList.add(format);
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(),one.getValue(),msgList,3);
            userService.pushToSingle("下单失败", "因商家长时间未接单，系统已自动为您取消订单，给您带来不便请谅解，如有疑问可联系客服！", userEntity.getClientid());
        }
    }



    /**
     * 获取指定时间几分钟前的时间
     * @return
     */
    public String getCurrentTime(int i){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.MINUTE, -i);
        Date beforeD = beforeTime.getTime();
        String time = sdf.format(beforeD);
        return time;
    }


    //定时更新用户的会员特权
 //   @Scheduled(cron = "0 * * * * ?", zone = "Asia/Shanghai")
    public void autoUpdateVip(){
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        List<UserEntity> userEntities = userDao.selectVipOverdue(date);
        for(int i = 0;i<userEntities.size();i++){
            userEntities.get(i).setIsVip(0);
            userDao.updateById(userEntities.get(i));
        }

    }


}
