package com.kxs.product.biz.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.common.core.constant.SecurityConstants;
import com.kxs.common.core.constant.enums.ErrorTypeEnum;
import com.kxs.common.core.exception.GlobalCustomerException;
import com.kxs.common.core.util.R;
import com.kxs.common.core.util.RetOps;
import com.kxs.common.security.util.SecurityUtils;
import com.kxs.product.api.dto.kxsapp.ticket.TicketTransferDTO;
import com.kxs.product.api.dto.kxsapp.ticket.TicketTransferQuery;
import com.kxs.product.api.model.KxsTicket;
import com.kxs.product.api.model.KxsTicketTransferInfo;
import com.kxs.product.api.vo.kxsapp.ticket.TicketTransferDetailVO;
import com.kxs.product.api.vo.kxsapp.ticket.TicketTransferListVO;
import com.kxs.product.biz.constant.enums.ProductErrorTypeEnum;
import com.kxs.product.biz.constant.enums.TicketTypeEnum;
import com.kxs.product.biz.mapper.KxsTicketMapper;
import com.kxs.product.biz.mapper.KxsTicketTransferInfoMapper;
import com.kxs.product.biz.mapper.KxsTicketTransferMapper;
import com.kxs.product.api.model.KxsTicketTransfer;
import com.kxs.product.biz.service.KxsTicketTransferInfoService;
import com.kxs.product.biz.service.KxsTicketTransferService;
import com.kxs.user.api.feign.RemoteKxsUserService;
import com.kxs.user.api.model.KxsUser;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 客小爽券码划拨记录表(KxsTicketTransfer)表服务实现类
 *
 * @author 系统
 * @since 2023-12-20 10:09:35
 */
@Service("kxsTicketTransferService")
@RequiredArgsConstructor
public class KxsTicketTransferServiceImpl extends ServiceImpl<KxsTicketTransferMapper, KxsTicketTransfer> implements KxsTicketTransferService {

    private final RemoteKxsUserService remoteKxsUserService;

    private final KxsTicketMapper kxsTicketMapper;

    private final KxsTicketTransferMapper kxsTicketTransferMapper;
    private final KxsTicketTransferInfoService kxsTicketTransferInfoService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R ticketTransfer(TicketTransferDTO param) {

        Integer userId = SecurityUtils.getUser().getId().intValue();

        //订单号
        Snowflake snowflake = IdUtil.getSnowflake(1, userId);
        String orderSn = "SC" + snowflake.nextId();

        //查询用户信息
        R<KxsUser> sendResult = remoteKxsUserService.loadUserById(userId, SecurityConstants.FROM_IN);
        KxsUser sendUser = RetOps.of(sendResult)
                .getData()
                .orElseThrow(() -> new GlobalCustomerException(ErrorTypeEnum.USER_NOT_FOUND.getDescription()));

        //查询拨入创客
        R<KxsUser> kxsUserR = remoteKxsUserService.loadUserByCode(param.getUserCode(), SecurityConstants.FROM_IN);
        KxsUser toUser = RetOps.of(kxsUserR)
                .getData()
                .orElseThrow(() -> new GlobalCustomerException(ErrorTypeEnum.USER_NOT_FOUND.getDescription()));

        R<Boolean> booleanR = remoteKxsUserService.checkUserIsChildren(userId, toUser.getId(), SecurityConstants.FROM_IN);
        if (!booleanR.getData()) {
            return R.failed(ProductErrorTypeEnum.USER_IS_NOT_FIND.getDescription());
        }

        //划拨明细集合
        List<KxsTicketTransferInfo> kxsTicketTransferInfos = new ArrayList<>();
        for (String ticketCode : param.getTicketCodes()) {
            KxsTicket kxsTicket = kxsTicketMapper.selectOne(Wrappers.<KxsTicket>lambdaQuery().eq(KxsTicket::getTicketCode, ticketCode));
            if (kxsTicket == null) {
                throw new GlobalCustomerException(ProductErrorTypeEnum.TICKET_NOT_FOUND.getDescription());
            }
            if(!kxsTicket.getUserId().equals(userId)){
                throw new GlobalCustomerException(ProductErrorTypeEnum.TICKET_NOT_USER.getDescription());
            }
            //机具轨迹路径
            String allotPath = kxsTicket.getTicketAllotPath() == null ? "0," : kxsTicket.getTicketAllotPath();
            kxsTicket.setTicketAllotPath(allotPath + kxsTicket.getUserId() + "," );
            kxsTicket.setUserId(toUser.getId());
            //修改机具所属
            kxsTicketMapper.updateById(kxsTicket);

            //划拨明细
            KxsTicketTransferInfo kxsTicketTransferInfo = new KxsTicketTransferInfo();
            kxsTicketTransferInfo.setTicketCode(ticketCode);
            kxsTicketTransferInfo.setTicketId(kxsTicket.getId());
            kxsTicketTransferInfo.setOrderSn(orderSn);
            kxsTicketTransferInfos.add(kxsTicketTransferInfo);
        }


        //添加划拨记录
        KxsTicketTransfer ticketTransfer = new KxsTicketTransfer();
        //拨出用户
        ticketTransfer.setSendUserId(userId);
        ticketTransfer.setSendUserName(sendUser.getUsername());
        ticketTransfer.setSendUserCode(sendUser.getUserCode());
        //拨入用户
        ticketTransfer.setToUserId(toUser.getId());
        ticketTransfer.setToUserName(toUser.getUsername());
        ticketTransfer.setToUserCode(toUser.getUserCode());
        ticketTransfer.setTransferNum(param.getTicketCodes().size());
        ticketTransfer.setTicketType(param.getTicketType());
        ticketTransfer.setOrderSn(orderSn);

        //插入划拨记录
        kxsTicketTransferMapper.insert(ticketTransfer);
        kxsTicketTransferInfoService.saveBatch(kxsTicketTransferInfos);
        return R.ok();
    }

    @Override
    public IPage<TicketTransferListVO> getByPage(Page<TicketTransferListVO> page, TicketTransferQuery ticketTransferQuery) {

        Long userId = SecurityUtils.getUser().getId();

        //拨入查询
        if (ticketTransferQuery.getTransferType() == 1) {
            ticketTransferQuery.setToUserId(userId.intValue());
        }
        //拨出查询
        if (ticketTransferQuery.getTransferType() == 2) {
            ticketTransferQuery.setSendUserId(userId.intValue());
        }

        return baseMapper.getByPage(page, ticketTransferQuery);
    }

    @Override
    public TicketTransferDetailVO getByData(Integer id) {

        Long userId = SecurityUtils.getUser().getId();

        TicketTransferDetailVO transferDetailVO = new TicketTransferDetailVO();

        KxsTicketTransfer kxsTicketTransfer = baseMapper.selectById(id);
        BeanUtils.copyProperties(kxsTicketTransfer, transferDetailVO);

        //拨入
        if(kxsTicketTransfer.getToUserId().equals(userId.intValue())){
            R<KxsUser> result = remoteKxsUserService.loadUserById(kxsTicketTransfer.getSendUserId(), SecurityConstants.FROM_IN);
            KxsUser sendUser = RetOps.of(result)
                    .getData()
                    .orElseThrow(() -> new GlobalCustomerException(ErrorTypeEnum.USER_NOT_FOUND.getDescription()));
            transferDetailVO.setUsername(kxsTicketTransfer.getSendUserName());
            transferDetailVO.setUserCode(kxsTicketTransfer.getSendUserCode());
            transferDetailVO.setPhone(sendUser.getPhone());
        }
        //拨出
        if(kxsTicketTransfer.getSendUserId().equals(userId.intValue())){
            R<KxsUser> result = remoteKxsUserService.loadUserById(kxsTicketTransfer.getToUserId(), SecurityConstants.FROM_IN);
            KxsUser toUser = RetOps.of(result)
                    .getData()
                    .orElseThrow(() -> new GlobalCustomerException(ErrorTypeEnum.USER_NOT_FOUND.getDescription()));
            transferDetailVO.setUsername(kxsTicketTransfer.getToUserName());
            transferDetailVO.setUserCode(kxsTicketTransfer.getToUserCode());
            transferDetailVO.setPhone(toUser.getPhone());
        }

        String ticketType = EnumUtil.getFieldBy(TicketTypeEnum::getDescription, TicketTypeEnum::getType, kxsTicketTransfer.getTicketType());
        transferDetailVO.setTicketType(String.valueOf(kxsTicketTransfer.getTicketType()));
        //查询券码集合
        List<KxsTicketTransferInfo> list = kxsTicketTransferInfoService.list(Wrappers.<KxsTicketTransferInfo>lambdaQuery().eq(KxsTicketTransferInfo::getOrderSn, kxsTicketTransfer.getOrderSn()));
        List<String> ticketCodes = list.stream().map(KxsTicketTransferInfo::getTicketCode).collect(Collectors.toList());
        transferDetailVO.setTicketType(ticketType);
        transferDetailVO.setTicketCodes(ticketCodes);

        return transferDetailVO;
    }







}

