package com.fs.his.service.impl;

import cn.hutool.json.JSONUtil;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.his.config.IntegralConfig;
import com.fs.his.domain.FsUser;
import com.fs.his.domain.FsUserIntegralLogs;
import com.fs.his.domain.FsUserNewTask;
import com.fs.his.enums.FsUserIntegralLogTypeEnum;
import com.fs.his.mapper.FsUserIntegralLogsMapper;
import com.fs.his.mapper.FsUserMapper;
import com.fs.his.mapper.FsUserNewTaskMapper;
import com.fs.his.param.FsUserAddIntegralParam;
import com.fs.his.param.FsUserAddIntegralTemplateParam;
import com.fs.his.param.FsUserIntegralLogsListUParam;
import com.fs.his.param.FsUserIntegralLogsParam;
import com.fs.his.service.IFsUserIntegralLogsService;
import com.fs.his.vo.FsUserIntegralLogsListUVO;
import com.fs.his.vo.FsUserIntegralLogsListVO;
import com.fs.his.vo.SubIntegralVO;
import com.fs.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 积分记录Service业务层处理
 *
 * @author fs
 * @date 2023-11-02
 */
@Service
public class FsUserIntegralLogsServiceImpl implements IFsUserIntegralLogsService
{
    private static final Logger log = LoggerFactory.getLogger(FsUserIntegralLogsServiceImpl.class);
    @Autowired
    private FsUserIntegralLogsMapper fsUserIntegralLogsMapper;
    @Autowired
    FsUserMapper fsUserMapper;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private FsUserNewTaskMapper fsUserNewTaskMapper;
    /**
     * 查询积分记录
     *
     * @param id 积分记录主键
     * @return 积分记录
     */
    @Override
    public FsUserIntegralLogs selectFsUserIntegralLogsById(Long id)
    {
        return fsUserIntegralLogsMapper.selectFsUserIntegralLogsById(id);
    }

    /**
     * 查询积分记录列表
     *
     * @param fsUserIntegralLogs 积分记录
     * @return 积分记录
     */
    @Override
    public List<FsUserIntegralLogs> selectFsUserIntegralLogsList(FsUserIntegralLogs fsUserIntegralLogs)
    {
        return fsUserIntegralLogsMapper.selectFsUserIntegralLogsList(fsUserIntegralLogs);
    }

    /**
     * 新增积分记录
     *
     * @param fsUserIntegralLogs 积分记录
     * @return 结果
     */
    @Override
    public int insertFsUserIntegralLogs(FsUserIntegralLogs fsUserIntegralLogs)
    {
        fsUserIntegralLogs.setCreateTime(DateUtils.getNowDate());
        return fsUserIntegralLogsMapper.insertFsUserIntegralLogs(fsUserIntegralLogs);
    }

    /**
     * 修改积分记录
     *
     * @param fsUserIntegralLogs 积分记录
     * @return 结果
     */
    @Override
    public int updateFsUserIntegralLogs(FsUserIntegralLogs fsUserIntegralLogs)
    {
        return fsUserIntegralLogsMapper.updateFsUserIntegralLogs(fsUserIntegralLogs);
    }

    /**
     * 批量删除积分记录
     *
     * @param ids 需要删除的积分记录主键
     * @return 结果
     */
    @Override
    public int deleteFsUserIntegralLogsByIds(Long[] ids)
    {
        return fsUserIntegralLogsMapper.deleteFsUserIntegralLogsByIds(ids);
    }

    /**
     * 删除积分记录信息
     *
     * @param id 积分记录主键
     * @return 结果
     */
    @Override
    public int deleteFsUserIntegralLogsById(Long id)
    {
        return fsUserIntegralLogsMapper.deleteFsUserIntegralLogsById(id);
    }

    @Override
    public List<FsUserIntegralLogsListVO> selectFsUserIntegralLogsListVO(FsUserIntegralLogsParam fsUserIntegralLogs) {
        return fsUserIntegralLogsMapper.selectFsUserIntegralLogsListVO(fsUserIntegralLogs);
    }

    @Override
    public List<FsUserIntegralLogsListUVO> selectFsUserIntegralLogsListUVO(FsUserIntegralLogsListUParam param) {
        return fsUserIntegralLogsMapper.selectFsUserIntegralLogsListUVO(param);
    }

    @Override
    public void subFsUserIntegralLogsByOrder5() {
        List<Long> longs = fsUserIntegralLogsMapper.subFsUserIntegralLogsByOrder5();
        for (Long id : longs) {

            FsUser fsUser = fsUserMapper.selectFsUserByUserId(id);
            if(fsUser!=null&&fsUser.getIntegral()!=0){
                List<FsUserIntegralLogs> log =  fsUserIntegralLogsMapper.selectFsUserIntegralByStatus0(id);
                for (FsUserIntegralLogs fsUserIntegralLogs : log) {
                    Long integral = fsUser.getIntegral();
                    Long integralLog = fsUserIntegralLogs.getIntegral();
                    Long balance = integral - integralLog;
                    if (balance<0){
                        balance=0L;
                    }
                    fsUser.setIntegral(balance);
                    fsUserMapper.updateFsUser(fsUser);
                    fsUserIntegralLogs.setStatus(1);
                    fsUserIntegralLogsMapper.updateFsUserIntegralLogs(fsUserIntegralLogs);
                    FsUserIntegralLogs logs = new FsUserIntegralLogs();
                    logs.setIntegral(0-integralLog);
                    logs.setUserId(id);
                    logs.setBalance(balance);
                    logs.setLogType(7);
                    logs.setStatus(1);
                    logs.setCreateTime(new Date());
                    fsUserIntegralLogsMapper.insertFsUserIntegralLogs(logs);
                }


            }

        }
    }


    @Override
    @Transactional
    public void addPatientIntegral(Long userId,Long patientId) {
        FsUser user = fsUserMapper.selectFsUserIsNew(userId);
        if (user!=null){
            FsUserIntegralLogs integralLogs = fsUserIntegralLogsMapper.selectFsUserIntegralLogsAddPatient(userId);
            if (integralLogs==null){
                FsUser userMap=new FsUser();
                userMap.setUserId(user.getUserId());
                userMap.setIntegral(user.getIntegral()+1000L);
                fsUserMapper.updateFsUser(userMap);
                integralLogs = new FsUserIntegralLogs();
                integralLogs.setIntegral(1000L);
                integralLogs.setUserId(userId);
                integralLogs.setBalance(userMap.getIntegral());
                integralLogs.setLogType(11);
                integralLogs.setBusinessId(patientId.toString());
                integralLogs.setCreateTime(new Date());
                fsUserIntegralLogsMapper.insertFsUserIntegralLogs(integralLogs);
            }
        }
    }

    @Override
    @Transactional
    public void addUserAddressIntegral(Long userId, Long addressId) {
        FsUser user = fsUserMapper.selectFsUserIsNew(userId);
        if (user!=null){
            FsUserIntegralLogs integralLogs = fsUserIntegralLogsMapper.selectFsUserIntegralLogsAddUserAddress(userId);
            if (integralLogs==null){
                FsUser userMap=new FsUser();
                userMap.setUserId(user.getUserId());
                userMap.setIntegral(user.getIntegral()+1000L);
                fsUserMapper.updateFsUser(userMap);
                integralLogs = new FsUserIntegralLogs();
                integralLogs.setIntegral(1000L);
                integralLogs.setUserId(userId);
                integralLogs.setBalance(userMap.getIntegral());
                integralLogs.setLogType(12);
                integralLogs.setBusinessId(addressId.toString());
                integralLogs.setCreateTime(new Date());
                fsUserIntegralLogsMapper.insertFsUserIntegralLogs(integralLogs);
            }
        }
    }

    @Override
    @Transactional
    public R addIntegral(FsUserAddIntegralParam param) {
        FsUser user = fsUserMapper.selectFsUserByUserId(param.getUserId());
        if (user!=null){
            String json =configService.selectConfigByKey("his.integral");
            IntegralConfig config= JSONUtil.toBean(json,IntegralConfig.class);
            System.out.println("Types: " + Arrays.toString(config.getIntegralTypeByOneDay()));
            System.out.println("User ID: " + param.getUserId());
            Integer todayTotalIntegral= fsUserIntegralLogsMapper.selectTodayTotalIntegral(config.getIntegralTypeByOneDay(),param.getUserId());
            if (todayTotalIntegral==null){
                todayTotalIntegral=0;
            }
            if (todayTotalIntegral>=config.getIntegralByOneDay()){
                return R.error("当天积分已达限额");
            }
            switch (param.getType()){
                case 1:
                    return addProductIntegral(config.getIntegralProduct(),user.getUserId(),user.getIntegral());
                case 2:
                    return addVideoIntegral(config.getIntegralFirstVideo(),config.getIntegralFinishVideo(),user.getUserId(),user.getIntegral());
            }
        }
        return R.error("用户信息不存在");
    }

    /**
     * 更新积分通用
     * @param param
     * @return
     */
    @Override
    @Transactional
    public R addIntegralTemplate(FsUserAddIntegralTemplateParam param) {
        FsUser user = fsUserMapper.selectFsUserByUserId(param.getUserId());
        if (user!=null){
            String json =configService.selectConfigByKey("his.integral");
            IntegralConfig config= JSONUtil.toBean(json,IntegralConfig.class);
            Integer[] integralTypeByOneDay = config.getIntegralTypeByOneDay();
            System.out.println("Types: " + Arrays.toString(integralTypeByOneDay));
            System.out.println("User ID: " + param.getUserId());

            //判断是否在限额类型内
            if (Arrays.asList(integralTypeByOneDay).contains(param.getLogType())){
                Integer todayTotalIntegral= fsUserIntegralLogsMapper.selectTodayTotalIntegral(integralTypeByOneDay,param.getUserId());
                if (todayTotalIntegral==null){
                    todayTotalIntegral=0;
                }
                if (todayTotalIntegral>=config.getIntegralByOneDay()){
                    return R.error("当天积分已达限额");
                }
            }
            Integer integralNum = null;
            FsUserIntegralLogTypeEnum logsType = null;
            switch (param.getLogType()){
//                case 1: //签到
//                    integralNum = config.getIntegralInvite();
//                    logsType = FsUserIntegralLogTypeEnum.TYPE_1;
//                    break;
//                case 2: //消费获得积分
//                    integralNum = config.getIntegralInvite();
//                    logsType = FsUserIntegralLogTypeEnum.TYPE_2;
//                    break;
                case 3: //分享获得积分
                    integralNum = config.getIntegralShare();
                    logsType = FsUserIntegralLogTypeEnum.TYPE_3;
                    break;
//                case 4: //退款扣除积分
//                    integralNum = config.getIntegralInvite();
//                    logsType = FsUserIntegralLogTypeEnum.TYPE_4;
//                    break;
//                case 5: // 购买积分商品
//                    integralNum = config.getIntegralInvite();
//                    logsType = FsUserIntegralLogTypeEnum.TYPE_5;
//                    break;
//                case 6: // 平台取消售后
//                    integralNum = config.getIntegralInvite();
//                    logsType = FsUserIntegralLogTypeEnum.TYPE_6;
//                    break;
//                case 7: //积分过期
//                    logsType = FsUserIntegralLogTypeEnum.TYPE_7;
//                    break;
//                case 8: //螳螂同步积分
//                    logsType = FsUserIntegralLogTypeEnum.TYPE_8;
//                    break;
//                case 9: //购买课程小节扣除
//                    logsType = FsUserIntegralLogTypeEnum.TYPE_9;
//                    break;
                case 10: //观看课程获取积分
                    integralNum = config.getIntegralCourse();
                    logsType = FsUserIntegralLogTypeEnum.TYPE_10;
                    break;
//                case 11: //新用户完善就诊人获得积分
//                    logsType = FsUserIntegralLogTypeEnum.TYPE_11;
//                    break;
//                case 12: //新用户填写收货地址获取积分
//                    logsType = FsUserIntegralLogTypeEnum.TYPE_12;
//                    break;
                case 13: //浏览商品获得积分
                    integralNum = config.getIntegralProduct();
                    logsType = FsUserIntegralLogTypeEnum.TYPE_13;
                    break;
                case 14: //浏览视频获得积分
                    return addVideoIntegral(config.getIntegralFirstVideo(),config.getIntegralFinishVideo(),user.getUserId(),user.getIntegral());
//                case 15: //首次下单疗法获得积分
//                    logsType = FsUserIntegralLogTypeEnum.TYPE_15;
//                    break;
//                case 16: //点播看课获得积分
//                    logsType = FsUserIntegralLogTypeEnum.TYPE_16;
//                    break;
//                case 17: //点播答题获得积分
//                    logsType = FsUserIntegralLogTypeEnum.TYPE_17;
//                    break;
                case 18: //邀请新用户获取积分
                    integralNum = config.getIntegralInvite();
                    logsType = FsUserIntegralLogTypeEnum.TYPE_18;
                    break;
                case 19: //填写邀请码获取积分
                    integralNum = config.getIntegralInvited();
                    logsType = FsUserIntegralLogTypeEnum.TYPE_19;
                    break;
                default:
                    return R.error("积分类型错误,联系管理员");
            }
            if (integralNum!=null && logsType!=null){
                R r = updateAddIntegral(integralNum, user.getUserId(), user.getIntegral(), logsType, param.getBusinessId());
                log.info("用户id为{},{}", user.getUserId(),r.get("msg").toString());
                return R.ok();
            }

        }
        return R.error("用户信息不存在");
    }


    /**
     *
     * @param integralNum
     * @param userId
     * @param userIntegral
     * @return
     */
    public R updateAddIntegral(Integer integralNum,Long userId,Long userIntegral, FsUserIntegralLogTypeEnum logsType,String businessId) {
        FsUser userMap=new FsUser();
        userMap.setUserId(userId);
        userMap.setIntegral(userIntegral+integralNum);
        fsUserMapper.updateFsUser(userMap);
        FsUserIntegralLogs integralLogs = new FsUserIntegralLogs();
        integralLogs.setIntegral(integralNum.longValue());
        integralLogs.setUserId(userId);
        integralLogs.setBalance(userMap.getIntegral());
        integralLogs.setLogType(logsType.getValue());
        integralLogs.setCreateTime(new Date());
        integralLogs.setBusinessId(businessId);
        if (fsUserIntegralLogsMapper.insertFsUserIntegralLogs(integralLogs)>0){
            return R.ok(logsType.getDesc()+":"+integralNum+"积分");
        }
        return R.error("获取积分失败");
    }

    private R addVideoIntegral(Integer integralFirstVideo,Integer integralFinishVideo,Long userId,Long userIntegral) {
        Integer videoIntegralCount = fsUserIntegralLogsMapper.selectTodayVideoIntegralCount(userId);
        Integer addIntegral = integralFirstVideo-videoIntegralCount;
        if (addIntegral<=integralFinishVideo){
            addIntegral=integralFinishVideo;
        }
        FsUser userMap=new FsUser();
        userMap.setUserId(userId);
        userMap.setIntegral(userIntegral+addIntegral);
        fsUserMapper.updateFsUser(userMap);
        FsUserIntegralLogs integralLogs = new FsUserIntegralLogs();
        integralLogs.setIntegral(addIntegral.longValue());
        integralLogs.setUserId(userId);
        integralLogs.setBalance(userMap.getIntegral());
        integralLogs.setLogType(14);
        integralLogs.setCreateTime(new Date());
        if (fsUserIntegralLogsMapper.insertFsUserIntegralLogs(integralLogs)>0){
            return R.ok("观看视频获得"+addIntegral+"积分");
        }
        return R.error("获取积分失败");
    }

    public R addProductIntegral(Integer integralProduct,Long userId,Long userIntegral) {
        FsUser userMap=new FsUser();
        userMap.setUserId(userId);
        userMap.setIntegral(userIntegral+integralProduct);
        fsUserMapper.updateFsUser(userMap);
        FsUserIntegralLogs integralLogs = new FsUserIntegralLogs();
        integralLogs.setIntegral(integralProduct.longValue());
        integralLogs.setUserId(userId);
        integralLogs.setBalance(userMap.getIntegral());
        integralLogs.setLogType(13);
        integralLogs.setCreateTime(new Date());
        if (fsUserIntegralLogsMapper.insertFsUserIntegralLogs(integralLogs)>0){
            return R.ok("浏览商品获得"+integralProduct+"积分");
        }
        return R.error("获取积分失败");
    }

    @Override
    public R subIntegral() {
        List<SubIntegralVO> list  = fsUserIntegralLogsMapper.selectSubIntegralByLogType12();
        for (SubIntegralVO vo : list){
            FsUser user = fsUserMapper.selectFsUserByUserId(vo.getUserId());
            if (user!=null){
                FsUser userMap = new FsUser();
                Long subIntegral = 1000 * vo.getNum();
                Long integral = user.getIntegral()-subIntegral;
                if (integral<0){
                    userMap.setIntegral(0L);
                }else {
                    userMap.setIntegral(integral);
                }
                userMap.setUserId(user.getUserId());
                fsUserMapper.updateFsUser(userMap);
            }

        }
        return R.ok();
    }

    @Override
    public R getNewcomerBenefits(Long userId) {

        int taskOne = 0;
        int taskTwo = 0;
        int taskThree = 0;
        int taskFour = 0;
        int taskFive = 0;
        int isNewUser = 0;
//        long expireDays = 0;
        Date createTime = null;
        FsUser fsUser = fsUserMapper.selectFsUserIsNew(userId);
        if (fsUser!=null){
            isNewUser = 1;

//            Date createTime = fsUser.getCreateTime(); // 获取用户创建时间
//            LocalDateTime createDateTime = LocalDateTime.ofInstant(createTime.toInstant(), ZoneId.systemDefault()); // 将 Date 转换为 LocalDateTime
//            LocalDateTime now = LocalDateTime.now(); // 获取当前时间
//            long daysElapsed = ChronoUnit.DAYS.between(createDateTime, now); // 计算已经过去的天数
//            long remainingDays = Math.max(0, 7 - daysElapsed); // 计算剩余天数，确保不为负数
//
//            // 输出剩余天数
//            System.out.println("剩余新手期天数：" + remainingDays);
//
//            expireDays = remainingDays;


        }
        FsUserNewTask newTask = fsUserNewTaskMapper.selectFsUserNewTaskByUserId(userId);
        if (newTask!=null){
            taskOne = newTask.getTaskOne();
            taskTwo = newTask.getTaskTwo();
            taskThree = newTask.getTaskThree();
            createTime = newTask.getCreateTime();
        }
        FsUserIntegralLogs logs1 = fsUserIntegralLogsMapper.selectFsUserIntegralLogsAddPatient(userId);
        if (logs1!=null){
            taskFour = 1;
        }
        FsUserIntegralLogs logs2 = fsUserIntegralLogsMapper.selectFsUserIntegralLogsAddUserAddress(userId);
        if (logs2!=null){
            taskFive = 1;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("taskOne",taskOne);
        map.put("taskTwo",taskTwo);
        map.put("taskThree",taskThree);
        map.put("taskFour",taskFour);
        map.put("taskFive",taskFive);
        return R.ok().put("data",map).put("isNewUser",isNewUser).put("createTime",createTime);
    }
}
