package com.fs.course.service.impl;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyMoneyLogs;
import com.fs.company.mapper.CompanyMapper;
import com.fs.company.mapper.CompanyMoneyLogsMapper;
import com.fs.course.param.FsCourseRedPacketLogParam;
import com.fs.course.vo.FsCourseRedPacketLogListPVO;
import com.fs.his.domain.FsUser;
import com.fs.his.mapper.FsUserMapper;
import com.fs.his.param.WxSendRedPacketParam;
import com.fs.his.service.IFsStorePaymentService;
import com.github.binarywang.wxpay.bean.transfer.TransferBillsResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.course.mapper.FsCourseRedPacketLogMapper;
import com.fs.course.domain.FsCourseRedPacketLog;
import com.fs.course.service.IFsCourseRedPacketLogService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 短链课程看课记录Service业务层处理
 *
 * @author fs
 * @date 2024-10-24
 */
@Service
public class FsCourseRedPacketLogServiceImpl implements IFsCourseRedPacketLogService
{
    @Autowired
    private FsCourseRedPacketLogMapper fsCourseRedPacketLogMapper;

    /**
     * 查询短链课程看课记录
     *
     * @param logId 短链课程看课记录主键
     * @return 短链课程看课记录
     */
    @Override
    public FsCourseRedPacketLog selectFsCourseRedPacketLogByLogId(Long logId)
    {
        return fsCourseRedPacketLogMapper.selectFsCourseRedPacketLogByLogId(logId);
    }

    /**
     * 查询短链课程看课记录列表
     *
     * @param fsCourseRedPacketLog 短链课程看课记录
     * @return 短链课程看课记录
     */
    @Override
    public List<FsCourseRedPacketLog> selectFsCourseRedPacketLogList(FsCourseRedPacketLog fsCourseRedPacketLog)
    {
        return fsCourseRedPacketLogMapper.selectFsCourseRedPacketLogList(fsCourseRedPacketLog);
    }

    /**
     * 新增短链课程看课记录
     *
     * @param fsCourseRedPacketLog 短链课程看课记录
     * @return 结果
     */
    @Override
    public int insertFsCourseRedPacketLog(FsCourseRedPacketLog fsCourseRedPacketLog)
    {
        fsCourseRedPacketLog.setCreateTime(DateUtils.getNowDate());
        return fsCourseRedPacketLogMapper.insertFsCourseRedPacketLog(fsCourseRedPacketLog);
    }

    /**
     * 修改短链课程看课记录
     *
     * @param fsCourseRedPacketLog 短链课程看课记录
     * @return 结果
     */
    @Override
    public int updateFsCourseRedPacketLog(FsCourseRedPacketLog fsCourseRedPacketLog)
    {
        return fsCourseRedPacketLogMapper.updateFsCourseRedPacketLog(fsCourseRedPacketLog);
    }

    /**
     * 批量删除短链课程看课记录
     *
     * @param logIds 需要删除的短链课程看课记录主键
     * @return 结果
     */
    @Override
    public int deleteFsCourseRedPacketLogByLogIds(Long[] logIds)
    {
        return fsCourseRedPacketLogMapper.deleteFsCourseRedPacketLogByLogIds(logIds);
    }

    /**
     * 删除短链课程看课记录信息
     *
     * @param logId 短链课程看课记录主键
     * @return 结果
     */
    @Override
    public int deleteFsCourseRedPacketLogByLogId(Long logId)
    {
        return fsCourseRedPacketLogMapper.deleteFsCourseRedPacketLogByLogId(logId);
    }

    @Override
    public R syncRedPacket(String outBatchNo) {
        FsCourseRedPacketLog log = fsCourseRedPacketLogMapper.selectFsCourseRedPacketLogByBatchNo(outBatchNo);
        if (log!=null){
            log.setStatus(1);
            log.setUpdateTime(new Date());
            fsCourseRedPacketLogMapper.updateFsCourseRedPacketLog(log);
            return R.ok();
        }
        return R.error("批次不存在");
    }

    @Override
    public List<FsCourseRedPacketLogListPVO> selectFsCourseRedPacketLogListVO(FsCourseRedPacketLogParam fsCourseRedPacketLog) {
        return fsCourseRedPacketLogMapper.selectFsCourseRedPacketLogListVO(fsCourseRedPacketLog);
    }

    @Override
    public List<FsCourseRedPacketLogListPVO> selectFsCourseRedPacketLogListVONew(FsCourseRedPacketLogParam fsCourseRedPacketLog) {
        return fsCourseRedPacketLogMapper.selectFsCourseRedPacketLogListVONew(fsCourseRedPacketLog);
    }

    /**
     * 查询红包金额数
     * @param companyUserId 销售ID
     * @return amount
     */
    @Override
    public BigDecimal getSumByCompanyUserIdId(Long companyUserId) {
        return fsCourseRedPacketLogMapper.getSumByCompanyUserIdId(companyUserId);
    }

    @Override
    public int getCountByCompanyUserIdId(Long companyUserId) {
        return fsCourseRedPacketLogMapper.getCountByCompanyUserIdId(companyUserId);
    }

    /**
     * 查询新用户红包金额总和
     * @param companyUserId 销售ID
     * @return amount
     */
    @Override
    public BigDecimal getNewVipRedPackAmountByCompanyUserIdId(Long companyUserId) {
        return fsCourseRedPacketLogMapper.getNewVipRedPackAmountByCompanyUserIdId(companyUserId);
    }
    @Autowired
    private IFsStorePaymentService paymentService;
    @Autowired
    private FsUserMapper fsUserMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private CompanyMoneyLogsMapper moneyLogsMapper;
    @Override
    @Transactional
    public int retryCourseRedPacketLog(Long[] logIds) {
        for (int i = 0; i < logIds.length; i++) {
            Long id = logIds[i];
            FsCourseRedPacketLog param = fsCourseRedPacketLogMapper.selectFsCourseRedPacketLogByLogId(id);


            if (param!=null&&param.getStatus()==2){
                Company company = companyMapper.selectCompanyByIdForUpdate(param.getCompanyId());
                BigDecimal amount = param.getAmount();
                BigDecimal money = company.getMoney();
                BigDecimal subtract = money.subtract(amount);
                if (subtract.compareTo(BigDecimal.ZERO)<0){
                    return 0;
                }


                WxSendRedPacketParam packetParam = new WxSendRedPacketParam();
                FsUser user = fsUserMapper.selectFsUserByUserId(param.getUserId());
                packetParam.setOpenId(user.getMaOpenId());
                packetParam.setOpenId(user.getCourseMaOpenId());
                packetParam.setAmount(param.getAmount());
                packetParam.setSource(2);
                packetParam.setRedPacketMode(1);
                packetParam.setCompanyId(param.getCompanyId());
                R sendRedPacket = paymentService.sendRedPacket(packetParam);
                if (sendRedPacket.get("code").equals(200)) {
                    FsCourseRedPacketLog redPacketLog = new FsCourseRedPacketLog();
                    TransferBillsResult transferBillsResult;
                    if (sendRedPacket.get("isNew").equals(1)){
                        transferBillsResult = (TransferBillsResult)sendRedPacket.get("data");
                        redPacketLog.setResult(JSON.toJSONString(sendRedPacket));
                        redPacketLog.setOutBatchNo(transferBillsResult.getOutBillNo());
                    }else {
                        redPacketLog.setOutBatchNo(sendRedPacket.get("orderCode").toString());
                    }
                    // 添加红包记录
                    redPacketLog.setStatus(0);
                    fsCourseRedPacketLogMapper.updateFsCourseRedPacketLog(redPacketLog);
                    // 更新观看记录的奖励类型

                    company.setMoney(subtract);
                    companyMapper.updateCompany(company);

                    CompanyMoneyLogs logs=new CompanyMoneyLogs();
                    logs.setCompanyId(company.getCompanyId());
                    logs.setRemark("扣除红包金额");
                    logs.setMoney(amount.multiply(new BigDecimal(-1)));
                    logs.setLogsType(15);
                    logs.setBalance(company.getMoney());
                    logs.setCreateTime(new Date());
                    moneyLogsMapper.insertCompanyMoneyLogs(logs);
                }
            }

        }
        return 0;
    }

}
