package com.sqx.modules.datacentre.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
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.coupon.dao.TbCouponUserDao;
import com.sqx.modules.coupon.entity.TbCouponUser;
import com.sqx.modules.datacentre.dao.DataCentreDao;
import com.sqx.modules.datacentre.service.DataCentreService;
import com.sqx.modules.errand.entity.Feedback;
import com.sqx.modules.errand.entity.TbIndent;
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.CashOut;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.service.WxErrRiderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

@Service
@Slf4j
public class DataCentreServiceImpl implements DataCentreService {

    @Autowired
    private DataCentreDao dataCentreDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private AppOrderDao appOrderDao;
    @Autowired
    private WxErrRiderService wxErrRiderService;
    @Autowired
    private AliPayController aliPayController;
    @Autowired
    private UserService userService;
    @Autowired
    private PayDetailsDao payDetailsDao;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private TbCouponUserDao tbCouponUserDao;

    @Override
    public Result dataCentre() {
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        HashMap dataCenter = new HashMap();
        //总用户数
        int allCount = dataCentreDao.findAllCount();
        //今日新增用户数
        int dayAddUser = dataCentreDao.findDayAddUser(format);
        //本月新增用户数
        int monthAddUser = dataCentreDao.findMonthAddUser(format);
        //本年新增用户数
        int yearAddUser = dataCentreDao.findYearAddUser(format);
        //今日收入
        BigDecimal dayIncome = dataCentreDao.findDayIncome(format);
        //本月收入
        BigDecimal monthIncome = dataCentreDao.findMonthIncome(format);
        //本年收入
        BigDecimal yearIncome = dataCentreDao.findYearIncome(format);
        //今日接单数量
        int indentCount = dataCentreDao.findIndentCount(format);
        dataCenter.put("allCount", allCount);
        dataCenter.put("dayAddUser", dayAddUser);
        dataCenter.put("monthAddUser", monthAddUser);
        dataCenter.put("yearAddUser", yearAddUser);
        dataCenter.put("dayIncome", dayIncome);
        dataCenter.put("monthIncome", monthIncome);
        dataCenter.put("yearIncome", yearIncome);
        dataCenter.put("indentCount", indentCount);
        return Result.success().put("data", dataCenter);
    }

    @Override
    public Result selectPayOrderAnalyze(Integer page, Integer limit, String date, String dateType) {
        Page<TbOrder> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(dataCentreDao.selectPayOrderAnalyze(pages, date, dateType));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result selectAllUser(Integer page, Integer limit, String userName, String phone) {
        Page<UserEntity> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(userDao.selectUser(pages, userName, phone));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result selectUserById(Long userId) {
        UserEntity userEntity = userDao.selectUserById(userId);
        //本月发单数量， 本月充值金额，
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        Integer orderMonth = dataCentreDao.sumOrderMonth(userId, date);
        Integer joinOrderMonth = dataCentreDao.sumJoinOrderMonth(userId, date);
        BigDecimal topUpMonth = dataCentreDao.sumTopUpMonth(userId, date);
        BigDecimal riderMoney = dataCentreDao.sumRiderMoney(userId);
        BigDecimal cashMoney = dataCentreDao.sumCashMoney(userId, date);
        //本月派单数量
        userEntity.setOrderMonth(orderMonth);
        //本月接单数量
        userEntity.setJoinOrderMonth(joinOrderMonth);
        //本月充值金额
        userEntity.setTopUpMonth(topUpMonth);
        //骑手收入
        userEntity.setRiderMoney(riderMoney);
        //本月提现
        userEntity.setCashMoney(cashMoney);
        return Result.success().put("data", userEntity);
    }

    @Override
    public Result selectOrderData(String date, String dateType) {
        HashMap hashMap = new HashMap();
        BigDecimal sumMoney = appOrderDao.selectSumMoney(date, dateType,null);
        int countOrder = appOrderDao.selectCountOrder(date, dateType,null);
        //到店订单数
        int takeCount = dataCentreDao.selectTakeCount(1, null, date, dateType);
        //外卖订单数
        int takeCount2 = dataCentreDao.selectTakeCount(2, null, date, dateType);
        //到店订单金额
        BigDecimal takeMoney = dataCentreDao.selectTakeMoney(1, null, date, dateType);
        //外卖订单金额
        BigDecimal takeMoney1 = dataCentreDao.selectTakeMoney(2, null, date, dateType);
        //退款订单数
        int cancelOrderCount = dataCentreDao.cancelOrderCount(null, date, dateType);
        //退款金额
        BigDecimal cancelOrderMoney = dataCentreDao.cancelOrderMoney(null, date, dateType);
        hashMap.put("sumMoney", sumMoney);
        hashMap.put("countOrder", countOrder);
        hashMap.put("takeCount", takeCount);
        hashMap.put("takeCount2", takeCount2);
        hashMap.put("takeMoney", takeMoney);
        hashMap.put("takeMoney1", takeMoney1);
        hashMap.put("cancelOrderCount", cancelOrderCount);
        hashMap.put("cancelOrderMoney", cancelOrderMoney);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result selectTopUpStatistics(String date, String dateType) {
        BigDecimal topUpStatistics = dataCentreDao.selectTopUpStatistics(date, dateType);

        return Result.success().put("data", topUpStatistics);
    }

    @Override
    public Result findAllCertification(Integer page,Integer limit,String userName,String phone, String checkCertification) {
        Page<UserEntity> pages=new Page<>(page,limit);
        return Result.success().put("data", new PageUtils(dataCentreDao.findAllCertification(pages, userName, phone,checkCertification )));
    }

    @Transactional
    @Override
    public Result checkCertification(Long userId, String checkCertification, String checkCertificationMessage) {
        if("2".equals(checkCertification)){
            UserEntity userEntity = userService.selectUserById(userId);
            PayDetails payDetails = payDetailsDao.selectByOrderId(userEntity.getCheckNumber());
            if(payDetails.getType().equals(4)){
                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)){
                        return Result.error("退款失败！"+alipay_trade_refund_response.getString("sub_msg"));
                    }
                }else{
                    return Result.error("退款失败！");
                }
            }else{
                boolean flag= wxErrRiderService.wxRefund(payDetails);
                if(!flag){
                    return Result.error("退款失败，请联系客服！");
                }
            }
            UserEntity userEntity1 = new UserEntity();
            userEntity1.setUserId(userId);
            userEntity1.setCheckCertification("2");
            userEntity1.setCashDeposit(BigDecimal.valueOf(0));
            userDao.updateById(userEntity1);
            //退保证金的记录
            UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setTitle("退还保证金");
            userMoneyDetails.setContent("实名认证审核未通过，保证金："+payDetails.getMoney()+"元已退还至原支付途径");
            userMoneyDetails.setType(2);
            userMoneyDetails.setClassify(1);
            userMoneyDetails.setMoney(BigDecimal.valueOf(payDetails.getMoney()));
            userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss").format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
        }
        dataCentreDao.checkCertification(userId, checkCertification, checkCertificationMessage);
        return Result.success();
    }

    @Override
    public Result findCertification(Long userId) {
        UserEntity certification = dataCentreDao.findCertification(userId);
        return Result.success().put("data", certification);
    }

    @Override
    public Result rankingList(Integer page, Integer limit, String address,String date, String dateType) {
        Page<TbIndent> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(dataCentreDao.rankingList(pages, address, date, dateType));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result selectShopCenter(String date, String dateType, Integer page, Integer limit) {
        HashMap hashMap = new HashMap();
        //新增门店数量
        int newShopCount = dataCentreDao.selectNewShopCount(date, dateType);
        //门店收益排行榜
        Page<TbOrder> pages=new Page<>(page,limit);
        IPage<TbOrder> tbOrderIPage = dataCentreDao.selectRankingList(pages, date, dateType);
        for(int i = 0;i<limit;i++){
            Integer a = ((page-1)*limit)+i+1;
            if(tbOrderIPage.getRecords().size()>i){
                tbOrderIPage.getRecords().get(i).setRank(a);
            }
        }
        PageUtils pageUtils = new PageUtils(tbOrderIPage);
        hashMap.put("newShopCount", newShopCount);
        hashMap.put("pageUtils", pageUtils);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result selectUserCenter(String date, String dateType) {
        HashMap hashMap = new HashMap();
        int userCount = dataCentreDao.allUserCount(date, dateType);
        int phoneUserCount = dataCentreDao.phoneUserCount(date, dateType);
        hashMap.put("allUserCount", userCount);
        hashMap.put("phoneUserCount", phoneUserCount);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result selectUserFeedback(String userEmail, Integer page, Integer limit) {
        Page<Feedback> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(dataCentreDao.selectUserFeedback(pages, userEmail));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result findUserAddIndent(Long userId, Integer page, Integer limit) {
        Page<TbIndent> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(dataCentreDao.findUserAddIndent(pages, userId));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result findUserReceivingIndent(Long userId, Integer page, Integer limit) {
        Page<TbIndent> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(dataCentreDao.findUserReceivingIndent(pages, userId));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result findTopUpMoney(Long userId, Integer page, Integer limit, String startTime, String endTime){
        Page<PayDetails> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(dataCentreDao.findTopUpMoney(pages, userId, startTime, endTime));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result findWithdrawMoney(Long userId, Integer page, Integer limit){
        Page<CashOut> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(dataCentreDao.findWithdrawMoney(pages, userId));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result findplatformMoney(String dateType, String date) {
        HashMap hashMap = new HashMap();
        BigDecimal indentMoney = dataCentreDao.billMoney(dateType, date);
        BigDecimal riderMoney = dataCentreDao.riderMoney(dateType, date);
        BigDecimal platformMoney = dataCentreDao.platformMoney(dateType, date);
        hashMap.put("indentMoney",indentMoney);
        hashMap.put("riderMoney",riderMoney);
        hashMap.put("platformMoney",platformMoney);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result selectCashDeposit(String phone, Integer type, Integer page, Integer limit, Long userId) {
        Page<UserMoneyDetails> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(dataCentreDao.selectCashDeposit(pages, phone, type, userId));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result tcwmplatformMoney(String date, String dateType) {
        HashMap<String, Object> hashMap = new HashMap();
        //总收入
        BigDecimal allBigDecimal = dataCentreDao.tcwmplatformMoney(date, dateType);
        //商家收入
        BigDecimal shopBigDecimal = dataCentreDao.tcwmShopMoney(date, dateType);
        //商铺收入
        BigDecimal adminBigDecimal = allBigDecimal.subtract(shopBigDecimal);
        hashMap.put("allBigDecimal", allBigDecimal);
        hashMap.put("adminBigDecimal", adminBigDecimal);
        hashMap.put("shopBigDecimal", shopBigDecimal);
        return Result.success().put("data",hashMap);
    }

    @Override
    public Result selectFeedbackList(Integer page, Integer limit, Integer type) {
        Page<Feedback> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(dataCentreDao.selectFeedbackList(pages, type));
        return Result.success().put("data", pageUtils);
    }

    @Transactional
    @Override
    public Result presenterVip(Long userId) {
        UserEntity userEntity1 = userDao.selectById(userId);
        if(userEntity1.getIsVip()==1){
            return Result.error("该用户已经是会员，不能重复添加！");
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        /*Calendar calendar1 = java.util.Calendar.getInstance();
        Calendar calendar2 = java.util.Calendar.getInstance();
        try {
            calendar1.setTime(dateFormat.parse(userEntity1.getVipExpirationTime()));
            calendar2.setTime(dateFormat.parse(dateFormat.format(new Date())));
        } catch (java.text.ParseException e) {
            System.out.println("日期格式不正确");
        }
        if(calendar1.compareTo(calendar2)>0){
            return Result.error("用户已经是会员，请勿重复操作！");
        }*/
        CommonInfo one = commonInfoService.findOne(314);
        CommonInfo one1 = commonInfoService.findOne(315);
        CommonInfo one2 = commonInfoService.findOne(316);
        UserEntity userEntity = new UserEntity();
        userEntity.setUserId(userId);
        userEntity.setIsVip(1);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, +Integer.valueOf(one.getValue()));    //得到前一个月
        userEntity.setVipExpirationTime(dateFormat.format(calendar.getTime()));
        userDao.updateById(userEntity);
        for(int i = 0;i<Integer.valueOf(one1.getValue());i++){
            TbCouponUser tbCouponUser = new TbCouponUser();
            tbCouponUser.setUserId(userId);
            tbCouponUser.setCouponName("会员专属优惠券");
            tbCouponUser.setCouponPicture("图片");
            tbCouponUser.setCreateTime(dateFormat.format(new Date()));
            tbCouponUser.setExpirationTime(dateFormat.format(calendar.getTime()));
            tbCouponUser.setMinMoney(BigDecimal.valueOf(0));
            tbCouponUser.setGoodsType("0");
            tbCouponUser.setMoney(new BigDecimal(one2.getValue()));
            tbCouponUser.setStatus(0);
            tbCouponUser.setEndTime(one.getValue());
            tbCouponUser.setShopId(0L);
            tbCouponUserDao.insert(tbCouponUser);
        }
        return Result.success();
    }


}
