package com.rongwei.bscommon.sys.utils;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rongwei.bscommon.sys.dao.CommonDao;
import com.rongwei.rwadmincommon.system.domain.PagePartDo;
import com.rongwei.rwadmincommon.system.service.PagePartService;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.*;

/**
 * @author zhou
 */
@Component
public class BusinessExcelUtil {

    private static Logger logger = LoggerFactory.getLogger(BusinessExcelUtil.class);

    @Autowired
    private PagePartService pagePartService;
    @Autowired
    private CommonDao commonDao;

    /**
     * 获取文件表头名集合
     * 用于校验上传文件与模板文件是否一致
     * @author chenjiahao
     * */
    @SneakyThrows
    public List<String> getColums(MultipartFile file) {
        List<String> cs = new ArrayList<>();
        XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
        int Sheets = wb.getNumberOfSheets();
        for (int i = 0; i < Sheets; i++) {
            XSSFSheet sheet = wb.getSheetAt(i);
            //获取工作簿表头
            XSSFRow head = sheet.getRow(0);
            if (head != null) {
                int o = 0;
                Iterator<Cell> it = head.iterator();
                while (it.hasNext()) {
                    Cell cell = it.next();
                    o++;
                    if (cell == null) continue;
                    String c = String.valueOf(cell);
                    cs.add(c);
                }
            }
        }
        return cs;
    }

    /**
     * 根据pageId获取模板文件
     * 用于校验上传文件与模板文件是否一致
     * @author chenjiahao
     * */
    @SneakyThrows
    public XSSFWorkbook getTemplate(Map<String, Object> map) {
        XSSFWorkbook wb = null;
        String pageId = (String) map.get("pageid");
        PagePartDo pagePart = pagePartService.getById(pageId);
        String roption = pagePart.getRoption();
        JSONObject jsonObject = JSONObject.parseObject(roption);
        JSONObject globalJson = JSONObject.parseObject(jsonObject.get("global").toString());
        JSONObject fileJson = JSONObject.parseObject(globalJson.get("base").toString());
        logger.info("fileJson：{}",fileJson);
        String fileId = JSONObject.parseObject(JSONObject.parseObject(fileJson.get("excelTemplate").toString()).get("data").toString()).get("id").toString();
        Map<String, Object> fileInfo = commonDao.getFileUrlById(fileId);
        if(ObjectUtil.isNotNull(fileInfo)){
            File file = new File(fileInfo.get("FULLPATH").toString());
            FileInputStream fileInputStream = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),"application/sql", fileInputStream);
            wb = new XSSFWorkbook(multipartFile.getInputStream());
        }
        return wb;
    }

    /**
     * 校验上传文件与模板文件是否一致
     * @author chenjiahao
     * */
    public String checkFile(List<String> colums, XSSFWorkbook wb) {
        StringBuilder errMsg = new StringBuilder();
        try {
            Sheet sheet = wb.getSheetAt(0);
            Row row = sheet.getRow(0);
            if (row != null) {
                int lastCellNum = row.getLastCellNum();//列数
                for (int idx = 0; idx < lastCellNum; idx++) {
                    String value = row.getCell(idx).getStringCellValue();//列名
                    if (!colums.contains(value)) {
                        errMsg.append("上传文件与模板不一致！");
                    }
                }
            } else {
                errMsg.append("上传的文件错误，请核对后再试");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ObjectUtil.isNull(errMsg)?"":errMsg.toString();
    }

    /**
     * 根据pageId获取当前列表的所有字段
     * 用于映射实体
     * @author chenjiahao
     * */
    public Map<String,Object> getKeyName(Map<String, Object> map){
        Map<String,Object> keyMap = new HashMap<>();
        String pageId = map.get("pageid").toString();
        PagePartDo pagePart = pagePartService.getById(pageId);
        String roption = pagePart.getRoption();
        JSONObject jsonObject = JSONObject.parseObject(roption);
        String columns1 = jsonObject.getString("columns");
        JSONObject jsonObject2 = JSONObject.parseObject(columns1);
        String base1 = jsonObject2.getString("base");
        JSONArray columns2 = JSONArray.parseArray(base1);
        for (int i = 0; i < columns2.size(); i++) {
            JSONObject jsonObject1 = columns2.getJSONObject(i);
            JSONObject base = jsonObject1.getJSONObject("base");
            String field = base.getString("field");
            String label = base.getString("label");
            keyMap.put(label, field);
        }
        return keyMap;
    }
}
