package com.engine.htsc.payment.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.htsc.payment.dao.BudgetDao;
import com.engine.htsc.payment.model.LeaderViewBaseModel;
import com.engine.htsc.payment.model.LeaderViewModel;
import com.engine.htsc.payment.service.BudgetService;
import com.engine.htsc.payment.service.impl.BudgetServiceImpl;
import com.engine.htsc.payment.service.impl.BxBudgetServiceImpl;
import com.engine.htsc.payment.service.impl.ClBxBudgetServiceImpl;
import com.engine.htsc.payment.util.PayUtil;
import com.engine.htsc.trip.util.AjaxResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;
import weaver.interfaces.htsc.cwtz.AddBudgetMidTable;
import weaver.interfaces.htsc.payment.PrePaymentInterfaceInvoke;
import weaver.soa.workflow.request.RequestInfo;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 预算接口, 帆帆
 */
public class BudgetInterfacelWeb {


    //入参日期格式
    static DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    BudgetDao budgetDao = new BudgetDao();


    /**
     * 同步财务调增到预算系统中间表
     * @return
     */
    @POST
    @Path("/reSyncFinancialAdjustToBudgetMiddle")
    public AjaxResult<String> reSyncFinancialAdjust(){
        try {
            AddBudgetMidTable addBudgetMidTable = new AddBudgetMidTable();
            RecordSet rs = new RecordSet();
            String sql = "select t.reqid,t.lcbh from uf_dsrwdb t where t.rwlx='CWTZYS'";
            rs.executeQuery(sql);
            while (rs.next()){
                RequestInfo requestInfo = new RequestInfo();
                requestInfo.setRequestid(Util.null2String(rs.getString("reqid")));
                addBudgetMidTable.execute(requestInfo);
            }
            return AjaxResult.ok("success");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     *  查询领导者视图
     * @return
     */
    @POST
    @Path("/queryLeaderView")
    @Produces({MediaType.APPLICATION_JSON})
    public AjaxResult<List<LeaderViewModel>> queryLeaderView(@Context HttpServletRequest request){
        //当前操作者id
        List<LeaderViewModel> leaderViewModelList = new ArrayList<>();
        String operator = Util.null2String(request.getParameter("operatorId"));
        String requestId = Util.null2String(request.getParameter("requestId"));
        /**
         * 测试时的代码
         */
//        requestId = "5776780";
//        operator = "26377";
        //生产删除
        List<String> bmidList = new ArrayList<>();
//        String queryBmid = " select deptid from HRMDEPARTMENTDEFINED t where ','||t.deptdirectors||',' like '%," + operator + ",%' ";
        String queryBmid = " select departmentid from hrmresource t where t.id= " + operator;
        RecordSet rs = new RecordSet();
        rs.executeQuery(queryBmid);
        while (rs.next()){
            bmidList.add(Util.null2String(rs.getString("departmentid")));
        }
        Map<String, String> allBudget = JAVATools.getAllBudget();
        Map<String, Map<String, Object>> leaderViewMap = new HashMap<>();
        String queryLeaderView = " select t.REQUESTID,t.LCBH,t.YSKMBM,t.YSKMMC,t.YSKMBMLJ,t.YSKMMCLJ,t.LJYZS,t.LJZXS,t.YSS,t.LJYYBFB,t.BMID,t.BMMC,t.BMBM,t.groupid  from uf_leaderView t";
        rs.execute(queryLeaderView);
        while (rs.next()){
            Map<String, Object> leaderView = new HashMap<>();
            leaderView.put("YSKMBM",rs.getString("YSKMBM"));
            leaderView.put("YSKMMC",rs.getString("YSKMMC"));
            leaderView.put("YSKMBMLJ",rs.getString("YSKMBMLJ"));
            leaderView.put("YSKMMCLJ",rs.getString("YSKMMCLJ"));
            leaderView.put("LJYZS",rs.getString("LJYZS"));
            leaderView.put("LJZXS",rs.getString("LJZXS"));
            leaderView.put("YSS",rs.getString("YSS"));
            leaderView.put("LJYYBFB",rs.getString("LJYYBFB"));
            leaderView.put("BMID",rs.getString("BMID"));
            leaderView.put("BMMC",rs.getString("BMMC"));
            leaderView.put("BMBM",rs.getString("BMBM"));
            leaderViewMap.put(rs.getString("YSKMBM") + "-" + rs.getString("BMID"), leaderView);
        }

        RecordSet rst = new RecordSet();
        if(CollectionUtils.isNotEmpty(bmidList)) {
            String bmIdStr = StringUtils.join(bmidList, "','");
            String sql  = " select t.REQUESTID,t.LCBH,t.YSKMBM,t.YSKMMC,t.YSKMBMLJ,t.YSKMMCLJ,t.BMID,t.BMMC,t.BMBM,t.groupid  " +
                    " from uf_leaderViewBase t where requestid = " + requestId +" and bmid in ('" + bmIdStr + "')";
            JAVATools.writelog("queryLeaderViewBase endSql :" + sql);
            rst.executeQuery(sql);
            while (rst.next()){
                LeaderViewModel leaderViewModel = new LeaderViewModel();
                String YSKMBMLJ = Util.null2String(rst.getString("YSKMBMLJ"));
                String level2Code = YSKMBMLJ.split("-")[1];
                String bmid = Util.null2String(rst.getString("BMID"));
                leaderViewModel.setYskmbm(level2Code);
                leaderViewModel.setYskmmc(allBudget.get(level2Code));
                leaderViewModel.setDeptId(bmid);
                leaderViewModel.setDeptCode(Util.null2String(rst.getString("BMBM")));
                leaderViewModel.setDeptName(Util.null2String(rst.getString("BMMC")));
                Map<String, Object> stringObjectMap = leaderViewMap.get(level2Code + "-" + bmid);
                leaderViewModel.setTotalBudget(stringObjectMap.get("YSS").toString());
                leaderViewModel.setPreUsedBudget(stringObjectMap.get("LJYZS").toString());
                leaderViewModel.setUsedBudget(stringObjectMap.get("LJZXS").toString());
                leaderViewModel.setUsedPercent(stringObjectMap.get("LJYYBFB").toString());
//
                List<LeaderViewBaseModel> baseModelList = new ArrayList<>();
                String groupid = rst.getString("groupid");
                String sqlGroup = " select t.REQUESTID,t.LCBH,t.YSKMBM,t.YSKMMC,t.YSKMBMLJ,t.YSKMMCLJ,t.BMID,t.BMMC,t.BMBM,t.groupid " +
                        " from uf_leaderViewBase t where groupid ='" + groupid + "' and t.REQUESTID is null order by id";
                RecordSet rstq = new RecordSet();
                rstq.executeQuery(sqlGroup);
                while (rstq.next()){
                    LeaderViewBaseModel baseModel = new LeaderViewBaseModel();
                    String yskmbm = Util.null2String(rstq.getString("YSKMBM"));
                    baseModel.setYskmbm(yskmbm);
                    baseModel.setYskmmc(Util.null2String(rstq.getString("YSKMMC")));
                    baseModel.setUsedPercent(Util.null2String(rstq.getString("LJYYBFB")));
                    Map<String, Object> stringObjectMapsub = leaderViewMap.get(yskmbm + "-" + bmid);
                    baseModel.setTotalBudget(stringObjectMapsub.get("YSS").toString());
                    baseModel.setPreUsedBudget(stringObjectMapsub.get("LJYZS").toString());
                    baseModel.setUsedBudget(stringObjectMapsub.get("LJZXS").toString());
                    baseModel.setUsedPercent(stringObjectMapsub.get("LJYYBFB").toString());
                    baseModelList.add(baseModel);
                }
                leaderViewModel.setYskmList(baseModelList);
                leaderViewModelList.add(leaderViewModel);

            }
            return AjaxResult.ok(leaderViewModelList);
        }

        return AjaxResult.error();

    }

    @POST
    @Path("/reSyncHesuan")
    @Produces(MediaType.APPLICATION_JSON)
    public String reSyncHesuan(@Context HttpServletRequest request) throws Exception{
        String requestIds = Util.null2String(request.getParameter("requestIds"));
        String tableName = Util.null2String(request.getParameter("tableName"));
        String[] requestIdList = requestIds.split(",");
        PrePaymentInterfaceInvoke prePaymentInterfaceInvoke = new PrePaymentInterfaceInvoke();
        for(String reqId : requestIdList){
            prePaymentInterfaceInvoke.doBudgetCost(reqId, tableName);
        }
        return "success";
    }


    @POST
    @Path("/reSyncMiddle")
    @Produces(MediaType.APPLICATION_JSON)
    public String reSyncBudgetMiddle(@Context HttpServletRequest request) {
        String requestIds = Util.null2String(request.getParameter("requestIds"));
        List<String> requestIdList = Arrays.asList(requestIds.split(","));
        BudgetServiceImpl budgetService = new BudgetServiceImpl();
        BxBudgetServiceImpl bxBudgetService = new BxBudgetServiceImpl();
        ClBxBudgetServiceImpl clBxBudgetService = new ClBxBudgetServiceImpl();
        for (String requestId : requestIdList) {
            String tableName = "";
            String code = "";
            String lcbh = "";
            //获取流程类型获取其主表名
            String sql = "select t1.tablename, t2.ECOLOGY_PINYIN_SEARCH as code,t2.WORKFLOWNAME\n" +
                    "  from workflow_bill t1, workflow_base t2, workflow_requestbase t3\n" +
                    " where t1.id = t2.formid\n" +
                    "   and t2.id = t3.workflowid\n" +
                    "   and t3.requestid = " + requestId;
            RecordSet rs = new RecordSet();
            JAVATools.writelog("requestId:" + requestId + "根据requestId获取流程类型和主表名Sql: " + sql);
            rs.executeQuery(sql);
            if (rs.next()) {
                tableName = Util.null2String(rs.getString("tableName"));
                code = Util.null2String(rs.getString("code"));
            }
            if (StringUtils.isNotEmpty(tableName)) {
                String sqlMain = "select lcbh from " + tableName + " where requestId = " + requestId;
                rs.execute(sqlMain);
                if (rs.next()) {
                    lcbh = Util.null2String(rs.getString("lcbh"));
                }
            }
            RecordSetDataSource rsdM = new RecordSetDataSource("BudgetRecords");
            String budgetTableName = new PropBean().getPropName("BudgetTableName");
            String sql1 = "select t.FBILLSTATUS,t.FBIZDATE from " + budgetTableName + " t where t.FNAME = '" + lcbh + "'";
            String status = "";
            String fdate="";
            rsdM.execute(sql1);
            if (rsdM.next()) {
                status = Util.null2String(rsdM.getString("fbillstatus"));
                fdate = Util.null2String(rsdM.getString("fbizdate"));
            }
            if (StringUtils.isNotEmpty(status)) {
                if ("zbghfk".equals(code) || "yfkfyqr".equals(code) || "zbitfk".equals(code) || "zbtyfk".equals(code) || "fzjgtyfk".equals(code) || "fyft".equals(code)) {
                    //通用付款
                    JAVATools.writelog("requestId:" + requestId + "lcbh: " + lcbh + "status:" + status);
                    String sqlFK = "select fkxx,fklx from " + tableName + " where requestId = " + requestId;
                    rs.execute(sqlFK);
                    String fkxx = "";
                    boolean isItFlag = false;
                    if (rs.next()) {
                        fkxx = Util.null2String(rs.getString("fkxx"));
                        isItFlag = "1".equals(Util.null2String(rs.getString("fklx")));
                    }
                    String dtTable = "0".equals(fkxx) ? tableName + "_dt8" : tableName + "_dt9";
                    budgetService.doBudgetMiddleTable(lcbh, status, fdate, dtTable, tableName, isItFlag);
                } else if ("zbtybx".equals(code) || "fzjgtybx".equals(code)) {
                    //通用报销
                    JAVATools.writelog("requestId:" + requestId + "lcbh: " + lcbh + "status:" + status);
                    bxBudgetService.doBudgetMiddleTable(lcbh, status,fdate, Arrays.asList(tableName + "_dt8", tableName + "_dt9"), tableName);
                } else if ("zbclbx".equals(code) || "fzjgclbx".equals(code)) {
                    //差旅报销
                    JAVATools.writelog("requestId:" + requestId + "lcbh: " + lcbh + "status:" + status);
                    clBxBudgetService.doBudgetMiddleTable(lcbh, status,fdate, Arrays.asList(tableName + "_dt9"), tableName);
                }
            }
        }
        return "success";
    }

    @POST
    @Path("/SyncbugetLC")
    @Produces(MediaType.APPLICATION_JSON)
    public String SyncbugetLC(@Context HttpServletRequest request) {
        JSONObject returnobject = new JSONObject();
        String requestids = Util.null2String(request.getParameter("requestid"));
        String modetable = Util.null2String(request.getParameter("modetable"));
        String billStatus = Util.null2String(request.getParameter("billStatus"));
        String datavalue = "";
        //  RequestManager requestManager = requestInfo.getRequestManager();
        try {
            if ("".equals(requestids) || "".equals(modetable)) {
                returnobject.put("code", "201");
                returnobject.put("error", "没有传参");
                return returnobject.toJSONString();
            }
            //get参数放sql注入
            modetable = JAVATools.getpreventsql(modetable);
            requestids = JAVATools.getpreventsql(requestids);


            // 主表

            for (String requestId : requestids.split(",")) {

                String tableName = JAVATools.getMaintable(requestId);// requestManager.getBillTableName();

                boolean flag = service(requestId, tableName, billStatus, modetable);
                if (!flag) {
                    datavalue += requestId + ",";
                }

            }
            if (!"".equals(datavalue) && datavalue.length() > 1) {
                datavalue = datavalue.substring(0, datavalue.length() - 1);
            }
            returnobject.put("code", "200");
            returnobject.put("data", datavalue);


            return returnobject.toJSONString();
        } catch (Exception e) {

            returnobject.put("code", "500");
            returnobject.put("error", "发生异常：" + e.getMessage());
            return returnobject.toJSONString();
        }
    }

    private Boolean service(String requestId, String tableName, String billStatus, String ModeTable) throws Exception {
        JSONObject params = new JSONObject();
        JSONObject returnobject = new JSONObject();
        RecordSet rs = new RecordSet();
        Boolean flag = true;
        ResourceComInfo rc = new ResourceComInfo();
        DepartmentComInfo dc = new DepartmentComInfo();

        //    String requestId = requestInfo.getRequestid();
        String budgetInvokeParam = budgetDao.mainFieldParam(tableName, requestId);
        rs.executeQuery(budgetInvokeParam);
        String bz = "0"; //对应fkxx字段
        String lcbh = "";
        String requestname = "";
        String ngr = "";
        String mainId = "";
        if (rs.next()) {
            lcbh = Util.null2String(rs.getString("lcbh"));
            ngr = Util.null2String(rs.getString("ngr"));
            mainId = Util.null2String(rs.getString("id"));
            bz = Util.null2String(rs.getString("fkxx"));
            requestname = Util.null2String(rs.getString("requestname"));

        }


        String yskmTable = tableName + "_dt8"; //预算科目表，本币dt8，外币dt9，主表字段fkxx区分
        if ("1".equals(bz)) {
            yskmTable = tableName + "_dt9";
        }
        params.put("billnum", requestId);
        params.put("billname", lcbh);
        params.put("billstatus", billStatus);
        params.put("billtitle", requestname);
        params.put("personName", rc.getLastname(ngr));
        params.put("bizdate", df.format(LocalDateTime.now()));
        JAVATools.SetCmdwritelog("同步到浪潮预算", ">>主表字段获取: @" + params + "@");
        rs.executeQuery(budgetDao.isItPay(tableName, lcbh));

        boolean isItFlag = false;
        if (rs.next()) {
            if ("1".equals(Util.null2String(rs.getString("FKLX")))) {
                isItFlag = true;
            }
        }
        JSONArray levelList = new JSONArray();

        String yskmTableFieldParam = budgetDao.yskmTableFieldParam(yskmTable, mainId);
        rs.executeQuery(yskmTableFieldParam);
        int i = 1;
        while (rs.next()) {
            JSONObject level = new JSONObject();
            String fycdbmfzr = Util.null2String(rs.getString("fycdbmfzr")); //费用承担部门负责人
            String fysjcdbm = Util.null2String(rs.getString("fysjcdbm")); //费用承担部门
            String yskm = Util.null2String(rs.getString("yskm")); //预算科目
            level.put("employeeNum", PayUtil.splitBmfzrThenJoin(fycdbmfzr, rc));
            level.put("deptNum", fysjcdbm);
            level.put("bgitem", PayUtil.superBudgetSubject(yskm)); //上级科目编码
            level.put("bgElement", "0101"); // 费用类型编码（默认传0101）
            level.put("billEntryID", UUID.randomUUID().toString() + "#" + i);
            level.put("itemEntryNum", yskm);
            //科目对应金额
            level.putAll(getKjKmCharges(yskmTable, mainId, isItFlag));
            levelList.add(level);
            i++;
        }
        if (i == 1) {
            //没有明细
            JAVATools.SetCmdwritelog("同步到浪潮预算" + requestId, "没有分摊的预算科目，流程提交");
            return true;
        }
        params.put("list", levelList);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("data", params);
        JAVATools.SetCmdwritelog("同步到浪潮预算" + requestId, ">>预算接口调用参数 params : @" + params + "@");
        String resp = new HTUtil().budgetCommit(dataMap);
        JAVATools.SetCmdwritelog("同步到浪潮预算" + requestId, ">>预算接口调用返回 resp : @" + resp + "@");
        if (!"F1001".equals(resp)) {
            flag = false;
            JAVATools.SetCmdwritelog("同步到浪潮预算" + requestId, "预算接口执行失败!返回值" + resp);
        } else {
            BudgetService bds = new BudgetServiceImpl();
            boolean isUpdate = true;
            //    bds.doBudgetMiddleTable(lcbh, billStatus, yskmTable, tableName, isItFlag);
            isUpdate = bds.dobugetModeUpdateYs(requestId, ModeTable);


            if (isUpdate) {

                flag = true;
            } else {
                JAVATools.SetCmdwritelog("同步到浪潮预算：" + requestId, "节点后附加操作更新预算表失败!返回值");
                flag = false;
            }
        }

        return flag;
    }

    /**
     * 预算明细表8或9 取科目对应数据
     * 金额,是否超标,实际金额,标准金额,不含税价金额,税金
     *
     * @param budgetKmTable 预算明细表
     * @param mainId        流程mainId
     * @param isIt          是否it付款
     * @return map
     */
    public JSONObject getKjKmCharges(String budgetKmTable, String mainId, boolean isIt) {
        RecordSet rs = new RecordSet();
        JSONObject subParam = new JSONObject();
        String yskmAmountParam = budgetDao.budgetKmTableInfo(budgetKmTable, mainId, isIt);
        rs.executeQuery(yskmAmountParam);
        if (rs.next()) {
            if (budgetKmTable.toLowerCase().contains("dt8")) {
                String JSHJJE = Util.null2String(rs.getString("JSHJJE"));
                String CYS = Util.null2String(rs.getString("CYS"));
                String BHSJE = Util.null2String(rs.getString("BHSJE"));
                String SJ = Util.null2String(rs.getString("SJ"));
                subParam.put("amount", JSHJJE); // 金额
                subParam.put("overweight", PayUtil.overWeight(CYS)); // 是否超标
                subParam.put("actualAmount", ""); // 实际金额
                subParam.put("standardAmount", ""); // 标准金额
                subParam.put("notaxAmount", BHSJE); // 不含价税金额
                subParam.put("taxAmount", SJ); //税金
            } else {
                String JSHJJE = Util.null2String(rs.getString("rmbje")); // 人民币金额
                String CYS = Util.null2String(rs.getString("CYS"));
                subParam.put("amount", JSHJJE); // 金额
                subParam.put("overweight", PayUtil.overWeight(CYS)); // 是否超标
                subParam.put("actualAmount", ""); // 实际金额
                subParam.put("standardAmount", ""); // 标准金额
                subParam.put("notaxAmount", "0.00"); // 不含价税金额
                subParam.put("taxAmount", "0.00"); //税金
            }

        }
        return subParam;
    }
}
