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

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
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.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.CarryThingsOutFactoryDAO;
import com.jpsoft.shinestar.modules.business.entity.CarryThingsOutFactory;
import com.jpsoft.shinestar.modules.business.service.CarryThingsOutFactoryService;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.github.pagehelper.PageHelper;

@Transactional
@Component(value="carryThingsOutFactoryService")
public class CarryThingsOutFactoryServiceImpl implements CarryThingsOutFactoryService {
	@Resource(name="carryThingsOutFactoryDAO")
	private CarryThingsOutFactoryDAO carryThingsOutFactoryDAO;

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

	@Autowired
	private ProcinstService procinstService;

	@Autowired
	private ProcinstActivityService procinstActivityService;

	@Autowired
	private ProcinstActUserService procinstActUserService;

	@Autowired
	private PersonInfoService personInfoService;

	@Autowired
	private WxConfig wxConfig;

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

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

		return carryThingsOutFactoryDAO.insert(model);
	}

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

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

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

		return count > 0 ? true : false;
	}

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

	@Override
	public int getAppointmentPassNum(Map<String, Object> searchParams){
		return carryThingsOutFactoryDAO.getAppointmentPassNum(searchParams);
	}

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

        return page;
	}

	@Override
	public String submitCarryThings(PersonPopedom personPopedom, String date, String images, String content, String formId,String ids,String draft) throws Exception {


		CarryThingsOutFactory carryThingsOutFactory = new CarryThingsOutFactory();
		if(StringUtils.isNotEmpty(ids)){
			carryThingsOutFactory=carryThingsOutFactoryDAO.get(ids);

		}else{
			carryThingsOutFactory = new CarryThingsOutFactory();
			carryThingsOutFactory.setId(UUID.randomUUID().toString());
		}

		carryThingsOutFactory.setPersonPopedomId(personPopedom.getId());
		carryThingsOutFactory.setLeaveFactoryTime(DateUtil.parse(date));
		carryThingsOutFactory.setLeaveFactoryReason(content);
		carryThingsOutFactory.setImage(images);
		carryThingsOutFactory.setAuditStatus("-99");
		carryThingsOutFactory.setCreateTime(new Date());

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

		if ("1".equals(draft)) {
			String procInstId = procinstService.addProcInst(carryThingsOutFactory.getId(),  "携物出厂", formId, personPopedom, null,null,null);

			carryThingsOutFactory.setProcinstId(procInstId);
			carryThingsOutFactory.setAuditStatus("0");
			update(carryThingsOutFactory);

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

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

					CarryThingsOutFactory finalCarryThingsOutFactory = carryThingsOutFactory;
					new Thread(() -> {
						for (ProcinstActUser procinstActUser : procinstActUserList) {
							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=" + finalCarryThingsOutFactory.getId() + "&procinstActUserId=" + procinstActUser.getId() + "&formId=" + formId + "&token=" + accessToken, wxConfig.getAppId(), wxConfig.getAppSecret());
						}
					}).start();
				}
			}
		}
		return carryThingsOutFactory.getId();

	}

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

		return page;
	}

}