package weaver.interfaces.htsc.cus;


import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.util.ArrayList;
import java.util.List;

/**
 * author: Weaver_nj_qlk
 * description: 出差申请办结前,
 * 保存明细2出差人集合到主表标题出差人(btccr);
 * 保存明细3第一行出发日期到主表行程开始日期(xcksrq)
 * 保存明细3最后一行返回日期到主表行程结束日期(xcjsrq)
 */
public class CcsqFinishNodeAction extends BaseBean implements Action {

    private final RecordSet rs = new RecordSet();

    @Override
    public String execute(RequestInfo requestInfo) {
        //流程requestId
        String requestId = Util.null2String(requestInfo.getRequestid());
        RequestManager requestManager = requestInfo.getRequestManager();
        //主表
        String tableName = Util.null2String(requestManager.getBillTableName());
        //明细表2
        String dt2TableName = tableName + "_dt2";
        //明细表3
        String dt3TableName = tableName + "_dt3";
        String dt4TableName = tableName + "_dt4";
        if ("".equals(requestId) || "".equals(tableName)) {
            requestManager.setMessagecontent("缺失有效参数,请检查CcsqFinishNodeAction接口");
            requestManager.setMessageid("500");
            return FAILURE_AND_CONTINUE;
        }
        //出差人
        List<String> ccrs = new ArrayList<>();
        String dt2_sql = String.format("select t1.xm from %s t1\n" +
                " left join %s t2\n" +
                " on t2.id=t1.mainid\n" +
                " where t2.requestid=?", dt2TableName, tableName);
        rs.executeQuery(dt2_sql, requestId);
        while (rs.next()) {
            ccrs.add(Util.null2String(rs.getString("xm")));
        }
        String btccr = String.join(",", ccrs);
        //首行出发日期,尾行返回日期
        String xcksrq = "";
        String xcjsrq = "";
        List<String> rqs = new ArrayList<>();
        String dt3_sql = String.format("select t1.cfsj,t1.fhsj from %s t1\n" +
                " left join %s t2\n" +
                " on t2.id=t1.mainid\n" +
                " where t2.requestid=?", dt4TableName, tableName);
        rs.executeQuery(dt3_sql, requestId);
        while (rs.next()) {
            rqs.add(Util.null2String(rs.getString("cfsj")));
            rqs.add(Util.null2String(rs.getString("fhsj")));
        }
        xcksrq = rqs.get(0);
        xcjsrq = rqs.get(rqs.size() - 1);
        //更新主表
        String update_sql = String.format(
                "update %s set btccr='%s', xcksrq='%s', xcjsrq='%s' where requestid=?",
                tableName, btccr, xcksrq, xcjsrq);
        rs.executeUpdate(update_sql, requestId);
        return SUCCESS;
    }
}
