package org.enfi.modules.visitor.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
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.cache.IAccessTokenCache;
import com.jfinal.wxaapp.api.WxaQrcodeApi;
import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.aspectj.weaver.ast.Var;
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.system.vo.LoginUser;
import org.enfi.common.util.QRCodeUtil;
import org.enfi.common.util.WxaQrcodeApiPlus;
import org.enfi.config.WXConfig;
import org.enfi.modules.system.entity.SysDepart;
import org.enfi.modules.system.service.ISysDepartService;
import org.enfi.modules.visitor.entity.InvitedToRecord;
import org.enfi.modules.visitor.service.IInvitedToRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @ClassName: VisitorManagementController
 * @Author: wanghao
 * @date: 2021.11.13 12:43
 * @version: 1.0
 */
@Slf4j
@Api(tags = "访客管理")
@ApiSupport(order = 1, author = "WangHao")
@RestController
@RequestMapping("/visitorManagement")
public class VisitorManagementController {

    @Autowired //申请邀请来访记录
    private IInvitedToRecordService iInvitedToRecordService;
    @Autowired
    private ISysDepartService iSysDepartService;

    @AutoLog("申请邀请来访记录")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "申请邀请来访记录", notes = "申请邀请来访记录")
    @PostMapping("invitedToRecord")
    @PrintLnTime
    public Result<?> invitedToRecord(@Validated @RequestBody InvitedToRecord invitedToRecord) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        invitedToRecord.setInviterId(sysUser.getId());
        invitedToRecord.setInviterName(sysUser.getRealname());
        invitedToRecord.setInviterEmail(sysUser.getEmail());
        invitedToRecord.setInviterDeptId(sysUser.getDepartIds());
        List<String> departNames = iSysDepartService.
                listByIds(StringUtils.isEmpty(sysUser.getDepartIds()) ?
                        Arrays.asList("占位") :
                        Arrays.asList(sysUser.getDepartIds().split(",")))
                .stream()
                .map(SysDepart::getDepartName)
                .collect(Collectors.toList());
        invitedToRecord.setInviterDeptName(String.join(",", departNames.isEmpty() ? CollectionUtil.newArrayList("") : departNames));
        iInvitedToRecordService.save(invitedToRecord);
        String QRCode = getYaoQiQRCode(invitedToRecord.getId());
        return Result.OK("成功", new JSONObject() {{
            put("QRCode", QRCode);
            put("inviteId", invitedToRecord.getId());
        }});
    }


    @AutoLog("获取邀请来访记录")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "获取邀请来访记录", notes = "获取邀请来访记录")
    @GetMapping("getinvitedToRecordList")
    @PrintLnTime
    public Result<Page<InvitedToRecord>> getinvitedToRecordList(@ApiParam(name = "beginTime", value = "开始时间") @RequestParam(required = false) String beginTime,
                                                                @ApiParam(name = "endTime", value = "结束时间") @RequestParam(required = false) String endTime,
                                                                @ApiParam(name = "pageSize", value = "每页条数", required = true) @RequestParam(defaultValue = "10") Integer pageSize,
                                                                @ApiParam(name = "pageNo", value = "页数", required = true) @RequestParam(defaultValue = "1") Integer pageNo) {

        LambdaQueryWrapper<InvitedToRecord> queryWrapper = new LambdaQueryWrapper<InvitedToRecord>();
        queryWrapper.orderByDesc(InvitedToRecord::getCreateTime);
        if (!StringUtils.isEmpty(beginTime) && !StringUtils.isEmpty(endTime)) {
            queryWrapper.between(InvitedToRecord::getBeginTime, beginTime, endTime);
        }
        Page<InvitedToRecord> page = iInvitedToRecordService.page(new Page<>(pageNo, pageSize), queryWrapper);
        page.getRecords().stream().forEach(invitedToRecord -> {
            invitedToRecord.setYaoQiCode(getYaoQiQRCode(invitedToRecord.getId()));
        });
        return Result.OK(page);
    }


    @AutoLog("下载邀请码")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "下载邀请码", notes = "下载邀请码")
    @GetMapping("downloadYaoQiCode")
    @PrintLnTime
    @SneakyThrows
    public void downloadYaoQiCode(@ApiParam(name = "inviteId", value = "邀请id", required = true) @RequestParam String inviteId, HttpServletResponse response) {
        InputStream inputStream = WxaQrcodeApiPlus.getUnLimit("inviteId=" + inviteId, "pages/apply/index");
        try (OutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {
            //显示下载进度
            // response.setHeader("Content-Length", String.valueOf(count));
            response.setContentType("image/png");
            // 指定下载的文件名
            response.setHeader("Content-disposition", "attachment; filename=" + new String("邀请码.png".getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
            IOUtils.copy(inputStream, outputStream);
            inputStream.close();
            outputStream.flush();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }


    private String getYaoQiQRCode(String inviteId) {
        String QRCode = QRCodeUtil.crateQRCode(WxaQrcodeApiPlus.getUnLimit("inviteId=" + inviteId, "pages/apply/index"));
        return QRCode;
    }

}
