package com.webclient.beans.assetdispo;

import com.alibaba.fastjson.JSONObject;
import com.webclient.beans.udbudgetTask.AssetCFImportData;
import com.webclient.beans.udpr.ImpExcelTool;
import org.apache.poi.ss.usermodel.*;
import psdi.mbo.MboRemote;
import psdi.mbo.MboSetRemote;
import psdi.server.MXServer;
import psdi.util.MXApplicationException;
import psdi.util.MXException;
import psdi.webclient.system.beans.DataBean;
import psdi.webclient.system.controller.MPFormData;
import psdi.webclient.system.session.WebClientSession;

import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.rmi.RemoteException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;

/**
 * 执行组批量导入
 * edit 2023-11-7
 */
public class ZxGroupImportDataBean extends DataBean{


    static Logger logger = Logger.getLogger(AssetCFImportData.class.getName());
    public static WebClientSession wcs;
    public static HttpSession mxSession;
    public static MboRemote mainMbo;
    public static MPFormData mpData;

    public void importExecute() throws MXException, RemoteException {
        wcs = this.clientSession;
        mpData = ImpExcelTool.getInstance().checkExcelType(wcs); // 校验文件正确性
        mxSession = wcs.getRequest().getSession();
        if (null == mxSession.getAttribute("mxClientSession")) {
            mxSession.setAttribute("mxClientSession", wcs);
        }
        if (this.app != null && this.app.getAppBean() != null) {
            mxSession.setAttribute("appMainMbo", this.app.getAppBean().getMbo());
        }
        mxSession.setAttribute("mpData", mpData);
        wcs.getResponse().setContentType("text/html; charset=UTF-8"); // 转码
        try {
            // 读取文件
            byte[] b = mpData.getFileOutputStream().toByteArray();
            InputStream ips = new ByteArrayInputStream(b);
            Workbook workBook= WorkbookFactory.create(ips);
            Sheet sheet = workBook.getSheetAt(0);
            int beginRowIndex = 2;// 处理数据的开始行，默认从0开始
            int beginColIndex = 0;// 处理数据开始列，默认从0开始
            // 验证EXCEL中的数据
            String result=validDataAndInsert(sheet, beginRowIndex,beginColIndex);
            JSONObject resObj = (JSONObject) JSONObject.parse(result);
            String code = resObj.getString("code");
            if(resObj!=null && code !=null && !"".equals(code)){
                if("10000".equals(code)){
                    wcs.showMessageBox("commoninfo", "commoninfo", new String[]{"导入成功!"});
//                    app.getAppBean().save();
                    //主表刷新
                    app.getAppBean().refreshTable();
                    app.getAppBean().reloadTable();
                    app.getAppBean().fireDataChangedEvent();
                    app.getAppBean().fireStructureChangedEvent();
                    //子表刷新
//                    app.getDataBean("1689688252472").refreshTable();//获取子表bean
//                    app.getDataBean("1689688252472").reloadTable();//获取子表bean
                }else{
                    wcs.showMessageBox("commoninfo", "commoninfo_err", new String[]{resObj.getString("msg")});
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            wcs.showMessageBox("commoninfo", "commoninfo_err2", new String[]{e.getMessage()});
        } finally {
            System.gc();
        }

    }

    public String validDataAndInsert(Sheet sheet, int beginRowIndex, int beginColIndex) throws RemoteException, MXException, ParseException {
        JSONObject result = new JSONObject();
        int rowi=1;
        try {
            // 主单编号
            int totalRows = sheet.getLastRowNum(); // 该excel表的总行数
            //执行组表
            MboSetRemote udzxzSet = MXServer.getMXServer().getMboSet("UDCJZ",MXServer.getMXServer().getSystemUserInfo());
            //人员组
            MboSetRemote personGroupSet = MXServer.getMXServer().getMboSet("PERSONGROUP",MXServer.getMXServer().getSystemUserInfo());

            boolean Flag = true;//先验证所有数据没有问题，在写入，但凡有一个数据有问题，都不允许插入。
            for (int i = beginRowIndex; i <= totalRows; i++) {
//                System.out.println("当前插入行：：" + i + "/" + totalRows);
                Row row = sheet.getRow(i);
                // 判断何时结束循环
                if (row == null || null==row.getCell(0)) {
                    break;
                }
                rowi=row.getRowNum()+1;
                Integer ASSETID = Integer.parseInt(getCellString(row, 0));
                String UDZXZGH = getCellString(row, 1);
                String ORGID = getCellString(row, 2);
                String SITEID =  getCellString(row, 3);
                String TYPE = getCellString(row, 4);
                //验证-执行组是否在人员组中，不在给出提示
                personGroupSet.setWhere("PERSONGROUP='"+UDZXZGH+"' AND SITEID='"+SITEID+"'");
                personGroupSet.reset();
                if(personGroupSet ==null || personGroupSet.isEmpty()){
                    result.put("code", "10001");
                    result.put("msg", "In row "+rowi+" 【"+UDZXZGH+"】 not exit in Person Group");
                    Flag = false;
                    break;
                }
                //验证--同一个设备，同一个执行组类型，不能有重复的执行组
                udzxzSet.setWhere("ASSETID="+ASSETID+" and TYPE='"+TYPE+"' and UDZXZGH='"+UDZXZGH+"' and SITEID='"+SITEID+"'");
                udzxzSet.reset();
                if(udzxzSet!=null && !udzxzSet.isEmpty()){
                    result.put("code", "10001");
                    result.put("msg", "In row "+rowi+" 【"+UDZXZGH+"】 is exit");
                    Flag = false;
                    break;
                }
            }
            if(Flag){
                for(int k = beginRowIndex; k <= totalRows; k++){
                    Row rowk = sheet.getRow(k);
                    // 判断何时结束循环
                    if (rowk == null || null==rowk.getCell(0)) {
                        break;
                    }
                    rowi=rowk.getRowNum()+1;
                    Integer ASSETID = Integer.parseInt(getCellString(rowk, 0));
                    String UDZXZGH = getCellString(rowk, 1);
                    String ORGID = getCellString(rowk, 2);
                    String SITEID =  getCellString(rowk, 3);
                    String TYPE = getCellString(rowk, 4);
                    MboRemote perGMbo=udzxzSet.add();
                    perGMbo.setValue("ASSETID",ASSETID, 2L);//资产编号
                    perGMbo.setValue("UDZXZGH",UDZXZGH, 11L);//人员组
                    perGMbo.setValue("ORGID",ORGID, 2L);//组织
                    perGMbo.setValue("SITEID",SITEID, 2L);//地点
                    perGMbo.setValue("TYPE",TYPE, 2L);//执行组类型
                    perGMbo.getThisMboSet().save(2L);
                }
                result.put("code", "10000");
                result.put("msg", "success");
            }
        }catch (Exception e){
            e.getMessage();
            e.getCause();
            result.put("code", "10001");
            result.put("msg", "In row "+rowi+" of excel."+e.getMessage());
        }
        return result.toString();
    }


    private String getCellString(Row row, int i) throws MXApplicationException {
        Cell cell = row.getCell(i);
        String cellStr = "";
        if (cell == null) {
            return cellStr;
        }
        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            cellStr = cell.getRichStringCellValue().getString().trim();
        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) { // 自定义的日期类型
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date date = cell.getDateCellValue();
                cellStr = sdf.format(date).trim();
            } else {
                NumberFormat nf = NumberFormat.getInstance();
                nf.setGroupingUsed(false); // 设置数字格式，不自动用科学计数法
                if (i == 15 || i == 18 || i == 19 || i == 21 || i == 23 || i == 47) {
                    Integer value = (int) cell.getNumericCellValue(); // 整数
                    cellStr = nf.format(value).trim();
                } else {
                    double value = cell.getNumericCellValue(); // 小数
                    cellStr = nf.format(value).trim();
                }
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) { // 公式
            cellStr = cell.getCellFormula().trim();
        } else {
            cellStr = cell.getRichStringCellValue().getString().trim();
        }
        return cellStr;
    }

}
