package weaver.interfaces.mingfeng.cron;

import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.util.*;

public class AnniversaryWishesCronJob extends BaseCronJob
{
	/**
	 * 
	 * 计划任务的入口，五任何输入参数
	 */
	@Override
	public void execute()
	{
		updateAnniversaryWishes();
	}

	public void updateAnniversaryWishes(){

		BaseBean log = new BaseBean();
		log.writeLog("updateAnniversaryWishes! ");

		String uftable  = "uf_rzznzfgly";
		RecordSet rs = new RecordSet();
		int days = 30 ;

		List<Map<String,String>> dataList = new ArrayList<Map<String,String>>();


		BaseBean bb = new BaseBean();
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd" ) ;
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy" ) ;

		try{
			Map<String,String> dataMap = null;
			for(int i=0;i<days;i++)
			{
				Calendar calendar = Calendar.getInstance();
				calendar.add(Calendar.DAY_OF_YEAR, i);
				String currentDay = sdf.format(calendar.getTime()) ;
				bb.writeLog("currentDay:"+currentDay);

				String currentYear = sdf2.format(calendar.getTime()) ;
				bb.writeLog("currentYear:"+currentYear);

				String sql ="  select k.* from (select h.id,h.lastname,h.sex,h.departmentid,d.departmentname,s.subcompanyname,k.jobtitlename," +
							"   h.companystartdate,convert(varchar(50), getdate(), 23) as enddate," +
							"   (datediff(year,h.companystartdate,convert(varchar(50), getdate(), 23))-1) as zn" +
							"   from hrmresource h\n" +
							"   inner join HrmDepartment d on d.id = h.departmentid\n" +
							"   inner join HrmSubCompany s on s.id = h.subcompanyid1\n" +
							"   left join HrmJobTitles k on k.id = h.jobtitle\n" +
							"   where right(h.companystartdate,5) = '"+currentDay+"'\n" +
							"   and h.status in(0,1,2,3)" +
							"   and (h.belongto is null or  h.belongto = -1 ) " +
							"   and h.companystartdate is not null " +
							" ) k " ;

				bb.writeLog("updateAnniversaryWishes-sql:"+sql);

				rs.executeQuery(sql);
				while (rs.next()){

					String companystartdate = Util.null2String(rs.getString("companystartdate"));
					String enddate = Util.null2String(rs.getString("enddate"));

					if(StringUtils.isNotBlank(companystartdate) && StringUtils.isNotBlank(enddate)){
						LocalDate date1 = LocalDate.parse(companystartdate);
						LocalDate date2 = LocalDate.parse(enddate);
						Period period = Period.between(date1, date2);
						int yearsDiff = period.getYears(); // 获取年数差距
						bb.writeLog("yearsDiff:"+yearsDiff+"</br>");
						if(yearsDiff > 0) {
							String userid = Util.null2String(rs.getString("id"));
							String lastname = Util.null2String(rs.getString("lastname"));
							int rzzn = Util.getIntValue(Util.null2String(rs.getString("rzzn")), 0);
							String subcompanyid1 = Util.null2String(rs.getString("subcompanyid1"));
							String departmentid = Util.null2String(rs.getString("departmentid"));
							String rzyr = Util.null2String(rs.getString("startday"));
							String zfy = getZfy(lastname, rzzn);

							dataMap = new HashMap<String, String>();
							dataMap.put("ry", userid);
							dataMap.put("xm", lastname);
							dataMap.put("zfy", zfy);
							dataMap.put("bm", departmentid);
							dataMap.put("rzrq", companystartdate);
							dataMap.put("rzyr", rzyr);
							dataMap.put("fb", subcompanyid1);
							dataMap.put("nf", currentYear);
							dataMap.put("rzzn", rzzn + "");
							dataList.add(dataMap);
						}
					}
				}
			}
			bb.writeLog("updateAnniversaryWishes-dataList1:"+dataList.size());

			for(int i=0;i<days;i++)
			{
				Calendar calendar = Calendar.getInstance();
				calendar.add(Calendar.DAY_OF_YEAR, 0-i);
				String currentDay = sdf.format(calendar.getTime()) ;
				bb.writeLog("currentDay:"+currentDay);

				String currentYear = sdf2.format(calendar.getTime()) ;
				bb.writeLog("currentYear:"+currentYear);

				String sql ="  select k.* from (select h.id,h.lastname,h.sex,h.departmentid,d.departmentname,s.subcompanyname,k.jobtitlename," +
							"   h.companystartdate,convert(varchar(50), getdate(), 23) as enddate," +
							"   (datediff(year,h.companystartdate,convert(varchar(50), getdate(), 23))-1) as zn" +
							"   from hrmresource h\n" +
							"   inner join HrmDepartment d on d.id = h.departmentid\n" +
							"   inner join HrmSubCompany s on s.id = h.subcompanyid1\n" +
							"   left join HrmJobTitles k on k.id = h.jobtitle\n" +
							"   where right(h.companystartdate,5) = '"+currentDay+"'\n" +
							"   and h.status in(0,1,2,3)" +
							"   and (h.belongto is null or  h.belongto = -1 ) " +
							"   and h.companystartdate is not null " +
							" ) k " ;

				bb.writeLog("updateAnniversaryWishes-sql:"+sql);

				rs.executeQuery(sql);
				while (rs.next()){

					String companystartdate = Util.null2String(rs.getString("companystartdate"));
					String enddate = Util.null2String(rs.getString("enddate"));

					if(StringUtils.isNotBlank(companystartdate) && StringUtils.isNotBlank(enddate)){
						LocalDate date1 = LocalDate.parse(companystartdate);
						LocalDate date2 = LocalDate.parse(enddate);
						Period period = Period.between(date1, date2);
						int yearsDiff = period.getYears(); // 获取年数差距
						bb.writeLog("yearsDiff:"+yearsDiff+"</br>");
						if(yearsDiff > 0) {
							String userid = Util.null2String(rs.getString("id"));
							String lastname = Util.null2String(rs.getString("lastname"));
							int rzzn = Util.getIntValue(Util.null2String(rs.getString("rzzn")), 0);
							String subcompanyid1 = Util.null2String(rs.getString("subcompanyid1"));
							String departmentid = Util.null2String(rs.getString("departmentid"));
							String rzyr = Util.null2String(rs.getString("startday"));
							String zfy = getZfy(lastname, rzzn);

							dataMap = new HashMap<String, String>();
							dataMap.put("ry", userid);
							dataMap.put("xm", lastname);
							dataMap.put("zfy", zfy);
							dataMap.put("bm", departmentid);
							dataMap.put("rzrq", companystartdate);
							dataMap.put("rzyr", rzyr);
							dataMap.put("fb", subcompanyid1);
							dataMap.put("nf", currentYear);
							dataMap.put("rzzn", rzzn + "");
							dataList.add(dataMap);
						}
					}
				}
			}
			bb.writeLog("updateAnniversaryWishes-dataList2:"+dataList.size());

			for(int i=0;i<dataList.size();i++){
				Map<String,String> dMap = dataList.get(i);
				String ry = dMap.get("ry");
				String nf = dMap.get("nf");
				String ufid = "" ;
				String sql = " select id from "+uftable+" where ry='"+ry+"' and nf = '"+nf+"'";
				rs.executeQuery(sql);
				if(rs.next()){
					ufid = Util.null2String(rs.getString("id"));
				}
				if(StringUtils.isBlank(ufid)){
					updateWishesInfo(uftable,dMap);
				}
			}

		}catch (Exception e){
			bb.writeLog("AnniversaryWishesCronJob--updateAnniversaryWishes:e"+e);
		}
	}

	public int updateWishesInfo(String fromtable,Map<String,String> datas){
		RecordSet rs = new RecordSet();
		BaseBean bb = new BaseBean();
		int count = 0;
		ModeRightInfo modeRightInfo = new ModeRightInfo();
		String uuid = UUID.randomUUID().toString().replace("-","");
		bb.writeLog("uuid:"+uuid);

		SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat formatter2 = new SimpleDateFormat("HH:mm:ss");
		String currentdate = formatter1.format(new Date());
		String currenttime = formatter2.format(new Date());
		String modedatacreater = "1";
		String modedatacreatertype = "0";

		String formmodeid = "" ;
		String sql =" select k.id from modeinfo k  \n" +
				" inner join workflow_bill l on formid = l.id\n" +
				" where l.tablename = '"+fromtable+"' " ;
		rs.execute(sql);
		if(rs.next()){
			formmodeid = Util.null2String(rs.getString("id"));
		}

		bb.writeLog("formmodeid:"+formmodeid);
		datas.put("formmodeid", formmodeid);
		datas.put("modedatacreater", modedatacreater);
		datas.put("modedatacreatertype", modedatacreatertype);
		datas.put("modedatacreatedate", currentdate);
		datas.put("modedatacreatetime", currenttime);
		datas.put("uuid", uuid);

		String tablenvalue = "";
		String tablename = "";
		for (Map.Entry<String, String> entry : datas.entrySet()) {
			String fieldname = Util.null2String(entry.getKey()).trim();
			String fieldvalue = Util.null2String(entry.getValue()).replace("'", "''").trim();
			tablename += tablename == "" ? fieldname : "," + fieldname;
			tablenvalue += tablenvalue == "" ? "'" + fieldvalue + "'" : ",'" + fieldvalue + "'";
		}
		if (tablename != "" && tablenvalue != "") {

			sql = " insert into " + fromtable + "(" + tablename + ") values (" + tablenvalue + ")";
			bb.writeLog("sql:" + sql);
			boolean boo = rs.executeUpdate(sql);
			if (boo) {
				count++;
			}
			bb.writeLog("count:" + count);
			if (count > 0) {
				String dataid = "";
				sql = " select id from " + fromtable + " where uuid='" + uuid + "'";
				bb.writeLog("sql:" + sql);
				rs.execute(sql);
				if (rs.next()) {
					dataid = Util.null2String(rs.getString("id"));
				}
				if (!"".equals(dataid)) {
					modeRightInfo.editModeDataShare(Integer.valueOf(modedatacreater), Util.getIntValue(formmodeid), Integer.parseInt(dataid));
				}
			}
		}

		return count;
	}



	public static String convert(int number) {
		if (number <= 0) {
			return "";
		}
		//数字对应的汉字
		String[] num = {"一", "二", "三", "四", "五", "六", "七", "八", "九"};
		//单位
		String[] unit = {"", "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千", "万亿"};
		//将输入数字转换为字符串
		String result = String.valueOf(number);
		//将该字符串分割为数组存放
		char[] ch = result.toCharArray();
		//结果 字符串
		String str = "";
		int length = ch.length;
		for (int i = 0; i < length; i++) {
			int c = (int) ch[i] - 48;
			if (c != 0) {
				str += num[c - 1] + unit[length - i - 1];
			}
		}
		if (number < 20 && number > 9) {
			str = str.substring(1);
		}
//		System.out.println(str);
		return str ;
	}

	public String getZfy(String lastname,int rzzn){
		String rzzzdx = "" ;
		if(rzzn > 0){
			rzzzdx = convert(rzzn);
		}

		String zfy =" <div style=\"width: 500px;text-align: left;font-size: 14px !important;\">\n" +
					"    <p class=\"p1\"  style=\"color: #202e7f;font-size: 18px;font-weight: 600;\">亲爱的<span class=\"s1\">"+lastname+"</span>：</p>\n" +
					"    <p class=\"p2\" >&nbsp;</p>\n" +
					"    <p class=\"p3\" style=\"color: #202e7f;line-height: 30px;\">衷心祝贺您与铭沣同行<span class=\"s1\">"+rzzzdx+"</span>周年快乐！</p>\n" +
					"    <p class=\"p3\" style=\"color: #202e7f;line-height: 30px;\">感谢您将自己的青春年华和工作热情奉献给了铭沣！</p>\n" +
					"    <p class=\"p3\" style=\"color: #202e7f;line-height: 30px;\">感谢您辛勤的付出与不懈的跟随与守候，期待我们一起度过下一个周年！</p>\n" +
					"    <p class=\"p3\" style=\"color: #202e7f;line-height: 30px;\">今天的您是否忙碌在工作岗位上而忽略了这个重要的日子......</p>\n" +
					"    <p class=\"p3\" style=\"color: #202e7f;line-height: 30px;\">但公司记得您每一份付出和努力！</p>\n" +
					"    <p class=\"p3\" style=\"color: #202e7f;line-height: 30px;\">感谢您的一路相伴，未来我们继续同行!</p>\n" +
					"    <p class=\"p2\">&nbsp;</p>\n" +
					"    <p class=\"p2\">&nbsp;</p>\n" +
					"    <p class=\"p4\" style=\"float: right;color: #202e7f;font-size: 18px;font-weight: 600;\">&nbsp;MATFRON</p>\n" +
					" </div> ";
		return zfy;
	}

}
