package jnpf.memberLog.controller;

import com.github.pagehelper.PageInfo;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.vo.PageListVO;
import jnpf.config.ConfigValueUtil;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.exception.LoginException;
import jnpf.exception.QueryException;
import jnpf.memberLog.service.WorkLogService;
import jnpf.model.memberLog.dto.*;
import jnpf.model.memberLog.vo.*;
import jnpf.util.*;
import jnpf.util.data.DataSourceContextHolder;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.rmi.server.ExportException;
import java.util.List;

/**
 * 工作日志控制器
 *
 * @author yanwenfu
 * @create 2023-08-08
 */
@RestController
@RequestMapping(value = "/log")
public class WorkLogController {

    @Resource
    private WorkLogService workLogService;

    @Resource
    private ExportUtil exportUtil;

    @Autowired
    private ConfigValueUtil configValueUtil;

    /**
     * 评论列表
     * @param logId 日志id
     * @param queryDto 查询条件
     * @return jnpf.base.ActionResult<jnpf.base.vo.PageListVO<jnpf.model.memberLog.vo.LogCommentVo>>
     */
    @GetMapping(value = "/comment/list/{logId}")
    public ActionResult<PageListVO<LogCommentVo>> getCommentList(@PathVariable(value = "logId") String logId, @Valid CommentQueryDto queryDto) {

        PageInfo<LogCommentVo> page = workLogService.getCommentList(logId, queryDto);
        CommentPaginationVo pagination = new CommentPaginationVo(FtbUtil.getPagination(page));
        pagination.setCommentTotalNum(workLogService.getCommentTotalNum(logId));
        return ActionResult.page(page.getList(), pagination);
    }

    /**
     * 日志详情 - 评论/回复
     * @param logId 日志id
     * @param addReplyDto 新增评论dto
     * @return java.lang.Object
     */
    @PostMapping(value = "/comment/reply/{logId}")
    public ActionResult<LogCommentVo> addCommentReply(@PathVariable(value = "logId") String logId, @RequestBody @Valid AddReplyDto addReplyDto) {

        LogCommentVo comment = workLogService.addCommentReply(logId, addReplyDto);
        return ActionResult.success(comment);
    }

    /**
     * 删除评论/回复
     * @param commentId 评论id
     * @return java.lang.Object
     */
    @DeleteMapping(value = "/comment/reply/{commentId}")
    public Object deleteCommentReply(@PathVariable(value = "commentId") String commentId) {

        workLogService.deleteCommentReply(commentId);
        return ActionResult.success();
    }

    /**
     * 新增/取消点赞
     * @param logId 日志id
     * @return java.lang.Object
     */
    @PostMapping(value = "/like/{logId}")
    public Object addOrCancelLike(@PathVariable(value = "logId") String logId) {

        workLogService.addOrCancelLike(logId);
        return ActionResult.success();
    }

    /**
     * 新增转发信息
     * @param logId 日志id
     * @param list 转发信息
     * @return java.lang.Object
     */
    @PostMapping(value = "/forward/{logId}")
    public Object addForwardRecord(@PathVariable(value = "logId") String logId, @RequestBody @Valid List<AddForwardDto> list) {

        workLogService.addForwardRecord(logId, list);
        return ActionResult.success();
    }

    /**
     * 日志统计
     * @param queryDto 查询条件
     * @return jnpf.base.ActionResult<jnpf.model.memberLog.vo.LogStatVo>
     */
    @GetMapping(value = "/dataStat")
    public ActionResult<LogStatVo> getLogDataStat(@Valid StatQueryDto queryDto) throws Exception {

        LogStatVo logStat = workLogService.getLogDataStat(queryDto);
        return ActionResult.success(logStat);
    }

    /**
     * 日志统计(按人分页)
     * @param queryDto 查询条件
     * @return jnpf.base.ActionResult<jnpf.model.memberLog.vo.LogStatVo>
     */
    @GetMapping(value = "/dataStat/page")
    public ActionResult<LogStatVo> getLogDataStatPage(@Valid StatQueryDto queryDto) throws Exception {

        LogStatVo logStat = workLogService.getLogDataStatPage(queryDto);
        return ActionResult.success(logStat);
    }

    /**
     * 日志统计 - 导出
     * @param queryDto 查询条件
     * @param response HttpServletResponse
     */
    @NoDataSourceBind
    @GetMapping(value = "/dataStat/export")
    public void getLogDataStatExport(@Valid StatQueryDto queryDto, HttpServletResponse response) throws Exception {
        if(StringUtil.isNotEmpty(queryDto.getTenantId())){
            switchTenant(queryDto.getTenantId());
        }
        Workbook workbook = workLogService.getLogDataStatWorkbook(queryDto);
        if (null != workbook) {
            exportUtil.exportTemplateExcel(workbook, response, ConstantUtil.LOG_DATA_FORM);
        } else {
            throw new ExportException("导出" + ConstantUtil.LOG_DATA_FORM + "失败");
        }
    }

    /**
     * 切换租户
     * @param tenantId 租户id
     */
    public void switchTenant(String tenantId){
        // 判断是否为多租户
        if (configValueUtil.isMultiTenancy()) {
            // 判断是不是从外面直接请求
            if (StringUtil.isNotEmpty(tenantId)) {
                //切换成租户库
                try {
                    TenantDataSourceUtil.switchTenant(tenantId);
                } catch (LoginException e) {
                    throw new RuntimeException("切换租户失败");
                }
            } else {
                UserInfo userInfo = UserProvider.getUser();
                Assert.notNull(userInfo.getUserId(), "缺少租户信息");
                DataSourceContextHolder.setDatasource(userInfo.getTenantId(), userInfo.getTenantDbConnectionString(), userInfo.isAssignDataSource());
            }
        }
    }
    /**
     * 日志列表 - app
     * @param queryDto 查询条件
     * @return jnpf.base.ActionResult<jnpf.base.vo.PageListVO<jnpf.model.memberLog.vo.MiniLogVo>>
     */
    @GetMapping(value = "/list")
    public ActionResult<PageListVO<MiniLogVo>> getAppLogPage(@Valid LogQueryDto queryDto) {

        PageInfo<MiniLogVo> page = workLogService.getAppLogPage(queryDto);
        return ActionResult.page(page.getList(), FtbUtil.getPagination(page));
    }

    /**
     * 日志列表 - 条件筛选 - app
     * @param queryDto 查询条件
     * @return jnpf.base.ActionResult<jnpf.base.vo.PageListVO<jnpf.model.memberLog.vo.MiniLogVo>>
     */
    @GetMapping(value = "/list/byCondition")
    public ActionResult<PageListVO<MiniLogVo>> getAppLogPageByCondition(ConditionLogQueryDto queryDto) throws QueryException {

        PageInfo<MiniLogVo> page = workLogService.getAppLogPageByCondition(queryDto);
        return ActionResult.page(page.getList(), FtbUtil.getPagination(page));
    }

    /**
     * 日志列表 - 指定人员查询 - app
     * @param queryDto 查询条件
     * @return jnpf.base.ActionResult<jnpf.base.vo.PageListVO<jnpf.model.memberLog.vo.MiniLogVo>>
     */
    @GetMapping(value = "/list/byUser")
    public ActionResult<PageListVO<MiniLogVo>> getAppLogPageByUser(ConditionLogQueryDto queryDto) throws QueryException {

        PageInfo<MiniLogVo> page = workLogService.getAppLogPageByUser(queryDto);
        return ActionResult.page(page.getList(), FtbUtil.getPagination(page));
    }

    /**
     * 日志列表 - web
     * @param queryDto 查询条件
     * @return jnpf.base.ActionResult<jnpf.base.vo.PageListVO<jnpf.model.memberLog.vo.MiniLogVo>>
     */
    @GetMapping(value = "/list/webPage")
    public ActionResult<PageListVO<WebLogVo>> getWebLogPage(@Valid LogWebQueryDto queryDto) throws QueryException {

        PageInfo<WebLogVo> page = workLogService.getWebLogPage(queryDto);
        return ActionResult.page(page.getList(), FtbUtil.getPagination(page));
    }
}
