package cn.com.poc.covenant.rest.impl;

import cn.com.poc.common.constant.FormReportingConstant;
import cn.com.poc.common.service.BosConfigService;
import cn.com.poc.common.utils.UUIDTool;
import cn.com.poc.covenant.convert.BizExtractionDocFlowConvert;
import cn.com.poc.covenant.dto.BizExtractionDocFlowDto;
import cn.com.poc.covenant.entity.BizExtractionDocFlowEntity;
import cn.com.poc.covenant.rest.BizExtractionDocFlowRest;
import cn.com.poc.covenant.service.BizExtractionDocFlowService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.tools.ant.taskdefs.Java;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import static org.apache.logging.log4j.core.util.FileUtils.getFileExtension;

@Component
public class BizExtractionDocFlowRestImpl implements BizExtractionDocFlowRest {

    @Resource
    private BizExtractionDocFlowService service;

    @Resource
    private BosConfigService bossConfigService;

    @Override
    public BizExtractionDocFlowDto getByTaskInId(String taskInId) throws Exception {
        Assert.notNull(taskInId);
        BizExtractionDocFlowEntity example = new BizExtractionDocFlowEntity();
        example.setBizTextInTaskId(taskInId);
        example.setIsDeleted("N");
        List<BizExtractionDocFlowEntity> bizExtractionDocFlowEntityList = service.findByExample(example, null);
        if (CollectionUtils.isEmpty(bizExtractionDocFlowEntityList)) {
            throw new Exception("未找到任务");
        }
        return BizExtractionDocFlowConvert.entityToDto(bizExtractionDocFlowEntityList.get(0));
    }
    @Override
    public BizExtractionDocFlowDto update(BizExtractionDocFlowDto bizExtractionDocFlowDto) throws Exception {
        BizExtractionDocFlowEntity bizExtractionDocFlowEntity = service.update(BizExtractionDocFlowConvert.dtoToEntity(bizExtractionDocFlowDto));
        if(bizExtractionDocFlowEntity!=null){
            return BizExtractionDocFlowConvert.entityToDto(bizExtractionDocFlowEntity);
        }
        return null;
    }

    @Override
    public String report(String bizTextInTaskId) throws Exception {
        Assert.notNull(bizTextInTaskId);

        BizExtractionDocFlowDto bizExtractionDocFlowDto = getByTaskInId(bizTextInTaskId);

        if(StringUtils.isEmpty(bizExtractionDocFlowDto.getBizDocFlowFields())){
            throw new Exception("数据为空");
        }

        List<List<String>> head = head(bizExtractionDocFlowDto.getBizDocFlowFields());
        List<List<String>> data = data(bizExtractionDocFlowDto.getBizDocFlowFields());

        // 设置响应体
//        response.reset();
//        response.setContentType("application/vnd.ms-excel;charset=utf-8");
//        response.setCharacterEncoding("utf-8");
//        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(  "识别内容导出.xls", "utf-8"));

        File file = File.createTempFile("temp", "." + UUIDTool.getUUID());


        EasyExcel.write(file)
                .excelType(ExcelTypeEnum.XLS) // excel类型
                .head(head).sheet("\"识别内容导出.xls\"")
                .registerWriteHandler(new AbstractColumnWidthStyleStrategy() {
                    @Override
                    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
                        // 设置列宽
                        Sheet sheet = writeSheetHolder.getSheet();
                        sheet.setColumnWidth(cell.getColumnIndex(), FormReportingConstant.EXCEL_CONFIG.COLUMN_WIDTH);
                    }
                }).doWrite(data);

        InputStream in = new FileInputStream(file);
        return bossConfigService.upload(in,"xls","");
    }

    public List<List<String>> head(String bizDocFlowItems){
        List<List<String>> list = new ArrayList<>();
        JSONArray jSONArray = JSONObject.parseArray(bizDocFlowItems);
        for (int i = 0; i < jSONArray.size(); i++) {
            List<String> head0 = new ArrayList<>();
            JSONObject jsonObject = jSONArray.getJSONObject(i);
            head0.add(jsonObject.get("key").toString());
            list.add(head0);
        }
        return list;
    }
    public List<List<String>> data(String bizDocFlowItems){
        List<List<String>> list = new ArrayList<>();
        JSONArray jSONArray = JSONObject.parseArray(bizDocFlowItems);
        List<String> head0 = new ArrayList<>();
        for (int i = 0; i < jSONArray.size(); i++) {
            JSONObject jsonObject = jSONArray.getJSONObject(i);
            head0.add(jsonObject.get("value").toString());
        }
        list.add(head0);
        return list;
    }




}