package com.willalp.web.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.willalp.clockingin.domain.BizLeave;
import com.willalp.clockingin.service.IBizLeaveService;
import com.willalp.common.core.controller.BaseController;
import com.willalp.common.core.domain.AjaxResult;
import com.willalp.common.core.page.TableDataInfo;
import com.willalp.common.utils.DateUtils;
import com.willalp.flow.domain.BizLeaveImg;
import com.willalp.flow.domain.HsFlowTask;
import com.willalp.flow.domain.req.FLowReq;
import com.willalp.flow.service.HsFlowEngineService;
import com.willalp.flow.service.IBizLeaveImgService;
import com.willalp.msg.domain.HsAppUserMsg;
import com.willalp.msg.service.IHsAppUserMsgService;
import com.willalp.wx.domain.WxMsgTemplateApproval;
import com.willalp.wx.enums.WxTemplateKeyEnum;
import com.willalp.wx.service.WxMsgService;
import com.willalp.wx.utils.WxUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Api("APP流控制器")
@RestController
@RequestMapping("/app")
public class AppFLowController extends BaseController {
    @Resource
    private IBizLeaveService bizLeaveService;

    @Resource
    private HsFlowEngineService flowEngineService;

    @Resource
    private IBizLeaveImgService leaveImgService;

    @Resource
    private WxMsgService wxMsgService;

    @Resource
    private WxUtils wxUtils;

    @Resource
    private IHsAppUserMsgService userMsgService;

    /**
     * 请假提交
     *
     * @param leave
     * @return
     */
    @ApiOperation("提交请假")
    @PostMapping("/submitApply/leave")
    public AjaxResult submitLeave(@RequestBody BizLeave leave) {
        String idStr = IdWorker.getIdStr();
        String taskId = IdWorker.getIdStr();
        leave.setId(Long.parseLong(idStr));
        leave.setTaskId(taskId);
        leave.setApplyTime(new Date());
        if (leave.getImgUrls().size() != 0) {
            leave.getImgUrls().forEach(i -> i.setBizLeaveId(idStr));
            leaveImgService.saveBatch(leave.getImgUrls());
        }
        bizLeaveService.insertBizLeave(leave);
        Map<String, String> map = new HashMap<>();
        if (null != leave.getCandidate()) {
            map.put("candidate", leave.getCandidate());
            map.put("user", leave.getApplyUserId());
        }
        flowEngineService.submitATask(new HsFlowTask(taskId, idStr, "1580107848471093250"), map);
        //生成审批结果消息列表
        HsAppUserMsg appUserMsg = new HsAppUserMsg();
        StringBuffer content = new StringBuffer();
        content.append("<p>标题：").append(leave.getTitle()).append("</p>")
                .append("<p>申请人：").append(leave.getApplyUserName()).append("</p>")
                .append("<p>开始时间：").append(DateUtils.parseDateToStr("yyyy-MM-dd", leave.getLeaveStartTime())).append("</p>")
                .append("<p>结束时间：").append(DateUtils.parseDateToStr("yyyy-MM-dd", leave.getLeaveEndTime())).append("</p>");
        appUserMsg.setMsgContent(content.toString());
        appUserMsg.setMsgIsRead("0");
        appUserMsg.setUserCode(leave.getCandidate());
        appUserMsg.setMsgType("1");
        appUserMsg.setRemark(taskId);
        appUserMsg.setCreateTime(new Date());
        userMsgService.save(appUserMsg);
        WxMsgTemplateApproval wxMsgTemplateApproval = new WxMsgTemplateApproval();
        wxMsgTemplateApproval.setThing5(wxUtils.getFormat(leave.getTitle()));
        wxMsgTemplateApproval.setThing11(wxUtils.getFormat(leave.getApplyUserName()));
        wxMsgTemplateApproval.setTime12(wxUtils.getFormat(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", leave.getApplyTime())));
        wxMsgService.sendQRCodeMsg(leave.getCandidate(), wxMsgTemplateApproval, WxTemplateKeyEnum.APPROVAL_WAIT, true);
        return AjaxResult.success();
    }

    /**
     * 下一步
     *
     * @param fr
     * @return
     */
    @ApiOperation("下一步")
    @PostMapping("/nextStep")
    public AjaxResult nextStep(@RequestBody FLowReq fr) {
        return AjaxResult.success(
                flowEngineService.nextStep(fr));
    }

    /**
     * 获取待办
     *
     * @param taskId
     * @param request
     * @return
     */
    @ApiOperation("获取指定待办任务")
    @RequestMapping("/gtdToId")
    public AjaxResult getToDoByTaskId(String taskId, HttpServletRequest request) {
        return AjaxResult.success(
                flowEngineService.getToDoByTaskId(taskId));
    }

    /**
     * 获取
     *
     * @param taskId
     * @param request
     * @return
     */
    @ApiOperation("获取指定待办任务")
    @RequestMapping("/gBlToId")
    public AjaxResult getLeaveByTaskId(String taskId, HttpServletRequest request) {
        return AjaxResult.success(
                bizLeaveService.getBaseMapper().selectOne(new QueryWrapper<BizLeave>()
                        .eq("task_id", taskId)));
    }

    /**
     * 获取待办
     *
     * @param request
     * @return
     */
    @ApiOperation("获取待办")
    @RequestMapping("/gtd")
    public TableDataInfo getToDo(HttpServletRequest request) {
        return getDataTable(
                flowEngineService.getToDo(request.getHeader("UserName")));
    }

    /**
     * 获取已办
     *
     * @param request
     * @return
     */
    @ApiOperation("获取已办")
    @RequestMapping("/gd")
    public TableDataInfo getDone(HttpServletRequest request) {
        return getDataTable(
                flowEngineService.getDone(request.getHeader("UserName")));
    }

    /**
     * 查询请假记录
     */
    @GetMapping("/leaveList")
    public TableDataInfo list(BizLeave bizLeave) {
        startPage();
        List<BizLeave> list = bizLeaveService.selectPersonnelList(bizLeave);
        List<BizLeave> bizLeaves = new ArrayList<>();
        list.forEach(i -> {
            List<BizLeaveImg> leaveImgs = leaveImgService.getBaseMapper()
                    .selectList(new QueryWrapper<BizLeaveImg>()
                            .eq("biz_leave_id", i.getId()));
            i.imgUrls = leaveImgs;
            bizLeaves.add(i);
        });
        return getDataTable(bizLeaves);
    }


    /**
     * 获取当前任务记录
     *
     * @param taskId
     * @param request
     * @return
     */
    @ApiOperation("获取当前任务进度")
    @RequestMapping("/ctr")
    public AjaxResult currentTaskRecords(String taskId, HttpServletRequest request) {
        return AjaxResult.success(
                flowEngineService.currentTaskRecords(taskId));
    }

    /**
     * 获取当前任务记录
     *
     * @param taskId
     * @return
     */
    @ApiOperation("获取当前任务进度")
    @RequestMapping("/revoke")
    public AjaxResult revoke(String taskId) {
        return toAjax(
                flowEngineService.revoke(taskId));
    }
}
