package cn.com.ty.lift.ud.payment.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
import java.util.List;

import cn.com.ty.lift.ud.common.RandomizingID;
import cn.com.ty.lift.ud.operation.mapper.entity.OtherSettingEntity;
import cn.com.ty.lift.ud.operation.service.IOtherSettingService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.ty.lift.ud.chat.controller.model.ChatSessionReq;
import cn.com.ty.lift.ud.payment.controller.query.UserWithdrawQuery;
import cn.com.ty.lift.ud.payment.mapper.UserBillMapper;
import cn.com.ty.lift.ud.payment.mapper.UserWithdrawMapper;
import cn.com.ty.lift.ud.payment.mapper.entity.UserBillEntity;
import cn.com.ty.lift.ud.payment.mapper.entity.UserWithdrawEntity;
import cn.com.ty.lift.ud.payment.service.IUserBillService;
import cn.com.ty.lift.ud.payment.service.IUserWithdrawService;
import cn.com.ty.lift.ud.userInfo.mapper.UserInfoMapper;
import cn.com.ty.lift.ud.userInfo.mapper.entity.UserInfoEntity;
import cn.com.ty.lift.ud.utils.UUIDUtil;
import cn.com.xwy.boot.web.dto.RestResponse;

/**
 * 用户提现申请 -ServiceImpl
 *
 * @author Xson
 * @date 2020-04-23
 */
@Service
@Transactional
public class UserWithdrawServiceImpl extends ServiceImpl<UserWithdrawMapper, UserWithdrawEntity>
    implements IUserWithdrawService {

    private @Autowired UserWithdrawMapper userWithdrawMapper;

    private @Autowired UserBillMapper userBillMapper;

    private @Autowired UserInfoMapper userInfoMapper;

    private @Autowired IUserBillService userBillService;

    private @Autowired
    IOtherSettingService otherSettingService;

    @Override
    public RestResponse selectByExample(UserWithdrawQuery query) {
        IPage page = query.page();
        List<UserWithdrawEntity> list = userWithdrawMapper.selectByQuery(query.condition(), query);
        int total = userWithdrawMapper.countByQuery(query.condition());
        page.setRecords(list);
        page.setTotal(total);
        return RestResponse.success(page, "Queried successfully");
    }

    @Override
    public RestResponse deleteUpdate(ChatSessionReq req) {
        int count = userWithdrawMapper.deleteUpdate(req);
        return RestResponse.success(count, "success");
    }

    @Override
    public RestResponse examine(UserWithdrawQuery req) {
        UserWithdrawEntity record = new UserWithdrawEntity();

        if (null == req.getId()) {
            return RestResponse.fail("审核id不能为空");
        }

        if (null == req.getStatuz()) {
            return RestResponse.fail("审核状态不能为空");
        }

        if (4 == req.getStatuz() && StringUtils.isBlank(req.getMome())) {
            return RestResponse.fail("审核描述不能为空");
        }

        if (StringUtils.isNotBlank(req.getMome())) {
            record.setMome(req.getMome());
        }
        UserWithdrawEntity entity = userWithdrawMapper.selectById(req.getId());
        if (entity.getStatuz() != 0) {
            return RestResponse.fail("提交已审批,不能重复操作");
        }

        record.setId(req.getId().longValue());
        record.setStatuz(req.getStatuz());
        userWithdrawMapper.updateByPrimaryKeySelective(record);

        return RestResponse.success("1", "SUCCESS");
    }

    @Override
    public RestResponse insetWithdrwa(UserWithdrawEntity req) {
        if (null == req.getUserId()) {
            return RestResponse.fail("0", "请输入用户ID");
        }
        if (null == req.getType()) {
            return RestResponse.fail("0", "请选择提现类型");
        }
        if (null == req.getAmount() || req.getAmount().compareTo(BigDecimal.ZERO) != 1) {
            return RestResponse.fail("0", "提现金额必须大于零");
        }

        QueryWrapper<UserInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", req.getUserId());
        UserInfoEntity userInfo = userInfoMapper.selectOne(queryWrapper);

        if (null == userInfo) {
            return RestResponse.fail("0", "所填用户不存在");
        }
        if (StringUtils.isBlank(userInfo.getAlipayAccount())) {
            return RestResponse.fail("400", "请先完善提现账号信息");
        }
        if (StringUtils.isBlank(userInfo.getAlipayRealName())) {
            return RestResponse.fail("400", "请先完善提现账号信息");
        }

        if (userInfo.getBalance().compareTo(req.getAmount()) != 1) {
            return RestResponse.fail("0", "平台账户余额不足，请及时充值");
        }

        //每月提现次数 和 单次提现金额都有限制
        int num = isOver(req);
        if(num == 1){
            return RestResponse.fail("0","本月提现申请次数达到上限");
        }
        if(num == 2){
            return RestResponse.fail("0","提现金额超过设置上限");
        }
        Long userId = Long.parseLong(req.getUserId());
        BigDecimal totalAmount = req.getAmount();
        int count = userInfoMapper.updateUserBalance(userId, totalAmount);

        //订单号
        String orders = UUIDUtil.getUuidByTime(9);
        req.setOrders(orders);
        req.setName(userInfo.getAlipayRealName());
        req.setStatuz(0);
        req.setAcount(userInfo.getAlipayAccount());
        req.setCreateTime(LocalDateTime.now());
        userWithdrawMapper.insert(req);

        // 新增消费记录
        UserBillEntity userBillEntity = new UserBillEntity();
        userBillEntity.setAmount(totalAmount);
        userBillEntity.setUserId(userId);
        userBillEntity.setTargetUserId(1L);
        userBillEntity.setType(1);
        userBillEntity.setDescr("用户提现");
        userBillEntity.setBusinessType(5);
        //此处不记录流水号，暂时记录订单号,等审批通过，支付宝返款了，再把那个流水号给他
        userBillEntity.setFlowNum(orders);
        // 查询最近一次的余额
        BigDecimal latestBalance = userBillService.getLatestBalance(userId);
        userBillEntity.setBalance(latestBalance.subtract(totalAmount));
        userBillService.save(userBillEntity);

        return RestResponse.success("提交成功");
    }

    /**
     * 判断用户当月提现次数是否超过设置值
     * @param req
     * @return
     */
    @Override
    public Integer isOver(UserWithdrawEntity req) {
        int flag = 0;
        LocalDateTime date = LocalDateTime.now();
        LocalDateTime firstDay = date.with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN);
        LocalDateTime lastDay = date.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX);
        //查询最新的提现设置
        RestResponse latestVersion = otherSettingService.getLatestVersion();
        OtherSettingEntity data = (OtherSettingEntity) latestVersion.getData();
        //单次提现金额
        BigDecimal withdrawFee = data.getWithdrawFee();
        //每月提现次数
        int withdrawNum = data.getWithdrawNum();
        //查询用户本月的提现情况
        QueryWrapper<UserWithdrawEntity> query = new QueryWrapper<>();
        query.eq("t.user_id", req.getUserId());
        query.between("t.statuz",0,3);
        query.between("t.create_time", firstDay, lastDay);
        int num = userWithdrawMapper.countByQuery(query);
        //判断是否超标
        if(num >= withdrawNum){
            flag  = 1;
        }
        if(req.getAmount().compareTo(withdrawFee) == 1){
            flag  = 2;
        }
        return flag;
    }

    public static void main(String[] args) {
        if (new BigDecimal("0.01").compareTo(BigDecimal.ZERO) != 1)
            System.out.println(111);
    }
}
