package com.pqs9000.controller.report;

import com.njcn.enums.LogTypeEnum;
import com.njcn.pojo.commons.DatePojo;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.commons.RedisDB;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.InstantiateUtil;
import com.njcn.utils.PubUtils;
import com.njcn.utils.redis.JedisManager;
import com.pqs9000.service.report.PercentService;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("percent")
public class PercentController {
    @Autowired
    private PercentService percentService;
    @Autowired
    private JedisManager jedisManager;
    @Autowired
    UserLogDetailService userLog;
    private InstantiateUtil<String> instantiateUtil;
    private byte[] fact;
    private Map<String, XWPFDocument> map;

    public PercentController() {
        instantiateUtil = new InstantiateUtil<>();
        fact = instantiateUtil.instantiate("fact");
        map = new HashMap<>();
    }

    @PostMapping("createPercent")
    @ResponseBody
    public HttpResult createTable(String startTime, String endTime, int timeType, String list, String factory, String listPointName, String lineName) {
        HttpResult httpResult;
        String userIndex = TokenManager.getUserId();
        byte[] userIndexs = instantiateUtil.instantiate(userIndex);
        byte[] value = instantiateUtil.instantiate(factory);

        jedisManager.hset(RedisDB.SHORT_TIME_QUERY, userIndexs, fact, value, RedisDB.SHORT_TIME);
        DatePojo datePojo = PubUtils.validateDate(startTime, endTime, "createTable");
        if (!datePojo.getValidity()) {
            httpResult = PubUtils.assignmentResult(null, 500, "解析前台传递的时间有误");
            return httpResult;
        }

        List<Integer> list1 = new ArrayList<>();
        String[] array = list.split(",");

        for (int i = 0; i < array.length; i++)
            list1.add(Integer.parseInt(array[i]));

        try {
            XWPFDocument xwpfDocument = percentService.createTable(datePojo.getStartTime(), datePojo.getEndTime(), list1, timeType, factory, listPointName, lineName);
            map.put(userIndex, xwpfDocument);

            if (xwpfDocument == null) {
                return PubUtils.assignmentResult(null, 500, "合格率报表生成失败");
            }
        } catch (Exception e) {
            return PubUtils.assignmentResult(null, 500, "合格率报表生成失败");
        }

        httpResult = PubUtils.assignmentResult(null, 200, "合格率报表生成成功");

        return httpResult;
    }

    @GetMapping(value = "/exportPercent")
    public void exportPercent(HttpServletResponse response,HttpServletRequest request) {
        try {
            String userIndex = TokenManager.getUserId();
            byte[] userIndexs = instantiateUtil.instantiate(userIndex);
            String factory = instantiateUtil.deInstantiate(jedisManager.hget(RedisDB.SHORT_TIME_QUERY, userIndexs, fact));
            XWPFDocument xwpfDocument = map.get(userIndex);
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;fileName=" + new String(factory.getBytes("GB2312"), "iso8859-1") + "_" + PubUtils.getNow() + ".docx");// 设置文件名
            OutputStream outputStream = response.getOutputStream();
            xwpfDocument.write(outputStream);
            outputStream.close();
            userLog.getLog("导出合格率报表", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (IOException e) {
            userLog.getLog("导出合格率报表", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        }
    }
}
