package weaver.interfaces.htsc.cwkhtzlc;

import com.alibaba.fastjson.JSON;
import com.api.integration.Base;
import tebie.applib.api.O;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Cwkhtz extends BaseBean implements Action {
    @Override
    public String execute(RequestInfo requestInfo) {
        BaseBean bb = new BaseBean();
        String sql="";
        String back = "";
        try{

//            获取主表数据
            Map mainData = MiniUtil.mainData(requestInfo);
//            获取明细表3数据
            List dtList = MiniUtil.dtData(requestInfo, 2);
//            加载缓存类
            DepartmentComInfo departmentComInfo = new DepartmentComInfo();
//            待插入数据库集合
            List<Map<String,Object>> insertData = new ArrayList<>();
            Map<String,Object> miniInsert = new HashMap<>();

            String title = Util.null2String(mainData.get("lcbt"));
            String workFlowNum = Util.null2String(mainData.get("lcbh"));
            String applicant = new ResourceComInfo().getLastname(Util.null2String(mainData.get("ngr")));
            String state = "办结";
            String applicantDeptName = departmentComInfo.getDepartmentName(Util.null2String(mainData.get("szbm")));
            String orgname = departmentComInfo.getDepartmentName(Util.null2String(mainData.get("szjg")));
            String drafterTel = Util.null2String(mainData.get("lxfs"));
            String draftDate = Util.null2String(mainData.get("ngsj"));
            String urgency = "";
            switch (Util.null2String(mainData.get("jjcd"))){
                case ("0"):{
                    urgency = "一般";
                    break;
                }
                case ("1"):{
                    urgency = "紧急";
                    break;
                }
                case ("2"):{
                    urgency = "特急";
                    break;
                }
                default:urgency = "";
            }
            String sumToSmart = Util.null2String(mainData.get("hjxxje"));
//            大写金额
            String totalBig = Util.null2String(digitCapital(Util.getDoubleValue(Util.null2String(mainData.get("hjdxje")))));
            bb.writeLog(Util.getDoubleValue(Util.null2String(mainData.get("hjdxje"))));
            String remark = Util.null2String(mainData.get("bz"));


            for (int i = 0; i < dtList.size(); i++) {
                RecordSet rs = new RecordSet();
//                rs.executeUpdateWithDatasource("", "", )

                Map map = (Map) dtList.get(i);
                String leaveDeptName = departmentComInfo.getDepartmentName(Util.null2String(map.get("dcbm")));
                String enterDeptName = departmentComInfo.getDepartmentName(Util.null2String(map.get("drbm")));
                String enterPeriod = Util.null2String(map.get("rzrq"));
                String AdjustMoney = Util.null2String(map.get("dzje"));
//                树形浏览框
                String costType = "";
                String allsrfylx = Util.null2String(map.get("srfylx"));
                bb.writeLog(allsrfylx+"---------");
                sql = "select LMMC from uf_srfylx where LMBM = "+allsrfylx.substring(allsrfylx.indexOf("_")+1);
                bb.writeLog("sql:"+sql);
                rs.execute(sql);
                if (rs.next()){
                    costType = rs.getString("LMMC");
                }
                bb.writeLog("从数据库中获取的收入费用类型："+costType);


                String isAfteravt = "";
                switch (Util.null2String(map.get("sfzzsh"))){
                    case "0":{
                        isAfteravt = "是";
                        break;
                    }
                    case "1":{
                        isAfteravt = "否";
                        break;
                    }
                    default:isAfteravt = "";
                }
                miniInsert = new HashMap<>();
                miniInsert.put("FBILLTITLE",title);
                miniInsert.put("FNAME",workFlowNum);
                miniInsert.put("FPERSONNAME",applicant);
                miniInsert.put("FBILLSTATUS",state);
                miniInsert.put("SZBM",applicantDeptName);
                miniInsert.put("SZJG",orgname);
                miniInsert.put("LXFS",drafterTel);
                miniInsert.put("NGRQ",draftDate);
                miniInsert.put("HJCD",urgency);
                miniInsert.put("DCBM",leaveDeptName);
                miniInsert.put("DRBM",enterDeptName);
                miniInsert.put("RZRQ",enterPeriod);
                miniInsert.put("TZJE",AdjustMoney);
                miniInsert.put("FYLX",costType);
                miniInsert.put("SFSH",isAfteravt);
                miniInsert.put("HJXX",sumToSmart);
                miniInsert.put("HJDX",totalBig);
                miniInsert.put("BZ",remark);
                insertData.add(miniInsert);
            }
            bb.writeLog("数据待插入集合填装完毕：共有"+insertData.size()+"条数据");
            bb.writeLog(JSON.toJSONString(insertData));
//            数据库插入
            RecordSetDataSource ckRS = new RecordSetDataSource("BudgetRecords");
            try {
                for (Map<String, Object> everyData : insertData) {
                    sql="";
                    //insertSQL组装
                    String tablename = "" ;
                    String tablenvalue = "" ;
                    for (Map.Entry<String, Object> entry : everyData.entrySet()) {
                        String fieldname = Util.null2String(entry.getKey()).trim();
                        String fieldvalue = Util.null2String(entry.getValue()).replace("'", "''").trim();
                        tablename += tablename==""? fieldname :","+fieldname ;
                        tablenvalue += tablenvalue=="" ? "'"+fieldvalue+"'" :",'"+fieldvalue+"'" ;
                    }
                    if(tablename !="" && tablenvalue !=""){
                        sql += " insert into LC029999.CWKHTZB("+tablename+") values ("+ tablenvalue +");";
                        bb.writeLog("sql:"+sql);
                    }
                    ckRS.execute(sql);
                }
                back = SUCCESS;
            }catch (Exception e){
//                try {
//                    sql = "delete from LC029999.CWKHTZB where FNAME = '"+workFlowNum+"'";
//                }
                requestInfo.getRequestManager().setMessageid("104");
                requestInfo.getRequestManager().setMessagecontent("find error when Insertting");
                back = FAILURE_AND_CONTINUE;
            }


        }catch (Exception e){
            requestInfo.getRequestManager().setMessageid("104");
            requestInfo.getRequestManager().setMessagecontent("流程流转异常：" + e.getMessage());
            e.printStackTrace();
            writeLog(e.getMessage());
            back = FAILURE_AND_CONTINUE;
        }
        return back;
    }
    private static String digitCapital(double n) {
        String fraction[] = {"角", "分"};
        String digit[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
        String unit[][] = {{"元", "万", "亿"}, {"", "拾", "佰", "仟"}};

        String head = n < 0 ? "负" : "";
        // 如果是负数取绝对值
        n = Math.abs(n);
        String s = "";
        BigDecimal bigDecimal = new BigDecimal(Double.valueOf(n).toString());
        String nStr = bigDecimal.toString();
        // 小数部分
        String[] split = nStr.split("\\.");
        if (split.length > 1) {
            // 小数点为特殊符号，在分割时需进行转义
            String decimalStr = split[1];
            if (decimalStr.length() > 2) {
                decimalStr = decimalStr.substring(0, 2);
            }
            // 将小数部分转换为整数
            Integer integer = Integer.valueOf(decimalStr);
            String p = "";
            for (int i = 0; i < decimalStr.length() && i < fraction.length; i++) {
                p = digit[integer % 10] + fraction[decimalStr.length() - i - 1] + p;
                integer = integer / 10;
            }
            s = p.replaceAll("(零.)+", "") + s;
        }
        if (s.length() < 1) {
            s = "整";
        }
        int integerPart = (int)Math.floor(n);
        // 整数部分
        for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
            String p = "";
            for (int j = 0; j < unit[1].length && n > 0; j++) {
                p = digit[integerPart % 10] + unit[1][j] + p;
                integerPart = integerPart / 10;
            }
            s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s;
        }
        return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整");
    }
}
