/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.cku.oa.dog.service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import com.cku.core.RESTResponse;
import com.cku.core.ZAErrorCode;
import com.cku.core.ZAException;
import com.cku.oa.dog.dao.DogAppraisalDao;
import com.cku.oa.dog.dao.DogChipChangeDao;
import com.cku.oa.dog.entity.Dog;
import com.cku.oa.dog.entity.DogAppraisal;
import com.cku.oa.dog.entity.DogBloodSave;
import com.cku.oa.dog.entity.DogChipChange;
import com.cku.oa.dog.entity.DogPedigreeCertifiedRedo;
import com.cku.oa.dog.entity.DogType;
import com.cku.oa.dog.entity.DogTypeShow;
import com.cku.oa.finance.dao.PaymentOrderDetailDao;
import com.cku.oa.finance.entity.PaymentChargingItem;
import com.cku.oa.finance.entity.PaymentOrderDetail;
import com.cku.oa.finance.service.PaymentChargingItemService;
import com.cku.oa.finance.service.PaymentOrderService;
import com.cku.oa.kennel.entity.Kennel;
import com.cku.oa.kennel.service.KennelService;
import com.cku.oa.show.dao.ChildShowsDao;
import com.cku.oa.show.dao.MainShowsDao;
import com.cku.oa.show.entity.ChildShows;
import com.cku.oa.show.entity.MainShows;
import com.cku.oa.sys.code.SysCodeUtil;
import com.cku.oa.sys.dao.OrgDao;
import com.cku.oa.sys.entity.Org;
import com.cku.oa.sys.entity.user.Member;
import com.cku.oa.sys.service.ExpressQueueService;
import com.cku.oa.sys.service.FileService;
import com.cku.oa.sys.service.LoginServerService;
import com.cku.oa.sys.service.user.MemberService;
import com.cku.oa.sys.util.MemberUtil;
import com.cku.oa.sys.zalog.SysContext;
import com.cku.restful.v1.dog.model.RestDogAppraisal;
import com.cku.restful.v1.finance.service.OADeleteService;
import com.cku.restful.v1.sys.utils.BeanUtil;
import com.cku.util.DateUtils;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 犬只鉴定表Service
 * 
 * @author lgl
 * @version 2016-08-09
 */
@Service
@Transactional(readOnly = true)
public class DogAppraisalService extends CrudService<DogAppraisalDao, DogAppraisal> {

	private static final String BUSINESS_NAME = "犬只鉴定";

	// 赛场犬只鉴定报名截至日期比赛事开始日期提前的天数。在赛事开始日期的基础上提前的天数
	public static final Integer SHOW_APPRAISAL_BEFORE_DAY = 4;

	@Autowired
	private PaymentChargingItemService paymentChargingItemService;
	@Autowired
	private DogService dogService;
	@Autowired
	private OrgDao orgDao;
	@Autowired
	private KennelService kennelService;
	@Autowired
	private DogChipChangeService dogChipChangeService;
	@Autowired
	private FileService fileService;
	@Autowired
	private ExpressQueueService expressQueueService;
	@Autowired
	private PaymentOrderService paymentOrderService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private OADeleteService oADeleteService;
	@Autowired
	private MainShowsDao mainShowsDao;
	@Autowired
	private ChildShowsDao childShowsDao;
	@Autowired
	private DogTypeService dogTypeService;
	@Autowired
	private DogTypeShowService dogTypeShowService;
	@Autowired
	private PaymentOrderDetailDao paymentOrderDetailDao;
	@Autowired
	private DogChipChangeDao dogChipChangeDao;
	@Autowired
	private DogBloodSaveService dogBloodSaveService;
	@Autowired
	private LoginServerService loginServerService;
	@Autowired
	private DogStickerApplyService dogStickerApplyService;
	@Autowired
	private DogVideoAppraisalService dogVideoAppraisalService;
	@Autowired
	private DogNoseService dogNoseService;
	@Autowired
	private DogPedigreeCertifiedRedoService  dogPedigreeCertifiedRedoService;
	

	public DogAppraisal get(String id) {
		return super.get(id);
	}


	@Transactional(readOnly = false)
	public String print(DogAppraisal request, Model model) throws ZAException {
		// 准备打印数据
		DogAppraisal dogAppraisal = get(request.getId());
		Dog dog = dogService.get(dogAppraisal.getDogId());
		return dogService.processPrintBusiness(dog, model, Boolean.TRUE);
	}

	/**
	 *
	 * @description: 重置犬只鉴定打印
	 * @author: laiguanglong
	 * @date: 2016年9月1日 下午3:13:01
	 */
	@Transactional(readOnly = false)
	public void resetPrint(DogAppraisal resetPrint) {
		// 准备打印数据
		DogAppraisal dogAppraisal = super.get(resetPrint.getId());
		Dog dog = dogService.getByPedigreeCertifiedCode(dogAppraisal.getPedigreeCertified());
		// 修改打印状态
		if ("01".equals(dog.getPrintState())) {
			dog.setPrintState("1");
			dogService.updatePrintState(dog);
		}
	}

	public List<DogAppraisal> findList(DogAppraisal dogAppraisal) {
		if (StringUtils.isBlank(dogAppraisal.getDogBreed())) {
			// 根据当前登录端查询犬种
			dogAppraisal.getSqlMap().put("dogBreedMap", loginServerService.dataScopeFilter());
		} else {
			dogAppraisal.getSqlMap().put("dogBreedMap", " ='" + dogAppraisal.getDogBreed() + "'");
		}
		return super.findList(dogAppraisal);
	}

	public Page<DogAppraisal> findPage(Page<DogAppraisal> page, DogAppraisal dogAppraisal) {
		dogAppraisal.setPage(page);
		page.setIbatisPagePluginEnable(false);
		if (StringUtils.isBlank(dogAppraisal.getDogBreed())) {
			// 根据当前登录端查询犬种
			dogAppraisal.getSqlMap().put("dogBreedMap", loginServerService.dataScopeFilter());
		} else {
			dogAppraisal.getSqlMap().put("dogBreedMap", " ='" + dogAppraisal.getDogBreed() + "'");
		}
		int count = dao.listCount(dogAppraisal);
		int pageNo = page.getPageNo();
		int pageSize = page.getPageSize();
		page.setCount(count);
		if ((pageNo - 1) * pageSize >= count) {
			page.setList(new ArrayList<DogAppraisal>(0));
			return page;
		}
		page.setList(dao.findList(dogAppraisal));
		return page;
	}

	public Page<DogAppraisal> findShowDogAppraisalPage(Page<DogAppraisal> page, DogAppraisal dogAppraisal) {
		dogAppraisal.setBefore(SHOW_APPRAISAL_BEFORE_DAY);
		dogAppraisal.setPage(page);
		page.setIbatisPagePluginEnable(false);
		int count = dao.listShowDogAppraisalCount(dogAppraisal);
		int pageNo = page.getPageNo();
		int pageSize = page.getPageSize();
		page.setCount(count);
		if ((pageNo - 1) * pageSize >= count) {
			page.setList(new ArrayList<DogAppraisal>(0));
			return page;
		}
		page.setList(dao.findShowDogAppraisalList(dogAppraisal));
		return page;
	}

	@Transactional(readOnly = false)
	public void save(DogAppraisal dogAppraisal) {
		super.save(dogAppraisal);
	}

	/**
	 *
	 * @description: 录入犬只鉴定记录
	 * @author: laiguanglong
	 * @date: 2016年8月16日 下午4:01:20
	 */
	@Transactional(readOnly = false)
	public void add(DogAppraisal dogAppraisal) {
		Member member = memberService.getByMemberCode(dogAppraisal.getPaymentMemberCode());
		// 校验犬种是否符合当前用户
		loginServerService.findDogTypeByMemberSite(dogAppraisal.getDogBreed(), member.getMemberSite());
		dogAppraisal.setDogOwnerCode(member.getMemberCode());
		dogAppraisal.setDogOwnerName(member.getName());
		dogAppraisal.setIdentifyCode(dogAppraisal.getDogChip());
		// 状态为 审核中
		dogAppraisal.setReviewState("5");
		// 都是线下已经支付了的订单，故状态为已支付
		dogAppraisal.setPaymentState("2");
		dogAppraisal.setPaymentTime(paymentOrderService.getPaymentTimeByOrderCode(dogAppraisal.getRunningNumber()));
		// 处理状态为未处理
		dogAppraisal.setProcessState("0");
		// 证书号未Null,防止关联出多条数据
		dogAppraisal.setPedigreeCertified(null);
		// 根据支付项查询金额
		PaymentChargingItem paymentChargingItem = paymentChargingItemService
				.get(dogAppraisal.getPaymentChargingItemId());
		dogAppraisal.setPrice(paymentChargingItem.getPrice());
		// 如果宠爱证书号不为空，根据宠爱证书编号进行查重
		if (StringUtils.isNotBlank(dogAppraisal.getChongaiCertificateCode())) {
			DogAppraisal po = dao.getByChongaiCertificateCode(dogAppraisal.getChongaiCertificateCode());
			if (po != null) {
				throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "该宠爱证书号已存在");
			}
		}
		// 填充赛事信息
		if (StringUtils.isNotBlank(dogAppraisal.getMainShowId())) {
			setMainshowsInfo(dogAppraisal, dogAppraisal.getMainShowId());
		}
		// 设置地方俱乐部信息 填充赛事编号
		if (StringUtils.isNotBlank(dogAppraisal.getHospitalId())) {
			setOrgInfo(dogAppraisal);
		}
		super.save(dogAppraisal);
	}

	/**
	 * 填充俱乐部赛事鉴定编号
	 * 
	 * @Author chaixueteng
	 * @2017年11月30日上午9:57:25
	 */
	@Transactional(readOnly = false)
	public void setOrgInfo(DogAppraisal dogAppraisal) {
		Org org = orgDao.get(dogAppraisal.getHospitalId());
		String orgAppraisalCode = SysCodeUtil.getOrgAppraisalCode(org.getMemberCode());
		dogAppraisal.setShowAppraisalCode(orgAppraisalCode);
	}

	@Transactional(readOnly = false)
	public void delete(DogAppraisal dogAppraisal) {
		// 已缴费的订单不允许删除
		if ("2".equals(dogAppraisal.getPaymentState())) {
			throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "该订单已缴费，不允许删除");
		}
		// OA删除订单
		oADeleteService.deleteUnpay(dogAppraisal.getPaymentState(), "dog_appraisal", dogAppraisal.getId(),
				dogAppraisal.getRunningNumber());
		// 如果是oa报名的话，没有订单，故没走上面的删除，所以需要再次删除
		super.delete(dogAppraisal);
	}

	@Transactional(readOnly = false)
	public void edit(DogAppraisal dogAppraisal) {
		DogAppraisal po = dao.findById(dogAppraisal.getId());
		if ("0".equals(dogAppraisal.getProcessState()) && !dogAppraisal.getDogChip().equals(po.getDogChip())) {
			// 未处理的情况下，如果芯片号变更了，关联更新芯片变更表
			if (StringUtils.isNotBlank(dogAppraisal.getShowAppraisalCode())) {
				DogChipChange dogChipChange = dogChipChangeDao
						.getByShowAppraisalCode(dogAppraisal.getShowAppraisalCode());
				if (dogChipChange != null) {
					dogChipChange.setChipCodeOld(po.getDogChip());
					dogChipChange.setChipCodeNew(dogAppraisal.getDogChip());
					dogChipChange.preUpdate();
					dogChipChangeDao.update(dogChipChange);
				}
			}
		} else {
			// 还原芯片号
			dogAppraisal.setDogChip(po.getDogChip());
		}
		// 鉴定人不转意
		dogAppraisal.setIdentifier(StringEscapeUtils.unescapeHtml4(dogAppraisal.getIdentifier()));
		super.save(dogAppraisal);
	}

	/**
	 *
	 * @description: 审核犬只鉴定
	 * @author: laiguanglong
	 * @date: 2016年8月18日 下午4:10:48
	 */
	@Transactional(readOnly = false)
	public void audit(DogAppraisal review) throws ZAException {
		try {
			DogAppraisal dogAppraisal = get(review.getId());
			String reviewState = dogAppraisal.getReviewState();
			// 由于犬只鉴定的审核状态与状态机的审核状态不一致，需要进行转换
			if ("5".equals(reviewState) || "2".equals(reviewState)) {
				// 审核中转换为未审核
				reviewState = "0";
			} else if ("1".equals(reviewState)) {
				// 通过
				reviewState = "1";
			} else {
				// 其他包括0不通过，3非纯种犬，4注销都转换为未通过
				reviewState = "2";
			}
			// 若处理状态字段为空，为处理状态赋初始值“0”
			if (dogAppraisal != null
					&& (dogAppraisal.getProcessState() == null || "".equals(dogAppraisal.getProcessState()))) {
				dogAppraisal.setProcessState("0");
			}
			SysContext sysContext = new SysContext(dogAppraisal.getPaymentState(), reviewState,
					dogAppraisal.getProcessState());
			// 审核的时候还能修改鉴定人、鉴定地点、芯片号、血统证书号（生成）、图片
			dogAppraisal.setIdentifier(review.getIdentifier());
			dogAppraisal.setIdentifySite(review.getIdentifySite());
			dogAppraisal.setDogChip(review.getDogChip());
			if (StringUtils.isBlank(review.getPedigreeCertified()) && "1".equals(review.getReviewState())) {
				// 如果血统证书号为空且审核通过，生成
				dogAppraisal.setPedigreeCertified(SysCodeUtil.getPedigreeCertifiedCode(dogAppraisal.getDogBreed()));
			}
			// 如果dna图片不为空且跟数据库值不一样，需要进行裁剪
			if (StringUtils.isNotBlank(review.getDogDnaImage())
					&& !review.getDogDnaImage().equals(dogAppraisal.getDogDnaImage())) {
				cutDogDnaImage(review.getDogDnaImage());
			}
			dogAppraisal.setDogDnaImage(review.getDogDnaImage());
			// 审核相关字段
			dogAppraisal.setReviewRemarks(review.getReviewRemarks());
			dogAppraisal.setReviewTime(new Date());
			if ("1".equals(review.getReviewState())) {
				// 审核通过
				sysContext.confirmSuccess(sysContext, BUSINESS_NAME, dogAppraisal.getPaymentMemberCode(),
						"dog_appraisal", dogAppraisal.getId(), dogAppraisal.getRunningNumber(), (str) -> {
						});
				dogAppraisal.setReviewState(review.getReviewState());
			} else if ("0".equals(review.getReviewState())) {
				// 审核不通过
				sysContext.confirmFail(sysContext, BUSINESS_NAME, review.getReviewRemarks(),
						dogAppraisal.getPaymentMemberCode(), "dog_appraisal", dogAppraisal.getId(),
						dogAppraisal.getRunningNumber(), (str) -> {
						});
				dogAppraisal.setReviewState(review.getReviewState());
			} else if ("3".equals(review.getReviewState())) {
				// 非纯种犬
				sysContext.confirmFail(sysContext, BUSINESS_NAME, review.getReviewRemarks(),
						dogAppraisal.getPaymentMemberCode(), "dog_appraisal", dogAppraisal.getId(),
						dogAppraisal.getRunningNumber(), (str) -> {
						});
				dogAppraisal.setReviewState(review.getReviewState());
			} else if ("4".equals(review.getReviewState())) {
				// 注销
				sysContext.confirmFail(sysContext, BUSINESS_NAME, review.getReviewRemarks(),
						dogAppraisal.getPaymentMemberCode(), "dog_appraisal", dogAppraisal.getId(),
						dogAppraisal.getRunningNumber(), (str) -> {
						});
				dogAppraisal.setReviewState(review.getReviewState());
			}
			super.save(dogAppraisal);
		} catch (ZAException e) {
			throw e;
		}
	}

	/**
	 *
	 * @description: 对DNA图片进行裁剪
	 * @author: laiguanglong
	 * @date: 2016年8月25日 下午4:35:07
	 */
	private void cutDogDnaImage(String dogDnaImage) throws ZAException {
		fileService.fileCut(dogDnaImage);
	}

	/**
	 *
	 * @description: 犬只鉴定处理
	 * @author: laiguanglong
	 * @date: 2016年8月18日 下午4:25:11
	 */
	@Transactional(readOnly = false)
	public void resolve(DogAppraisal review) throws ZAException {
		try {
			DogAppraisal dogAppraisal = get(review.getId());
			String reviewState = dogAppraisal.getReviewState();
			// 由于犬只鉴定的审核状态与状态机的审核状态不一致，需要进行转换
			if ("2".equals(reviewState) || "5".equals(reviewState)) {
				// 审核中转换为未审核
				reviewState = "0";
			} else if ("1".equals(reviewState)) {
				// 通过
				reviewState = "1";
			} else {
				// 其他包括0不通过，3非纯种犬，4注销都转换为未通过
				reviewState = "2";
			}
			SysContext sysContext = new SysContext(dogAppraisal.getPaymentState(), reviewState,
					dogAppraisal.getProcessState());
			sysContext.updateData(sysContext, BUSINESS_NAME, dogAppraisal.getPaymentMemberCode(), "dog_appraisal",
					dogAppraisal.getId(), dogAppraisal.getRunningNumber(), (str) -> {
					});
			dogAppraisal.setProcessState("1");
			dogAppraisal.setProcessTime(new Date());
			dogAppraisal.setPedigreeCertified(SysCodeUtil.getPedigreeCertifiedCode(dogAppraisal.getDogBreed()));
			// 写入犬只信息表
			Dog dog = insertDog(dogAppraisal);
			
			// 关联鼻纹信息
			if (StringUtils.isNotEmpty(dogAppraisal.getDogNose())) {
				dogNoseService.saveNoseIdByAdmin(dogAppraisal.getDogNose(), null, dog.getId());
			}

			dogAppraisal.setDogId(dog.getId());
			super.save(dogAppraisal);
			// 写入犬只芯片变更表
			insertDogChipChange(dog.getId(), dogAppraisal);
			// update by zjw 2023-02-07 工单号：ID1005116 取消宠爱护照发放
			// 等级贴纸业务
//			if ("1".equals(dogAppraisal.getStickerFlag())) {
//				dogStickerApplyService.applySticker(dog, dogAppraisal.getDogOwnerCode(),
//						dogAppraisal.getRunningNumber());
//			}
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 *
	 * @description: 写入犬只信息表
	 * @author: laiguanglong
	 * @date: 2016年8月17日 下午4:47:02
	 */
	private Dog insertDog(DogAppraisal dogAppraisal) {
		Dog dog = new Dog();
		dog.setPrintState("1");// 打印鉴定证书
		dog.setDogBreed(dogAppraisal.getDogBreed());
		// 设置FCi赛事编码
		List<DogTypeShow> dogTypeShowList = dogTypeShowService.findListByDogBreed(dog.getDogBreed());
		if (dogTypeShowList != null && dogTypeShowList.size() == 1) {
			dog.setShowDogBreed(dogTypeShowList.get(0).getDogShowCode());
		}
		dog.setColorFlag(dogAppraisal.getDogFurColor());
		dog.setBirthdate(dogAppraisal.getBirthday());
		dog.setGender(dogAppraisal.getDogGender());
		dog.setMemberCode(dogAppraisal.getDogOwnerCode());
		dog.setDogOwner(dogAppraisal.getDogOwnerName());
		dog.setPedigreeCertifiedCode(dogAppraisal.getPedigreeCertified());
		if (StringUtils.isBlank(dogAppraisal.getDogChip())) {
			throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "芯片号为空，不能进行处理");
		}
		dog.setIdentificationFlag(dogAppraisal.getDogChip());
		// 由于血统证书号是刚生成的，所以该犬只为第0代
		dog.setDogGeneration("0");
		// 生成犬只姓名
		dog.setNameEn(getDogName(dogAppraisal));
		dog.setDelFlag("0");
		dog.setDogState("0");
		// 判断血样留存
		DogBloodSave bloodSave = dogBloodSaveService.getByShowAppraisalCode(dogAppraisal.getShowAppraisalCode());
		if (bloodSave != null && !StringUtils.isBlank(bloodSave.getId())) {
			dog.setDnaSaveWay("0");
		}
		
		dogService.save(dog);
		return dog;
	}

	/**
	 *
	 * @description: 生成犬只姓名
	 * @author: laiguanglong
	 * @date: 2016年8月17日 下午4:38:04
	 */
	private String getDogName(DogAppraisal dogAppraisal) {
		Kennel kennel = kennelService.getKennelByMemberCode(dogAppraisal.getDogOwnerCode());
		if (kennel == null) {
			return dogAppraisal.getDogName();
		} else {
			return dogAppraisal.getDogName() + " of " + kennel.getNameEn() + "’s";
		}
	}

	/**
	 *
	 * @description: 写入犬只芯片变更表
	 * @author: laiguanglong
	 * @date: 2016年8月17日 下午4:48:22
	 */
	private void insertDogChipChange(String dogId, DogAppraisal dogAppraisal) {
		DogChipChange dogChipChange;
		// 如果赛场鉴定编号不为空，必须要缴纳芯片费，缴纳芯片费的时候已经写入了芯片变更表，所以这里不需要在写入芯片变更表
		if (StringUtils.isNotBlank(dogAppraisal.getShowAppraisalCode())) {
			dogChipChange = dogChipChangeDao.getByShowAppraisalCode(dogAppraisal.getShowAppraisalCode());
			if (dogChipChange == null) {
				return;
			}
			dogChipChange.setDogId(dogId);
		} else {
			dogChipChange = new DogChipChange();
			dogChipChange.setDogId(dogId);
			dogChipChange.setChipCodeNew(dogAppraisal.getDogChip());
			dogChipChange.setPaymentMemberCode(dogAppraisal.getPaymentMemberCode());
			dogChipChange.setReviewState("1");
			dogChipChange.setReviewTime(new Date());
			dogChipChange.setPaymentState("2");
			dogChipChange.setProcessState("0");
			dogChipChange.setRunningNumber(dogAppraisal.getRunningNumber());
		}
		dogChipChangeService.save(dogChipChange);
	}

	/**
	 *
	 * @description: 获取已付款待审核的犬只鉴定申请记录数
	 * @author: laiguanglong
	 * @date: 2016年8月29日 下午4:15:10
	 */
	public int getAuditCount() {
		DogAppraisal dogAppraisal = new DogAppraisal();
		// 已付款
		dogAppraisal.setPaymentState("2");
		// 未审核
		dogAppraisal.setReviewState("2");
		return dao.listCount(dogAppraisal);
	}

	/**
	 *
	 * @description: 根据血统证书号进行查询
	 * @author: laiguanglong
	 * @date: 2016年9月1日 下午4:10:27
	 */
	public DogAppraisal getByPedigreeCertified(String pedigreeCertified) {
		return dao.getByPedigreeCertified(pedigreeCertified);
	}

	/**
	 *
	 * @Description：DNA打印数据维护
	 * @author: zhuoHeng
	 * @version: 2016年10月9日 下午4:04:09
	 */
	@Transactional(readOnly = false)
	public String printDna(DogAppraisal print, Model model) {
		// 准备打印数据
		model.addAttribute("dogAppraisal", print);
		String reviewState = print.getReviewState();
		if ("3".equals(reviewState)) {
			model.addAttribute("reviewState", "1");
		} else {
			model.addAttribute("reviewState", "2");
		}
		// 修改打印状态
		print.setDnaPrintFlag("1");
		dao.update(print);

		// 通过状态机记录日志
		SysContext sysContext = new SysContext(null, null, null);
		sysContext.noStateExecute(sysContext, BUSINESS_NAME + "DNA打印", print.getPaymentMemberCode(), "dog_appraisal",
				print.getId(), print.getRunningNumber(), (str) -> {
				});

		// 添加待邮寄物品
		expressQueueService.push(print.getDogOwnerCode(), print.getRunningNumber(), "犬只DNA鉴定证书",
				print.getPedigreeCertified(), "22"); // GYH1 modified

		// 设置跳转页面
		return "oa/dog/dogappraisal/dogAppraisalDnaPrint";
	}

	/**
	 *
	 * @description: 重置犬只DNA鉴定打印
	 * @author: laiguanglong
	 * @date: 2016年9月1日 下午3:13:01
	 */
	@Transactional(readOnly = false)
	public void resetPrintDna(DogAppraisal resetPrint) {
		resetPrint.setDnaPrintFlag("0");
		dao.update(resetPrint);
	}

	/**
	 * @description: 业务校验
	 * @author: laiguanglong
	 * @date: 2017/5/10 14:49
	 */
	public void validateBusiness(DogAppraisal po) {
		
		if(!StringUtils.isEmpty(po.getVideoAppraisalId())) {
			DogAppraisal dogAppraisal = this.getbyVideoId(po.getVideoAppraisalId());
			if(dogAppraisal != null) {
				throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "视频鉴定犬无效");
			}
		}
		// 报名截至时间校验
		MainShows mainShows = mainShowsDao.get(po.getMainShowId());
		Calendar calendar = Calendar.getInstance();
//		calendar.setTime(mainShows.getClosingTime());
//		calendar.add(Calendar.DATE, -DogAppraisalService.SHOW_APPRAISAL_BEFORE_DAY);
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (System.currentTimeMillis() > mainShows.getClosingTime().getTime()) {
			throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "报名时间已截止");
		}
		 
		// 藏獒犬种不能在线申请犬只鉴定
		if ("230".equals(po.getDogBreed())) {
			throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "藏獒犬种不能在线申请犬只鉴定");
		}
		// 6） 办理此业务需要保证cku会员（基础或者专业）有效
		Member member = UserUtils.getLoginMember();
		if (!MemberUtil.isActiveMember(member)) {
			throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "该业务仅限有效会员办理");
		}
		if (UserUtils.getMemberCardType(member) <= 0) {
			throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "该业务仅限基础白银以上会员办理");
		}
//		if(!"basic".equals(member.getMemberType())&&!"professional".equals(member.getMemberType())){
//			throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "该业务仅限基础会员或专业会员办理");
//		}
		// 犬名为英文名
		if (!po.getDogName().matches("^[a-zA-Z ]+$")) {
			throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "犬名只能是英文");
		}
		// 犬只年龄大于3个月
		calendar.setTime(po.getBirthday());
		calendar.add(Calendar.MONTH, 3); // 月份加x
		if (calendar.getTimeInMillis() > mainShows.getStartTime().getTime()) {
			throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "犬只年龄必须大于3个月");
		}
		// 每场最多40条报名记录
		int count = dao.countByMainShowId(po.getMainShowId());
		if (count >= 40) {
			throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "报名人数已达上限，请选择其他赛事报名。");
		}
	}

	/**
	 *
	 * @description: 赛场鉴定批量打印
	 * @author: laiguanglong
	 * @date: 2016年8月2日 上午10:42:15
	 */
	public String printList(String showCodePrefix, Model model) {
		if (!checkShowCode(showCodePrefix)) {
			throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "犬只鉴定报名未结束，不允许打印");
		}
		List<DogAppraisal> list = dao.findShowDogAppraisalListByShowCode(showCodePrefix);
		model.addAttribute("list", list);
		return "oa/show/dogappraisal/dogAppraisalPrintList";
	}

	/**
	 *
	 * @description: 赛场鉴定单个打印
	 * @author: laiguanglong
	 * @date: 2016年8月2日 上午10:42:15
	 */
	public String printOne(String id, Model model) {
		DogAppraisal dogAppraisal = dao.findShowDogAppraisalById(id);
		model.addAttribute("dogAppraisal", dogAppraisal);
		return "oa/show/dogappraisal/dogAppraisalPrintOne";
	}

	/**
	 *
	 * @description: 根据赛事编号检验是否可以打印
	 * @author: laiguanglong
	 * @date: 2016年8月2日 上午10:42:15
	 */
	public Boolean checkShowCode(String showCodePrefix) {
		List<DogAppraisal> list = dao.findShowDogAppraisalListByShowCode(showCodePrefix);
		if (list.size() > 0) {
			DogAppraisal dogAppraisal = list.get(0);
			MainShows mainShows = mainShowsDao.get(dogAppraisal.getMainShowId());
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.DATE, DogAppraisalService.SHOW_APPRAISAL_BEFORE_DAY);
			if (calendar.getTimeInMillis() > mainShows.getStartTime().getTime()) {
				return true;
			}
		}
		return false;
	}

	/**
	 *
	 * @Description：根据赛场鉴定编号进行查询,返回是否存在数据标识
	 * @author: zhuoHeng
	 * @version: 2016年10月14日 下午4:27:21
	 */
	public HashMap<String, String> getMessageByBirthCerRegCode(String birthCerRegCode) {
		HashMap<String, String> map = new HashMap<String, String>();
		DogAppraisal model = dao.getByShowAppraisalCode(birthCerRegCode);
		String flag = "failure";
		if (model != null) {
			flag = "success";
			map.put("dogChip", model.getDogChip());
		}
		map.put("flag", flag);
		return map;
	}

	/**
	 *
	 * @description: 添加DNA存档订单页面，根据赛场鉴定编号查询犬只信息
	 * @author: laiguanglong
	 * @date: 2016年8月23日 下午5:22:03
	 */
	public HashMap<String, String> getDogByShowAppraisalCode(String showAppraisalCode) {
		HashMap<String, String> map = new HashMap<String, String>();
		DogAppraisal dogAppraisal = dao.getByShowAppraisalCode(showAppraisalCode);
		if (dogAppraisal != null) {
			map.put("nameEn", dogAppraisal.getDogName());
			map.put("birthdate", DateUtils.dateToStr(dogAppraisal.getBirthday()));
			map.put("gender", DictUtils.getDictLabel(dogAppraisal.getDogGender(), "dog_gender", ""));
			map.put("colorFlag", dogAppraisal.getDogFurColor());
			map.put("identificationFlag", dogAppraisal.getDogChip());
			DogType dogType = dogTypeService.getByDogBreedCode(dogAppraisal.getDogBreed());
			if (dogType != null) {
				map.put("dogBreed", dogType.getBreedCnName());
			}
		}
		return map;
	}

	/**
	 * @description: 根据赛场鉴定流水号查询清单详情，看是否有id为15，22，240,241的收费项id
	 * @author: laiguanglong
	 * @date: 2017/5/15 17:54
	 */
	public String getIsFinishOrder(DogAppraisal po) {
		if (StringUtils.isNotBlank(po.getShowAppraisalOrderRunningNumber())) {
			List<PaymentOrderDetail> paymentOrderDetailList = paymentOrderDetailDao
					.getOrderByRunningNum(po.getShowAppraisalOrderRunningNumber(), po.getDogOwnerCode());
			boolean flag15 = false;
			boolean flag22 = false;
			for (PaymentOrderDetail paymentOrderDetail : paymentOrderDetailList) {
				if ("15".equals(paymentOrderDetail.getChargingItemId())) {
					flag15 = true;
				} else if ("22".equals(paymentOrderDetail.getChargingItemId())
						|| "246".equals(paymentOrderDetail.getChargingItemId())) {
					flag22 = true;
				}
			}
			if (flag15 && flag22 && StringUtils.isNotBlank(po.getDogChip())) {
				return "1";
			}
		}
		return "0";
	}

	/**
	 * @description: 获取业务状态
	 * @author: laiguanglong
	 * @date: 2017/5/17 19:11
	 */
	public String getBusinessState(DogAppraisal po) {
//		if("1".equals(po.getIsCanceled())){
//			return "已撤销";
//		}else if("2".equals(po.getReviewState())){
//			return "未通过";
//		}else if("1".equals(po.getReviewState())){
//			Dog dog = dogDao.getByPedigreeCertifiedEn(po.getOverseasPedigreeCertified());
//			if(dog==null){
//				return "已通过";
//			}else{
//				if("2".equals(dog.getPrintState())){
//					return "待打印";
//				}else if("02".equals(dog.getPrintState())){
//					if(po.getSendDate()!=null&&System.currentTimeMillis()>po.getSendDate().getTime()){
//						return "已寄出";
//					}else{
//						return "待邮寄";
//					}
//				}
//			}
//		}else if("0".equals(po.getReviewState())){
//			if("1".equals(po.getPaymentState())){
//				return "待支付";
//			}else if("2".equals(po.getPaymentState())){
//				return "待审核";
//			}
//		}
		return "";
	}

	/**
	 * @description: 生成赛场鉴定编号
	 * @author: laiguanglong
	 * @date: 2017/5/12 18:35
	 */
	private String getShowAppraisalCodeByShowCode(String showCode) {
		String maxShowAppraisalCode = dao.getMaxShowAppraisalCodeByShowCode(showCode);
		if (StringUtils.isBlank(maxShowAppraisalCode)) {
			return showCode + "0001";
		}
		int index = Integer.valueOf(maxShowAppraisalCode.replace(showCode, "")).intValue();
		DecimalFormat format = new DecimalFormat("0000");
		return showCode + format.format(index + 1);
	}

	/**
	 * @description: 设置赛场鉴定相关字段
	 * @author: laiguanglong
	 * @date: 2017/6/7 15:34
	 */
	public void setMainshowsInfo(DogAppraisal po, String mainShowId) {
		// 获取赛事信息
		MainShows mainShows = mainShowsDao.get(mainShowId);
		List<ChildShows> childShowsList = childShowsDao.getByMainShowId(mainShows.getId());
		String showCode = "";
		if (childShowsList.size() > 0) {
			ChildShows childShows = childShowsList.get(0);
			if (childShows != null && StringUtils.isNotBlank(childShows.getShowCode())
					&& childShows.getShowCode().length() >= 7) {
				if (StringUtils.isNumeric(childShows.getShowCode().substring(0, 7))) {
					showCode = childShows.getShowCode().substring(0, 7);
				} else if (StringUtils.isNumeric(childShows.getShowCode().substring(0, 6))) {
					showCode = childShows.getShowCode().substring(0, 6);
				}
			}
		}
		po.setMainShowId(mainShows.getId());
		po.setMainShowInfo(showCode + mainShows.getShowLocation());
		// 生成赛场鉴定编号
		po.setShowAppraisalCode(getShowAppraisalCodeByShowCode(showCode));
		String[] locations = mainShows.getShowLocation().split("-");
		po.setIdentifySite(locations.length > 0 ? locations[0] : "");
		po.setIdentifyDate(mainShows.getStartTime());
	}

	// 繁殖鉴定退款详情
	public RESTResponse getRefundList(String ids) {
//		// 繁殖鉴定
//		PaymentOrderDetail paymentOrderDetail = new PaymentOrderDetail();
//		// 获取繁殖鉴定收费项
//		PaymentChargingItem dogAppraisalItem1 = paymentChargingItemService.getByShortName("dog_appraisal@All");
//		collect.entrySet().forEach(i -> {
//			i.getValue().forEach(j -> {
//				// 繁殖鉴定
//				if (j.getChargingItemId().equals(dogAppraisalItem1.getId())
//						&& j.getBusinessTable().equals("dog_appraisal")) {
//					paymentOrderDetail.setBusinessIds(j.getBusinessIds());
//					paymentOrderDetail.setBusinessTable(j.getBusinessTable());
//				}
//			});
//		});
//		// 返回数据集合
//		List<RestDogAppraisal> list = new ArrayList<>();
//		if (paymentOrderDetail.getBusinessIds() == null) {
//			return new RESTResponse("data", list);
//		}
		List<RestDogAppraisal> list = new ArrayList<>();
//		// 条件
		DogAppraisal dogAppraisal = new DogAppraisal();
		dogAppraisal.setDelFlag("0");
		dogAppraisal.setId(ids);
		List<DogAppraisal> lists = this.findList(dogAppraisal);
		for (DogAppraisal l : lists) {
			RestDogAppraisal vo = new RestDogAppraisal();
			BeanUtil.copyProperties(vo, l, "yyyy-MM-dd");
			DogType byDogBreedCode = dogTypeService.getByDogBreedCode(vo.getDogBreed());
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			vo.setDogBreed(byDogBreedCode.getBreedCnName());
            vo.setCreateDate(simpleDateFormat.format(l.getCreateDate()));
            vo.setIdentifyDate(simpleDateFormat.format(l.getIdentifyDate()));
			vo.setReviewState(DictUtils.getDictLabel(vo.getReviewState(), "dog_appraisal_review_state", ""));
			list.add(vo);
		}
		return new RESTResponse("data", list);
	}

	public void afterPay(String id) {
		DogAppraisal dogAppraisal = this.get(id);
		if (dogAppraisal == null) {
			return;
		}
		String videoAppraisalId = dogAppraisal.getVideoAppraisalId();
		if(StringUtils.isEmpty(videoAppraisalId)) {
			return;
		}
		dogVideoAppraisalService.updateAppraisalStatus(videoAppraisalId);
	}
	
	public DogAppraisal getbyVideoId (String videoAppraisalId) {
		return dao.getbyVideoId(videoAppraisalId);
	}
}