package com.engine.htsc.seal.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.htsc.seal.entity.ApplyPrintEntity;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.GlobatTools.MessageDetailLog;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;

import java.text.SimpleDateFormat;
import java.util.*;

public class SendApplyPrintService extends Service {

    /**
     * 触发用印信息变更
     * @param user
     * @param requestid
     * @param docids
     * @return
     */
    public String SendApplyPrint(User user, String requestid, String docids, String bglx){
        PropBean pb = new PropBean();
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        HTUtil htUtil = new HTUtil();
        JSONObject resobject=new JSONObject();

        String appid = Util.null2String(pb.getPropName("AutoSign.appId"));//应用ID
        String secret = Util.null2String(pb.getPropName("AutoSign.secret"));//秘钥

        try{
            String tableName = JAVATools.getMaintable(requestid);
            MessageDetailLog messageDetailLog = new MessageDetailLog(tableName);

            String mainid = "";
            String sql = "select id from "+tableName+" where requestid = "+requestid;
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                mainid = Util.null2String(rs.getString("id"));
            }

            for(String docid:docids.split(",")){
                ApplyPrintEntity applyPrint = new ApplyPrintEntity();
                applyPrint.setAppId(appid);
                applyPrint.setSecret(secret);

                String yyid = "";
                sql = "select id,dsmdy,yqxdyr,fwdyfs,yyid from "+tableName+"_dt1 where mainid = '"+mainid+"' and wjmc = '"+docid+"' or scwj = '"+docid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    yyid = Util.null2String(rs.getString("yyid"));
                    applyPrint.setDocId(yyid);

                    //有权限打印人
                    String yqxdyr = Util.null2String(rs.getString("yqxdyr"));
                    yqxdyr += ","+user.getUID();
                    List<String> yqxdyrList = Arrays.asList(yqxdyr.split(","));
                    List<String> useridList = new ArrayList<>();
                    List<String> usernameList = new ArrayList<>();
                    if(StringUtils.isNotEmpty(yqxdyr)){
                        for(String id:yqxdyrList){
                            User u = new User(Integer.parseInt(id));
                            useridList.add(JAVATools.getHrmworkcode(u.getLoginid()));
                            usernameList.add(u.getUsername());
                        }
                    }
                    String useridStr = StringUtils.join(useridList, ",");
                    String usernameStr = StringUtils.join(usernameList, ",");
                    applyPrint.setPersonNum(useridStr);
                    applyPrint.setPersonName(usernameStr);

                    //防伪打印份数
                    String fwdyfs = Util.null2String(rs.getString("fwdyfs"));
                    if("1".equals(bglx)){//增加
                        applyPrint.setPrintNum(fwdyfs);
                    }else if("4".equals(bglx)){//减少
                        applyPrint.setPrintNum("-"+fwdyfs);
                    }
                    SealInformationService sealInformationService = ServiceUtil.getService(SealInformationService.class);
                    JSONObject printInfo = sealInformationService.getPrintInfo(Arrays.asList(yyid));
                    if("200".equals(Util.null2String(printInfo.get("status")))){
                        JSONArray jsonArray = printInfo.getJSONArray("data");
                        JSONObject date = jsonArray.getJSONObject(0);
                        String oldUserId = date.getString("userId");
                        applyPrint.setOldPersonNum(oldUserId);

//                        String fwdyfs = Util.null2String(rs.getString("fwdyfs"));
//                        String totalNum = date.getString("totalNum");
//                        String printNum = date.getString("printNum");
//                        if(!totalNum.equals(fwdyfs)){
//                            int fwdyfsInt = Integer.parseInt(fwdyfs);
//                            int totalNumInt = Integer.parseInt(totalNum);
//                            int printNumInt = Integer.parseInt(printNum);
//                            if(fwdyfsInt<printNumInt){
//                                resobject.put("status","500");
//                                resobject.put("error","文件变更后打印份数小于当前已打印份数，无法触发用印信息变更");
//                                return resobject.toJSONString();
//                            }
//                            int changeNum = fwdyfsInt-totalNumInt;
//                            String changeStr = String.valueOf(changeNum);
//                            applyPrint.setPrintNum(changeStr);
//                        }
                    }else {
                        resobject.put("status","500");
                        resobject.put("error","查询文件当前用印信息失败");
                        return resobject.toJSONString();
                    }
                }
                bs.writeLog("applyPrint:"+ JSON.toJSONString(applyPrint));
                messageDetailLog.writLogsnotretrun(requestid,JSON.toJSONString(applyPrint),"1",messageDetailLog.Other);

                //触发用印信息变更
                String response = htUtil.ApplyPrintPost(JSONArray.toJSON(applyPrint).toString());
                bs.writeLog(response);
                if(StringUtils.isEmpty(response)){
                    resobject.put("status","500");
                    resobject.put("error","触发用印信息变更接口返回结果为空");
                    return resobject.toJSONString();
                }
                JSONObject res = JSONObject.parseObject(response);
                String status = Util.null2String(res.get("status"));//标识200-成功,否则失败
                String message = Util.null2String(res.get("message"));
                bs.writeLog("status:"+status);
                bs.writeLog("message:"+message);
                if(!"200".equals(status)){
                    resobject.put("status","500");
                    resobject.put("error","触发用印信息变更失败");
                    updateSignStatus(tableName+"_dt1",mainid,yyid,"4");
                    messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.fail,messageDetailLog.success,response);
                    return resobject.toJSONString();
                }
                updateSignStatus(tableName+"_dt1",mainid,yyid,"3");
                updateMainTable(requestid,tableName,mainid);
                messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.success,messageDetailLog.success,response);
            }
        }catch (Exception e){
            e.printStackTrace();
            resobject.put("status","500");
            resobject.put("error","处理异常");
            return resobject.toJSONString();
        }

        bs.writeLog("SendApplyPrint-----END-----"+requestid);
        resobject.put("status","200");
        resobject.put("data","触发用印信息变更发送成功");
        return resobject.toJSONString();
    }

    public String getDatetime(){
        Random random=new Random();
        int inum=  random.nextInt(900)+100;
        return new SimpleDateFormat("yyyyMMddmmssdd").format(new Date()).toString()+inum;
    }

    /**
     * 更新用印状态
     * @param tableName
     * @param mainid
     * @param yyid
     * @param yyzt
     */
    private void updateSignStatus(String tableName, String mainid, String yyid, String yyzt){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();

        String update_sql = "update "+tableName+" set yyzt = '"+yyzt+"'";
        if("3".equals(yyzt)){
            String yywj = "";
            String sql = "select yywj from uf_yyxx where yyid = '"+yyid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                yywj = Util.null2String(rs.getString("yywj"));
            }

            update_sql += ", yyhwj = '"+yywj+"'";
        }
        update_sql += " where mainid = '"+mainid+"' and yyid = '"+yyid+"'";
        bs.writeLog(update_sql);
        rs.executeUpdate(update_sql);

    }

    /**
     * 更新主表电子用印件
     * @param requestid
     * @param tableName
     */
    public void updateMainTable(String requestid, String tableName, String mainid){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();

        List<String> dzyyjList = new ArrayList<>();
        String dzyyj = "";

        String sql = "select yyhwj from "+tableName+"_dt1 where mainid = '"+mainid+"'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        while (rs.next()){
            String yyhwj = Util.null2String(rs.getString("yyhwj"));
            if(StringUtils.isNotEmpty(yyhwj)){
                dzyyjList.add(yyhwj);
            }
        }

        dzyyj = org.apache.commons.lang3.StringUtils.join(dzyyjList,",");
        bs.writeLog("dzyyj:"+dzyyj);

        String update_sql = "update "+tableName+" set dzyyj = '"+dzyyj+"' where requestid = '"+requestid+"'";
        bs.writeLog(update_sql);
        rs.executeUpdate(update_sql);
    }
}
