package com.jpsoft.shinestar.modules.business.service.impl;

import java.util.*;
import javax.annotation.Resource;

import cn.hutool.core.date.DateUtil;
import com.jpsoft.shinestar.config.WxConfig;
import com.jpsoft.shinestar.modules.base.entity.PersonInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonPopedom;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.base.service.WorkShiftInfoService;
import com.jpsoft.shinestar.modules.business.entity.SupplementWorkPerson;
import com.jpsoft.shinestar.modules.business.entity.WorkScheduleAttendance;
import com.jpsoft.shinestar.modules.business.service.SupplementWorkPersonService;
import com.jpsoft.shinestar.modules.business.service.WorkScheduleAttendanceService;
import com.jpsoft.shinestar.modules.common.utils.JwtUtil2;
import com.jpsoft.shinestar.modules.common.utils.WechatMessageUtil;
import com.jpsoft.shinestar.modules.workflow.entity.ProcinstActUser;
import com.jpsoft.shinestar.modules.workflow.entity.ProcinstActivity;
import com.jpsoft.shinestar.modules.workflow.service.ProcinstActUserService;
import com.jpsoft.shinestar.modules.workflow.service.ProcinstActivityService;
import com.jpsoft.shinestar.modules.workflow.service.ProcinstService;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.jpsoft.shinestar.modules.business.dao.SupplementWorkDAO;
import com.jpsoft.shinestar.modules.business.entity.SupplementWork;
import com.jpsoft.shinestar.modules.business.service.SupplementWorkService;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.github.pagehelper.PageHelper;

@Transactional(rollbackFor = Exception.class)
@Component(value="supplementWorkService")
public class SupplementWorkServiceImpl implements SupplementWorkService {
	@Resource(name="supplementWorkDAO")
	private SupplementWorkDAO supplementWorkDAO;

	@Value("${jwt.secret}")
	private String jwtSecret;

	@Autowired
	private WxConfig wxConfig;

	@Autowired
	private WorkShiftInfoService workShiftInfoService;

	@Autowired
	private PersonInfoService personInfoService;

	@Autowired
	private WorkScheduleAttendanceService workScheduleAttendanceService;

	@Autowired
	private ProcinstActivityService procinstActivityService;

	@Autowired
	private ProcinstActUserService procinstActUserService;

	@Autowired
	private ProcinstService procinstService;

	@Autowired
	private SupplementWorkPersonService supplementWorkPersonService;

	@Override
	public SupplementWork get(String id) {
		// TODO Auto-generated method stub
		return supplementWorkDAO.get(id);
	}

	@Override
	public int insert(SupplementWork model) {
		// TODO Auto-generated method stub
		//model.setId(UUID.randomUUID().toString());

		return supplementWorkDAO.insert(model);
	}

	@Override
	public int update(SupplementWork model) {
		// TODO Auto-generated method stub
		return supplementWorkDAO.update(model);
	}

	@Override
	public int delete(String id) {
		// TODO Auto-generated method stub
		return supplementWorkDAO.delete(id);
	}

	@Override
	public boolean exist(String id) {
		// TODO Auto-generated method stub
		int count = supplementWorkDAO.exist(id);

		return count > 0 ? true : false;
	}

	@Override
	public List<SupplementWork> list() {
		// TODO Auto-generated method stub
		return supplementWorkDAO.list();
	}

	@Override
	public Page<SupplementWork> pageSearch(Map<String, Object> searchParams, int pageNumber, int pageSize,boolean count,List<Sort> sortList) {
        Page<SupplementWork> page = PageHelper.startPage(pageNumber,pageSize,count).doSelectPage(()->{
            supplementWorkDAO.search(searchParams,sortList);
        });

        return page;
	}

	@Override
	public String supplementWorkSubmit(PersonPopedom personPopedom, String id, String reason, String imageUrl,String formId,String ids,String draft) throws Exception {

		//考勤记录
		WorkScheduleAttendance workScheduleAttendance = workScheduleAttendanceService.get(id);
		if (!"0".equals(workScheduleAttendance.getResult())){
			throw new  Exception("只有缺卡才能进行补卡");
		}

		SupplementWork supplementWork = new SupplementWork();
		SupplementWorkPerson supplementWorkPerson = new SupplementWorkPerson();
		if(StringUtils.isNotEmpty(ids)){
			supplementWork=supplementWorkDAO.get(ids);
			supplementWorkPerson = supplementWorkPersonService.findBySupplementWorkId(ids).get(0);
		}else{
			supplementWork = new SupplementWork();
			supplementWorkPerson = new SupplementWorkPerson();
			supplementWork.setId(UUID.randomUUID().toString());
			supplementWorkPerson.setId(UUID.randomUUID().toString());
		}

		supplementWork.setPersonPopedomId(personPopedom.getId());
		supplementWork.setWorkShiftId(workScheduleAttendance.getWorkShiftId());
		supplementWork.setAttendanceDate(DateUtil.format(workScheduleAttendance.getRecordTime(),"yyyy-MM-dd HH:mm"));
		supplementWork.setClassify(workScheduleAttendance.getClassify());
		supplementWork.setType("1");
		supplementWork.setStatus("-99");
		supplementWork.setSubmitTime(new Date());
		supplementWork.setReason(reason);
		supplementWork.setImageUrl(imageUrl);
		supplementWork.setCreateTime(new Date());


		//新增个人记录
		supplementWorkPerson.setPersonPopedomId(personPopedom.getId());
		supplementWorkPerson.setSupplementWorkId(supplementWork.getId());
		supplementWorkPerson.setScheduleAttendanceId(id);
		supplementWorkPerson.setCreateTime(new Date());


		//考勤记录中记录补卡记录id
		workScheduleAttendance.setSupplementWorkPersonId(supplementWorkPerson.getId());
		workScheduleAttendanceService.update(workScheduleAttendance);

		if(StringUtils.isNotEmpty(ids)){
			update(supplementWork);
			supplementWorkPersonService.update(supplementWorkPerson);
		}else {
			insert(supplementWork);
			supplementWorkPersonService.insert(supplementWorkPerson);
		}

		if ("1".equals(draft)) {
			//创建审核流程id
			String procinstId = procinstService.addProcInst(supplementWork.getId(),  "补卡", formId, personPopedom, null,null,null);

			supplementWork.setProcinstId(procinstId);
			supplementWork.setStatus("0");
			update(supplementWork);


			ProcinstActivity procinstActivity = procinstActivityService.findByActivityIndexAndProcinstId(1, procinstId);

			if (procinstActivity != null) {
				List<ProcinstActUser> procinstActUserList = procinstActUserService.findByProcinstActivityIdActionType(procinstActivity.getId(), "0", "1");
				if (procinstActUserList.size() > 0) {

					SupplementWork finalSupplementWork = supplementWork;
					new Thread(() -> {
						for (ProcinstActUser procinstActUser : procinstActUserList) {
							try {
								PersonInfo personInfo = personInfoService.get(Long.parseLong(procinstActUser.getUserId()));

								//提交人
								PersonInfo personInfo1 = personInfoService.get(personPopedom.getPersonId());
								String accessToken = JwtUtil2.createToken(jwtSecret, personInfo.getId() + "", DateTime.now().plusHours(30 * 24).toDate());
								WechatMessageUtil.sendEvenMessage(personInfo.getOpenId(), "有一条新的补卡信息待审核", personInfo1.getName(), com.jpsoft.shinestar.modules.common.utils.StringUtils.getApprovalNo(), "前往处理", wxConfig.getPortalUrl() + "xsy/approval/infosp?id=" + finalSupplementWork.getId() + "&procinstActUserId=" + procinstActUser.getId() + "&formId=" + formId + "&token=" + accessToken, wxConfig.getAppId(), wxConfig.getAppSecret());
							} catch (Exception ex) {
								ex.printStackTrace();
							}

						}
					}).start();

				}
			}

		}



		return supplementWork.getId();
	}

	@Override
	public String supplementWorkBatchSubmit(PersonPopedom personPopedom, String date,String personIds, String reason, String imageUrl, String formId,String ids,String draft) throws Exception {

		List<String> personIdList = Arrays.asList(personIds.split(","));
		if (personIdList.size() ==0){
			throw new Exception("请选择补卡人员");
		}

	//	WorkShiftInfo workShiftInfo = workShiftInfoService.get(workShiftId);

		/*String time = workShiftInfo.getWorkTime();
		if ("2".equals(classify)){
			time = workShiftInfo.getClosingTime();
		}*/


		SupplementWork supplementWork = new SupplementWork();
		if(StringUtils.isNotEmpty(ids)){
			supplementWork=supplementWorkDAO.get(ids);

		}else{
			supplementWork = new SupplementWork();
			supplementWork.setId(UUID.randomUUID().toString());
		}

		supplementWork.setPersonPopedomId(personPopedom.getId());
	//	supplementWork.setWorkShiftId(workShiftId);
		supplementWork.setAttendanceDate(date);
	//	supplementWork.setClassify(classify);
		supplementWork.setType("2");
		supplementWork.setStatus("-99");
		supplementWork.setSubmitTime(new Date());
		supplementWork.setReason(reason);
		supplementWork.setImageUrl(imageUrl);
		supplementWork.setCreateTime(new Date());

		supplementWorkPersonService.deletePerson(ids);

		int n = 0;
		for (String personId : personIdList){
			WorkScheduleAttendance workScheduleAttendance = workScheduleAttendanceService.findByPersonIdRecordTimeResult(Long.parseLong(personId),date,"0");
			if (workScheduleAttendance == null){
				n++;
			}else {
				PersonInfo personInfo = personInfoService.get(Long.parseLong(personId));
				SupplementWorkPerson supplementWorkPerson = new SupplementWorkPerson();
				supplementWorkPerson.setId(UUID.randomUUID().toString());
				supplementWorkPerson.setPersonPopedomId(personInfo.getPopedom());
				supplementWorkPerson.setSupplementWorkId(supplementWork.getId());
				supplementWorkPerson.setScheduleAttendanceId(workScheduleAttendance.getId());
				supplementWorkPerson.setCreateTime(new Date());
				supplementWorkPersonService.insert(supplementWorkPerson);
				workScheduleAttendance.setSupplementWorkPersonId(supplementWorkPerson.getId());
				workScheduleAttendanceService.update(workScheduleAttendance);
			}
		}

		if (n == personIdList.size()){
			throw new Exception("所选人员在此班次下没有缺卡记录");
		}

		if(StringUtils.isNotEmpty(ids)){
			update(supplementWork);
		}else {
			insert(supplementWork);
		}

		if ("1".equals(draft)) {
			//创建审核流程id
			String procInstId = procinstService.addProcInst(supplementWork.getId(),  "补卡", formId, personPopedom, null,null,null);

			supplementWork.setProcinstId(procInstId);
			supplementWork.setStatus("0");
			update(supplementWork);

			ProcinstActivity procinstActivity = procinstActivityService.findByActivityIndexAndProcinstId(1, procInstId);

			if (procinstActivity != null) {
				List<ProcinstActUser> procinstActUserList = procinstActUserService.findByProcinstActivityIdActionType(procinstActivity.getId(), "0", "1");
				if (procinstActUserList.size() > 0) {

					SupplementWork finalSupplementWork = supplementWork;
					new Thread(() -> {
						for (ProcinstActUser procinstActUser : procinstActUserList) {
							try {
								PersonInfo personInfo = personInfoService.get(Long.parseLong(procinstActUser.getUserId()));

								//提交人
								PersonInfo personInfo1 = personInfoService.get(personPopedom.getPersonId());
								String accessToken = JwtUtil2.createToken(jwtSecret, personInfo.getId() + "", DateTime.now().plusHours(30 * 24).toDate());
								WechatMessageUtil.sendEvenMessage(personInfo.getOpenId(), "有一条新的补卡信息待审核", personInfo1.getName(), com.jpsoft.shinestar.modules.common.utils.StringUtils.getApprovalNo(), "前往处理", wxConfig.getPortalUrl() + "xsy/approval/infosp?id=" + finalSupplementWork.getId() + "&procinstActUserId=" + procinstActUser.getId() + "&formId=" + formId + "&token=" + accessToken, wxConfig.getAppId(), wxConfig.getAppSecret());
							} catch (Exception ex) {
								ex.printStackTrace();
							}

						}
					}).start();

				}
			}
		}


		return supplementWork.getId();
	}
}