package org.enfi.modules.visitor.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.cache.IAccessTokenCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.enfi.common.api.TemplateMsgApi;
import org.enfi.common.api.vo.Result;
import org.enfi.common.aspect.annotation.AutoLog;
import org.enfi.common.aspect.annotation.PrintLnTime;
import org.enfi.common.exception.EnFiBootException;
import org.enfi.common.util.QRCodeUtil;
import org.enfi.config.WXConfig;
import org.enfi.modules.visitor.entity.ApplyFor;
import org.enfi.modules.visitor.entity.EnFiPage;
import org.enfi.modules.visitor.service.IApplyForService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.HashMap;

/**
 * @Description:
 * @ClassName: VisitorAuditController
 * @Author: wanghao
 * @date: 2021.11.13 12:45
 * @version: 1.0
 */
@Slf4j
@Api(tags = "访客审核")
@ApiSupport(order = 2, author = "WangHao")
@RestController
@RequestMapping("/visitorAudit")
public class VisitorAuditController {
    @Autowired //申请邀请来访记录
    private IApplyForService iApplyForService;

    @AutoLog("获取邀请来访记录")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "获取邀请来访记录", notes = "获取邀请来访记录")
    @GetMapping("getApplyForList")
    @PrintLnTime
    public Result<Page<ApplyFor>> getApplyForList(
            @ApiParam(name = "status", value = "审核状态 1未审核 2审核通过 3审核拒绝", required = true) @RequestParam Integer status,
            @ApiParam(name = "name", value = "姓名") @RequestParam(required = false) String name,
            @ApiParam(name = "deptName", value = "被访部门名称") @RequestParam(required = false) String deptName,
            @ApiParam(name = "date", value = "日期") @RequestParam(required = false) String date,
            @ApiParam(name = "pageSize", value = "每页条数", required = true) @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam(name = "pageNo", value = "页数", required = true) @RequestParam(defaultValue = "1") Integer pageNo) {

        LambdaQueryWrapper<ApplyFor> applyForLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (status == 1) {
            applyForLambdaQueryWrapper.eq(ApplyFor::getStatus, status);
        } else {
            if (!Arrays.asList(2, 3).contains(status)) {
                throw new EnFiBootException("审核状态不合法");
            }
            applyForLambdaQueryWrapper.ne(ApplyFor::getStatus, 1);
        }
        if (!StringUtils.isEmpty(name)) {
            applyForLambdaQueryWrapper.like(ApplyFor::getApplicantName, name);
        }
        if (!StringUtils.isEmpty(deptName)) {
            applyForLambdaQueryWrapper.like(ApplyFor::getInviterDeptName, deptName);
        }
        if (!StringUtils.isEmpty(date)) {
            applyForLambdaQueryWrapper.between(ApplyFor::getBeginTime, date, date + " 23:59:59");
        }
        applyForLambdaQueryWrapper.orderByDesc(ApplyFor::getCreateTime);
        EnFiPage<ApplyFor> page = iApplyForService.page(new EnFiPage<>(pageNo, pageSize), applyForLambdaQueryWrapper);
        page.getRecords().forEach(applyFor -> {
            String qRCode = QRCodeUtil.crateQRCode(JSONObject.toJSONString(applyFor), 400, 400);
            applyFor.setSuiShenCode(qRCode);
        });
        page.setParams(new HashMap<String, Object>() {{
            put("auditCount", iApplyForService.count(new LambdaQueryWrapper<ApplyFor>().ne(ApplyFor::getStatus, 1)));
            put("noAuditCount", iApplyForService.count(new LambdaQueryWrapper<ApplyFor>().eq(ApplyFor::getStatus, 1)));
        }});
        return Result.OK(page);
    }

    @AutoLog("审核来访记录")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "审核来访记录", notes = "审核来访记录")
    @GetMapping("auditApplyFor")
    @PrintLnTime
    public Result<?> auditApplyFor(@ApiParam(name = "id", value = "id", required = true) @RequestParam String id,
                                   @ApiParam(name = "status", value = "审核状态 2审核通过 3审核拒绝", required = true) @RequestParam Integer status,
                                   @ApiParam(name = "refusalCause", value = "拒绝原因") @RequestParam(required = false) String refusalCause) {
        if (!Arrays.asList(2, 3).contains(status)) {
            throw new EnFiBootException("审核状态不合法");
        }
        ApplyFor byId = iApplyForService.getById(id);
        if (ObjectUtil.isEmpty(byId)) {
            throw new EnFiBootException("来访id无效");
        }
        String message = "审核成功";
        if (status == 3 && StringUtils.isEmpty(refusalCause)) {
            throw new EnFiBootException("拒绝原因不能为空");
        } else if (status == 3 && !StringUtils.isEmpty(refusalCause)) {
            byId.setRefusalCause(refusalCause);
            byId.setStatus(status);
            message = "审核拒绝: " + refusalCause;
        }
        sendMessage(byId, message);
        byId.setStatus(status).updateById();
        return Result.ok("审核成功");
    }

    private void sendMessage(ApplyFor byId, String auditMessage) {
        // 模板消息，发送测试：pass
        HashMap<String, Object> params = new HashMap<String, Object>() {{
            put("touser", byId.getWxOpenid());
            put("template_id", "yTKx_JYnuosHCUgxky2eNOXWoqNn3X0L4bi9_MY6HQI");
            put("data", new HashMap<String, Object>() {{
                put("thing2", new HashMap<String, String>() {{
                    put("value", StringUtils.isEmpty(byId.getApplicantName()) ? "暂无" : byId.getApplicantName());//访客姓名
                }});
                put("time1", new HashMap<String, String>() {{
                    put("value", DateUtil.formatDateTime(byId.getBeginTime())); //来访时间
                }});
                put("thing3", new HashMap<String, String>() {{
                    put("value", StringUtils.isEmpty(byId.getVisitTheReason()) ? "暂无" : byId.getVisitTheReason()); //拜访事由
                }});
                put("thing6", new HashMap<String, String>() {{
                    put("value", StringUtils.isEmpty(byId.getReceptionSite()) ? "暂无" : byId.getReceptionSite());//拜访地址
                }});
                put("thing5", new HashMap<String, String>() {{
                    put("value", auditMessage); //审核备注
                }});
            }});
        }};
        ApiResult send = TemplateMsgApi.send(params);

//        ApiResult result = TemplateMsgApi.send(TemplateData.New()
//                // 消息接收者
//                .setTouser(byId.getWxOpenid())
//                // 模板id
//                .setTemplate_id("MauTBPlUv62sKrX0K2FE_P6ybpNjoXAsQrFi82Vqs88")
//                //.setUrl("http://m.xxxx.cn/qrcode/t/xxxxxx")
//                // 模板参数
//                .add("thing2", byId.getApplicantName(), "#999") //访客姓名
//                .add("time1", DateUtil.formatDateTime(byId.getBeginTime()), "#999") //来访时间
//                .add("thing3", byId.getVisitTheReason(), "#999") //拜访事由
//                .add("thing6", byId.getReceptionSite(), "#999") //拜访地址
//                .add("thing5", auditMessage, "#999") //审核备注
//                .build());
        System.out.println(send.getAttrs());

    }
}
