package shop.alien.lawyer.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LawFirm;
import shop.alien.entity.store.LawyerServiceArea;
import shop.alien.entity.store.LawyerUser;
import shop.alien.entity.store.StoreUser;
import shop.alien.entity.store.dto.LawyerUserDto;
import shop.alien.entity.store.vo.LawyerUserVo;
import shop.alien.lawyer.config.BaseRedisService;
import shop.alien.lawyer.service.LawyerUserLogInService;
import shop.alien.mapper.LawFirmMapper;
import shop.alien.mapper.LawyerServiceAreaMapper;
import shop.alien.mapper.LawyerUserMapper;
import shop.alien.util.common.JwtUtil;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 二期-门店用户 服务实现类
 *
 * @author ssk
 * @since 2024-12-11
 */
@Transactional
@Service
@RequiredArgsConstructor
public class LawyerUserLogInServiceImpl extends ServiceImpl<LawyerUserMapper, LawyerUser> implements LawyerUserLogInService {

    @Value("${jwt.expiration-time}")
    private String effectiveTime;

    /**
     * 设定初始化默认密码
     */

    private final BaseRedisService baseRedisService;
    private final LawyerUserMapper lawyerUserMapper;
    private final LawyerServiceAreaMapper lawyerServiceAreaMapper;
    private final LawFirmMapper lawFirmMapper;

    /**
     * token
     *
     * @param lawyerUser
     * @return
     */
    @Override
    public R<LawyerUserVo> createToKen(LawyerUser lawyerUser) {
        int effectiveTimeInt = Integer.parseInt(effectiveTime.substring(0, effectiveTime.length() - 1));
        String effectiveTimeUnit = effectiveTime.substring(effectiveTime.length() - 1);
        long effectiveTimeIntLong = 0L;
        switch (effectiveTimeUnit) {
            case "s": {
                effectiveTimeIntLong = effectiveTimeInt * 1000L;
                break;
            }
            case "m": {
                effectiveTimeIntLong = effectiveTimeInt * 60L * 1000L;
                break;
            }
            case "h": {
                effectiveTimeIntLong = effectiveTimeInt * 60L * 60L * 1000L;
                break;
            }
            case "d": {
                effectiveTimeIntLong = effectiveTimeInt * 24L * 60L * 60L * 1000L;
                break;
            }
        }

        LawyerUserVo lawyerUserVo = new LawyerUserVo();
        BeanUtils.copyProperties(lawyerUser, lawyerUserVo);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("phone", lawyerUser.getPhone());
        tokenMap.put("userName", lawyerUser.getName());
        tokenMap.put("userId", lawyerUser.getId().toString());
        tokenMap.put("userType", "lawyer");
        tokenMap.put("passType", lawyerUser.getPassType().toString());
        lawyerUserVo.setToken(JwtUtil.createJWT("lawyer_" + lawyerUser.getPhone(), lawyerUser.getName(), JSONObject.toJSONString(tokenMap), effectiveTimeIntLong));
        baseRedisService.setString("lawyer_" + lawyerUser.getPhone(), lawyerUserVo.getToken());
        return R.data(lawyerUserVo);
    }

    @Override
    public R<LawyerUserVo> register(LawyerUserDto lawyerUserDto) {
        LawyerUser lawyerUser = lawyerUserMapper.selectOne(new LambdaQueryWrapper<LawyerUser>()
                .eq(LawyerUser::getPhone, lawyerUserDto.getPhone()).last("limit 1"));
        if (ObjectUtils.isNotEmpty(lawyerUser)) {
            if (lawyerUser.getStatus() == 0) {
                return R.fail("账号被禁用");
            }
            return createToKen(lawyerUser);
        }else {
            LawyerUser user = new LawyerUser();
            BeanUtils.copyProperties(lawyerUserDto, user);
            user.setLogoutFlag(0);
            user.setStatus(1);
            user.setDeleteFlag(0);
            user.setIsOnline(1);
            user.setIsRecommended(0);
            user.setOrderReceivingStatus(1);
            user.setPassType(2);
            user.setNickName(user.getName() != null && !user.getName().isEmpty() ?
                    user.getName().charAt(0) + "律师" : "律师");
            lawyerUserMapper.insert(user);
            List<Integer> problemScenarioIds = lawyerUserDto.getProblemScenarioIds();
            for (int i = 0; i < problemScenarioIds.size(); i++) {
                LawyerServiceArea lawyerServiceArea = new LawyerServiceArea();
                lawyerServiceArea.setLawyerUserId(user.getId());
                lawyerServiceArea.setProblemScenarioId(problemScenarioIds.get( i));
                lawyerServiceArea.setSortOrder(i);
                lawyerServiceArea.setCreatedTime(new Date());
                lawyerServiceAreaMapper.insert(lawyerServiceArea);
            }
            /*LambdaQueryWrapper<LawyerUser> lawFirmLambdaQueryWrapper = new LambdaQueryWrapper<>();
            lawFirmLambdaQueryWrapper.eq(LawyerUser::getFirmId, lawyerUserDto.getFirmId());
            List<LawyerUser> lawyerUsers = lawyerUserMapper.selectList(lawFirmLambdaQueryWrapper);
            if (ObjectUtils.isNotEmpty(lawyerUsers)) {
                String lawFirmIds = lawyerUsers.stream().map(u -> String.valueOf(u.getFirmId())).filter(Objects::nonNull).distinct().collect(Collectors.joining(","));
                LawFirm lawFirm = new LawFirm();
                lawFirm.setId(lawyerUserDto.getFirmId());
                lawFirm.setPaymentAccount(lawFirmIds);
                lawFirmMapper.updateById(lawFirm);
            }*/
            return createToKen(user);
        }
    }

    @Override
    public R checkMsgCode(LawyerUserDto lawyerUserDto) {
        String string = baseRedisService.getString("verification_lawyer_" + lawyerUserDto.getPhone());
        if (StringUtils.isNotEmpty(string)) {
            if (lawyerUserDto.getMsgCode().equals(string)) {
                LawyerUser lawyerUser = lawyerUserMapper.selectOne(new LambdaQueryWrapper<LawyerUser>()
                        .eq(LawyerUser::getPhone, lawyerUserDto.getPhone()));
                LawyerUserVo vo = new LawyerUserVo();
                if (ObjectUtils.isNotEmpty(lawyerUser)) {
                    BeanUtils.copyProperties(lawyerUser, vo);
                    return createToKen(lawyerUser);
                }
                return R.data(ObjectUtils.isNotEmpty(lawyerUser) ? vo : "null");
            }else {
                return R.fail("验证码错误");
            }
        }else {
            return R.fail("验证码已过期");
        }
    }

    @Override
    public R logout(LawyerUserDto lawyerUserDto) {
        LawyerUser lawyerUser = new LawyerUser();
        lawyerUser.setId(lawyerUserDto.getId());
        lawyerUser.setLastOnlineTime(new Date());
        lawyerUser.setIsOnline(0);
        lawyerUserMapper.updateById(lawyerUser);
        baseRedisService.delete("lawyer_" + lawyerUserDto.getPhone());
        return R.success("退出成功");
    }

    @Override
    public R updatePassWord(LawyerUserDto lawyerUserDto) {
        String string = baseRedisService.getString("verification_lawyer_" + lawyerUserDto.getPhone());
        if (StringUtils.isNotEmpty(string)) {
            if (lawyerUserDto.getMsgCode().equals(string)) {
                LawyerUser lawyerUser = lawyerUserMapper.selectOne(new LambdaQueryWrapper<LawyerUser>()
                        .eq(LawyerUser::getPhone, lawyerUserDto.getPhone()));
                LawyerUserVo vo = new LawyerUserVo();
                if (ObjectUtils.isNotEmpty(lawyerUser)) {
                    LawyerUser update = new LawyerUser();
                    update.setPassword(lawyerUserDto.getPassword());
                    update.setId(lawyerUser.getId());
                    lawyerUserMapper.updateById(update);
                    BeanUtils.copyProperties(lawyerUser, vo);
                    return createToKen(lawyerUser);
                }
                return R.data(ObjectUtils.isNotEmpty(lawyerUser) ? vo : "null");
            }else {
                return R.fail("验证码错误");
            }
        }else {
            return R.fail("验证码已过期");
        }
    }

    @Override
    public Boolean checkRegister(LawyerUserDto lawyerUserDto) {
        LambdaQueryWrapper<LawyerUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LawyerUser::getPhone, lawyerUserDto.getPhone());
        queryWrapper.in(LawyerUser::getStatus, 1);
        List<LawyerUser> lawyerUsers = lawyerUserMapper.selectList(queryWrapper);
        return CollectionUtils.isEmpty(lawyerUsers) ? Boolean.TRUE : Boolean.FALSE;
    }

}
