package com.github.wxiaoqi.security.common.rest;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.context.BaseContextHandler;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.util.Query;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

/**
 * ${DESCRIPTION}
 *
 * @author wanghaobin
 * @create 2017-06-15 8:48
 */
@Slf4j
public class CommonBaseController {
    @Autowired
    public HttpServletRequest request;

    public HttpServletRequest getRequest() {
        return request;
    }

    @Autowired
    public HttpServletResponse response;

    public HttpServletResponse getResponse() {
        return response;
    }

    public String getCurrentUserName(){
        return BaseContextHandler.getUsername();
    }

    public String getCurrentUserId(){
        return BaseContextHandler.getUserID();
    }

    public Integer getCurrentUserIdInt(){
        if(null != BaseContextHandler.getUserID()) {
            return Integer.valueOf(BaseContextHandler.getUserID());
        }else {
            return null;
        }
    }

    public void export(Logger log, Map<String, Object> headerAlias, Supplier<List<Map>> function, String fileName) throws  Exception {
        HttpServletResponse httpServletResponse = getResponse();
        ExcelWriter writer = ExcelUtil.getWriter(true);
        if(StrUtil.isBlank(fileName)) {
            fileName = System.currentTimeMillis()+ "";
        }

        try {

            //封装表头
            headerAlias.keySet().forEach(key -> {
                writer.addHeaderAlias(key, headerAlias.get(key).toString());
            });

            log.info("======export==== ");

            //处理数据
            List<Map> list = function.get();
            if (list.size() == 0) {
                Map<String, Object> map = CollUtil.newHashMap();
                headerAlias.keySet().forEach(key -> {
                    writer.addHeaderAlias(key, "");
                });
                list.add(map);
            }
            log.info("list: {} ", JSONUtil.toJsonStr(list));
            writer.write(list);
            httpServletResponse.setContentType("application/octet-stream;charset=utf-8");
            httpServletResponse.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName+ ".xlsx","utf-8"));
            writer.flush(httpServletResponse.getOutputStream());
        }catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            throw ex;
        }finally {
            writer.close();
        }
    }

    public <T>void exportBean(Logger log, T headerAlias, Supplier<List<Map>> function, String fileName) throws  Exception {
        export(log, BeanUtil.beanToMap(headerAlias), ()->
                        function.get()
                , fileName);
    }

}
