package com.qxgmat.service.inline;

import com.github.pagehelper.Page;
import com.nuliji.tools.AbstractService;
import com.nuliji.tools.exception.ParameterException;
import com.nuliji.tools.exception.SystemException;
import com.nuliji.tools.mybatis.Example;
import com.qxgmat.data.dao.UserServiceMapper;
import com.qxgmat.data.dao.entity.Pay;
import com.qxgmat.data.dao.entity.UserPay;
import com.qxgmat.data.dao.entity.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class UserServiceService extends AbstractService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceService.class);

    @Resource
    private UserServiceMapper userServiceMapper;

    @Resource
    private UserPayService userPayService;

    // 完成服务支付
    public boolean payed(Pay pay){
        String[] extend = pay.getModuleExtend().split(":");
        Integer userId = Integer.valueOf(extend[0]);
        // 写入用户购买
        userPayService.add(UserPay.builder().module(pay.getModule()).moduleExtend("").isUse(0).userId(userId).build());
        return true;
    }

    // 开通服务
    public boolean used(UserPay pay){
        String[] extend = pay.getModuleExtend().split(":");
        Integer userId = Integer.valueOf(extend[0]);
        String category = extend[1];
        // todo 分析时长
        add(UserService.builder().userId(userId).service(category).build());
        return true;
    }

    /**
     * 合并用户信息，将old转移至new
     * @param oldUserId
     * @param newUserId
     */
    public void mergeUser(Number oldUserId, Integer newUserId){
        Example example = new Example(UserService.class);
        example.and(
                example.createCriteria().andEqualTo("userId", oldUserId)
        );
        update(userServiceMapper, example, UserService.builder().userId(newUserId).build());
    }

    public Collection<UserService> getByUser(Number userId){
        Example example = new Example(UserService.class);
        example.and(
                example.createCriteria()
                        .andEqualTo("userId", userId)
                        .andGreaterThanOrEqualTo("startTime", new Date())
                        .andLessThan("expireTime", new Date())
        );
        return select(userServiceMapper, example);
    }

    public Map<Object, Collection<UserService>> mapByUser(Collection userIds){
        Map<Object, Collection<UserService>> relationMap = new HashMap<>();
        if(userIds.size() == 0) return relationMap;
        Example example = new Example(UserService.class);
        example.and(
                example.createCriteria()
                        .andIn("userId", userIds)
                        .andGreaterThanOrEqualTo("startTime", new Date())
                        .andLessThan("expireTime", new Date())
        );
        List<UserService> userServiceList = select(userServiceMapper, example);
        if(userServiceList.size() == 0) return relationMap;
        for(UserService row: userServiceList){
            List<UserService> l;
            Number userId = row.getUserId();
            if(!relationMap.containsKey(userId)){
                l = new ArrayList<>();
                relationMap.put(userId, l);
            }else{
                l = (List<UserService>)relationMap.get(userId);
            }
            l.add(row);
        }
        return relationMap;
    }

    public UserService add(UserService service){
        int result = insert(userServiceMapper, service);
        service = one(userServiceMapper, service.getId());
        if(service == null){
            throw new SystemException("服务记录添加失败");
        }
        return service;
    }

    public UserService edit(UserService service){
        UserService in = one(userServiceMapper, service.getId());
        if(in == null){
            throw new ParameterException("服务记录不存在");
        }
        int result = update(userServiceMapper, service);
        return service;
    }

    public boolean delete(Number id){
        UserService in = one(userServiceMapper, id);
        if(in == null){
            throw new ParameterException("服务记录不存在");
        }
        int result = delete(userServiceMapper, id);
        return result > 0;
    }

    public UserService get(Number id){
        UserService in = one(userServiceMapper, id);

        if(in == null){
            throw new ParameterException("服务记录不存在");
        }
        return in;
    }

    public Page<UserService> select(int page, int pageSize){
        return select(userServiceMapper, page, pageSize);
    }

    public List<UserService> select(Collection ids){
        return select(userServiceMapper, ids);
    }

}
