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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Query;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserCashOutDao;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.dao.UserMoneyDetailsDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
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.message.dao.MessageInfoDao;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.pay.dao.CashOutDao;
import com.sqx.modules.pay.entity.CashOut;
import com.sqx.modules.pay.service.CashOutService;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.sys.entity.SysUserRoleEntity;
import com.sqx.modules.sys.service.SysUserRoleService;
import com.sqx.modules.sys.service.SysUserService;
import com.sqx.modules.utils.AmountCalUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import weixin.popular.api.MessageAPI;
import weixin.popular.bean.message.templatemessage.TemplateMessage;
import weixin.popular.bean.message.templatemessage.TemplateMessageItem;
import weixin.popular.bean.message.templatemessage.TemplateMessageResult;
import weixin.popular.support.TokenManager;

import javax.websocket.SendResult;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 提现申请记录
 */
@Service
public class CashOutServiceImpl extends ServiceImpl<CashOutDao, CashOut> implements CashOutService {

    /**
     * 提现申请记录
     */
    @Autowired
    private CashOutDao cashOutDao;
    /**
     * 通用配置
     */
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private MessageInfoDao messageInfoDao;
    @Autowired
    private UserCashOutDao userCashOutDao;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private UserMoneyDetailsDao userMoneyDetailsDao;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true);

    @Override
    public PageUtils selectCashOutList(Map<String, Object> params) {
        String zhifubaoName = (String) params.get("zhifubaoName");
        String zhifubao = (String) params.get("zhifubao");
        String userId = String.valueOf(params.get("userId"));
        String type = String.valueOf(params.get("type"));
        String state = String.valueOf(params.get("state"));
        String phone = String.valueOf(params.get("phone"));
        Integer userType = (Integer) params.get("userType");
        IPage<CashOut> page = this.page(new Query<CashOut>().getPage(params),
                new QueryWrapper<CashOut>().
                        eq(StringUtils.isNotBlank(zhifubaoName) && !"null".equals(zhifubaoName), "zhifubao_name", zhifubaoName)
                        .eq(StringUtils.isNotBlank(zhifubao) && !"null".equals(zhifubao), "zhifubao", zhifubao)
                        .eq(StringUtils.isNotBlank(userId) && !"null".equals(userId), "user_id", userId)
                        .eq(StringUtils.isNotBlank(type) && !"null".equals(type), "type", type)
                        .eq(StringUtils.isNotBlank(state) && !"null".equals(state), "state", state)
                        .eq(userType != null, "user_type", userType)
                        .like(StringUtils.isNotBlank(phone) && !"null".equals(phone), "phone", phone).orderByDesc("create_at"));

        return new PageUtils(page);
    }


    @Override
    public CashOut selectById(Long id) {
        return cashOutDao.selectById(id);
    }

    @Override
    public int saveBody(CashOut cashOut) {
        return cashOutDao.insert(cashOut);
    }


    @Override
    public int update(CashOut cashOut) {
        return cashOutDao.updateById(cashOut);
    }


    @Override
    public void cashOutSuccess(UserEntity userByWxId, String date, String money, String payWay, String url) {
        if (userByWxId != null) {
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState(String.valueOf(5));
            messageInfo.setContent("您好，您的提现转账成功，请注意查收！提现金额【" + money + "元】！如有疑问请在公众号中发送您的问题联系客服");
            messageInfo.setTitle("提现成功通知");
            messageInfo.setUserName(userByWxId.getNickName());
            messageInfo.setUserId(String.valueOf(userByWxId.getUserId()));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date now = new Date();
            messageInfo.setCreateAt(sdf.format(now));
            messageInfo.setIsSee("0");
            messageInfoDao.insert(messageInfo);
            if (userByWxId.getClientid() != null) {
                userService.pushToSingle("提现成功通知", "您好，您的提现转账成功，请注意查收！提现金额【" + money + "元】！如有疑问请在公众号中发送您的问题联系客服", userByWxId.getClientid());
            }
            CommonInfo three = commonInfoService.findOne(39);
            String apkey = "";
            if (three != null) {
                apkey = three.getValue();
            }
            if (StringUtils.isNotBlank(userByWxId.getOpenId())) {
                LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
                data.put("first", new TemplateMessageItem("您好，您的提现转账成功，请注意查收", "#d71345"));
                data.put("keyword1", new TemplateMessageItem(money + " 元", "#d71345"));
                data.put("keyword2", new TemplateMessageItem(date, "#d71345"));
                data.put("remark", new TemplateMessageItem("如有疑问请在公众号中发送您的问题联系客服", null));
                sendWxMessage(apkey, data, userByWxId.getOpenId(), url);
            }
        }

    }

    /**
     * 退款成功通知
     *
     * @param
     * @param date
     * @param money
     * @param url
     */
    @Override
    public void refundSuccess(UserEntity userByWxId, String date, String money, String url, String content) {
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setState(String.valueOf(5));
        messageInfo.setContent(content);
        messageInfo.setTitle("提现失败提醒");
        messageInfo.setUserName(userByWxId.getNickName());
        messageInfo.setUserId(String.valueOf(userByWxId.getUserId()));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        messageInfo.setCreateAt(sdf.format(now));
        messageInfo.setIsSee("0");
        messageInfoDao.insert(messageInfo);
        if (userByWxId.getClientid() != null) {
            userService.pushToSingle("提现失败提醒", content, userByWxId.getClientid());
        }
        CommonInfo three = commonInfoService.findOne(77);
        String apkey = "";
        if (three != null) {
            apkey = three.getValue();
        }
        if (StringUtils.isNotBlank(userByWxId.getOpenId())) {
            LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
            data.put("first", new TemplateMessageItem("您好，您发起的提现失败了", "#d71345"));
            data.put("keyword1", new TemplateMessageItem(money + " 元", "#d71345"));
            data.put("keyword2", new TemplateMessageItem(date, "#d71345"));
            data.put("keyword3", new TemplateMessageItem(content, "#d71345"));
            data.put("remark", new TemplateMessageItem("请您按照失败原因修改相关信息后，重新提现！", null));
            sendWxMessage(apkey, data, userByWxId.getOpenId(), url);
        }

    }

    @Override
    public Double selectCashOutSum(Long userId, Date startTime, Date endTime) {
        return cashOutDao.selectCashOutSum(userId, startTime, endTime);
    }

    @Override
    public BigDecimal sumMoney(String date,String dateType,Integer state){
        return baseMapper.sumMoney(date, dateType, state);
    }

    @Override
    public void updateMayMoney(int i, Long userId, Double money) {
        cashOutDao.updateMayMoney(i, userId, money);
    }


    @Override
    public List<CashOut> selectCashOutLimit3() {
        return cashOutDao.selectCashOutLimit3();
    }

    private void sendWxMessage(String templateId, LinkedHashMap<String, TemplateMessageItem> data, String openid, String url) {
        TemplateMessage templateMessage = new TemplateMessage();
        templateMessage.setTouser(openid);
        templateMessage.setTemplate_id(templateId);
        templateMessage.setData(data);
        templateMessage.setUrl(url);
        TemplateMessageResult templateMessageResult = MessageAPI.messageTemplateSend(getWxToken(), templateMessage);
        if (templateMessageResult.isSuccess()) {
            new SendResult();
        } else {
            new SendResult();
        }
    }

    private String getWxToken() {
        try {
            //微信appid
            CommonInfo one = commonInfoService.findOne(5);
            return TokenManager.getToken(one.getValue());
        } catch (Exception e) {
            throw new RuntimeException("GET_ACCESS_TOKEN_FAIL");
        }
    }

    @Override
    @Transactional
    public Result cashMoney(Long userId, Double money, Integer classify, Integer userType) {
        return cashMoneys(userId, money, classify, userType);
    }

    /**
     *
     * @param userId
     * @param money
     * @param classify
     * @param userType 1管理端 2用户端
     * @return
     */
    public Result cashMoneys(Long userId, Double money, Integer classify, Integer userType) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            if (money == null || money <= 0.00) {
                return Result.error("请不要输入小于0的数字,请输入正确的提现金额！");
            }
            //最低提现金额
            CommonInfo one = commonInfoService.findOne(87);
            if (one != null && money < Double.parseDouble(one.getValue())) {
                return Result.error("输入金额不满足最低提现金额，请重新输入！");
            }
            //最高提现金额
            CommonInfo one2 = commonInfoService.findOne(11);
            if (one2 != null && money > Double.parseDouble(one2.getValue())) {
                return Result.error(-100, "输入金额过大，不能大于" + one2.getValue() + "，请重新输入！");
            }
            //手续费
            CommonInfo one1 = commonInfoService.findOne(114);
            //计算提现金额所需要的手续费  小于0.01 的按0.01来算
            double mul = AmountCalUtils.mul(money, Double.parseDouble(one1.getValue()));
            if (mul < 0.01) {
                mul = 0.01;
            }
            UserEntity userEntity = userService.selectUserById(userId);

            double userMoney;
            if(userType==1){
                UserMoney userMoney1 = userMoneyService.selectUserMoneyByUserId(userId);
                userMoney=userMoney1.getInviteMoney().doubleValue();
            }else{
                userMoney=userEntity.getBalance().doubleValue();
            }

            if (money > userMoney) {
                return Result.error("金额不足，请输入正确的金额！");
            }

            //提现判断金额是否足够
            double moneySum = AmountCalUtils.add(new BigDecimal(money), new BigDecimal(mul)).doubleValue(); //金额=提现金额+手续费
            double moneySub = AmountCalUtils.sub(new BigDecimal(money), new BigDecimal(mul)).doubleValue(); //金额=提现金额+手续费
            if (new BigDecimal(userMoney).compareTo(BigDecimal.valueOf(moneySum)) > -1) { //用户金额足够
                //扣除可提现金额直接在数据库进行操作
                //增加金额操作记录
                UserMoneyDetails moneyDetails = new UserMoneyDetails();
                if(userType==1){
                    userMoneyService.updateInviteMoney(2, userId, moneySum);
                    moneyDetails.setClassify(5);
                }else{
                    userCashOutDao.updateMoney(2, userId, moneySum);
                    moneyDetails.setClassify(6);
                }
                CashOut cashOut = new CashOut();

                moneyDetails.setUserId(userId);
                moneyDetails.setUserType(userType);


                if (classify == 1) {
                    moneyDetails.setTitle("支付宝提现：");
                    moneyDetails.setContent("支付宝提现：" + money + "，扣除总金额：" + moneySum + "，手续费：" + mul);
                } else {
                    moneyDetails.setTitle("微信提现：");
                    cashOut.setCashQrCode(userEntity.getCashQrCode());
                    moneyDetails.setContent("微信提现：" + money + "，扣除总金额：" + moneySum + "，手续费：" + mul);
                }
                moneyDetails.setType(2);
                moneyDetails.setMoney(new BigDecimal(moneySum));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                moneyDetails.setCreateTime(sdf.format(new Date()));
                userMoneyDetailsDao.insert(moneyDetails);
                cashOut.setZhifubao(userEntity.getZhiFuBao());
                cashOut.setZhifubaoName(userEntity.getZhiFuBaoName());
                cashOut.setUserId(userEntity.getUserId());
                cashOut.setState(0);
                cashOut.setMoney(money.toString());
                cashOut.setCreateAt(DateUtils.format(new Date()));
                cashOut.setRate(moneySum);
                cashOut.setUserType(userType);
                cashOut.setOrderNumber(String.valueOf(System.currentTimeMillis()));
                cashOut.setType(1);
                cashOut.setClassify(classify);
                baseMapper.insert(cashOut);
                //扣除金额直接在数据库进行操作
                return Result.success("提现成功，将在三个工作日内到账，请耐心等待！");
            } else {
                UserMoneyDetails moneyDetails = new UserMoneyDetails();
                if(userType==1){
                    userMoneyService.updateInviteMoney(2, userId, money);
                    moneyDetails.setClassify(5);
                }else{
                    userCashOutDao.updateMoney(2, userId, money);
                    moneyDetails.setClassify(6);
                }
                moneyDetails.setUserType(userType);
                moneyDetails.setUserId(userId);
                moneyDetails.setTitle("提现：" + moneySub);
                if (classify == 1) {
                    moneyDetails.setContent("支付宝提现：" + moneySub + "，扣除总金额：" + money + "，手续费：" + mul);
                } else {
                    moneyDetails.setContent("微信提现：" + moneySub + "，扣除总金额：" + money + "，手续费：" + mul);
                }
                moneyDetails.setType(2);
                moneyDetails.setMoney(new BigDecimal(money));
                moneyDetails.setCreateTime(DateUtils.format(new Date()));
                userMoneyDetailsDao.insert(moneyDetails);

                CashOut cashOut = new CashOut();

                cashOut.setZhifubao(userEntity.getZhiFuBao());
                cashOut.setZhifubaoName(userEntity.getZhiFuBaoName());
                cashOut.setUserId(userEntity.getUserId());
                cashOut.setState(0);
                cashOut.setMoney(Double.toString(moneySub));
                cashOut.setCreateAt(DateUtils.format(new Date()));
                cashOut.setRate(money);
                cashOut.setUserType(userType);
                cashOut.setOrderNumber(String.valueOf(System.currentTimeMillis()));
                cashOut.setType(1);
                cashOut.setClassify(classify);
                baseMapper.insert(cashOut);
                return Result.success("提现成功，将在三个工作日内到账，请耐心等待！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发起提现出错！" + e.getMessage(), e);
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }


    @Override
    @Transactional
    public Result cashDepositMoney(Long userId) {
        //将保证金退还到用户钱包
        UserEntity userEntity = userService.selectUserById(userId);
        UserEntity userEntity1 = new UserEntity();
        userEntity1.setUserId(userId);
        userEntity1.setCashDeposit(userEntity.getCashDeposit().subtract(userEntity.getCashDeposit()));
        userEntity1.setBalance(userEntity.getBalance().add(userEntity.getCashDeposit()));
        userService.updateById(userEntity1);
        //退保证金
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        userMoneyDetails.setMoney(userEntity.getCashDeposit());
        userMoneyDetails.setUserId(userId);
        userMoneyDetails.setUserType(2);
        userMoneyDetails.setContent("退保证金：" + userEntity.getCashDeposit() + "元");
        userMoneyDetails.setTitle("退保证金");
        userMoneyDetails.setType(1);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
        userMoneyDetailsService.save(userMoneyDetails);

        UserMoneyDetails userMoneyDetails1 = new UserMoneyDetails();
        userMoneyDetails1.setMoney(userEntity.getCashDeposit());
        userMoneyDetails1.setUserType(2);
        userMoneyDetails1.setUserId(userId);
        userMoneyDetails1.setContent("退保证金：" + userEntity.getCashDeposit() + "元");
        userMoneyDetails1.setTitle("退保证金");
        userMoneyDetails1.setType(2);
        userMoneyDetails1.setClassify(1);
        userMoneyDetails1.setCreateTime(simpleDateFormat.format(new Date()));
        userMoneyDetailsService.save(userMoneyDetails1);

        return Result.success("保证金已退回到您的钱包");
    }

    @Override
    public Result statisticsMoney(String date, String dateType) {
        HashMap hashMap = new HashMap();
        BigDecimal sumMoney = cashOutDao.sumMoney(date, dateType, null);
        Integer countMoney = cashOutDao.countMoney(date, dateType, null);
        Integer stayMoney = cashOutDao.stayMoney(date, dateType);
        BigDecimal sumMoneySucceed = cashOutDao.sumMoney(date, dateType, 1);
        Integer countMoneySucceed = cashOutDao.countMoney(date, dateType, 1);
        BigDecimal sumMoneyAwait = cashOutDao.sumMoney(date, dateType, 0);
        BigDecimal applyMoneySum = cashOutDao.applyMoneySum(date, dateType);
        BigDecimal accomplishMoneySum = cashOutDao.accomplishMoneySum(date, dateType);
        BigDecimal refuseMoneySum = cashOutDao.refuseMoneySum(date, dateType);
        BigDecimal zhifubaoMoneySum = cashOutDao.zhifubaoMoneySum(date, dateType);
        BigDecimal weixinMoneySum = cashOutDao.weixinMoneySum(date, dateType);
        BigDecimal cashDepositMoneySum = cashOutDao.cashDepositMoneySum(date, dateType);
        hashMap.put("sumMoney", sumMoney);//累计提现
        hashMap.put("countMoney", countMoney);//提现次数
        hashMap.put("stayMoney", stayMoney);//带转账次数
        hashMap.put("sumMoneySucceed", sumMoneySucceed);//提现成功总金额
        hashMap.put("countMoneySucceed", countMoneySucceed);//提现成功笔数
        hashMap.put("sumMoneyAwait", sumMoneyAwait);//待提现总金额
        hashMap.put("applyMoneySum", applyMoneySum);//申请提现金额
        hashMap.put("accomplishMoneySum", accomplishMoneySum);//已转账金额
        hashMap.put("refuseMoneySum", refuseMoneySum);//已拒绝金额
        hashMap.put("zhifubaoMoneySum", zhifubaoMoneySum);//支付宝提现金额
        hashMap.put("weixinMoneySum", weixinMoneySum);//微信提现金额
        hashMap.put("cashDepositMoneySum", cashDepositMoneySum);//保证金退款金额
        return Result.success().put("data", hashMap);
    }


    @Override
    public IPage<CashOut> selectAdminHelpProfit(Integer page, Integer limit, String startTime, String endTime, CashOut cashOut) {
        Page<CashOut> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.selectAdminHelpProfit(pages, startTime, endTime, cashOut);
    }



}
