package com.ai.da.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.ai.da.common.config.exception.BusinessException;
import com.ai.da.common.context.UserContext;
import com.ai.da.common.response.ResultEnum;
import com.ai.da.common.utils.CopyUtil;
import com.ai.da.common.utils.RequestInfoUtil;
import com.ai.da.common.utils.SendEmailUtil;
import com.ai.da.mapper.primary.AccountMapper;
import com.ai.da.mapper.primary.TrialOrderMapper;
import com.ai.da.mapper.primary.entity.Account;
import com.ai.da.mapper.primary.entity.TrialOrder;
import com.ai.da.model.dto.AccountTrialDTO;
import com.ai.da.model.dto.TrialOrderDTO;
import com.ai.da.model.enums.AutoApproved;
import com.ai.da.model.enums.Language;
import com.ai.da.model.vo.AuthPrincipalVo;
import com.ai.da.service.LibraryService;
import com.ai.da.service.TrialOrderService;
import com.ai.da.service.UserLikeGroupService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

@Service
public class TrialOrderServiceImpl extends ServiceImpl<TrialOrderMapper, TrialOrder> implements TrialOrderService {

    @Resource
    private AccountMapper accountMapper;
    @Resource
    private LibraryService libraryService;
    @Resource
    private UserLikeGroupService userLikeGroupService;

    @Override
    public Boolean addTrialUser(AccountTrialDTO accountTrialDTO, HttpServletRequest request) {
        // 获取用户申请试用IP
        String ipAddress = RequestInfoUtil.getIpAddress(request);
        boolean link = false;
        if (StringUtils.isNotBlank(accountTrialDTO.getRef())) {
            link = true;
        }
        // 先检测试用订单
        QueryWrapper<TrialOrder> trialOrderQueryWrapper = new QueryWrapper<>();
//        trialOrderQueryWrapper.eq("BINARY email", accountTrialDTO.getEmail());
        trialOrderQueryWrapper.eq("email", accountTrialDTO.getEmail());
//        trialOrderQueryWrapper.lambda().eq(TrialOrder::getIp, ipAddress);
//        trialOrderQueryWrapper.lambda().and(wrapper ->
//                wrapper.eq(TrialOrder::getEmail, accountTrialDTO.getEmail())
//                        .or() // OR
//                        .like(TrialOrder::getUserName, accountTrialDTO.getUserName()));
        List<TrialOrder> trialOrders = baseMapper.selectList(trialOrderQueryWrapper);
        if (CollectionUtil.isNotEmpty(trialOrders)) {
            TrialOrder trialOrder = trialOrders.get(0);
            if (trialOrder.getStatus() == 1) {
                throw new BusinessException("You have submitted a trial application, please wait for approval.");
            }else {
                throw new BusinessException("You have already been approved for a trial, please do not apply for the trial again");
            }
        }
        // 先检测用户名和邮箱
        QueryWrapper<Account> qw = new QueryWrapper<>();
//        qw.eq("BINARY user_email", accountTrialDTO.getEmail());
        qw.eq("user_email", accountTrialDTO.getEmail());
        List<Account> accountList = accountMapper.selectList(qw);
        if (CollectionUtil.isNotEmpty(accountList) && !accountList.get(0).getSystemUser().equals(0)) {
            if (accountList.get(0).getIsTrial() == 1) {
                throw new BusinessException("email.has.been.registered", ResultEnum.PROMPT.getCode());
            } else {
                Account account = accountList.get(0);
                if (null == account.getValidEndTime() || account.getValidEndTime() > System.currentTimeMillis()) {
                    throw new BusinessException("email.has.been.registered", ResultEnum.PROMPT.getCode());
                }
            }
        }
        // 接收到数据后要形成一条使用订单信息
        TrialOrder trialOrder = CopyUtil.copyObject(accountTrialDTO, TrialOrder.class);
        trialOrder.setCreateTime(LocalDateTime.now());
        trialOrder.setStatus(0);
        trialOrder.setIp(ipAddress);
        baseMapper.insert(trialOrder);
//        SendEmailUtil.sendCustomEmail("1023316923@qq.com", null, trialOrder,1);
//        SendEmailUtil.sendCustomEmail("calvinwong@aidlab.hk", null, trialOrder,1);
//        SendEmailUtil.sendCustomEmail("kaicpang.pang@connect.polyu.hk", null, trialOrder,1);
        // 判断当前的试用订单是否自动批准
        if (AutoApproved.getStatus()) {
            // 改变试用订单状态，新增试用用户
            trialOrder.setStatus(1);
            trialOrder.setUpdateTime(LocalDateTime.now());
            baseMapper.updateById(trialOrder);
            Account account = new Account();
            if (CollectionUtil.isNotEmpty(accountList)) {
                account = CopyUtil.copyObject(accountList.get(0), Account.class);
                account.setIsTrial(1);
                account.setIsBeginner(1);
                account.setSystemUser(3);
                account.setValidStartTime(System.currentTimeMillis());
                account.setCountry(accountTrialDTO.getCountry());
                if (link) {
                    account.setValidEndTime(toDayEnd(Instant.now().plus(5, ChronoUnit.DAYS).toEpochMilli()));
                } else {
                    account.setValidEndTime(toDayEnd(Instant.now().plus(5, ChronoUnit.DAYS).toEpochMilli()));
                }
                account.setCredits(BigDecimal.valueOf(100));
                accountMapper.updateById(account);
            } else {
                account.setUserName(trialOrder.getUserName());
                account.setUserPassword("Third-000000");
                account.setUserEmail(trialOrder.getEmail());
                account.setLanguage(Language.ENGLISH.name());
                account.setCountry(accountTrialDTO.getCountry());
                account.setValidStartTime(System.currentTimeMillis());
                if (link) {
                    account.setValidEndTime(toDayEnd(Instant.now().plus(5, ChronoUnit.DAYS).toEpochMilli()));
                } else {
                    account.setValidEndTime(toDayEnd(Instant.now().plus(5, ChronoUnit.DAYS).toEpochMilli()));
                }
                account.setCreateDate(new Date());
                account.setIsTrial(1);
                account.setIsBeginner(1);
                account.setSystemUser(3);
                account.setCredits(BigDecimal.valueOf(100));
                accountMapper.insert(account);
            }
            // 发送邮件提醒用户试用用户已创建
//            SendEmailUtil.sendCustomEmail("1023316923@qq.com", null, trialOrder,2);
//            SendEmailUtil.sendCustomEmail("calvinwong@aidlab.hk", null, trialOrder,2);
//            SendEmailUtil.sendCustomEmail("kaicpang.pang@connect.polyu.hk", null, trialOrder,2);
            if (trialOrder.getCountry().equals("China")) {
                SendEmailUtil.sendCustomEmail(account.getUserEmail(), null, trialOrder, 3, trialOrder.getCountry(), link);
            } else {
                SendEmailUtil.sendCustomEmail(account.getUserEmail(), null, trialOrder, 3, trialOrder.getCountry(), link);
            }
        }
        return Boolean.TRUE;
    }

    // 将指定unix时间置为当天的23：59：59
    public long toDayEnd(long unixTimestampMillis){
        // 将UNIX时间戳转换为LocalDateTime对象
        LocalDateTime dateTime = Instant.ofEpochMilli(unixTimestampMillis)
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();

        // 获取日期部分并设置时间为23:59:59
        LocalDate date = dateTime.toLocalDate();
        LocalDateTime endOfDay = date.atTime(LocalTime.of(23, 59, 59));

        // 将LocalDateTime对象转换为UNIX时间戳（以毫秒为单位） 北京时间
        return endOfDay.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
    }

    @Override
    public IPage<TrialOrder> trialOrderList(TrialOrderDTO trialOrderDTO) {
        QueryWrapper<TrialOrder> qw = new QueryWrapper<>();
        qw.lambda().eq(trialOrderDTO.getStatus() != null, TrialOrder::getStatus, trialOrderDTO.getStatus());
        return baseMapper.selectPage(new Page<>(trialOrderDTO.getPage(), trialOrderDTO.getSize()), qw);
    }

    @Override
    public Boolean trialOrderApproval(List<Long> ids) {
        for (Long id : ids) {
            TrialOrder trialOrder = baseMapper.selectById(id);
            trialOrder.setStatus(1);
            trialOrder.setUpdateTime(LocalDateTime.now());
            baseMapper.updateById(trialOrder);

            QueryWrapper<Account> qw = new QueryWrapper<>();
//            qw.eq("BINARY user_email", trialOrder.getEmail());
            qw.eq("user_email", trialOrder.getEmail());
            List<Account> accountList = accountMapper.selectList(qw);

            Account account = new Account();
            if (CollectionUtil.isNotEmpty(accountList)) {
                account = CopyUtil.copyObject(accountList.get(0), Account.class);
                account.setIsTrial(1);
                account.setIsBeginner(1);
                account.setValidStartTime(System.currentTimeMillis());
                account.setValidEndTime(toDayEnd(Instant.now().plus(5, ChronoUnit.DAYS).toEpochMilli()));
                accountMapper.updateById(account);
            } else {
                account.setUserName(trialOrder.getUserName());
                account.setUserPassword("Third-000000");
                account.setUserEmail(trialOrder.getEmail());
                account.setLanguage(Language.ENGLISH.name());
                account.setValidStartTime(System.currentTimeMillis());
                account.setValidEndTime(toDayEnd(Instant.now().plus(5, ChronoUnit.DAYS).toEpochMilli()));
                account.setCreateDate(new Date());
                account.setIsTrial(1);
                account.setIsBeginner(1);
                account.setSystemUser(1);
                accountMapper.insert(account);
            }
            // 发送邮件提醒用户试用用户已创建
//            SendEmailUtil.sendCustomEmail("1023316923@qq.com", null, trialOrder,2, trialOrder.getCountry());
//            SendEmailUtil.sendCustomEmail("calvinwong@aidlab.hk", null, trialOrder,2, trialOrder.getCountry());
//            SendEmailUtil.sendCustomEmail("kaicpang.pang@connect.polyu.hk", null, trialOrder,2, trialOrder.getCountry());
            if (trialOrder.getCountry().equals("China")) {
                SendEmailUtil.sendCustomEmail(account.getUserEmail(), null, trialOrder, 3, trialOrder.getCountry(), false);
            } else {
                SendEmailUtil.sendCustomEmail(account.getUserEmail(), null, trialOrder, 3, trialOrder.getCountry(), false);
            }
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean trialOrderRefuse(List<Long> ids) {
        for (Long id : ids) {
            TrialOrder trialOrder = baseMapper.selectById(id);
            trialOrder.setStatus(2);
            trialOrder.setUpdateTime(LocalDateTime.now());
            baseMapper.updateById(trialOrder);
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean trialUserLogout() {
        AuthPrincipalVo userInfo = UserContext.getUserHolder();
        Account account = accountMapper.selectById(userInfo.getId());
        if (account.getIsTrial() != 1) {
            throw new BusinessException("用户为正式用户");
        }
        libraryService.deleteTrialData(userInfo.getId());
        userLikeGroupService.deleteTrialData(userInfo.getId());
        return Boolean.TRUE;
    }
}
