package com.tanpu.fund.service.impl;

import com.github.pagehelper.page.PageMethod;
import com.tanpu.common.auth.UserInfo;
import com.tanpu.common.auth.UserInfoThreadLocalHolder;
import com.tanpu.common.enums.Constant;
import com.tanpu.common.model.Page;
import com.tanpu.common.model.Pageable;
import com.tanpu.common.utils.SnowFlakeUtil;
import com.tanpu.fund.api.model.Answer;
import com.tanpu.fund.api.model.req.FundQaAskReq;
import com.tanpu.fund.api.model.resp.QAVO;
import com.tanpu.fund.api.model.resp.UserInfoVo;
import com.tanpu.fund.entity.generator.FundQa;
import com.tanpu.fund.entity.generator.FundQaExample;
import com.tanpu.fund.feign.user.FeignClientForFatools;
import com.tanpu.fund.mapper.generator.FundQaMapper;
import com.tanpu.fund.service.FundQAService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class FundQAServiceImpl implements FundQAService, Constant {

    @Resource
    private SnowFlakeUtil snowFlakeUtil;
    @Resource
    private FundQaMapper fundQaMapper;
    @Resource
    private FeignClientForFatools feignClientForFatools;

    @Override
    public QAVO productQaAsk(FundQaAskReq fundQaAskReq) {
        UserInfo userInfo = UserInfoThreadLocalHolder.getserInfo();
        String userId = userInfo.getId();

        FundQa p = new FundQa();
        p.setId(this.snowFlakeUtil.uniqueLong());
        p.setFundId(fundQaAskReq.getFundId());
        p.setContent(fundQaAskReq.getContent());
        p.setQaType(ONE_NUM);
        p.setStatus(ZERO_NUM);
        p.setCreateBy(userId);
        // 初始化为平台用户来源
        p.setQaSource(TWO_NUM);
        // 初始化为待审核状态
        p.setVerifyStatus(ONE_NUM);
        p.setCreateTime(new Date());
        p.setUpdateTime(new Date());
        this.fundQaMapper.insertSelective(p);

        p = this.fundQaMapper.selectByPrimaryKey(p.getId());

        return QAVO.builder()
                .userId(userId)
                .headImg(userInfo.getUiHeadimgMp())
                .userName(userInfo.getUiUsernameMp() == null ? userInfo.getUiHeadimg() : userInfo.getUiUsernameMp())
                .time(p.getCreateTime().getTime())
                .question(p.getContent())
                .build();
    }

    @Override
    public Page<QAVO> getProductQAInfo(String fundId, Pageable pageable) {

        FundQaExample example = new FundQaExample();
        example.createCriteria().andFundIdEqualTo(fundId)
                .andQaTypeEqualTo(ONE_NUM)
                .andDeleteTagEqualTo(Constant.ZERO_NUM)
                .andVerifyStatusEqualTo(ONE_NUM);
        example.setOrderByClause("create_time desc");

        com.github.pagehelper.Page<QAVO> page = PageMethod.startPage(pageable.getPageNumber(), pageable.getPageSize());

        List<FundQa> askList = this.fundQaMapper.selectByExampleWithBLOBs(example);

        if (CollectionUtils.isEmpty(askList)) {
            return new Page<>(pageable, 0L, new ArrayList<>(0));
        }

        List<String> askIds = askList.stream().map(FundQa::getId).collect(Collectors.toList());

        //查询答案
        Map<String, List<Answer>> answerMap;
        {
            example.clear();
            example.createCriteria().
                    andFundIdEqualTo(fundId).andAskIdIn(askIds)
                    .andDeleteTagEqualTo(Constant.ZERO_NUM)
                    .andVerifyStatusEqualTo(Constant.ONE_NUM);
            example.setOrderByClause("create_time asc");
            List<FundQa> answerList = this.fundQaMapper.selectByExampleWithBLOBs(example);

            answerMap = answerList.stream().collect(Collectors.toMap(FundQa::getAskId, c -> {
                        List<Answer> list = new ArrayList<>();
                        list.add(Answer.builder()
                                .time(c.getCreateTime() == null ? null : c.getCreateTime().getTime())
                                .answerInfo(c.getContent()).build());
                        return list;
                    },
                    (List<Answer> list1, List<Answer> list2) -> {
                        list1.addAll(list2);
                        return list1;
                    }));
        }

        //查询用户
        Map<String, UserInfoVo> userInfoMap;
        {
            List<String> userIdList = askList.stream().map(FundQa::getCreateBy).collect(Collectors.toList());
            userInfoMap = feignClientForFatools.queryUsersList(userIdList).getAttributes().stream()
                    .collect(Collectors.toMap(UserInfoVo::getId, c -> c));

        }

        //组装返回结果
        List<QAVO> resList = askList.stream().map(item -> {
            String userName, headImg;
            if (userInfoMap.get(item.getCreateBy()) != null) {
                UserInfoVo userInfoVo = userInfoMap.get(item.getCreateBy());
                userName = userInfoVo.getUiUsername();
                headImg = userInfoVo.getUiHeadimg();
            } else {
                userName = item.getUserNickname();
                headImg = item.getUserHead();
            }

            return QAVO.builder()
                    .userId(item.getCreateBy())
                    .headImg(headImg)
                    .userName(userName)
                    .time(item.getCreateTime().getTime())
                    .question(item.getContent())
                    .answers(answerMap.get(item.getId())).build();
        }).collect(Collectors.toList());

        return new Page<>(pageable, page.getTotal(), resList);
    }

}