package com.fs.his.service.impl;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.his.config.IntegralConfig;
import com.fs.his.domain.FsUserAddress;
import com.fs.his.domain.FsUserIntegralLogs;
import com.fs.his.mapper.*;
import com.fs.his.param.FsStoreOrderParam;
import com.fs.his.param.FsUserParam;
import com.fs.his.vo.FsUserExportListVO;
import com.fs.his.vo.FsUserFollowDoctorVO;
import com.fs.his.vo.FsUserVO;
import com.fs.his.vo.UserVo;
import com.fs.qw.param.QwFsUserParam;
import com.fs.qw.vo.QwFsUserVO;
import com.fs.system.service.ISysConfigService;
import com.fs.watch.domain.WatchUser;
import com.fs.watch.service.WatchUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.his.domain.FsUser;
import com.fs.his.service.IFsUserService;
import org.springframework.transaction.annotation.Transactional;

import static com.fs.his.utils.PhoneUtil.encryptPhone;

/**
 * 用户Service业务层处理
 *
 * @author fs
 * @date 2023-06-07
 */
@Service
public class FsUserServiceImpl implements IFsUserService
{
    Logger logger= LoggerFactory.getLogger(getClass());;
    @Autowired
    private FsUserMapper fsUserMapper;
    @Autowired
    private FsUserAddressMapper fsUserAddressMapper;
    @Autowired
    private FsStoreOrderMapper fsStoreOrderMapper;
    @Autowired
    private FsFollowMapper fsFollowMapper;
    @Autowired
    private WatchUserService watchUserService;
    /**
     * 查询用户
     *
     * @param userId 用户主键
     * @return 用户
     */
    @Override
    public FsUser selectFsUserByUserId(Long userId)
    {
        return fsUserMapper.selectFsUserByUserId(userId);
    }

    /**
     * 查询用户列表
     *
     * @param fsUser 用户
     * @return 用户
     */
    @Override
    public List<FsUser> selectFsUserList(FsUser fsUser)
    {
        return fsUserMapper.selectFsUserList(fsUser);
    }

    /**
     * 新增用户
     *
     * @param fsUser 用户
     * @return 结果
     */
    @Override
    @Transactional
    public int insertFsUser(FsUser fsUser)
    {
        fsUser.setCreateTime(DateUtils.getNowDate());
        if (StringUtils.isNotEmpty(fsUser.getPhone())){
            fsUser.setPhone(encryptPhone(fsUser.getPhone()));
        }
        int i = fsUserMapper.insertFsUser(fsUser);

        //生成腕表模块默认设置
        WatchUser watchUser = new WatchUser();
        watchUser.setUserId(fsUser.getUserId());
        watchUserService.insert(watchUser);
        return i;
    }

    /**
     * 修改用户
     *
     * @param fsUser 用户
     * @return 结果
     */
    @Override
    public int updateFsUser(FsUser fsUser)
    {
        fsUser.setUpdateTime(DateUtils.getNowDate());
        if (fsUser.getPhone()!=null&&fsUser.getPhone().length()==11&&fsUser.getPhone().matches("\\d+")){
            fsUser.setPhone(encryptPhone(fsUser.getPhone()));
        }else {
            fsUser.setPhone(null);
        }
        return fsUserMapper.updateFsUser(fsUser);
    }

    /**
     * 批量删除用户
     *
     * @param userIds 需要删除的用户主键
     * @return 结果
     */
    @Override
    public int deleteFsUserByUserIds(Long[] userIds)
    {
        for (Long userId : userIds) {
            fsUserMapper.updateFsUserByUserId(userId);
        }
        return userIds.length;
    }

    /**
     * 删除用户信息
     *
     * @param userId 用户主键
     * @return 结果
     */
    @Override
    public int deleteFsUserByUserId(Long userId)
    {
        return fsUserMapper.updateFsUserByUserId(userId);
    }

    @Override
    public List<FsUserVO> selectFsUserListVO(FsUserParam fsUser) {
        return fsUserMapper.selectFsUserListVO(fsUser);
    }

    @Override
    public FsUser selectFsUserByOpenId(String openId) {
        return fsUserMapper.selectFsUserByOpenId(openId);
    }

    @Override
    public FsUser selectFsUserByChhyOpenId(String openId) {
        return fsUserMapper.selectFsUserByChhyOpenId(openId);
    }

    @Override
    public FsUser selectFsUserByPhone(String phone) {
        return fsUserMapper.selectFsUserByPhone(phone);
    }

    @Override
    public List<FsUserAddress> selectFsUserAddressByUserId(Long userId) {
        FsUserAddress fsUserAddress = new FsUserAddress();
        fsUserAddress.setUserId(userId);
        return fsUserAddressMapper.selectFsUserAddressList(fsUserAddress);
    }

    @Override
    public List<UserVo> selectUserVOList(String name) {
        return fsUserAddressMapper.selectUserVOList(name);
    }

    @Override
    public List<FsUserVO> selectFsUserListVOByComponentsUser(FsUserParam fsUser) {
        return fsUserMapper.selectFsUserListVOByComponentsUser(fsUser);
    }

    @Override
    public List<FsUserExportListVO> selectFsUserExportListVO(FsUserParam fsUser) {
        return fsUserMapper.selectFsUserExportListVO(fsUser);
    }
    @Autowired
    private FsUserIntegralLogsMapper integralLogsMapper;

    @Autowired
    private ISysConfigService configService;

    @Override
    @Transactional
    public void addUserIntegral(BigDecimal payMoney,Long userId,Long orderId ,Integer orderType) {
            FsUser fsUser = fsUserMapper.selectFsUserByUserId(userId);
            if(fsUser!=null){
                String json =configService.selectConfigByKey("his.integral");
                IntegralConfig config= JSONUtil.toBean(json,IntegralConfig.class);
                Long integral = payMoney.divide(BigDecimal.valueOf(config.getIntegralRatio()),new MathContext(10, RoundingMode.HALF_UP)).longValue();
                //实付多少获取多少积分
                if (integral>0){
                    FsUser u = new FsUser();
                    u.setUserId(userId);
                    u.setIntegral(fsUser.getIntegral()+integral);
                    fsUserMapper.updateFsUser(u);
                    logger.info("用户{}获取积分{}",fsUser.getUserId(),integral);
                    //写入日志
                    FsUserIntegralLogs logs = new FsUserIntegralLogs();
                    logs.setIntegral(integral.longValue());
                    logs.setBusinessType(orderType);
                    logs.setUserId(userId);
                    logs.setBalance(u.getIntegral());
                    logs.setLogType(2);
                    logs.setBusinessId(orderId.toString());
                    logs.setCreateTime(new Date());
                    integralLogsMapper.insertFsUserIntegralLogs(logs);
                }
            }
    }

    @Override
    @Transactional
    public void followAddIntegral(Long userId,Long orderId) {
        FsUser fsUser = fsUserMapper.selectFsUserByUserId(userId);
        if(fsUser!=null){
            String json =configService.selectConfigByKey("his.integral");
            IntegralConfig config= JSONUtil.toBean(json,IntegralConfig.class);
            Integer todayTotalIntegral= integralLogsMapper.selectTodayTotalIntegral(config.getIntegralTypeByOneDay(),userId);
            if (todayTotalIntegral==null){
                todayTotalIntegral=0;
            }
            if (todayTotalIntegral!=null&&todayTotalIntegral>=config.getIntegralByOneDay()){
                return;
            }
            Long integral = config.getIntegralFollow()+0L;
                FsUser u = new FsUser();
                u.setUserId(userId);
                u.setIntegral(fsUser.getIntegral()+integral);
                fsUserMapper.updateFsUser(u);
                logger.info("用户{}获取积分{}",fsUser.getUserId(),integral);
                //写入日志
                FsUserIntegralLogs logs = new FsUserIntegralLogs();
                logs.setIntegral(integral.longValue());
                logs.setBusinessType(4);
                logs.setUserId(userId);
                logs.setBalance(u.getIntegral());
                logs.setLogType(6);
                logs.setBusinessId(orderId.toString());
                logs.setCreateTime(new Date());
                integralLogsMapper.insertFsUserIntegralLogs(logs);

        }
    }

    @Transactional
    public void subIntegral(Long userId) {
        FsUser fsUser = fsUserMapper.selectFsUserByUserId(userId);
        if(fsUser!=null&&fsUser.getIntegral()!=0){
            Long integral = fsUser.getIntegral();
            fsUser.setIntegral(0L);
            fsUserMapper.updateFsUser(fsUser);
            logger.info("用户{}扣除积分{}",fsUser.getUserId(),0-integral);
            FsUserIntegralLogs logs = new FsUserIntegralLogs();
            logs.setIntegral(0-integral);
            logs.setUserId(userId);
            logs.setBalance(0L);
            logs.setLogType(7);
            logs.setCreateTime(new Date());
            integralLogsMapper.insertFsUserIntegralLogs(logs);
            }

        }

    @Override
    public FsUserFollowDoctorVO getUserFollowDoctorAndOrderId(Long userId) {
        FsUserFollowDoctorVO fsUserFollowDoctorVO = fsStoreOrderMapper.selectFsFollowDoctorIdByUserId(userId);
        if (fsUserFollowDoctorVO!=null&&fsUserFollowDoctorVO.getFollowDoctorId()!=null){
            Long followId = fsFollowMapper.selectFsFollowByStoreOrderId(fsUserFollowDoctorVO.getOrderId());
            fsUserFollowDoctorVO.setFollowId(followId);
        }
        return fsUserFollowDoctorVO;
    }

    @Override
    public List<FsUserVO> selectFsUserListVOByComponent(FsUserParam fsUser) {
        return fsUserMapper.selectFsUserListVOByComponent(fsUser);
    }


    @Override
    @Transactional
    public void subUserIntegral(Long userId,Long orderId ,Integer orderType) {
            FsUser fsUser = fsUserMapper.selectFsUserByUserId(userId);
            if(fsUser!=null){
                FsUserIntegralLogs maps=new FsUserIntegralLogs();
                maps.setLogType(2);
                maps.setBusinessType(orderType);
                maps.setBusinessId(orderId.toString());
                List<FsUserIntegralLogs> logsList=integralLogsMapper.selectFsUserIntegralLogsList(maps);
                if(logsList.size()>0){
                    for (FsUserIntegralLogs userLogs : logsList) {
                        fsUser.setIntegral(fsUser.getIntegral()-userLogs.getIntegral());
                        fsUserMapper.updateFsUser(fsUser);
                        logger.info("用户{}扣除积分{}",fsUser.getUserId(),userLogs.getIntegral());
                        //写入日志
                        FsUserIntegralLogs logs = new FsUserIntegralLogs();
                        logs.setIntegral(-logsList.get(0).getIntegral());
                        logs.setUserId(userId);
                        logs.setBalance(fsUser.getIntegral());
                        logs.setBusinessType(orderType);
                        logs.setLogType(4);
                        logs.setBusinessId(orderId.toString());
                        logs.setCreateTime(new Date());
                        integralLogsMapper.insertFsUserIntegralLogs(logs);
                    }
                }

            }

    }

    @Override
    public void shareAddIntegral(Long userId) {
        FsUser fsUser = fsUserMapper.selectFsUserByUserId(userId);
        if(fsUser!=null) {
            String json = configService.selectConfigByKey("his.integral");
            IntegralConfig config = JSONUtil.toBean(json, IntegralConfig.class);
            Integer integral = config.getIntegralRatio();
            FsUser u = new FsUser();
            u.setUserId(userId);
            u.setIntegral(fsUser.getIntegral() + integral);
            fsUserMapper.updateFsUser(u);
            logger.info("用户{}获取积分{}", fsUser.getUserId(), integral);
            FsUserIntegralLogs logs = new FsUserIntegralLogs();
            logs.setIntegral(integral + 0L);
            logs.setUserId(userId);
            logs.setBalance(fsUser.getIntegral());
            logs.setLogType(3);
            logs.setCreateTime(new Date());
            integralLogsMapper.insertFsUserIntegralLogs(logs);
        }
    }

    @Override
    public FsUser selectFsUserByUnionid(String unionid) {
        return fsUserMapper.selectFsUserByUnionid(unionid);
    }

    @Override
    public List<QwFsUserVO> selectQwFsUserListVO(QwFsUserParam qwFsUserParam) {
        return fsUserMapper.selectQwFsUserListVO(qwFsUserParam);
    }


    @Override
    public R clearUserVip(Long userId) {
        FsUser user = new FsUser();
        user.setUserId(userId);
        user.setIsVip(0);
        user.setVipStartDate(null);
        user.setVipEndDate(null);
        if (fsUserMapper.updateFsUser(user)>0){
            return R.ok("清除成功");
        }
        return R.error("清除vip失败");
    }

    @Override
    public List<QwFsUserVO> selecQwFsUserListVO(QwFsUserParam qwFsUserParam) {
        return fsUserMapper.selecQwFsUserListVO(qwFsUserParam);
    }

    @Override
    public Boolean isEntityNull(FsUserParam param) {
        if (param == null) {
            return true; // 整个实体对象为null
        }
        Class<? extends FsUserParam> entityClass = param.getClass();
        Field[] fields = entityClass.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                Object value = field.get(param);
                if (value != null) {
                    return false; // 实体对象中有字段不为null
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return true; // 实体对象内所有字段为null
    }

    @Override
    public Long selectFsUserExportListVOCount(FsUserParam fsUser) {
        return fsUserMapper.selectFsUserExportListVOCount(fsUser);
    }

    @Override
    public FsUser selectFsUserByMpOpenId(String openId) {
        return fsUserMapper.selectFsUserByMpOpenId(openId);
    }

}
