package weaver.mingfeng.action;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import weaver.conn.RecordSet;
import weaver.email.EmailWorkRunnable;
import weaver.general.BaseBean;
import weaver.general.SendMail;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.WFPathUtil;

/**
 * 铭沣
 * 技术日报流程
 * 内部接收人，明细对应销售，区域service以及销售直接上级发送邮件
 * 外部接收人进行邮件抄送
 * @author cjy
 */

public class Technology_Daily_Action extends BaseBean implements Action {

	@Override
	public String execute(RequestInfo requestinfo) {
		writeLog("-----Begin Technology_Daily_Action ------");
		String requestid = Util.null2String(requestinfo.getRequestid());//流程RequestId
		String workflowid = Util.null2String(requestinfo.getWorkflowid());//流程WorkflowId
		String tablename = requestinfo.getRequestManager().getBillTableName();//表单名称 
		User usr = requestinfo.getRequestManager().getUser();//获取当前操作用户对象
		String creater = usr.getUID()+"";
		String creatername = "";//填报人名称
		String createremail = "";//填报人邮件
		String requestname = "";//流程标题
		String dataid = "";
		
		writeLog("requestid:"+requestid+"   workflowid:"+workflowid+"    tablename:"+tablename);
		try{
			RecordSet rs = new RecordSet();
			RecordSet rs1 = new RecordSet();
			
			String select_mail = " select id,(select lastname from HrmResource where id = sqr) as lastname,(select requestname from workflow_requestbase where requestid = "+requestid+") as requestname,(select email from HrmResource where id = sqr) as email from "+tablename+" where requestid = "+requestid;
			writeLog("select_mail:"+select_mail);
			rs.executeQuery(select_mail);
			rs.next();
			dataid = Util.null2String(rs.getString("id"));
			creatername = Util.null2String(rs.getString("lastname"));
			createremail = Util.null2String(rs.getString("email"));
			requestname = Util.null2String(rs.getString("requestname"));
			
			writeLog("creatername:"+creatername+"  createremail:"+createremail+"    requestname:"+requestname);
			
			
			String select_modemain = " select * from uf_mode_mail where Mail_Modeid = 'Technology_Daily_Workflow' ";
			rs.executeQuery(select_modemain);
			rs.next();
			String mode_id = Util.null2String(rs.getString("id"));
			String mail_title = Util.null2String(rs.getString("mail_title"));
			String main_content = Util.null2String(rs.getString("main_content"));
			String detail_content_begin = Util.null2String(rs.getString("detail_content_begin"));
			String detail_content_center = Util.null2String(rs.getString("detail_content_center"));
			String detail_content_end = Util.null2String(rs.getString("detail_content_end"));
			String mail_url_field = Util.null2String(rs.getString("mail_url"));//发送给用户的字段
			String outside_user_mail_url = Util.null2String(rs.getString("outside_user"));//外部人员邮件字段
			String send_mail = Util.null2String(rs.getString("send_mail"));
			
			writeLog("mail_url_field:"+mail_url_field);
			
				String main_field = "";//主表字段
				String main_sqlfield = "";//主表数据库查询语句
				String detail_field = "";
				String detail_sqlfield = "";
				String select_modedetail = " select * from uf_mode_mail_dt1 where mainid = "+mode_id;
				rs.executeQuery(select_modedetail);
				while(rs.next()){
					String field_type = Util.null2String(rs.getString("field_type"));
					String zhuanhuan = Util.null2String(rs.getString("zhuanhuan"));
					String zhuanhuanvalue = Util.null2String(rs.getString("zhuanhuanvalue"));
					String oa_field = Util.null2String(rs.getString("oa_field"));
					
					if("0".equals(field_type)){//字段类型 主表
						main_field += oa_field + ",";
						if("1".equals(zhuanhuan)){//是否转换字段
							main_sqlfield += zhuanhuanvalue.replaceAll("&nbsp;", " ") + ",";
						}else{
							main_sqlfield += oa_field + ",";
						}
					}else{
						detail_field += oa_field + ",";
						if("1".equals(zhuanhuan)){
							detail_sqlfield += zhuanhuanvalue.replaceAll("&nbsp;", " ") + ",";
						}else{
							detail_sqlfield += oa_field + ",";
						}
						
					}
				}
				
				if(main_sqlfield.length() > 0 ){
					main_sqlfield = main_sqlfield.substring(0, main_sqlfield.length()-1);
					main_field = main_field.substring(0, main_field.length()-1);
				}
				
				if(detail_sqlfield.length() > 0){
					detail_sqlfield = detail_sqlfield.substring(0, detail_sqlfield.length()-1);
					detail_field = detail_field.substring(0, detail_field.length()-1);
				}
				
				writeLog("main_sqlfield:"+main_sqlfield);
				writeLog("main_field:"+main_field);
				writeLog("detail_sqlfield:"+detail_sqlfield);
				writeLog("detail_field:"+detail_field);
				
				String select_sql = " select id,"+main_sqlfield+" from "+tablename+" where requestid = '"+requestid+"' ";
				writeLog("select_sql:"+select_sql);
				rs.executeQuery(select_sql);
				rs.next();
				String id = Util.null2String(rs.getString("id"));
				
				String[] main_fieldarr = main_field.split(",");
				for(int i = 0 ; i < main_fieldarr.length; i++){
					if(main_content.lastIndexOf("{&"+main_fieldarr[i]+"}") > -1){
						main_content = main_content.replace("{&"+main_fieldarr[i]+"}", rs.getString(main_fieldarr[i]));
					}
				}
				
				//writeLog("main_content:"+main_content);
				
				String[] detail_fieldarr = detail_field.split(",");
				String new_detail_content_center = "";
				
				String select_detail = " select ROW_NUMBER() OVER(ORDER BY ID) rownu,"+detail_sqlfield+" from "+tablename+"_dt1 where mainid = '"+id+"' ";
				rs1.executeQuery(select_detail);
				while(rs1.next()){
					String detail_content_center_str = detail_content_center;
					String rownu = Util.null2String(rs1.getString("rownu"));//序号
					detail_content_center_str = detail_content_center_str.replace("{&rownu}", rownu);
					for(int i = 0 ; i < detail_fieldarr.length ; i++){
						if(detail_content_center_str.lastIndexOf("{&"+detail_fieldarr[i]+"}") > -1){
							detail_content_center_str = detail_content_center_str.replace("{&"+detail_fieldarr[i]+"}", rs1.getString(detail_fieldarr[i]));
						}
					}
					new_detail_content_center += detail_content_center_str;
				}
				
				String detail_content = detail_content_begin+new_detail_content_center+detail_content_end;
				//writeLog("detail_content:"+detail_content);
				
				String content = main_content+detail_content;
				
				writeLog("content:"+content);
				
				//发送人后缀以及邮件地址
				content = content.replace("{&creatername}", creatername).replace("{&createremail}", createremail).replace("{&requestname}", requestname);
				
				String newcontent = content.replaceAll("&nbsp;", " ");
				writeLog("newcontent:"+newcontent);
				
				
				mail_title = mail_title.replace("{&requestname}", requestname);
				writeLog("mail_title:"+mail_title+"   send_mail:"+send_mail);
				
				//明细对应销售的邮件地址
				String dyxs_mail = getDyxs_mailurl(tablename,dataid,"qyxs");
				
				//明细对应区域service邮件地址
				String qys_mail = getDyxs_mailurl(tablename,dataid,"qys");
				
				//明细销售上级的邮件地址
				String xsh_mail = getDyxs_mailurl(tablename,dataid,"xsh");
				
				String inneremail = "";
				//内部人员邮件地址  
				if(!"".equals(mail_url_field)){//字段已逗号分割获取人员邮件地址
					inneremail = getMial_url(tablename,mail_url_field,requestid);
				}
				
				//获取外部人员邮件直接抄送
				String outmail = "";
				if(!"".equals(outside_user_mail_url)){
					 outmail = OutUserMial_url(tablename, requestid, outside_user_mail_url);
				}
				
				String fs_user = inneremail +","+ dyxs_mail + "," + qys_mail + "," + xsh_mail + "," + createremail; 
				writeLog("发送人fs_user："+fs_user);
				
				String quchong = getDuplicate_Removal(fs_user);
				writeLog("去重后:"+quchong);
				
				writeLog("dyxs_mail:"+dyxs_mail+"   outmail:"+outmail);
				if(!"".equals(dyxs_mail) || !"".equals(outmail)){
					SendMail sendmail = new SendMail();
					//boolean mailresult = sendmail.send(send_mail, dyxs_mail, outmail, "", mail_title, newcontent, "3");
					boolean mailresult = sendmail.sendhtml(send_mail, quchong, outmail, "", mail_title, newcontent, 3, "3");
					writeLog("mailresult:"+mailresult);
					
					if(!mailresult){
						 writeLog("邮件发送失败");
						 requestinfo.getRequestManager().setMessageid("11111" + requestid + "22222");
						 requestinfo.getRequestManager().setMessagecontent("邮件发送失败，请联系管理员！");
						 return "0";
					}
				}
				
				
		
		}catch (Exception e) {
			 e.printStackTrace();
			 writeLog("获取该流程事物数据集异常:[" + e.getMessage() + "/" + e.toString() + "]");
			 requestinfo.getRequestManager().setMessageid("11111" + requestid + "22222");
			 requestinfo.getRequestManager().setMessagecontent("获取该流程事物数据集异常:[" + e.getMessage() + "/" + e.toString() + "]");
			 return "0";
		}
		
		writeLog("-----End Technology_Daily_Action ------");
		return "1";
	}

	/**
	 * 获取明细对应销售的邮件地址
	 * @param tablename
	 * @param dataid
	 * @return
	 */
	public String getDyxs_mailurl(String tablename, String dataid,String field) {
		
		RecordSet rs4 = new RecordSet();
		String resulturl = "";
		String select = " select (select email from HrmResource where id = "+field+") as email  from "+tablename+"_dt1 where mainid = "+dataid+" ";
		rs4.executeQuery(select);
		while(rs4.next()){
			String email = Util.null2String(rs4.getString(1));
			if(!"".equals(email)){
				resulturl += email+",";
			}
		}
		
		if(!"".equals(resulturl)){
			resulturl = resulturl.substring(0, resulturl.length()-1);
		}
		
		writeLog("对应销售邮件："+resulturl);
		return resulturl;
	}

	/**
	 * 发送邮件
	 * @param content
	 * @param mail_title
	 * @param email
	 */
	public void SendMail_Remind(String content,String mail_title, ArrayList<String> email) {
		String mailobject = mail_title;
		for(int i = 0 ; i < email.size(); i++){
			new WFPathUtil().getFixedThreadPool().execute(new EmailWorkRunnable(email.get(i), mailobject, content));
		}
	}
	
	/**
	 * 获取用户邮件地址
	 * @param tablename
	 * @param mail_url_field
	 * @param requestid
	 * @return
	 */
	public String getMial_url(String tablename,String mail_url_field,String requestid){
		String url = "";
		String[] mail_url_fieldarr = mail_url_field.split(",");
		String userid = "";
		RecordSet rs2 = new RecordSet();
		String select = " select "+mail_url_field+" from "+tablename+" where requestid = "+requestid;
		rs2.executeQuery(select);
		rs2.next();
		for(int i = 0 ; i < mail_url_fieldarr.length ; i++){
			String user = Util.null2String(rs2.getString((i+1)));
			if(!"".equals(user)){
				userid += user+",";
			}
		}
		
		if(!"".equals(userid)){
			userid = userid.substring(0, userid.length()-1);
		}
		writeLog("userid:"+userid);
		
		String select_url = " select email from HrmResource where id in ("+userid+") and email <> '' ";
		rs2.executeQuery(select_url);
		while(rs2.next()){
			url += Util.null2String(rs2.getString(1))+",";
		}
		writeLog("内部url:"+url);
		return url;
	}
	
	
	/**
	 * 整理外部人员的邮件地址
	 * @param tablename
	 * @param requestid
	 * @param outsidefield
	 * @return
	 */
	public String OutUserMial_url(String tablename,String requestid,String outsidefield){
		RecordSet rs3 = new RecordSet();
	    String resultmail = "";
		String select_out = " select "+outsidefield+" from "+tablename+" where requestid = '"+requestid+"' ";
		rs3.executeQuery(select_out);
		rs3.next();
		String outsidemail = Util.null2String(rs3.getString(1));
		writeLog("outsidemail:"+outsidemail);
		if(outsidemail.contains(";") || outsidemail.contains("；")){
			resultmail = outsidemail.replaceAll(";", ",").replaceAll("；", ",");
		}else{
			resultmail = outsidemail;
		}
		writeLog("resultmail:"+resultmail);
		
		return resultmail;
	}
	
	/**
	 * 邮件地址去重
	 * @param usermail
	 */
	public String getDuplicate_Removal(String usermail) {
		
		String[] mailurlstr = usermail.split(",");
		String returnmail = "";
		Set<String> set = new HashSet<String>();
		for(int i = 0;i < mailurlstr.length; i++){
			if(!"".equals(mailurlstr[i])){
				set.add(mailurlstr[i]);
			}
		}
		mailurlstr = (String[]) set.toArray(new String[0]);
		for(int j = 0 ;j <mailurlstr.length ; j++){
			returnmail += mailurlstr[j]+",";
		}
		writeLog("去重-》getDuplicate_Removal:"+returnmail);	
		if(returnmail.contains(",")){
			returnmail = returnmail.substring(0, returnmail.length()-1);
		}
		return returnmail;
	}

}
