package com.engine.htsc.capitalbusinessPayment.service;


import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ParamUtil;
import com.engine.core.impl.Service;
import com.engine.htsc.capitalbusinessPayment.Constants.Constant;
import com.engine.htsc.capitalbusinessPayment.dao.OperateLiquidationDataDao;
import com.engine.htsc.convertor.EcologyValueConvertor;
import com.engine.htsc.doc.model.UserInfoModel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.common.StringUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;
import weaver.workflow.workflow.WfForceOver;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 资金业务付款服务类
 */
public class CapitalBusinessPaymentService extends Service {

    private final Log log = LogFactory.getLog(CapitalBusinessPaymentService.class);

    private BaseBean bb = new BaseBean();


    /**
     * 自动付款
     * @param ids  前端requestids
     * @param  userId
     * @return
     * @throws Exception
     */
    public String doAutoPay(String ids, String userId) throws Exception {
        Constant.PAYTYPE paytype = Constant.PAYTYPE.AUTO;
        log.info("====自动付款开始====");
        if(!checkValidPay(paytype,ids)) {
            log.info("====包含已付款数据，不能修改!====");
            throw new Exception("包含已付款数据，不能修改!");
        }
        synPaydetail(paytype, ids, userId);
        return "数据已开始修改，请刷新列表查看状态";
    }

    /**
     * 手动付款
     * @param ids
     * @param userId
     * @return
     * @throws Exception
     */
    public String doManualPay(String ids, String userId) throws Exception {
        Constant.PAYTYPE paytype = Constant.PAYTYPE.MANUAL;
        log.info("====手动付款开始====");
        if(!checkValidPay(paytype,ids)) {
            log.info("====包含已付款数据，不能修改!====");
            throw new Exception("包含已付款数据，不能修改!");
        }
        synPaydetail(paytype, ids, userId);
        return "数据已开始修改，请刷新列表查看状态";
    }

    /**
     * 自动付款+手动付款 通用处理步骤
     * @param ids
     * @param userId
     * @throws Exception
     */
    public void synPaydetail(Constant.PAYTYPE payType, String ids, String userId) throws Exception {
        bb.writeLog("ids:"+ids+" 开始付款 synPaydetail payType:"+payType+" userId:"+userId);
        OperateLiquidationDataDao dao = new OperateLiquidationDataDao();
        UserInfoModel user = EcologyValueConvertor.getUserInfoModelById(userId);
        String result = "";
        List<String> idArray = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        for(String id : idArray) {
            String requestid = "";
            String workflownum = "";
            RecordSet rs = new RecordSet();
            String sql = " select t.reqid,t.WORKFLOW_NUM from uf_paydetal t where t.id = (" + id + ") ";
            log.info("查询requestid和workflow_num" + sql);
            rs.execute(sql);
            if(rs.next()) {
                requestid = rs.getString("reqid");
                workflownum = rs.getString("WORKFLOW_NUM");
            }

            //修改数据库支付记录状态
            updatePayStatus(payType, id);

            //保存数据到数据中心
            dao.saveToDC(requestid,user);

            // 调用泛微接口强制归档办结
            forceArchive(userId,id);

            // 更新付款表的办结时间
            String sqlUpdate = " update uf_paydetal t set t.endtime = to_char(SYSDATE,'YYYY-MM-DD HH24:MI:SS')  where t.id  = '"+id+"' ";
            log.info("更新付款表的办结时间sql" + sql);
            rs.execute(sqlUpdate);

            // 如果是衡泰触发的  调用xquantServiceInvoke
            sendXquant(workflownum,requestid);
        }

    }

    /**
     * 检查是否有存在已付款记录
     * @param payType
     * @param ids
     * @return
     * @throws Exception
     */
    public boolean checkValidPay(Constant.PAYTYPE payType, String ids) throws Exception {
        RecordSet rs =new RecordSet();
        if(Constant.PAYTYPE.AUTO.equals(payType)) {
            String sql = " select t.payflag from uf_paydetal t where t.payflag in ('1','9') and t.id in (" + ids + ") ";
            log.info("检查是否有存在已付款记录Sql" + sql);
            rs.executeQuery(sql);
            if(rs.next()) {
                return false;
            }
        }else if(Constant.PAYTYPE.MANUAL.equals(payType)){
            String sql = " select t.payflag from uf_paydetal t where t.payflag = '1' and t.id in (" + ids + ") ";
            log.info("检查是否有存在已付款记录Sql" + sql);
            rs.executeQuery(sql);
            if(rs.next()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 更新付款状态和时间
     * @param payType
     * @param id
     */
    public void updatePayStatus(Constant.PAYTYPE payType, String id) {
        RecordSet rs =new RecordSet();
        bb.writeLog("更新付款状态和时间 id:"+id+" payType:"+payType);
        if(Constant.PAYTYPE.AUTO.equals(payType)) {
            String sql = " update uf_paydetal t set t.payflag = '9',t.paytype = 'AUTO' ,t.set_auto_time = to_char(SYSDATE,'YYYY-MM-DD HH24:MI:SS')  where t.id  = '"+id+"' ";
            log.info("更新付款状态和时间sql" + sql);
            rs.execute(sql);
        }else if(Constant.PAYTYPE.MANUAL.equals(payType)) {
            String sql = " update uf_paydetal t set t.payflag = '1',t.paytype = 'MANUAL' where t.id  = '"+id+"' ";
            log.info("更新付款状态和时间sql" + sql);
            rs.execute(sql);
        }
    }

    //调用衡泰接口
    public void sendXquant(String workflownum,String requestid){
        bb.writeLog("requestId:"+requestid+" sendXquant workflownum:"+workflownum+" 调用衡泰接口");
        RecordSet rs = new RecordSet();
        String mainTableName = EcologyValueConvertor.getMainTableNameByRequestId(requestid);
        String sql = " select t.autoLaunchPlatformId from "+mainTableName+" t where t.requestid = '"+requestid+"'";
        log.info("查询是否调用衡泰接口:" + sql);
        rs.execute(sql);
        if(rs.next()) {
            String autoLaunchPlatformId = rs.getString("autoLaunchPlatformId");
            if(null!=autoLaunchPlatformId&&"衡泰".equals(autoLaunchPlatformId)){
                PropBean pb = new PropBean();
                String url = pb.getPropName("XQuantUrl");;
                Map<String, String> headers = new HashMap<>();
                JSONObject jsonObject = new JSONObject();
                //流程业务编号
                jsonObject.put("workflownum",workflownum);
                //流程业务唯一编码
                jsonObject.put("workflownumber",requestid);
                //是否终止
                jsonObject.put("isZZ","否");
                bb.writeLog("sendPost url:"+url+" params:" + jsonObject.toJSONString()+" sendPost发送请求到衡泰");
                sendPost(url,jsonObject.toJSONString(),headers);
            }
        }
    }

    //强制归档
    public void forceArchive(String userId,String ids){
        bb.writeLog("forceArchive userId:"+userId+" ids:" + ids+ " 强制归档");
        User user = new User();
        user.setUid(Integer.valueOf(userId).intValue());
        user.setLogintype("1");
        WfForceOver wfo = new WfForceOver();
        ArrayList requestidlist = new ArrayList();
        RecordSet rs =new RecordSet();
        String sql = " select t.reqid from uf_paydetal t where t.id in (" + ids + ") ";
        log.info("强制归档获取requestid" + sql);
        rs.execute(sql);
        while (rs.next()){
            requestidlist.add(Util.null2String(rs.getString("reqid")));
        }
        String remark = "流程强制归档";
        wfo.setRemark(remark);
        wfo.doForceOver(requestidlist, null, null, user);
    }

    /***
     *
     * @param url
     * @param params
     * @param headsMap
     * @return
     */
    public String sendPost(String url, String params, Map<String,String> headsMap)
    {
        //BaseBean bb = new BaseBean();
        String body = "";
        String encoding = "UTF-8";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);


        //设置参数到请求对象中
        StringEntity strEntity = new StringEntity(params,encoding);//解决中文乱码问题
        strEntity.setContentEncoding(encoding);
        strEntity.setContentType("application/json");
        httpPost.setEntity(strEntity);

        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        if (headsMap != null && !headsMap.isEmpty()) {
            headsMap.forEach((key, value) -> {
                //bb.writeLog("key:"+key+" value:"+value);
                httpPost.addHeader(key, value);
            });
        }
        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (IOException e) {
            System.out.println("OrganizationSyn-e:"+e);
            e.printStackTrace();
        }
        return body;
    }

    //流程终止,强制归档
    public String doEndProcess(String requestid, String userId)  throws Exception {
        // 调用泛微接口强制归档办结
        log.info("====流程终止,强制归档开始,requestid:"+requestid+"====");
        User user = new User();
        user.setUid(Integer.valueOf(userId).intValue());
        user.setLogintype("1");
        WfForceOver wfo = new WfForceOver();
        ArrayList requestidlist = new ArrayList();
        requestidlist.add(requestid);
        String remark = "流程强制归档";
        wfo.setRemark(remark);
        wfo.doForceOver(requestidlist, null, null, user);
        sendXquantByRequestIdEnd(requestid);
        return "success";

    }

    //Action调用衡泰接口
    public void sendXquantByRequestId(String requestid) {
        bb.writeLog("requestid:"+requestid+" sendXquantByRequestId Action调用衡泰接口");
        RecordSet rs = new RecordSet();
        String mainTableName = EcologyValueConvertor.getMainTableNameByRequestId(requestid);
        String sql = "select t.autoLaunchPlatformId,t.lcbh from "+mainTableName+" t where t.requestid = '"+requestid+"'";
        log.info("查询是否调用衡泰接口:" + sql);
        rs.execute(sql);
        if(rs.next()) {
            String autoLaunchPlatformId = Util.null2String(rs.getString("autoLaunchPlatformId"));
            String workflownum = Util.null2String(rs.getString("lcbh"));
            if("衡泰".equals(autoLaunchPlatformId)){
                PropBean pb = new PropBean();
                String url = pb.getPropName("XQuantUrl");;
                Map<String, String> headers = new HashMap<>();
                JSONObject jsonObject = new JSONObject();
                //流程业务编号
                jsonObject.put("workflownum",workflownum);
                //流程业务唯一编码
                jsonObject.put("workflownumber",requestid);
                //是否终止
                jsonObject.put("isZZ","否");
                bb.writeLog("sendPost url:"+url+" params:" + jsonObject.toJSONString()+" sendPost发送请求到衡泰");
                sendPost(url,jsonObject.toJSONString(),headers);
            }
        }
    }

    public void sendXquantByRequestIdEnd(String requestid) {
        bb.writeLog("requestid:"+requestid+" sendXquantByRequestIdEnd 流程终止调用衡泰接口");
        RecordSet rs = new RecordSet();
        String mainTableName = EcologyValueConvertor.getMainTableNameByRequestId(requestid);
        String sql = "select t.autoLaunchPlatformId,t.lcbh from "+mainTableName+" t where t.requestid = '"+requestid+"'";
        log.info("查询是否调用衡泰接口:" + sql);
        rs.execute(sql);
        if(rs.next()) {
            String autoLaunchPlatformId = Util.null2String(rs.getString("autoLaunchPlatformId"));
            String workflownum = Util.null2String(rs.getString("lcbh"));
            if("衡泰".equals(autoLaunchPlatformId)){
                PropBean pb = new PropBean();
                String url = pb.getPropName("XQuantUrl");;
                Map<String, String> headers = new HashMap<>();
                JSONObject jsonObject = new JSONObject();
                //流程业务编号
                jsonObject.put("workflownum",workflownum);
                //流程业务唯一编码
                jsonObject.put("workflownumber",requestid);
                //是否终止
                jsonObject.put("isZZ","是");
                bb.writeLog("sendPost url:"+url+" params:" + jsonObject.toJSONString()+" sendPost发送请求到衡泰");
                sendPost(url,jsonObject.toJSONString(),headers);
            }
        }
    }

}
