package com.jeequan.jeepay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.db.entity.CashoutRecord;
import com.jeequan.jeepay.service.mapper.CashoutRecordMapper;
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 java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 提现结算记录表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2022-03-12
 */
@Service
public class CashoutRecordService extends ServiceImpl<CashoutRecordMapper, CashoutRecord> {

    @Autowired private InfoAccountService infoAccountService;
    public IPage<CashoutRecord> listByPage(IPage iPage, CashoutRecord record, JSONObject paramJSON, LambdaQueryWrapper<CashoutRecord> wrapper) {

        wrapper.eq(record.getRid() != null, CashoutRecord::getRid, record.getRid());
        wrapper.eq(StringUtils.isNotEmpty(record.getInfoId()), CashoutRecord::getInfoId, record.getInfoId());
        wrapper.eq(StringUtils.isNotEmpty(record.getInfoType()), CashoutRecord::getInfoType, record.getInfoType());
        wrapper.eq(StringUtils.isNotEmpty(record.getInfoName()), CashoutRecord::getInfoName, record.getInfoName());
        wrapper.eq(record.getState() != null, CashoutRecord::getState, record.getState());
        wrapper.eq(record.getSettType() != null, CashoutRecord::getSettType, record.getSettType());
        wrapper.eq(StringUtils.isNotEmpty(record.getSettAccountType()), CashoutRecord::getSettAccountType, record.getSettAccountType());
        wrapper.eq(StringUtils.isNotEmpty(record.getSettAccountTelphone()), CashoutRecord::getSettAccountTelphone, record.getSettAccountTelphone());

        // 多状态查询
        if (paramJSON != null && StringUtils.isNotEmpty(paramJSON.getString("unionOrderState"))) {
            String[] stateArr = paramJSON.getString("unionOrderState").split(",");
            List<String> statesList = Arrays.asList(stateArr);
            wrapper.in(CashoutRecord::getState, statesList);
        }
        // 时间范围条件
        Date[] dateRange = record.buildQueryDateRange();
        if (dateRange[0] != null) {
            wrapper.ge(CashoutRecord::getCreatedAt, dateRange[0]);
        }
        if (dateRange[1] != null) {
            wrapper.le(CashoutRecord::getCreatedAt, dateRange[1]);
        }
        wrapper.orderByDesc(CashoutRecord::getCreatedAt);

        return page(iPage, wrapper);
    }

    /**
     * @author: xiaoyu
     * @date: 2022/3/23 17:15
     * @describe: 发起提现
     */
    @Transactional
    public void settAmount(CashoutRecord record) {

        boolean save = save(record);
        if (!save) {
            throw new BizException("提现记录保存失败");
        }

        // 不可用金额
        infoAccountService.changeUnAmountWithEx(record.getInfoId(), record.getInfoType(), record.getApplyAmount(), true);
    }


    /** 审核 */
    @Transactional
    public void audit(Long rid, byte state, String auditRemark, String transferCertImg) {

        // 判断状态
        if(state != CashoutRecord.CASHOUT_STATE_SETT_ING && state != CashoutRecord.CASHOUT_STATE_AUDIT_FAIL
        && state != CashoutRecord.CASHOUT_STATE_SETT_SUCCESS && state != CashoutRecord.CASHOUT_STATE_SETT_FAIL){
            throw new BizException("状态参数有误");
        }

        // 更新主订单
        boolean isUpdSuccess = update(new LambdaUpdateWrapper<CashoutRecord>()
                .set(CashoutRecord::getState, state).set(CashoutRecord::getAuditRemark, auditRemark)
                .set(CashoutRecord::getTransferCertImg, transferCertImg).set(CashoutRecord::getAuditTime, new Date())
        .eq(CashoutRecord::getRid, rid).in(CashoutRecord::getState, Arrays.asList(CashoutRecord.CASHOUT_STATE_AUDIT_ING, CashoutRecord.CASHOUT_STATE_SETT_ING)));

        if(!isUpdSuccess){
            throw new BizException("当前状态不可操作");
        }

        CashoutRecord record = getById(rid);
        // 审核成功
        if(state == CashoutRecord.CASHOUT_STATE_SETT_SUCCESS){
            infoAccountService.changeAmountByCashoutAuditSuccess(record);

        }

        // 审核失败
        if(state == CashoutRecord.CASHOUT_STATE_AUDIT_FAIL || state == CashoutRecord.CASHOUT_STATE_SETT_FAIL){
            // 恢复 不可用金额
            infoAccountService.changeUnAmountWithEx(record.getInfoId(), record.getInfoType(),  (0 - record.getApplyAmount()), false);
        }
    }

    /** 提现申请统计 **/
    public Map<String, Object> countByCashout(CashoutRecord record) {
        LambdaQueryWrapper<CashoutRecord> queryWrapper = CashoutRecord.gw();

        queryWrapper.eq(record.getRid() != null, CashoutRecord::getRid, record.getRid());
        queryWrapper.eq(StringUtils.isNotEmpty(record.getInfoId()), CashoutRecord::getInfoId, record.getInfoId());
        queryWrapper.eq(StringUtils.isNotEmpty(record.getInfoType()), CashoutRecord::getInfoType, record.getInfoType());
        queryWrapper.eq(record.getState() != null, CashoutRecord::getState, record.getState());
        queryWrapper.eq(record.getSettType() != null, CashoutRecord::getSettType, record.getSettType());
        // 名称搜索
        queryWrapper.like(StringUtils.isNotEmpty(record.getInfoName()), CashoutRecord::getInfoName, record.getInfoName());

        // 时间范围条件
        Date[] dateRange = record.buildQueryDateRange();
        if (dateRange[0] != null) {
            queryWrapper.ge(CashoutRecord::getCreatedAt, dateRange[0]);
        }
        if (dateRange[1] != null) {
            queryWrapper.le(CashoutRecord::getCreatedAt, dateRange[1]);
        }

        Map<String, Object> result = baseMapper.countByCashout(queryWrapper);

        return result;
    }
}
