package com.webclient.beans.udbudgetTask;

import com.alibaba.fastjson.JSONObject;
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;

/**
 * 任务管理-资产拆分导入Excel
 * @author lip
 * @date 2023-09-25 21:35
 *
 */
public class AssetCFImportData 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 {
            // MboRemote mainMbo = this.app.getAppBean().getMbo();
            mainMbo = (MboRemote) mxSession.getAttribute("appMainMbo");
            String status=mainMbo.getString("STATUS");
//            if(!"WAPPR".equalsIgnoreCase(status)){
//                wcs.showMessageBox("prline", "prline_statusno", new String[]{"导入成功!"});
//                return;
//            }

            //以上代码校验是否是文件通过

            //以下验证数据及导入数据

            // 读取文件
            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开始
            String tableName = "ASSET"; //要处理的表名
            // 验证EXCEL中的数据
            String result=validDataAndInsert(sheet, beginRowIndex,beginColIndex, tableName, mainMbo, wcs);
            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();
                }else{
                    wcs.showMessageBox("commoninfo", "commoninfo_err", new String[]{resObj.getString("msg")});
                }
            }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,
                                     String tableName, MboRemote mainMbo, WebClientSession wcs) throws RemoteException, MXException, ParseException {
        JSONObject result = new JSONObject();
        int rowi=1;
        try {
            // 主单编号
            String langcode2=getMXSession().getUserInfo().getLangCode();
            int totalRows = sheet.getLastRowNum(); // 该excel表的总行数
            MboSetRemote assetSet = mainMbo.getMboSet("&ASSET","ASSET","1=2");
            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;
                MboRemote assetMbo=assetSet.add();
                assetMbo.setValue("ASSETNUM", assetMbo.getInt("ASSETUID")+"",2L);
                assetMbo.setValue("UDBUDGETTASKID", mainMbo.getInt("UDBUDGETTASKID"),2L);
                assetMbo.setValue("LANGCODE", "EN",2L);
                assetMbo.setValue("AFASL", "Z001",2L);//折旧码------默认值
                assetMbo.setValue("ORGID", getCellString(row, 28),2L);
                assetMbo.setValue("SITEID", getCellString(row, 29),2L);
                assetMbo.setValue("DESCRIPTION", getCellString(row, 1),2L);//资产名称英文
                assetMbo.setValue("SDUNITTYPE", getCellString(row, 3),2L);//规格型号
                assetMbo.setValue("MEMORYCODE", getCellString(row, 4),2L);//助记码
                assetMbo.setValue("SDGDZCBM", getCellString(row, 5),2L);//固定资产编码
                assetMbo.setValue("SDSYBM", getCellString(row, 6),2L);//使用部门编号
                assetMbo.setValue("SDWXBM", getCellString(row, 8),2L);//维修部门编号
                assetMbo.setValue("COSTCENTER", getCellString(row, 10),2L);//成本中心编号
                assetMbo.setValue("USESTATUS", getCellString(row, 12),2L);//使用状态代码
                assetMbo.setValue("ATYPE", getCellString(row, 14),2L);//资产类型代码
                assetMbo.setValue("TEMPLATEID", getCellString(row, 16),2L);//资产模板编号
                assetMbo.setValue("SDZCZYX", getCellString(row, 18),2L);//资产重要性代码
                assetMbo.setValue("LOCATION", getCellString(row, 20),11L);//位置代码
                assetMbo.setValue("INSTALLDATE", getCellString(row, 22),2L);//安装日期
                assetMbo.setValue("FIRSTDATE", getCellString(row, 23),2L);//基准日期
                assetMbo.setValue("SDGYS", getCellString(row, 24),2L);//供应商
                assetMbo.setValue("SDZZS", getCellString(row, 25),2L);//制造商
                if(null==getCellString(row, 26) || "".equalsIgnoreCase(getCellString(row, 26))){
                    assetMbo.setValue("REPLACECOST", 0,2L);//更换成本
                }else{
                    assetMbo.setValue("REPLACECOST", getCellString(row, 26),2L);//更换成本
                }
                if(null==getCellString(row, 27) || "".equalsIgnoreCase(getCellString(row, 27))){
                    assetMbo.setValue("PURCHASEPRICE", 0,2L);//资产金额
                }else{
                    assetMbo.setValue("PURCHASEPRICE", getCellString(row, 27),2L);//资产金额
                }

                //增加转固字段信息
//                assetMbo.setValue("SDGDZCBM", getCellString(row, 30),2L);//固定资产编码（转固）
                assetMbo.setValue("ANLKL", getCellString(row, 30),2L);//资产分类编码（转固）
                assetMbo.setValue("MEINS", getCellString(row, 31),2L);//单位值（转固）
                assetMbo.setValue("PROZS", getCellString(row, 32),2L);//结算百分比（转固）
                assetMbo.setValue("USEDFROM", getCellString(row, 33),2L);//期间/年度（转固）
//                assetMbo.setValue("NDJAR", getCellString(row, 35),2L);//折旧年限（转固） 20240730要求取消
                assetMbo.setValue("NDPER", getCellString(row, 34),2L);//折旧期间(月份)（转固）
                assetMbo.setValue("AFABG", getCellString(row, 35),2L);//折旧计算开始日期（转固）
                assetMbo.setValue("SDMEMO", getCellString(row, 36),2L);//备注
                assetMbo.getThisMboSet().save();
                MboSetRemote lassetSetZh=assetMbo.getMboSet("$L_ASSET", "L_ASSET", "OWNERID ="+assetMbo.getInt("ASSETUID")+" and LANGCODE='ZH'");
                if(null!=lassetSetZh && !lassetSetZh.isEmpty() && "ZH".equalsIgnoreCase(langcode2)){
                    lassetSetZh.getMbo(0).setValue("DESCRIPTION", getCellString(row, 0), 2L);
                    lassetSetZh.save();

                    MboRemote l_assetMbo2=lassetSetZh.add();
                    l_assetMbo2.setValue("OWNERID", assetMbo.getInt("ASSETUID"), 2L);
                    l_assetMbo2.setValue("LANGCODE", "FR", 2L);
                    l_assetMbo2.setValue("DESCRIPTION", getCellString(row, 2), 2L);
                    l_assetMbo2.getThisMboSet().save();

                    MboSetRemote assetSetEn = MXServer.getMXServer().getMboSet("ASSET",MXServer.getMXServer().getSystemUserInfo());
                    assetSetEn.setWhere("ASSETUID="+assetMbo.getInt("ASSETUID")+"");
                    assetSetEn.reset();
                    assetSetEn.getMbo(0).setValue("DESCRIPTION", getCellString(row, 1), 2L);
                    assetSetEn.save();
                }
            }
            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;
    }

}
