package com.ruoyi.common.utils.poi;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class Excel {
    public static String filter(Row row, String type) {
        String strValue = null;
        for (Cell cell : row) {
            String s = CellReference.convertNumToColString(cell.getColumnIndex());
            if (s.equals(type)) {
                strValue = cell.getStringCellValue();
            }
        }
        return strValue;
    }

    public String excelImportCorp(MultipartFile file) throws IOException, ParseException, JSONException {
        JSONArray jsonArray = new JSONArray();
        InputStream inputStream = file.getInputStream();
        Workbook workbook = WorkbookFactory.create(inputStream);
        int sheetIndex = workbook.getNumberOfSheets();
        //for (int i = 0; i < sheetIndex; i++) {
        Sheet sheet = workbook.getSheetAt(0);
        sheet.getLastRowNum();
        int maxRow = sheet.getLastRowNum();
        //projectbills.put("branchId", sheet.getRow(1).getCell(1).getStringCellValue());
        try {

            for (int i = 2; i <= maxRow; i++) {
//                if (
//                        (getRowValue(sheet.getRow(i).getCell(0)) == null || "".equals(getRowValue(sheet.getRow(i).getCell(0))))
//                                &&
//                                (getRowValue(sheet.getRow(i).getCell(1)) == null || "".equals(getRowValue(sheet.getRow(i).getCell(1))))
//                ) {
//                    continue;
//                }
                if (getRowValue(sheet.getRow(i).getCell(0)).startsWith("注意事项")) {
                    break;
                }
                JSONObject bcorpsDto = new JSONObject();
                if (sheet.getRow(i).getCell(0).getStringCellValue().equals("系统内")) {
                    bcorpsDto.put("systemType", 1);
                } else if (sheet.getRow(i).getCell(0).getStringCellValue().equals("系统外")) {
                    bcorpsDto.put("systemType", 0);
                } else {
                    bcorpsDto.put("systemType", null);
                }
                bcorpsDto.put("cname", getRowValue(sheet.getRow(i).getCell(1)).trim());
                bcorpsDto.put("taxNo", getRowValue(sheet.getRow(i).getCell(2)).trim());
                bcorpsDto.put("bank", getRowValue(sheet.getRow(i).getCell(3)).trim());
                bcorpsDto.put("bankAccNo", getRowValue(sheet.getRow(i).getCell(4)).trim());
                bcorpsDto.put("remarks", getRowValue(sheet.getRow(i).getCell(5)).trim());
                bcorpsDto.put("details", getRowValue(sheet.getRow(i).getCell(6)).trim());

                bcorpsDto.put("status", "A");
                jsonArray.add(bcorpsDto);
            }

        } catch (Exception e) {

        }
        workbook.close();
        return jsonArray.toString();

    }

    public String getRowValue(Cell cell) {
        String str = "";
        boolean isRun = true;
        try {
            str = cell.getStringCellValue();
            isRun = true;
        } catch (Exception e) {
            isRun = false;
        }
        if (!isRun) {
            try {
                str = cell.getNumericCellValue() + "";
            } catch (Exception e) {

            }
        }
        try {
            str = new BigDecimal(str).toPlainString();
        } catch (Exception e) {

        }

        return str.replace(".0", "");
    }

    public Map<String, Object> excelImportRenewProject(MultipartFile file) throws IOException, ParseException {
        DecimalFormat df = new DecimalFormat("0.00");

        Map<String, Object> map = new HashMap<>();
        map.put("isSuccess", "success");
        InputStream inputStream = file.getInputStream();
        Workbook workbook = WorkbookFactory.create(inputStream);
        //前台返回数据参数 dataForm +dataList
        Map<String, Object> projectbills = new HashMap<>();
        //前台返回数据参数 subContracts
        List<Map<String, Object>> subContracts = new ArrayList<>();
        //前台返回数据参数 proBudgets
        List<Map<String, Object>> proBudgets = new ArrayList<>();
        int sheetIndex = workbook.getNumberOfSheets();
        // for (int i = 0; i < sheetIndex; i++) {
        Sheet sheet = workbook.getSheetAt(0);
        //单位名称
        projectbills.put("branchId", sheet.getRow(1).getCell(1).getStringCellValue());
        //工程名称
        projectbills.put("projectName", sheet.getRow(2).getCell(1).getStringCellValue());

        //工程类型projectTypeItemName
        projectbills.put("projectTypeId", sheet.getRow(2).getCell(6).getStringCellValue());
//        projectbills.put("projectTypeItemId", sheet.getRow(2).getCell(6).getStringCellValue());

        try {
            //NC工程编号
            projectbills.put("ncProjectNo", sheet.getRow(3).getCell(1).getStringCellValue());

        } catch (Exception e) {
            //NC工程编号
            projectbills.put("ncProjectNo", sheet.getRow(3).getCell(1).getNumericCellValue());

        }
//        try {
//            //系统工程编号
//            projectbills.put("projectNo", sheet.getRow(3).getCell(6).getStringCellValue());
//        } catch (Exception e) {
//            //系统工程编号
//            projectbills.put("projectNo", sheet.getRow(3).getCell(6).getNumericCellValue());
//        }

        //业主单位
        projectbills.put("corpId", "");
        projectbills.put("corpId", sheet.getRow(4).getCell(1).getStringCellValue());
        //实际实施单位
        projectbills.put("constructorId", "");
        projectbills.put("constructorId", sheet.getRow(4).getCell(6).getStringCellValue());


        String start = null;
        Date startDate = null;
        String end = null;
        Date endDate = null;
        try {
            start = sheet.getRow(5).getCell(1).getStringCellValue();
        } catch (Exception e) {
            startDate = sheet.getRow(5).getCell(1).getDateCellValue();
        }
        try {
            end = sheet.getRow(5).getCell(6).getStringCellValue();
        } catch (Exception e) {
            endDate = sheet.getRow(5).getCell(6).getDateCellValue();
        }
        DateFormat formater1 = new SimpleDateFormat("yyyy.MM.dd");
        DateFormat formater2 = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat formater3 = new SimpleDateFormat("yyyy/MM/dd");
        Date date = null;
        String str = null;
        if (start != null && start.equals("")) {

        } else {
            try {
                if (start != null) {
                    str = start;
                } else {
                    str = formater2.format(startDate);
                }
                //实际开工日期
                if (str.indexOf(".") != -1) {
                    date = formater1.parse(str);
                } else if (str.indexOf("-") != -1) {
                    date = formater2.parse(str);
                } else if (str.indexOf("/") != -1) {
                    date = formater3.parse(str);
                } else {
                }
                projectbills.put("actStartDate", date.getTime());
            } catch (Exception e) {
            }
        }
        if (end != null && end.equals("")) {

        } else {
            try {
                if (end != null) {
                    str = end;
                } else {
                    str = formater2.format(endDate);
                }
                //实际竣工日期
                if (str.indexOf(".") != -1) {
                    date = formater1.parse(str);
                } else if (str.indexOf("-") != -1) {
                    date = formater2.parse(str);
                } else if (str.indexOf("/") != -1) {
                    date = formater3.parse(str);
                } else {
                }
                projectbills.put("actEndDate", date.getTime());
            } catch (Exception e) {

            }
        }
        //工程收入(含税)
//        projectbills.put("proIncomeAmt", df.format(get0(sheet.getRow(6).getCell(1).getNumericCellValue())));
        //账面收入(不含税)
        projectbills.put("boAmtDr", df.format(sheet.getRow(6).getCell(6).getNumericCellValue()));


        //工程成本(含税)
//        projectbills.put("projectCost", df.format(get0(sheet.getRow(7).getCell(1).getNumericCellValue())));
        //账面成本(不含税)
        projectbills.put("boAmtCr", df.format(sheet.getRow(7).getCell(6).getNumericCellValue()));

        //工程毛利额(元)
//        projectbills.put("projectProfit", df.format(get0(sheet.getRow(8).getCell(1).getNumericCellValue())));
        // 账面毛利额(元)
        projectbills.put("boAmtProfit", df.format(sheet.getRow(8).getCell(6).getNumericCellValue()));

        try {


            //工程毛利率(%)
            double f = get0(sheet.getRow(9).getCell(1).getNumericCellValue());
//            projectbills.put("projectProfitRate", Double.parseDouble(df.format(f)) * 100);
//        账面毛利率(%)
            f = sheet.getRow(9).getCell(6).getNumericCellValue();
            projectbills.put("boAmtProfitRate", Double.parseDouble(df.format(f)) * 100);
        } catch (Exception e) {

        }
//        //项目经理
//        projectbills.put("manager", sheet.getRow(8).getCell(1).getStringCellValue());
//        //备注（非必填）
//        projectbills.put("mainRemarks", sheet.getRow(8).getCell(6).getStringCellValue());


        //dataList
        //总包合同金额(元)
        if (sheet.getRow(12).getCell(0) == null) {
            projectbills.put("contractAmt", 0.00);
        } else {
            projectbills.put("contractAmt", df.format(get0(sheet.getRow(12).getCell(0).getNumericCellValue())));
        }
        //总包审定金额(元)
        if (sheet.getRow(12).getCell(1) == null) {
            projectbills.put("contractAuditAmt", 0.00);
        } else {
            projectbills.put("contractAuditAmt", df.format(get0(sheet.getRow(12).getCell(1).getNumericCellValue())));
        }
        //总包预估金额(元)
        if (sheet.getRow(12).getCell(2) == null) {
            projectbills.put("estimatedAmt", 0.00);
        } else {
            projectbills.put("estimatedAmt", df.format(get0(sheet.getRow(12).getCell(2).getNumericCellValue())));
        }
        //结算金额(元)
//        projectbills.put("settlementAmt", df.format(get0(sheet.getRow(12).getCell(3).getNumericCellValue())));
        //已开发票金额(元)
        if (sheet.getRow(12).getCell(5) == null) {
            projectbills.put("subInvAmtCr", 0.00);
        } else {
            projectbills.put("subInvAmtCr", df.format(get0(sheet.getRow(12).getCell(5).getNumericCellValue())));
        }
        //未开发票金额(元)
//        projectbills.put("subInvAmtBlc", df.format(get0(sheet.getRow(12).getCell(6).getNumericCellValue())));
        //已收款金额(元)
        if (sheet.getRow(12).getCell(7) == null) {
            projectbills.put("subAmtDr", 0.00);
        } else {
            projectbills.put("subAmtDr", df.format(get0(sheet.getRow(12).getCell(7).getNumericCellValue())));
        }
        //剩余应收金额(元)
//        projectbills.put("subAmtBlc", df.format(get0(sheet.getRow(12).getCell(8).getNumericCellValue())));
        //结算时间
        //projectbills.put("contractAuditDate", sheet.getRow(12).getCell(1).getStringCellValue());
        //备注
        projectbills.put("remarks", sheet.getRow(12).getCell(10).getStringCellValue());

        projectbills.put("settlementStatus", 1);

        map.put("project", projectbills);
        int rowIndex = 0;
        //subContracts
        int subContractsIndex = 0;
        //subContractsIndexEnd
        int subContractsIndexEnd = 0;
        //proBudgets
        int proBudgetsIndex = 0;
        //proBudgetsEnd
        int proBudgetsIndexEnd = 0;
        //工程部负责人
        int principalInde = 0;
        for (Row rows : sheet) {

            if (rows.getRowNum() == 0) {
                continue;
            }
            rowIndex++;
            for (int a = 0; a < rows.getPhysicalNumberOfCells(); a++) {

                Cell cell = rows.getCell(a);
                try {
                    cell.setCellType(CellType.STRING);
                } catch (Exception e) {
                    continue;
                }

                if (cell.getStringCellValue().equals("工程成本情况")) {
                    subContractsIndex = rowIndex + 2;
                }
                if (cell.getStringCellValue().equals("工程款小计")) {
                    subContractsIndexEnd = rowIndex;
                    proBudgetsIndex = rowIndex + 2;
                }
                if (cell.getStringCellValue().equals("其他直接成本小计")) {
                    proBudgetsIndexEnd = rowIndex;
                }
                if (cell.getStringCellValue().startsWith("工程部负责人")) {
                    principalInde = rowIndex;
                }

            }
        }
        for (int i = subContractsIndex; i < subContractsIndexEnd; i++) {
            Map<String, Object> subContractsMap = new HashMap<>();
            //成本名称
            subContractsMap.put("budgetName", sheet.getRow(i).getCell(0).getStringCellValue());
            //供应商名称
            subContractsMap.put("purchaseId", sheet.getRow(i).getCell(1).getStringCellValue());
            //分包合同金额;
            subContractsMap.put("contractAmt", KeepDecimal2Point(get0(sheet.getRow(i).getCell(2).getStringCellValue())));
            //分包审定金额
            subContractsMap.put("contractAuditAmt", KeepDecimal2Point(get0(sheet.getRow(i).getCell(3).getStringCellValue())));
            //分包预估金额
            subContractsMap.put("estimatedAmt", KeepDecimal2Point(get0(sheet.getRow(i).getCell(4).getStringCellValue())));
            //分包结算金额
//            subContractsMap.put("settlementAmt", KeepDecimal2Point(get0(sheet.getRow(i).getCell(5).getStringCellValue())));
            //已开发票金额
            subContractsMap.put("subInvAmtCr", KeepDecimal2Point(get0(sheet.getRow(i).getCell(6).getStringCellValue())));
            //未开发票金额
//            subContractsMap.put("subInvAmtBlc", KeepDecimal2Point(get0(sheet.getRow(i).getCell(7).getStringCellValue())));
            //已付款金额
            subContractsMap.put("subAmtCr", KeepDecimal2Point(get0(sheet.getRow(i).getCell(8).getStringCellValue())));
            //剩余应付金额
//            subContractsMap.put("subAmtBlc", KeepDecimal2Point(get0(sheet.getRow(i).getCell(9).getStringCellValue())));
            //备注
            subContractsMap.put("remark", sheet.getRow(i).getCell(10).getStringCellValue());
            subContracts.add(subContractsMap);
        }
        for (int i = proBudgetsIndex; i < proBudgetsIndexEnd; i++) {
            Map<String, Object> proBudgetsMap = new HashMap<>();
            //成本名称
            proBudgetsMap.put("budgetId", sheet.getRow(i).getCell(0).getStringCellValue());
            //结算金额
            proBudgetsMap.put("settlementAmt", KeepDecimal2Point(get0(sheet.getRow(i).getCell(5).getStringCellValue())));
            //已开发票金额
            proBudgetsMap.put("subInvAmtCr", KeepDecimal2Point(get0(sheet.getRow(i).getCell(6).getStringCellValue())));
            //未开发票金额
//            proBudgetsMap.put("subInvAmtBlc", KeepDecimal2Point(get0(sheet.getRow(i).getCell(7).getStringCellValue())));
            //已付款金额
            proBudgetsMap.put("subAmtCr", KeepDecimal2Point(get0(sheet.getRow(i).getCell(8).getStringCellValue())));
            //剩余应付金额
//            proBudgetsMap.put("subAmtBlc", KeepDecimal2Point(get0(sheet.getRow(i).getCell(9).getStringCellValue())));
            //备注
            proBudgetsMap.put("remarks", sheet.getRow(i).getCell(10).getStringCellValue());
            proBudgets.add(proBudgetsMap);
        }

        Map<String, Object> proBudgetsMap = new HashMap<>();
        try {

            proBudgetsMap.put("subAmtBlc", sheet.getRow(principalInde).getCell(1).getStringCellValue());
            proBudgetsMap.put("projectLeader", sheet.getRow(principalInde).getCell(1).getStringCellValue());
            proBudgetsMap.put("manager", sheet.getRow(principalInde).getCell(6).getStringCellValue());

        } catch (Exception e) {

        }
        //项目经理
//        projectbills.put("subAmtBlc", sheet.getRow(principalInde).getCell(1).getStringCellValue());
////        //备注（非必填）
//        projectbills.put("projectLeader", sheet.getRow(principalInde).getCell(6).getStringCellValue());

//        }
        map.put("subContracts", subContracts);
        map.put("proBudgets", proBudgets);
        map.put("user", proBudgetsMap);
        workbook.close();
        return map;
    }


    public String excelTime(Cell cell) {
        String guarantee_time = null;
        if (DateUtil.isCellDateFormatted(cell)) {
            //用于转化为日期格式
            Date d = cell.getDateCellValue();
//	             System.err.println(d.toString());
//	             DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            DateFormat formater = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
            guarantee_time = formater.format(d);
        }
        return guarantee_time;
    }

    public String get0(String str) {
        if (str == null) {
            return "0";
        } else if (str.equals("")) {
            return "0";
        } else {
            return str;
        }
    }

    public Double get0(Double str) {
        if (str == null) {
            return Double.valueOf(0);
        } else {
            return str;
        }
    }

    public String KeepDecimal2Point(String str) {
        if (str.indexOf(".") == -1) {
            str = str + ".00";
        }
        if (str.length() - str.indexOf(".") == 2) {
            str = str + "0";
        }
        if (str != null && !"".equals(str) && str.indexOf(".") != -1) {
            return str.substring(0, str.indexOf(".") + 3);
        } else {
            return str;
        }
    }
}
