package com.yonge.cooleshow.tenant.controller;

import com.microsvc.toolkit.common.response.paging.QueryInfo;
import com.microsvc.toolkit.common.webportal.exception.BizException;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.queryInfo.SysMusicCompareRecordQueryInfo;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.wrapper.OssFileWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.PaymentDivMemberRecordWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.TenantPersonStatWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.teacher.TeacherWrapper;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.toolset.base.page.PageInfo;
import com.yonge.toolset.mybatis.support.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Api(tags = "首页统计")
@RequestMapping("${app-config.url.tenant:}/index")
@RestController
public class IndexController extends BaseController {

    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private SysMusicCompareRecordService sysMusicCompareRecordService;
    @Autowired
    private TenantPersonStatService tenantPersonStatService;
    @Autowired
    private PaymentDivMemberRecordService paymentDivMemberRecordService;
    @Autowired
    private UserOrderService userOrderService;
    @Autowired
    private OssFileService ossFileService;


    @ApiOperation("学员训练数据统计列表")
    @PostMapping("queryStudentTrainData")
    public HttpResponseResult<PageInfo<SysMusicCompareRecordQueryInfo.WechatCompareRecordPageDto>> queryStudentTrainData
            (@RequestBody SysMusicCompareRecordQueryInfo.WechatCompareRecordQueryInfo queryInfo){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("获取用户信息失败");
        }
        if(StringUtils.isEmpty(queryInfo.getStartTime())){
            throw new BizException("请选择筛选时间");
        }
        queryInfo.setTenantId(sysUser.getTenantId());
        return succeed(sysMusicCompareRecordService.weChatStudentTrainData(queryInfo));
    }

    @ApiOperation("导出学员训练数据统计列表")
    @PostMapping("exportStudentTrainData")
    public HttpResponseResult<OssFileWrapper.ExportFile> exportStudentTrainData
            (@RequestBody SysMusicCompareRecordQueryInfo.WechatCompareRecordQueryInfo queryInfo){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("获取用户信息失败");
        }
        if(StringUtils.isEmpty(queryInfo.getStartTime())){
            throw new BizException("请选择筛选时间");
        }
        queryInfo.setTenantId(sysUser.getTenantId());
        List<SysMusicCompareRecordQueryInfo.WechatCompareRecordPageDto> rows = sysMusicCompareRecordService.weChatStudentTrainData(queryInfo).getRows();
        if (rows.isEmpty()) {
            throw new BizException("没有可导出数据");
        }

        List<SysMusicCompareRecordQueryInfo.WechatCompareRecordExportDto> templates = rows.stream().map(next -> {
            SysMusicCompareRecordQueryInfo.WechatCompareRecordExportDto template = new SysMusicCompareRecordQueryInfo.WechatCompareRecordExportDto();
            template.setUsername(next.getUsername());
            template.setSubjectName(next.getSubjectName());
            template.setAvgTrainTimes(next.getAvgTrainTimes());
            template.setTrainTimes(next.getTrainTimes());
            template.setTrainDays(next.getTrainDays());
            return template;
        }).collect(Collectors.toList());

        String format = new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
        OssFileWrapper.ExportFile exportFile = ossFileService.uploadFile(templates,
                SysMusicCompareRecordQueryInfo.WechatCompareRecordExportDto.class, format, "练习统计列表");
        return succeed(exportFile);
    }


    @ApiOperation("首页学员训练数据统计列表、汇总")
    @PostMapping("studentTrainData")
    public HttpResponseResult<SysMusicCompareRecordQueryInfo.WechatCompareRecordDto> studentTrainData
            (@RequestBody SysMusicCompareRecordQueryInfo.WechatCompareRecordQueryInfo queryInfo){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("获取用户信息失败");
        }
        if(StringUtils.isEmpty(queryInfo.getStartTime())){
            throw new BizException("请选择筛选时间");
        }
        queryInfo.setTenantId(sysUser.getTenantId());
        queryInfo.setRows(10);
        SysMusicCompareRecordQueryInfo.WechatCompareRecordDto result = new SysMusicCompareRecordQueryInfo.WechatCompareRecordDto();
        SysMusicCompareRecordQueryInfo.WechatCompareRecordSumDto sumDto = sysMusicCompareRecordService.getDao().wechatCompareRecordSum(queryInfo);
        if(Objects.nonNull(sumDto)){
            if(sumDto.getStudentNum() > 0){
                if(sumDto.getTrainDays() > 0){
                    sumDto.setAvgTrainDays(sumDto.getTrainDays() / sumDto.getStudentNum());
                }
                if(sumDto.getTrainTimes() > 0){
                    sumDto.setAvgTrainTimes(sumDto.getTrainTimes() / sumDto.getStudentNum());
                }
            }
        }
        result.setSumDto(sumDto);
        result.setPage(sysMusicCompareRecordService.weChatStudentTrainData(queryInfo).getRows());
        return succeed(result);
    }

    @ApiOperation("机构人数统计列表")
    @PostMapping("tenantPersonStatSum")
    public HttpResponseResult<TenantPersonStatWrapper.TenantPersonStatSum> tenantPersonStatSum
            (@RequestBody TenantPersonStatWrapper.TenantPersonStatQuery query){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("获取用户信息失败");
        }
        query.setTenantId(sysUser.getTenantId());
        return succeed(tenantPersonStatService.indexSum(query));
    }

    @ApiOperation("收入、支出汇总")
    @PostMapping("incomeSummary")
    public HttpResponseResult<PaymentDivMemberRecordWrapper.IndexIncomeSummaryDto>
    incomeSummary(@RequestBody PaymentDivMemberRecordWrapper.IndexIncomeQuery query){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("获取用户信息失败");
        }
        query.setTenantId(sysUser.getTenantId());
        return succeed(paymentDivMemberRecordService.incomeSummary(query));
    }

    @ApiOperation("收入明细列表")
    @PostMapping("queryIncome")
    public HttpResponseResult<PageInfo<PaymentDivMemberRecordWrapper.IndexIncomeQueryDto>>
        queryIncome(@RequestBody PaymentDivMemberRecordWrapper.IndexIncomeQuery query){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("获取用户信息失败");
        }
        query.setTenantId(sysUser.getTenantId());
        return succeed(PageUtil.pageInfo(paymentDivMemberRecordService.queryIncome(QueryInfo.getPage(query), query)));
    }

    @ApiOperation("导出收入明细列表")
    @PostMapping("exportIncome")
    public HttpResponseResult<OssFileWrapper.ExportFile>
    exportIncome(@RequestBody PaymentDivMemberRecordWrapper.IndexIncomeQuery query){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("获取用户信息失败");
        }
        query.setTenantId(sysUser.getTenantId());
        List<PaymentDivMemberRecordWrapper.IndexIncomeQueryDto> rows = paymentDivMemberRecordService.queryIncome(QueryInfo.getPage(query), query).getRecords();
        if (rows.isEmpty()) {
            throw new BizException("没有可导出数据");
        }

        List<PaymentDivMemberRecordWrapper.IndexIncomeExportDto> templates = rows.stream().map(next -> {
            PaymentDivMemberRecordWrapper.IndexIncomeExportDto template = new PaymentDivMemberRecordWrapper.IndexIncomeExportDto();
            template.setName(next.getName());
            template.setPhone(next.getPhone());
            template.setAmount(next.getAmount());
            template.setPayTime(next.getPayTime());
            template.setOrderType(next.getOrderType().getName());
            return template;
        }).collect(Collectors.toList());

        String format = new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
        OssFileWrapper.ExportFile exportFile = ossFileService.uploadFile(templates,
                TeacherWrapper.ExportTeacherTemplate.class, format, "练习统计列表");
        return succeed(exportFile);
    }

    @ApiOperation("收入订单详情")
    @PostMapping("getIncomeOrderDetail")
    public HttpResponseResult<PaymentDivMemberRecordWrapper.OrderDetailDto> getIncomeOrderDetail(String orderNo){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("获取用户信息失败");
        }
        return succeed(paymentDivMemberRecordService.getIncomeOrderDetail(orderNo,sysUser.getTenantId()));
    }

    @ApiOperation("支出明细列表")
    @PostMapping("queryExpend")
    public HttpResponseResult<PageInfo<PaymentDivMemberRecordWrapper.IndexIncomeQueryDto>>
    queryExpend(@RequestBody PaymentDivMemberRecordWrapper.IndexIncomeQuery query){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("获取用户信息失败");
        }
        query.setTenantId(sysUser.getTenantId());
        return succeed(PageUtil.pageInfo(userOrderService.queryExpend(QueryInfo.getPage(query), query)));
    }

    @ApiOperation("支出订单详情")
    @PostMapping("getExpendOrderDetail")
    public HttpResponseResult<PaymentDivMemberRecordWrapper.OrderDetailDto> getExpendOrderDetail(String orderNo){
        return succeed(userOrderService.getExpendOrderDetail(orderNo));
    }
}
