package com.engine.htsc.workflow.service.impl;

import com.engine.core.impl.Service;
import com.engine.htsc.workflow.cmd.WorkflowShelveCmd;
import com.engine.htsc.workflow.service.WorkflowShelveService;
import com.weaver.general.TimeUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;

import java.util.HashMap;
import java.util.Map;

public class WorkflowShelveServiceImpl extends Service implements WorkflowShelveService {
    private Log log = LogFactory.getLog(this.getClass());

    @Override
    public Map<String, Object> workflowShelveButton(Map<String, Object> params,User user) {
        Map<String, Object> datas = new HashMap<>();
        RecordSetTrans rst = new RecordSetTrans();
        RecordSet rs = new RecordSet();
        try {
            rst.setAutoCommit(false);
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            DepartmentComInfo deptComInfo = new DepartmentComInfo();
            //1.获取参数
            String code = (String)params.get("code");//0 取消搁置状态 1 搁置状态
            String requestid = (String)params.get("requestid");
            String userid = (String)params.get("userid");
            String datetime = (String)params.get("datetime");
            String time = (String)params.get("time");
            String nodeid = (String)params.get("nodeid");
            String workflowid = (String)params.get("workflowid");
            String remark = (String)params.get("remark");
            String showName = (String)params.get("showName");
            String src = (String)params.get("src");

            //2.判断主次账号并获取所有账号id
            String useridAll = "";
            String account_type = user.getAccount_type();
            int uid = user.getUID();
            if (account_type.equals("1")){//次账号情况下
                rs.executeQuery("select belongto from hrmresource where status < 4 and id = ?",uid);
                if (rs.next()){
                    int belongto = Util.getIntValue(rs.getString("belongto"));
                    User userNew = new User(belongto);
                    useridAll = userNew.getUID() + "";
                    String belongtoids = userNew.getBelongtoids();
                    if (!"".equals(belongtoids)) {
                        useridAll += "," + belongtoids;
                    }
                }
            }else {//主账号情况下
                useridAll = user.getUID() + "";
                String belongtoids = user.getBelongtoids();
                if (!"".equals(belongtoids)) {
                    useridAll += "," + belongtoids;
                }
            }
            log.info("===判断主次账号并获取所有账号id==="+useridAll);

            //===功能===
            //获取该条数据的状态、与当前操作的code做比较
            Boolean flag = true;
            rs.executeQuery("select lcdqzt from uf_lcgzb where lcid = ? and dbms_lob.instr(gzczz, '"+useridAll+"', 1,1)>0",requestid);
            if (rs.next()){
                String lcdqzt = Util.null2String(rs.getString("lcdqzt"));
                if(code.equals(lcdqzt)){
                    flag = false;
                    datas.put("isOperation","1");//1是已操作
                }else {
                    datas.put("isOperation","0");//0是未操作
                }
            }
            log.info("==该条流程是否已操作=="+flag);


            if(flag) {
                //3.保存信息到流程搁置表uf_lcgzb
                String lastname = resourceComInfo.getLastname(userid);
                String departmentID = resourceComInfo.getDepartmentID(userid);
                String deptName = deptComInfo.getDepartmentName(departmentID);
                rst.executeUpdate("delete from uf_lcgzb where lcid = ? and dbms_lob.instr(gzczz, '"+useridAll+"', 1,1)>0", requestid);
                String sql = "insert into uf_lcgzb(lcid,workflowid,nodeid,gzr,lastName,departmentId,gzczz,gzrq,gzsj,lcdqzt,remark,showName) values (?,?,?,?,?,?,?,?,?,?,?,?)";
                rst.executeUpdate(sql, new Object[]{requestid, workflowid, nodeid, userid, lastname, departmentID, useridAll, datetime, time, code, remark, showName});
                log.info("==流程搁置表保存完成==");

                //4.更新签字意见表（workflow）
                //流程是否被代理，获取receivedPersons代理信息
                String agentSql = "select agentorbyagentid from workflow_currentoperator " +
                        "where requestid = "+requestid+" and agenttype = 2 and " +
                        " userid = "+userid+" and nodeid = "+nodeid;
                rs.executeQuery(agentSql);
                int agentorbyagentid = -1;
                while (rs.next()){
                    agentorbyagentid = Util.getIntValue(rs.getString("agentorbyagentid"));
                }
                String receivedPersons = "";
                String receiveName = resourceComInfo.getLastname(userid);
                String agentor = resourceComInfo.getLastname(String.valueOf(agentorbyagentid));
                if (agentorbyagentid != -1){
                    receivedPersons = agentor +"->"+receiveName;
                }else {
                    receivedPersons = receiveName;
                }
                log.info("==流程代理信息=="+receivedPersons);

                String operatedate = TimeUtil.getCurrentDateString();
                String operatetime = TimeUtil.getOnlyCurrentTimeString();
                if (code.equals("1")) {
                    String logtype = "w";
                    String logSql = "insert into workflow_requestlog(requestid,workflowid,nodeid,logtype,operatedate,operatetime,agentorbyagentid,operator,receivedPersons,remark,operatorDept,historydeptname) values(?,?,?,?,?,?,?,?,?,?,?,?)";
                    rst.executeUpdate(logSql, new Object[]{requestid,workflowid,nodeid,logtype,operatedate,operatetime,agentorbyagentid,userid,receivedPersons,remark,departmentID,deptName});
                }else {
                    String logtype = "u";
                    String logSql = "insert into workflow_requestlog(requestid,workflowid,nodeid,logtype,operatedate,operatetime,agentorbyagentid,operator,receivedPersons,remark,operatorDept,historydeptname) values(?,?,?,?,?,?,?,?,?,?,?,?)";
                    rst.executeUpdate(logSql, new Object[]{requestid,workflowid,nodeid,logtype,operatedate,operatetime,agentorbyagentid,userid,receivedPersons,remark,departmentID,deptName});
                }
                log.info("==流程签字意见表保存完成==");

                //3.表单关注标签操作（workflow_attention）涉及主次账号处理
                //3.1.当前操作者增加关注标签
                AttentionUtil(userid,showName,src,requestid);
                //3.2.所属主账户增加关注标签
                String belongTo = resourceComInfo.getBelongTo(userid);
                if (!belongTo.equals("")){
                    AttentionUtil(belongTo,showName,src,requestid);
                }
                log.info("==关注标签==增加完成");

                datas.put("isOperation","0");//0是未操作
                datas.put("message",true);
                rst.commit();
            }

        }catch (Exception e){
            datas.put("message",false);
            e.printStackTrace();
            rst.rollback();
        }
        return datas;
    }


    /**
     * 流程表单增加关注标签工具类
     */
    public void AttentionUtil(String userid,String showName,String src,String requestid){
        try {
            String colorval = "#87101C";
            String operatedate = TimeUtil.getCurrentDateString();
            String operatetime = TimeUtil.getOnlyCurrentTimeString();
            RecordSet rs = new RecordSet();
            rs.executeQuery("select id from workflow_attentionTypeSet where userid = ? and SHOWNAME = ?", userid, showName);
            if (rs.next()) {//搁置标签已经存在
                Integer ids = Util.getIntValue(rs.getString("id"));
                if ("add".equals(src)) {
                    rs.executeQuery("select * from workflow_attention where userid= ? and " +
                            " usertype= 0 and requestid = ? and atypeid = ?", userid, requestid, ids);
                    if (rs.next()) {
                    } else {
                        String addSql = "insert into workflow_attention(userid,usertype,requestid,atypeid,operatedate,operatetime) values(?,?,?,?,?,?)";
                        rs.executeUpdate(addSql, new Object[]{userid, 0, requestid, ids, operatedate, operatetime});
                    }
                } else {
                    rs.executeUpdate("delete from workflow_attention where userid= ? and " +
                            " usertype= 0 and requestid = ? and atypeid = ?", userid, requestid, ids);
                }
            } else {//搁置标签不存在
                String insertSql = "insert into workflow_attentionTypeSet(userid,usertype,showname,colorval,showorder,operatedate,operatetime) values(?,?,?,?,?,?,?)";
                rs.executeUpdate(insertSql, new Object[]{userid, 0, showName, colorval, -1, operatedate, operatetime});
                rs.executeQuery("select id from workflow_attentionTypeSet where userid= ? and SHOWNAME = ?", userid, showName);
                if (rs.next()) {
                    Integer ids = Util.getIntValue(rs.getString("id"));
                    if ("add".equals(src)) {
                        rs.executeQuery("select * from workflow_attention where userid= ? and " +
                                " usertype= 0 and requestid = ? and atypeid = ?", userid, requestid, ids);
                        if (rs.next()) {
                        } else {
                            String addSql = "insert into workflow_attention(userid,usertype,requestid,atypeid,operatedate,operatetime) values(?,?,?,?,?,?)";
                            rs.executeUpdate(addSql, new Object[]{userid, 0, requestid, ids, operatedate, operatetime});
                        }
                    } else {
                        rs.executeUpdate("delete from workflow_attention where userid= ? and " +
                                " usertype= 0 and requestid = ? and atypeid = ?", userid, requestid, ids);
                    }
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取流程最后一次接收时间
     * @param params
     * @return
     * @Author weaver-cl
     */
    @Override
    public Map<String, Object> getReceiveTime(Map<String, Object> params) {
        return commandExecutor.execute(new WorkflowShelveCmd(params, user));
    }
}
