package com.fs.app.controller;


import com.alibaba.fastjson.JSON;
import com.fs.app.annotation.Login;
import com.fs.app.config.ImageStorageConfig;
import com.fs.app.param.FsUserTagUpdateParam;
import com.fs.app.param.FsUserUpdateParam;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.ResponseResult;
import com.fs.common.exception.ServiceException;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyTagUserService;
import com.fs.company.service.ICompanyUserService;
import com.fs.course.param.newfs.FsUserCourseBeMemberImageParam;
import com.fs.course.param.newfs.FsUserCourseBeMemberParam;
import com.fs.course.service.IFsUserCourseService;
import com.fs.course.vo.newfs.FsCourseAnalysisVO;
import com.fs.store.param.h5.CourseAnalysisParam;
import com.fs.store.domain.FsUser;
import com.fs.store.param.h5.FsUserPageListParam;
import com.fs.store.param.h5.TagListParam;
import com.fs.store.param.h5.UserStatisticsCommonParam;
import com.fs.store.service.IFsUserService;
import com.fs.store.vo.h5.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

@Slf4j
@Api(tags = "用户会员相关接口")
@RestController
@RequestMapping("/app/fs/user")
public class FsUserController extends AppBaseController {

    @Autowired
    private IFsUserService fsUserService;

    @Autowired
    private ICompanyUserService companyUserService;

    @Autowired
    private ICompanyTagUserService companyTagUserService;

    @Autowired
    private ImageStorageConfig imageConfig;

    @Autowired
    private IFsUserCourseService fsUserCourseService;

    @Login
    @PostMapping("/pageList")
    @ApiOperation("用户会员分页列表")
    public ResponseResult<PageInfo<FsUserPageListVO>> pageList(@RequestBody FsUserPageListParam param) {
        param.setUserId(Long.parseLong(getUserId()));
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<FsUserPageListVO> list = fsUserService.selectFsUserPageList(param);
        PageInfo<FsUserPageListVO> pageInfo = new PageInfo<>(list);
        return ResponseResult.ok(pageInfo);
    }

    @Login
    @GetMapping("/allCompanyUser")
    @ApiOperation("获取所有公司销售")
    public ResponseResult<List<CompanyUser>> getAllCompanyUser() {
        List<CompanyUser> companyUsers = companyUserService.selectAllCompanyUserAndSelf(Long.parseLong(getUserId()));
        return ResponseResult.ok(companyUsers);
    }

    @Login
    @GetMapping("/totalNumber")
    @ApiOperation("用户会员数量统计")
    public ResponseResult<UserListPageVO> getTotalNumber() {
        UserListPageVO userNumber = fsUserService.getUserNumber(Long.parseLong(getUserId()));
        return ResponseResult.ok(userNumber);
    }

    @Login
    @GetMapping("/details")
    @ApiOperation("用户会员详情")
    public ResponseResult<UserDetailsVO> getUserDetails(@ApiParam(value = "用户id", required = true) @RequestParam Long userId,
                                                        @ApiParam(value = "时间tab，不传表示查询全部，分别是：今天、昨天、前天、近七天", required = true) @RequestParam(required = false) String dateTag) {
        UserDetailsVO userDetails = fsUserService.getUserDetails(Long.parseLong(getUserId()), userId, dateTag);
        return ResponseResult.ok(userDetails);
    }

    @Login
    @GetMapping("/tagList")
    @ApiOperation("用户会员标签列表")
    public ResponseResult<PageInfo<CompanyUserTagListVO>> getTagList(TagListParam param) {
        param.setUserId(Long.parseLong(getUserId()));
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<CompanyUserTagListVO> tagList = companyTagUserService.getTagList(param);
        PageInfo<CompanyUserTagListVO> pageInfo = new PageInfo<>(tagList);
        return ResponseResult.ok(pageInfo);
    }

    @Login
    @PostMapping("/disabled")
    @ApiOperation("批量禁用会员")
    public ResponseResult<Boolean> disabledUser(@ApiParam(value = "联系人id集合", required = true) @RequestBody String[] ids) {
        Boolean r = fsUserService.disabledUser(ids, false);
        return ResponseResult.ok(r);
    }

    @Login
    @PostMapping("/enabled")
    @ApiOperation("批量启用会员")
    public ResponseResult<Boolean> enabledUser(@ApiParam(value = "联系人id集合", required = true) @RequestBody String[] ids) {
        Boolean r = fsUserService.disabledUser(ids, true);
        return ResponseResult.ok(r);
    }

    @Login
    @GetMapping("/firstPage/summaryCount")
    @ApiOperation("首页数据-顶部汇总统计")
    public ResponseResult<FsUserSummaryCountVO> userSummaryCount() {
        long userId = Long.parseLong(getUserId());
        return ResponseResult.ok(fsUserService.userSummaryCount(userId));
    }

    @Login
    @GetMapping("/firstPage/statistics")
    @ApiOperation("首页数据-课程/答题/红包统计")
    public ResponseResult<FsUserStatisticsVO> userStatistics(@ApiParam(value = "开始时间", required = true) @RequestParam String startTime,
                                                             @ApiParam(value = "结束时间", required = true) @RequestParam String endTime) {
        long userId = Long.parseLong(getUserId());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowDate = dateFormat.format(new Date());
        /*---------- 如果传入的日期是今天 ----------*/
        UserStatisticsCommonParam param = new UserStatisticsCommonParam();
        param.setUserId(userId).setStartTime(startTime).setEndTime(endTime);
        FsUserStatisticsVO vo = fsUserService.userStatistics(param);
        if (nowDate.compareTo(startTime) > 0 && nowDate.compareTo(endTime) < 0) {
            String yesterday = LocalDate.now().minusDays(1).toString();
            UserStatisticsCommonParam paramYes = new UserStatisticsCommonParam();
            paramYes.setUserId(userId).setStartTime(yesterday + " 00:00:00").setEndTime(yesterday + " 23:59:59");
            FsUserStatisticsVO fsUserStatisticsVO = fsUserService.userStatistics(paramYes);
            vo.setYesterdayVO(fsUserStatisticsVO);
        }
        return ResponseResult.ok(vo);
    }

    @Login
    @GetMapping("/statistics/details")
    @ApiOperation("数据统计详情-课程/答题/红包统计")
    public ResponseResult<FsUserStatisticsVO> userStatisticsDetails(@ApiParam(value = "营期id") @RequestParam(required = false) String periodId,
                                                                    @ApiParam(value = "视频id") @RequestParam(required = false) String videoId) {
        long userId = Long.parseLong(getUserId());
        long companyId = getCompanyId();
        UserStatisticsCommonParam param = new UserStatisticsCommonParam();
        param.setUserId(userId).setPeriodId(periodId).setVideoId(videoId).setCompanyId(companyId);
        FsUserStatisticsVO fsUserStatisticsVO = fsUserService.userStatisticsDetails(param);
        return ResponseResult.ok(fsUserStatisticsVO);
    }

    @Login
    @GetMapping("/firstPage/userRanking")
    @ApiOperation("首页数据/详情-销售排行榜统计")
    public ResponseResult<List<FsUserRankingVO>> userRanking(
            @ApiParam(value = "开始时间") @RequestParam(required = false) String startTime,
            @ApiParam(value = "结束时间") @RequestParam(required = false) String endTime,
            @ApiParam(value = "营期id") @RequestParam(required = false) String periodId,
            @ApiParam(value = "视频id") @RequestParam(required = false) String videoId,
            @ApiParam(value = "asc-正序，desc-倒序", required = true) @RequestParam String order,
            @ApiParam(value = "类型，1-按完播率，2-按正确率", required = true) @RequestParam Integer type
    ) {
        long userId = Long.parseLong(getUserId());
        return ResponseResult.ok(fsUserService.userRanking(userId, startTime, endTime, periodId, videoId, order, type));
    }

    @Login
    @GetMapping("/firstPage/courseRanking")
    @ApiOperation("首页数据/详情-课程排行榜统计")
    public ResponseResult<List<FsCourseRankingVO>> courseRanking(
            @ApiParam(value = "开始时间") @RequestParam(required = false) String startTime,
            @ApiParam(value = "结束时间") @RequestParam(required = false) String endTime,
            @ApiParam(value = "课程id") @RequestParam(required = false) String courseId,
            @ApiParam(value = "视频id") @RequestParam(required = false) String videoId,
            @ApiParam(value = "asc-正序，desc-倒序", required = true) @RequestParam String order,
            @ApiParam(value = "类型，1-按完播率，2-按正确率", required = true) @RequestParam Integer type
    ) {
        long userId = Long.parseLong(getUserId());
        return ResponseResult.ok(fsUserService.courseRanking(userId, startTime, endTime, courseId, videoId, order, type));
    }

    @Login
    @GetMapping("/firstPage/graphic")
    @ApiOperation("首页数据-转化漏斗图")
    public ResponseResult<List<FsUserGraphicStatisticsVO>> graphicStatistics(@ApiParam(value = "开始时间", required = true) @RequestParam String startTime,
                                                                             @ApiParam(value = "结束时间", required = true) @RequestParam String endTime) {
        long userId = Long.parseLong(getUserId());
        UserStatisticsCommonParam param = new UserStatisticsCommonParam();
        param.setUserId(userId).setStartTime(startTime).setEndTime(endTime);
        List<FsUserGraphicStatisticsVO> list = fsUserService.graphicStatistics(param);
        return ResponseResult.ok(list);
    }

    @Login
    @GetMapping("/graphic/details")
    @ApiOperation("详情-转化漏斗图")
    public ResponseResult<List<FsUserGraphicStatisticsVO>> graphicStatisticsDetails(@ApiParam(value = "营期id") @RequestParam(required = false) String periodId,
                                                                                    @ApiParam(value = "视频id") @RequestParam(required = false) String videoId) {
        long userId = Long.parseLong(getUserId());
        UserStatisticsCommonParam param = new UserStatisticsCommonParam();
        param.setUserId(userId).setPeriodId(periodId).setVideoId(videoId);
        List<FsUserGraphicStatisticsVO> list = fsUserService.graphicStatistics(param);
        return ResponseResult.ok(list);
    }

    @Login
    @ApiOperation("修改用户备注、姓名")
    @PostMapping("/changeUserInfo")
    public ResponseResult<Object> changeUserInfo(@Valid @RequestBody FsUserUpdateParam param) {
        log.debug("修改用户备注、姓名 param:{}", JSON.toJSONString(param));
        FsUser fsUser = fsUserService.selectFsUserById(param.getFsUserId());
        if (Objects.isNull(fsUser)) {
            throw new ServiceException("用户不存在");
        }

        fsUser.setNickname(param.getNickName());
        fsUser.setRemark(param.getRemark());
        fsUserService.updateFsUser(fsUser);
        return ResponseResult.ok();
    }

    @Login
    @ApiOperation("修改用户标签")
    @PostMapping("/changeUserTags")
    public ResponseResult<Object> changeUserTags(@Valid @RequestBody FsUserTagUpdateParam param) {
        companyTagUserService.changeUserTags(param.getFsUserIds(), param.getTagIds());
        return ResponseResult.ok();
    }

    @Login
    @GetMapping("/courseAnalysis")
    @ApiOperation("管理-课程分析-分页列表查询")
    public ResponseResult<PageInfo<FsCourseAnalysisVO>> courseAnalysisList(CourseAnalysisParam param) {
        param.setCompanyId(getCompanyId());
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<FsCourseAnalysisVO> list = fsUserService.courseAnalysis(param);
        PageInfo<FsCourseAnalysisVO> pageInfo = new PageInfo<>(list);
        return ResponseResult.ok(pageInfo);
    }

    @Login
    @GetMapping("/companyUser/details")
    @ApiOperation("管理-群管数据-根据销售id,群管数据统计")
    public ResponseResult<FsUserStatisticsVO> companyUserStatistics(@ApiParam(value = "营期id") @RequestParam(required = false) String periodId,
                                                                    @ApiParam(value = "视频id") @RequestParam(required = false) String videoId,
                                                                    @ApiParam(value = "销售用户id", required = true) @RequestParam String companyUserId) {
        UserStatisticsCommonParam param = new UserStatisticsCommonParam();
        param.setUserId(Long.parseLong(getUserId()))
                .setPeriodId(periodId).setVideoId(videoId)
                .setCompanyId(getCompanyId())
                .setCompanyUserId(companyUserId);
        FsUserStatisticsVO fsUserStatisticsVO = fsUserService.userStatisticsDetails(param);
        return ResponseResult.ok(fsUserStatisticsVO);
    }

    @Login
    @GetMapping("/companyUser/summaryCount")
    @ApiOperation("管理-群管数据-顶部会员统计")
    public ResponseResult<CompanyUserSummaryCountVO> companyUserSummaryCount(@ApiParam(value = "销售用户id", required = true) @RequestParam String companyUserId) {
        long userId = Long.parseLong(getUserId());
        return ResponseResult.ok(fsUserService.companyUserSummaryCount(userId, companyUserId));
    }

    @Login
    @ApiOperation("会员关联绑定销售")
    @PostMapping("/beMember")
    public ResponseResult<Boolean> becomeMember(@Valid @RequestBody FsUserCourseBeMemberParam param) {
        return fsUserService.becomeMember(param);
    }

    @Login
    @PostMapping("/userImage")
    @ApiOperation("生成分享会员海报")
    public R createCourseImage(@RequestBody FsUserCourseBeMemberImageParam param) {
        try {
            //获取用户头像
//            FsUser fsUser = fsUserService.selectFsUserById(param.getUserId());
//            String url = "";
//            if(fsUser != null) {
//                url = fsUser.getAvatar();
//            }
            String path = imageConfig.getServerPath();
            InputStream inputStream = fsUserCourseService.handleImage("", path);

            // todo 为了给客户演示，生成会员的封面暂时随便找的课程封面，如果后期要修改的话就调整
            String backgroundImagePath = "https://cos.his.cdwjyyh.com/fs/20240914/250af4b0041b46d1a36a34af1d5ccd54.jpg";
            String base64Image = fsUserCourseService.createUserImageQR(param.getRealLink(), backgroundImagePath, inputStream, "png", param.getCompanyUserId());
            // 返回Base64编码的图片字符串
            Map<String, Object> map = new HashMap<>();
            map.put("url", base64Image);
            return R.ok().put("posterImage", map);
        } catch (Exception e) {
            log.error("生成海报失败，param：{}", param);
            return R.error("生成海报失败！");
        }
    }

}
