package com.webclient.beans.resultshowlist;

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-13
 */
public class LocationImportDataBean 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)){
                    app.getAppBean().refreshTable();
                    app.getAppBean().reloadTable();
                    app.getAppBean().fireDataChangedEvent();
                    app.getAppBean().fireStructureChangedEvent();
                    this.app.getDataBean("1697451775058").reloadTable();
                    this.app.getDataBean("1697451775058").refreshTable();
                    this.app.getDataBean("results_showlist").reloadTable();
                    this.app.getDataBean("results_showlist").refreshTable();
                    wcs.showMessageBox("commoninfo", "commoninfo", new String[]{"导入成功!"});
//                    app.getAppBean().save();

                }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 locationsSet = MXServer.getMXServer().getMboSet("LOCATIONS",MXServer.getMXServer().getSystemUserInfo());
            MboSetRemote l_locationsSet = MXServer.getMXServer().getMboSet("L_LOCATIONS",MXServer.getMXServer().getSystemUserInfo());
            String userid=MXServer.getMXServer().getSystemUserInfo().getPersonId();
            MboSetRemote locancestorSet = MXServer.getMXServer().getMboSet("LOCANCESTOR",MXServer.getMXServer().getSystemUserInfo());

            MboSetRemote locsystemSet = MXServer.getMXServer().getMboSet("LOCSYSTEM",MXServer.getMXServer().getSystemUserInfo());


            Date curdate=new Date();
            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;
                String location=getCellString(row, 0);//位置编号
                String orgid=getCellString(row, 4);//组织
                String siteid=getCellString(row, 5);//地点

                locsystemSet.setWhere("SYSTEMID='"+siteid+"' AND SITEID='"+siteid+"' AND ORGID='"+orgid+"'");
                locsystemSet.reset();
                if(locsystemSet.isEmpty()){
                    MboRemote locsystemMbo=locsystemSet.add();
                    locsystemMbo.setValue("SYSTEMID", siteid, 2L);
                    locsystemMbo.setValue("NETWORK", 0, 2L);
                    locsystemMbo.setValue("SITEID", siteid, 2L);
                    locsystemMbo.setValue("ORGID", orgid, 2L);
                    locsystemMbo.setValue("PRIMARYSYSTEM", 1, 2L);
                    locsystemMbo.setValue("HASLD", 0, 2L);
                    locsystemMbo.setValue("ADDRESS", 0, 2L);
                    locsystemMbo.getThisMboSet().save();
                    locsystemMbo.getThisMboSet().close();
                }

                locationsSet.setWhere("LOCATION='"+location+"' AND ORGID='"+orgid+"' AND SITEID='"+siteid+"'");
                locationsSet.reset();

                if(null!=locationsSet && locationsSet.count()<=0){
                    MboRemote locMbo=locationsSet.add(11L);
                    locMbo.setValue("LOCATION", location, 2L);
                    locMbo.setValue("DESCRIPTION", getCellString(row, 1), 2L);
                    locMbo.setValue("TYPE", "OPERATING", 2L);
                    locMbo.setValue("CHANGEBY", userid, 2L);
                    locMbo.setValue("CHANGEDATE", curdate, 2L);
                    locMbo.setValue("DISABLED", 0, 2L);
                    locMbo.setValue("SITEID", siteid, 2L);
                    locMbo.setValue("ORGID", orgid, 2L);
                    locMbo.setValue("ISDEFAULT", 0, 2L);
                    locMbo.setValue("STATUS", "OPERATING", 2L);
                    locMbo.setValue("USEINPOPR", 0, 2L);
                    locMbo.setValue("LANGCODE", "EN", 2L);
                    locMbo.setValue("AUTOWOGEN", 0, 2L);
                    locMbo.setValue("STATUSDATE", curdate, 2L);
                    locMbo.setValue("ISREPAIRFACILITY", 0, 2L);
                    locMbo.setValue("PLUSCLOOP", 0, 2L);
                    locMbo.setValue("PLUSCPMEXTDATE", 0, 2L);
                    locMbo.setValue("EXPECTEDLIFE", 0, 2L);
                    locMbo.setValue("REPLACECOST", 0, 2L);
                    locMbo.getThisMboSet().save(11L);
                    locMbo.getThisMboSet().close();

                    MboRemote l_fcMbo=l_locationsSet.add();
                    l_fcMbo.setValue("OWNERID", locMbo.getInt("LOCATIONSID"), 2L);
                    l_fcMbo.setValue("LANGCODE", "ZH", 2L);
                    l_fcMbo.setValue("DESCRIPTION", getCellString(row, 2), 2L);
                    l_fcMbo.getThisMboSet().save();
                    l_fcMbo.getThisMboSet().close();

                    MboRemote l_fcMboFr=l_locationsSet.add();
                    l_fcMboFr.setValue("OWNERID", locMbo.getInt("LOCATIONSID"), 2L);
                    l_fcMboFr.setValue("LANGCODE", "FR", 2L);
                    l_fcMboFr.setValue("DESCRIPTION", getCellString(row, 3), 2L);
                    l_fcMboFr.getThisMboSet().save();
                    l_fcMboFr.getThisMboSet().close();

                    MboRemote lochierarchyMbo=locMbo.getMboSet("LOCHIERARCHY").add();
                    lochierarchyMbo.setValue("LOCATION", location, 2L);
                    lochierarchyMbo.setValue("PARENT", getCellString(row, 6), 11L);
                    lochierarchyMbo.setValue("SYSTEMID", siteid, 2L);
                    if("".equalsIgnoreCase(getCellString(row, 6)) || null==getCellString(row, 6)){
                        lochierarchyMbo.setValue("CHILDREN", 0, 2L);
                    }else{
                        lochierarchyMbo.setValue("CHILDREN", 1, 2L);
                    }
                    lochierarchyMbo.setValue("SITEID", siteid, 2L);
                    lochierarchyMbo.setValue("ORGID", orgid, 2L);
                    lochierarchyMbo.setValue("HASCHILDREN", 1, 2L);
                    lochierarchyMbo.setValue("HASPARENT", 0, 2L);
                    lochierarchyMbo.getThisMboSet().save();
                    lochierarchyMbo.getThisMboSet().close();

//                    MboRemote locancestorMbo=locMbo.getMboSet("LOCANCESTOR").add();
                    try{
                        MboRemote locancestorMbo=locancestorSet.add();
                    }catch (Exception e){

                    }

//                    locancestorMbo.setValue("LOCATION", location, 11L);
//                    if("".equalsIgnoreCase(getCellString(row, 6)) || null==getCellString(row, 6)){
//                        locancestorMbo.setValue("ANCESTOR", location, 11L);//上级位置编号
//                    }else{
//                        locancestorMbo.setValue("ANCESTOR", getCellString(row, 6), 11L);//上级位置编号
//                    }
//                    locancestorMbo.setValue("SYSTEMID", siteid, 2L);
//                    locancestorMbo.setValue("SITEID", siteid, 2L);
//                    locancestorMbo.setValue("ORGID", orgid, 2L);
//                    locancestorMbo.getThisMboSet().save();
//                    locancestorMbo.getThisMboSet().close();

                    result.put("code", "10000");
                    result.put("msg", "success");

                }else{
                    result.put("code", "10001");
                    result.put("msg", "In row "+rowi+" of excel."+location+" already exists. ");
                    return result.toString();
                }
            }

        }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;
    }

}
