package weaver.interfaces.htsc.yfkqrlc;

import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.htsc.yfkqrlc.util.ActionsUtil;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @Describe 新增预付款管理台账报表, 当网报付款流程中，票据明细中选项“是否先付款后提供发票”选择为“是”时，流程办结后数据进入此报表；
 * @tableName uf_PrepayMageAccRep
 */
public class DataAddAction extends BaseBean implements Action {

    @Override
    public String execute(RequestInfo requestInfo) {
        String back;
        RecordSet rs = new RecordSet();
        RecordSetTrans rst = new RecordSetTrans();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map mainInfo = ActionsUtil.getMainInfo(requestInfo);
        writeLog("主表数据是：" + JSONObject.toJSONString(mainInfo));
        if ("0".equals(Util.null2String(mainInfo.get("sfxfkhtgfp")))) {
//            票据明细中选项“是否先付款后提供发票”选择为“是”,需要将数据写入建模表
            // 当前付款流程的requestId
            String requestId = requestInfo.getRequestid();
            Map<String, Object> paramsMap = ActionsUtil.yfkParamsMap(requestId);
            String lcbh = Util.null2String(mainInfo.get("lcbh"));
            String ngr = Util.null2String(mainInfo.get("ngr"));
            String szbm = Util.null2String(mainInfo.get("szbm"));
            String lclx = getLclcByRequestid(requestId);
            writeLog("流程类型是："+lclx);
            String lczbm = Util.null2String(getLczbmByRequestId(requestId));
            writeLog("流程主表名是："+lczbm);

            // 办结时间
            String bjsj = df.format(new Date());
            // 合同编号---明细表4
            String htbh = ActionsUtil.getDataStringByRequestInfo("htbh", 4, requestInfo, "；");
            // 收款方---明细表11
            String skf = ActionsUtil.getDataStringByRequestInfo("skdw", 11, requestInfo, "；");
            // 费用确认流程编号
            String fyqrlcbh = Util.null2String(paramsMap.get("lcbh"));
            // 开票方
            String kpf = Util.null2String(paramsMap.get("kpf"));
            // 预付款金额
            String yfkje = Util.null2String(mainInfo.get("hjxxjezfmx"));
            // 已核销金额
            String yhxje = "".equals(Util.null2String(paramsMap.get("yhxje"))) ? "0.00" : Util.null2String(paramsMap.get("yhxje"));
            // 待核销金额---String.valueOf(Double.parseDouble(yfkje) - Double.parseDouble(yhxje));
            String dhxje = "".equals(yfkje)?"0.00":new BigDecimal((Double.parseDouble(yfkje) - Double.parseDouble(("".equals(yhxje)?"0.00":yhxje)))).setScale(2, RoundingMode.HALF_UP).toString();
            // 是否逾期，默认给否，具体由定时任务赋值
            String sfyq = "1";
            // 逾期天数，默认为0，具体由定时任务赋值
            String yqts = "0";
            // 付款状态，默认为1，待付款
            String fkzt = "1";
            // 建模权限所需字段
            String formmodeid = "";
            String modedatacreater = "1";
            String modedatacreatertype = "0";
            String modeuuid = UUID.randomUUID().toString();
            rs.execute("select k.id from modeinfo k inner join workflow_bill l on formid = l.id where l.tablename = 'uf_PrepayMageAccRep'");
            if (rs.next()) {
                formmodeid = Util.null2String(rs.getString("id"));
            }
            // 判断是否已经插入过数据
            rs.executeQuery("select id from uf_PrepayMageAccRep where REQUTID = '" + requestId + "'");
            if (rs.next()){
                String insertedId = Util.null2String(rs.getString("id"));
                rs.executeUpdate("delete from uf_PrepayMageAccRep where id = '"+insertedId+"'");
            }
            rst.setAutoCommit(false);
            String insertSql = "insert into uf_PrepayMageAccRep(REQUTID,fklcbh,jbr,jbbm,lcbjsj,htbh,skf,fyqrlcbh," +
                    "kpf,yfkje,yhxje,dhxje,sfyq,yqts,formmodeid,modedatacreater,modedatacreatertype,modeuuid,FKZT,LCLX,LCZBM) " +
                    "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            writeLog("即将执行添加台账表的insert sql 是：insert into uf_PrepayMageAccRep(REQUTID,fklcbh,jbr,jbbm,lcbjsj,htbh,skf,fyqrlcbh," +
                    "kpf,yfkje,yhxje,dhxje,sfyq,yqts,formmodeid,modedatacreater,modedatacreatertype,modeuuid) " +
                    "VALUES ('"+requestId+"','"+lcbh+"','"+ngr+"','"+szbm+"','"+bjsj+"','"+htbh+"','"+skf+"','"+fyqrlcbh+"','"+kpf+"','"+yfkje+"','"+yhxje+"','"+dhxje+"','"+sfyq+"','"+yqts+"','"+formmodeid+"','"+modedatacreater+"','"+modedatacreatertype+"','"+modeuuid+"')");
            try {
                rst.executeUpdate(insertSql,requestId,lcbh,ngr,szbm,bjsj,htbh,skf,fyqrlcbh,
                        kpf,yfkje,yhxje,dhxje,sfyq,yqts,formmodeid,modedatacreater,modedatacreatertype,modeuuid,fkzt,lclx,lczbm);
                rst.commit();
                // 权限重构
                int dataId = ActionsUtil.getDataIdByUUID(modeuuid,"uf_PrepayMageAccRep");
                ModeRightInfo modeRightInfo = new ModeRightInfo();
                modeRightInfo.editModeDataShare(1, Integer.parseInt(formmodeid), dataId);
                back = SUCCESS;
            } catch (Exception e) {
                e.printStackTrace();
                back = FAILURE_AND_CONTINUE;
                writeLog("数据插入失败，"+e.getMessage());
            }
        } else {
            back = SUCCESS;
            writeLog("“是否先付款后提供发票”选择为“否”，不需要将流程数据写入建模表");
        }
        return back;
    }

    /**
     * 根据流程编号获取流程类型
     * @param requestid
     * @return
     */
    private String getLclcByRequestid(String requestid){
        RecordSet rs = new RecordSet();
        rs.executeQuery("select b.unnumber as jc from workflow_requestbase a join workflow_base b on a.WORKFLOWID = b.id where a.REQUESTID = ?",requestid);
        if (rs.next()){
            return Util.null2String(rs.getString("jc"));
        }else {
            return "";
        }
    }

    private String getLczbmByRequestId(String requestId) {
        RecordSet rs = new RecordSet();
        String sql = "select t2.tablename from workflow_requestbase t0,workflow_base t1,workflow_bill t2 where t0.workflowid = t1.id and t1.formid = t2.id and  t0.requestid = ?";
        rs.executeQuery(sql,requestId);
        if (rs.next()){
            return Util.null2String(rs.getString("tablename"));
        }else {
            return "";
        }
    }
}
