package com.chinaweal.aiccs.aiccs.nonIocalCirculation.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.nonIocalCirculation.entity.EOtCase;
import com.chinaweal.aiccs.aiccs.nonIocalCirculation.entity.dto.EOTCaseDto;
import com.chinaweal.aiccs.aiccs.nonIocalCirculation.excelListener.EOTCaseExcelListener;
import com.chinaweal.aiccs.aiccs.nonIocalCirculation.service.EOtCaseService;
import com.chinaweal.aiccs.aiccs.revoke.Vo.DisableListVo;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.DateUtils;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.page.PageRequestDto;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.chinaweal.youfool.framework.springboot.util.AssertUtils;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 行政处罚信息(临时) 前端控制器
 * </p>
 *
 * @author Yweirdo
 * @since 2021-08-18
 */
@RestController
@RequestMapping("/eOtCase")
public class EOtCaseController extends BaseController {

    @Autowired
    EOtCaseService eOtCaseService;

    @RequestMapping("queryAll")
    public RestResult<?> queryAll(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request){
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
        String entname = "";
        String uniscid = "";
        String regno = "";

        if(customParamMap != null){
            entname = StringUtils.tranObject(customParamMap.get("entname"));
            uniscid = StringUtils.tranObject(customParamMap.get("uniscid"));
            regno = StringUtils.tranObject(customParamMap.get("regno"));
        }

        LambdaQueryWrapper<EOtCase> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(regno), EOtCase::getRegno,regno)
                .like(StringUtils.isNotBlank(entname),EOtCase::getEntname,entname)
                .eq(StringUtils.isNotBlank(uniscid),EOtCase::getUniscid,uniscid);

        Page<EOtCase> page = eOtCaseService.page(new Page<>(pageRequestDto.getCurPage(),pageRequestDto.getPageSize()),wrapper);
//        return RestResult.ok(page);
        return RestResult.ok(page);
    }

    /**
     * 行政处罚信息上传并保存至数据库
     * @param httpServletRequest
     * @param file
     * @return
     */
    @PostMapping("uploadAndSave")
    public RestResult<?> uploadAndSave(HttpServletRequest httpServletRequest, MultipartFile file){
        AssertUtils.isNotNull(file);
        String filename = file.getOriginalFilename();
        if (filename == null || (!filename.toLowerCase().endsWith(".xls") && !filename.toLowerCase().endsWith(".xlsx"))) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR,"文件类型错误");
        }
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            EasyExcel.read(inputStream, EOTCaseDto.class, new EOTCaseExcelListener(eOtCaseService)).sheet().doRead();
            return RestResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResult.error(ResultCode.MYSTERIOUS_ERROR);
    }

    /**
     *  行政处罚信息清单Excel下载
     *
     * @return
     */
    @GetMapping("listDownload")
    public RestResult<?> listDownload(String ids, HttpServletRequest request, HttpServletResponse response) {
        AssertUtils.isNotBlank(ids);
        String[] idArray = ids.split(Constant.SEMICOLON);
        LambdaQueryWrapper<EOtCase> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(EOtCase::getId, Arrays.asList(idArray));
        List<EOtCase> list = eOtCaseService.list(wrapper);
        ArrayList<EOTCaseDto> exportList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)){
            for (EOtCase eOtCase : list) {
                EOTCaseDto eotCaseDto = new EOTCaseDto();
                BeanUtils.copyProperties(eOtCase,eotCaseDto);
                if(eOtCase.getPublicDate() !=null){
                    String publicDateStr = DateUtils.localDateFormat(eOtCase.getPublicDate(), DateUtils.DATE_DEFAULT_FORMAT);
                    eotCaseDto.setPublicDateStr(publicDateStr);
                }
                if(eOtCase.getPendecissdate() !=null){
                    String pendecissdateStr = DateUtils.localDateFormat(eOtCase.getPendecissdate(), DateUtils.DATE_DEFAULT_FORMAT);
                    eotCaseDto.setPendecissdateStr(pendecissdateStr);
                }
                exportList.add(eotCaseDto);
            }
        }

        ExcelWriter writer = null;
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            //添加响应头信息
            String fileName = "行政处罚信息下载.xlsx";
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/msexcel;charset=UTF-8");//设置类型
            response.setHeader("Pragma", "No-cache");//设置头
            response.setHeader("Cache-Control", "no-cache");//设置头
            response.setDateHeader("Expires", 0);//设置日期头
            //实例化 ExcelWriter，传入输出流，excel格式，表头true
            writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLSX, true);

            //使用Lists.partition 将list集合按指定长度进行切分，避免导出数据量大于excel的上限
            List<List<EOTCaseDto>> partition = Lists.partition(exportList, 10000);
            for (int i = 1; i <= partition.size(); i++) {
                Sheet sheet = new Sheet(i, 0, EOTCaseDto.class);
                sheet.setSheetName("清单" + i);
                //输出
                writer.write(partition.get(i - 1), sheet);
            }
            writer.finish();
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.getOutputStream().close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return OK;
    }

    @RequestMapping("queryEOtCaseOne")
    public RestResult<?> queryEOtCaseOne(String pripid){
        Map rs = eOtCaseService.queryByUNISCID(pripid);
        return RestResult.ok(rs);
    }
}

