package com.xxfc.platform.activity.rest;

import cn.hutool.core.bean.BeanUtil;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.admin.feign.rest.UserRestInterface;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreClientToken;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.util.XxBizAssert;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.activity.biz.*;
import com.xxfc.platform.activity.dto.ItemAddDTO;
import com.xxfc.platform.activity.entity.*;
import com.xxfc.platform.activity.vo.popularize.FinishUserVO;
import com.xxfc.platform.activity.vo.popularize.ItemVO;
import com.xxfc.platform.activity.vo.popularize.PopularizeVO;
import com.xxfc.platform.activity.vo.popularize.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.WeekendSqls;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_FALSE;
import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_TRUE;

@RestController
@RequestMapping("activityPopularize")
@Api(value = "推广活动", tags = "推广活动")
@Slf4j
public class ActivityPopularizeController extends BaseController<ActivityPopularizeBiz,ActivityPopularize> implements UserRestInterface {

    @Autowired
    ActivityPopularizeBiz popularizeBiz;

    @Autowired
    ActivityPopularizeItemBiz popularizeItemBiz;

    @Autowired
    ActivityPopularizeUserBiz popularizeUserBiz;

    @Autowired
    ActivityPopularizeLogBiz popularizeLogBiz;

    @Autowired
    ActivityPopularizeRelationBiz popularizeRelationBiz;

    @Autowired
    UserFeign userFeign;

    @Override
    public UserFeign getUserFeign() {
        return userFeign;
    }

    @RequestMapping(value = "/app/unauth/popularize-list", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询活动")
    @IgnoreClientToken
    @IgnoreUserToken
    public ObjectRestResponse<PopularizeVO> popularizeList(String code, Integer type) {
        AppUserDTO appUserDTO = getAppUser();
        List<PopularizeVO> popularizeVOs = popularizeBiz.selectList(new ActivityPopularize(){{
            setCode(code);
            setType(type);
        }}).stream().map(v -> {
            PopularizeVO vo = BeanUtil.toBean(v, PopularizeVO.class);
            ActivityPopularizeUser[] apu = new ActivityPopularizeUser[1];
            Map<Integer, ActivityPopularizeLog>[] aplMap = new HashMap[1];
            if(null != appUserDTO) {

                //获取用户和活动的关联信息
                apu[0] = popularizeUserBiz.selectOne(new ActivityPopularizeUser(){{
                    setPopularizeId(v.getId());
                    setUserId(appUserDTO.getUserid());
                }});

                //获取日志
                aplMap[0] = popularizeLogBiz.selectList(new ActivityPopularizeLog(){{
                    setPopularizeId(v.getId());
                    setUserId(appUserDTO.getUserid());
                }}).parallelStream().collect(Collectors.toMap(ActivityPopularizeLog::getItemId, l -> l));

                //设置用户列表
                vo.setUserVOs(popularizeRelationBiz.selectList(new ActivityPopularizeRelation(){{
                    setMajorUserId(appUserDTO.getUserid());
                    setPopularizeId(v.getId());
                }}).stream().map(pr -> {
                    UserVO userVO = BeanUtil.toBean(userFeign.userDetailById(pr.getMinorUserId()).getData(), UserVO.class);
                    return userVO;
                }).collect(Collectors.toList()));
                vo.setActivityPopularizeUser(apu[0]);
            }

            //设置任务项
            vo.setItems(popularizeItemBiz.selectByExample(
                    new Example.Builder(ActivityPopularizeItem.class)
                    .where(WeekendSqls.<ActivityPopularizeItem>custom()
                            .andEqualTo(ActivityPopularizeItem::getPopularizeId, v.getId())).orderByAsc("sort").build())
                    .stream().map(item -> {
                        ItemVO itemVO = BeanUtil.toBean(item, ItemVO.class);
                        itemVO.setStatus(SYS_FALSE);

                        if(null != apu[0]) {
                            ActivityPopularizeLog log = aplMap[0].get(item.getId());
                            if(null != log && SYS_TRUE.equals(log.getStatus())) {
                                itemVO.setStatus(SYS_TRUE);
                            }
                        }
                        if (null != appUserDTO) {
                            ActivityPopularizeLog activityPopularizeLog = popularizeLogBiz.selectByUserIdAndPopularIdAndItemId(new ActivityPopularizeLog(){{
                                setUserId(appUserDTO.getUserid());
                                setPopularizeId(v.getId());
                                setItemId(item.getId());
                            }});
                            if (activityPopularizeLog != null) {
                                itemVO.setStatus(activityPopularizeLog.getStatus());
                            }
                        }
                        return itemVO;
                    }).collect(Collectors.toList()));
            return vo;
        }).collect(Collectors.toList());

        if(popularizeVOs.size() > 0) {
            return ObjectRestResponse.succ(popularizeVOs.get(0));
        }else {
            throw new BaseException(ResultCode.NOTEXIST_CODE);
        }
    }

    @RequestMapping(value = "/item-add", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "完成任务")
    @IgnoreClientToken
    public ObjectRestResponse itemAdd(@RequestBody ItemAddDTO itemAddDTO) {
        checkAppUser();
        ActivityPopularize ap = popularizeBiz.selectById(itemAddDTO.getPopularizeId());
        XxBizAssert.notNull(ap);
        ActivityPopularizeItem item = popularizeItemBiz.selectById(itemAddDTO.getItemId());
        XxBizAssert.notNull(item);
        ActivityPopularizeUser activityPopularizeUser = popularizeUserBiz.selectOne(new ActivityPopularizeUser(){{
            setUserId(getAppUser().getUserid());
            setPopularizeId(itemAddDTO.getPopularizeId());
        }});

        //添加用户活动关系
        if(null == activityPopularizeUser) {
            activityPopularizeUser = popularizeUserBiz.insertSelectiveReT(new ActivityPopularizeUser(){{
                setPopularizeId(itemAddDTO.getPopularizeId());
                setUserId(getAppUser().getUserid());
                setEndProgress(new BigDecimal(ap.getProgress()));
            }});
        }

        //判断是否已经添加过
        ActivityPopularizeLog itemLog = BeanUtil.toBean(itemAddDTO, ActivityPopularizeLog.class);
        itemLog.setUserId(getAppUser().getUserid());
        ActivityPopularizeLog activityPopularizeLog = popularizeLogBiz.selectOne(itemLog);
        if(activityPopularizeLog != null) {
            return ObjectRestResponse.createFailedResult(1023, "参加成功，请勿重复参加！");
        }

        //添加活动日志
        itemLog.setStatus(SYS_TRUE);
        popularizeLogBiz.insertSelective(itemLog);

        //更新用户活动进度
            //查询 所有log
        List<ActivityPopularizeLog> activityPopularizeLogs = popularizeLogBiz.selectList(new ActivityPopularizeLog(){{
            setUserId(getAppUser().getUserid());
            setPopularizeId(ap.getId());
            setStatus(SYS_TRUE);
        }});

        Integer progress = 0;
        String itemsContent;
        for(ActivityPopularizeLog al : activityPopularizeLogs){
            ActivityPopularizeItem item1 = popularizeItemBiz.selectById(al.getItemId());
            progress += item1.getProgress();
        }
        activityPopularizeUser.setCurrentProgress(new BigDecimal(progress));
        popularizeUserBiz.updateSelectiveById(activityPopularizeUser);
        return ObjectRestResponse.succ();
    }

    @RequestMapping(value = "/app/unauth/relation-list", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询该活动参与成功的人")
    @IgnoreClientToken
    @IgnoreUserToken
    public ObjectRestResponse<List<FinishUserVO>> relationList(String code) {

        ActivityPopularize activityPopularize = popularizeBiz.selectOne(new ActivityPopularize(){{
            setCode(code);
        }});

        PageDataVO<ActivityPopularizeUser> pageDataVO = PageDataVO.pageInfo(1, 20, () -> popularizeUserBiz.selectByExample(new Example.Builder(ActivityPopularizeUser.class)
                .where(WeekendSqls.<ActivityPopularizeUser>custom()
                        .andEqualTo(ActivityPopularizeUser::getPopularizeId, activityPopularize.getId())
                        .andEqualTo(ActivityPopularizeUser::getStatus, SYS_TRUE))
                .orderByDesc("updTime").build()));

        return ObjectRestResponse.succ(pageDataVO.getData().stream().map(value -> {
            AppUserDTO appUserDTO = userFeign.userDetailById(value.getUserId()).getData();
            FinishUserVO finishUserVO = BeanUtil.toBean(appUserDTO, FinishUserVO.class);
            log.error(StringUtils.overlay(appUserDTO.getUsername(), "*****", 3, 8));
            finishUserVO.setPhone(StringUtils.overlay(appUserDTO.getUsername(), "*****", 3, 8));
            return finishUserVO;
        }).collect(Collectors.toList()));
    }
}