package com.cku.partner.club.service;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cku.core.ZAErrorCode;
import com.cku.core.ZAException;
import com.cku.oa.dog.entity.Dog;
import com.cku.oa.dog.entity.DogBirthCertificate;
import com.cku.oa.dog.entity.DogColorMark;
import com.cku.oa.dog.service.DogBirthCertificateService;
import com.cku.oa.dog.service.DogColorMarkService;
import com.cku.oa.dog.service.DogService;
import com.cku.oa.finance.dao.PaymentOrderDetailDao;
import com.cku.oa.finance.entity.PaymentChargingItem;
import com.cku.oa.finance.entity.PaymentOrder;
import com.cku.oa.finance.entity.PaymentOrderDetail;
import com.cku.oa.finance.service.PaymentChargingItemService;
import com.cku.oa.finance.service.SaPaymentDetailTotalService;
import com.cku.oa.sys.entity.Org;
import com.cku.oa.sys.entity.user.Member;
import com.cku.partner.club.dao.CompanionDogAppraisalDao;
import com.cku.partner.club.entity.CompanionDogAppraisal;
import com.cku.partner.club.entity.FsbDogGrounding;
import com.cku.restful.v1.finance.service.RestOrderService;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

import net.sf.json.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 伴侣级鉴定Service
 *
 * @author pp
 * @version 2019-07-04
 */
@Service
@Transactional(readOnly = true)
public class CompanionDogAppraisalService extends CrudService<CompanionDogAppraisalDao, CompanionDogAppraisal> {

    public static final String COMPANION_DOG_APPRAISAL = "dbdfb76d10c245b0a54c829ef4d31f03";//伴侣犬鉴定收费项序号;
    @Autowired
    private PaymentOrderDetailDao paymentOrderDetailDao;
    @Autowired
    private PaymentChargingItemService paymentChargingItemService;

    @Autowired
    private RestOrderService restOrderService;

    @Autowired
    public DogBirthCertificateService dogBirthCertificateService;
    @Autowired
    public DogService dogService;
    @Autowired
    private DogColorMarkService dogColorMarkService;
    @Autowired
    private FsbDogGroundingService fsbDogGroundingService;
    @Autowired
    private SaPaymentDetailTotalService saPaymentDetailTotalService;

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

    /**
     * 根据芯片号获取伴侣信息
     *
     * @param request
     * @param response
     * @return
     */
    public Object getByIdentificationFlag(HttpServletRequest request, HttpServletResponse response) {
        String identificationFlag = request.getParameter("identificationFlag");
        String id = request.getParameter("id");
        CompanionDogAppraisal cda = new CompanionDogAppraisal();
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isNotEmpty(identificationFlag)) {
            FsbDogGrounding fsb = fsbDogGroundingService.getByIdentificationFlag(identificationFlag);
            if (fsb != null) {
                map.put("rc", "-1");
                map.put("msg", "芯片号已申请宠集盒，不能重复申请");
                return map;
            }
            cda = dao.getByIdentificationFlag(identificationFlag, "");

        } else
            cda = dao.get(id);
        if (cda == null) {
            map.put("rc", "-1");
            map.put("msg", "数据不存在");
            return map;
        }
        if (!"2".equals(cda.getPaymentState()) || !"1".equals(cda.getAppraisalResult())) {
            map.put("rc", "-1");
            map.put("msg", "未交费或者未审核通过不能上架申请");
            return map;
        }
        map.put("rc", "0");
        map.put("petType", cda.getPetType());
        map.put("petName", cda.getPetName());
        map.put("dogGender", cda.getPetGender());
        map.put("petBirthdate", DateUtils.formatDate(cda.getPetBirthdate(), "yyyy-MM-dd"));
        map.put("petColor", cda.getPetColor());
        map.put("petOwnerMobile", cda.getPetOwnerMobile());
        map.put("petOwner", cda.getPetOwner());
        map.put("appraisalResult", cda.getAppraisalResult());
        map.put("appraisal", cda.getAppraisal());
        map.put("appraisalDate", DateUtils.formatDate(cda.getAppraisalDate(), "yyyy-MM-dd"));
        map.put("frontPic", cda.getFrontPic());
        map.put("sidePic", cda.getSidePic());
        map.put("backPic", cda.getBackPic());
        map.put("identificationFlag", cda.getIdentificationFlag());
        map.put("passportNo", cda.getPassportNo());
        map.put("id", cda.getId());
        return map;
    }

    public Object getByIdentificationFlag(HttpServletRequest request) {
        String identificationFlag = request.getParameter("identificationFlag");
        String id = request.getParameter("id");
        CompanionDogAppraisal cda = new CompanionDogAppraisal();
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isNotEmpty(identificationFlag)) {
            cda = dao.getByIdentificationFlag(identificationFlag, "0");
            if (cda != null) {
                FsbDogGrounding f = new FsbDogGrounding();
                f.setAppraisalId(cda.getId());
                List<FsbDogGrounding> ls = fsbDogGroundingService.findList(f);
                if (ls != null && ls.size() > 0) {
                    map.put("rc", "-1");
                    map.put("msg", "不能重复申请已上架");
                    return map;
                }
            }
        }
        if (StringUtils.isNotEmpty(id))
            cda = get(id);
        if (StringUtils.isEmpty(id) && StringUtils.isEmpty(identificationFlag)) {
            map.put("rc", "-1");
            map.put("msg", "参数错误");
            return map;
        }
        if (cda == null) {
            map.put("rc", "-1");
            map.put("msg", "数据不存在");
            return map;
        }
        if (!"2".equals(cda.getPaymentState())) {
            map.put("rc", "-1");
            map.put("msg", "未缴费不能申请上架");
            return map;
        }
        if (!"1".equals(cda.getAppraisalResult())) {
            map.put("rc", "-1");
            map.put("msg", "未通过审核");
            return map;
        }
        Org org = (Org) UserUtils.getSession().getAttribute("org");
        if (org != null)
            if (!cda.getCreateBy().getId().equals(org.getUser().getId())) {
                map.put("rc", "-1");
                map.put("msg", "宠物不在门店名下，无法办理上架业务");
                return map;
            }
        map.put("rc", "0");
        map.put("petType", cda.getPetType());
        map.put("petName", cda.getPetName());
        map.put("dogGender", cda.getPetGender());
        map.put("petBirthdate", DateUtils.formatDate(cda.getPetBirthdate(), "yyyy-MM-dd"));
        map.put("petColor", cda.getPetColor());
        map.put("petOwnerMobile", cda.getPetOwnerMobile());
        map.put("petOwner", cda.getPetOwner());
        map.put("appraisalResult", cda.getAppraisalResult());
        map.put("appraisal", cda.getAppraisal());
        map.put("appraisalDate", DateUtils.formatDate(cda.getAppraisalDate(), "yyyy-MM-dd"));
        map.put("frontPic", cda.getFrontPic());
        map.put("sidePic", cda.getSidePic());
        map.put("backPic", cda.getBackPic());
        map.put("identificationFlag", cda.getIdentificationFlag());
        map.put("passportNo", cda.getPassportNo());
        map.put("id", cda.getId());
        return map;
    }

    /**
     * 犬毛色
     *
     * @return
     */
    public Map<String, String> getDogClorMark() {
        Map<String, String> map = new LinkedHashMap<>();
        List<DogColorMark> lst = dogColorMarkService.findAllList();
        for (DogColorMark d : lst)
            map.put(d.getDogColorMarkCn().split("-")[1], d.getDogColorMarkCn().split("-")[1]);
        map.put("其他", "其他");
        return map;
    }
//    public List<DogColorMark> getDogClorMark() {
//        List<DogColorMark> lst = new ArrayList<>();
//        dogColorMarkService.findAllList().forEach(i -> {
//            DogColorMark dc = new DogColorMark();
//            dc.setDogColorMarkCn(i.getDogColorMarkCn().split("-")[1]);
//            dc.setDogColorMarkCode(i.getDogColorMarkCn().split("-")[1]);
//            lst.add(dc);
//        });
//        DogColorMark dc = new DogColorMark();
//        dc.setDogColorMarkCn("其他");
//        dc.setDogColorMarkCode("0");
//        lst.add(dc);
//        return lst;
//    }


    public Map<String, String> getCatClorMark() {
        Map<String, String> map = new LinkedHashMap<>();
        try {
            OkHttpClient client = new OkHttpClient();
            //获取breedCode
            Request request = new Request.Builder()
                    .url(Global.getConfig("CaacUrl") + "/api/public/v1/cat/outerCommon/getCatColorMark")
                    .build();
            Response response = client.newCall(request).execute();
            String breedCode = response.body().string();
            JSONObject jo = JSONObject.fromObject(breedCode);
            map = jo.getJSONObject("data");
        } catch (Exception e) {

        }
        Map<String, String> m = new LinkedHashMap<>();
        for (Map.Entry<String, String> entry : map.entrySet())
            if (StringUtils.isNotEmpty(entry.getValue()))
                m.put(entry.getValue(), entry.getValue());
        m.put("其他", "其他");
        return m;
    }

    @Transactional(readOnly = false)
    public Long customSql(String sql) {
        return dao.customSql(sql);
    }

    /**
     * 猫芯片号校验
     *
     * @param request
     * @return
     */
    public Object verCatChipNo(HttpServletRequest request) {
        String identificationFlag = request.getParameter("identificationFlag");
        String chipType = request.getParameter("chipType");
        String orgid = request.getParameter("orgid");
        String id = request.getParameter("id");
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isEmpty(identificationFlag) || StringUtils.isEmpty(chipType)) {
            map.put("rc", "-1");
            map.put("msg", "芯片号或芯片类型不能为空");
            return map;
        }
        CompanionDogAppraisal c = dao.getByIdentificationFlag(identificationFlag, "1");
        if ((StringUtils.isEmpty(id) && c != null) || (StringUtils.isNotEmpty(id) && c != null && !c.getId().equals(id))) {
            map.put("rc", "-1");
            map.put("msg", "芯片号已使用");
            return map;
        }
        if (StringUtils.isEmpty(orgid)) {
            Org org = (Org) UserUtils.getSession().getAttribute("org");
            if (org != null)
                orgid = org.getId();
        }
        List<Map<String, String>> catlst = dao.getCatByIdentificationFlag(identificationFlag);
        List<Map<String, String>> catBirthlst = dao.getCatBirthCertificateByIdentificationFlag(identificationFlag);
        if ("1".equals(chipType)) {
            Long s = customSql(
                    "select count(1) from `cyber-form-business`.cat_org_chip where org_id = " + orgid + " and del_flag = '0' AND chip_code IS NOT NULL AND chip_code='" + identificationFlag + "'");
            if (s < 1L) {
                map.put("rc", "-1");
                map.put("msg", "芯片登记不在该门店名下");
                return map;
            }
            //埋置芯片是：芯片登记在该门店名下，且未使用
            // 犬只数据库及出生纸数据库中查重，如重复提示：该芯片号已经登记，请更换其他芯片号
            if (catlst != null && catlst.size() > 0) {
                map.put("rc", "-1");
                map.put("msg", "该芯片号已经登记,请更换其他芯片号");
                return map;
            }
            if (catBirthlst != null && catBirthlst.size() > 0) {
                map.put("rc", "-1");
                map.put("msg", "该芯片号已存在出生纸数据库中,请更换其他芯片号");
                return map;
            }
        }
        if ("2".equals(chipType)) {
            //已有芯片：犬只数据库及出生纸数据库中查重
            if (catBirthlst != null && catBirthlst.size() > 0) {
                map.put("rc", "-1");
                map.put("msg", "该芯片号已存在出生纸数据库中,请更换其他芯片号");
                return map;
            }
            if (catlst != null && catlst.size() > 0) {
                map.put("rc", "-1");
                map.put("msg", "该芯片号已经登记,请更换其他芯片号");
                return map;
            }
        }
        map.put("rc", "0");
        return map;
    }

    public Map<String, String> verCatDogChipNo(String identificationFlag, String orgid, String id, String chipType) {

        Map<String, String> map = new HashMap<>();
        if (StringUtils.isEmpty(identificationFlag)) {
            map.put("rc", "-1");
            map.put("msg", "参数错误");
            return map;
        }
        CompanionDogAppraisal c = dao.getByIdentificationFlag(identificationFlag, "0");
        if ((StringUtils.isEmpty(id) && c != null) || (StringUtils.isNotEmpty(id) && c != null && !c.getId().equals(id))) {
            map.put("rc", "-1");
            map.put("msg", "芯片号已使用");
            return map;
        }
        if (StringUtils.isEmpty(orgid)) {
            Org org = (Org) UserUtils.getSession().getAttribute("org");
            if (org != null)
                orgid = org.getId();
        }
        //犬库校验
        if ("1".equals(chipType)) {
            Long s = customSql(
                    "select count(1) from sys_org_chip where org_id = '" + orgid + "' and del_flag = '0' AND chip_code IS NOT NULL AND chip_code='" + identificationFlag + "'");
            s = s + customSql(
                    "select count(1) from `cyber-form-business`.cat_org_chip where org_id = '" + orgid + "' and del_flag = '0' AND chip_code IS NOT NULL AND chip_code='" + identificationFlag + "'");

            if (s < 1L) {
                map.put("rc", "-1");
                map.put("msg", "芯片登记不在该门店名下");
                return map;
            }
        }

        DogBirthCertificate db = dogBirthCertificateService.getByIdentificationFlag(identificationFlag);
        //埋置芯片是：芯片登记在该门店名下，且未使用
        // 犬只数据库及出生纸数据库中查重，如重复提示：该芯片号已经登记，请更换其他芯片号
        if (db != null) {
            map.put("rc", "-1");
            map.put("msg", "该芯片号已经登记，请更换其他芯片号");
            return map;
        }
        Dog dog = dogService.getByIdentificationFlag(identificationFlag);
        if (dog != null) {
            map.put("rc", "-1");
            map.put("msg", "该芯片号已经登记，请更换其他芯片号");
            return map;
        }
        List<Map<String, String>> catlst = dao.getCatByIdentificationFlag(identificationFlag);
        if (catlst != null && catlst.size() > 0) {
            map.put("rc", "-1");
            map.put("msg", "该芯片号已经登记，请更换其他芯片号");
            return map;
        }
        List<Map<String, String>> catBirthlst = dao.getCatBirthCertificateByIdentificationFlag(identificationFlag);
        if (catBirthlst != null && catBirthlst.size() > 0) {
            map.put("rc", "-1");
            map.put("msg", "该芯片号已经登记，请更换其他芯片号");
            return map;
        }
        map.put("rc", "0");
        return map;
    }

    /**
     * 猫和犬统一验证芯片号
     *
     * @param request
     * @return
     */
    public Object verCatDogChipNo(HttpServletRequest request) {
        String identificationFlag = request.getParameter("identificationFlag");
        String orgid = request.getParameter("orgid");
        String chipType = request.getParameter("chipType");
        String id = request.getParameter("id");
        return verCatDogChipNo(identificationFlag, orgid, id, chipType);
    }

    /**
     * 验证犬芯片号
     *
     * @param request
     * @return
     */
    public Object verChipNo(HttpServletRequest request) {
        String identificationFlag = request.getParameter("identificationFlag");
        String chipType = request.getParameter("chipType");
        String orgid = request.getParameter("orgid");
        String id = request.getParameter("id");
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isEmpty(identificationFlag) && StringUtils.isEmpty(chipType)) {
            map.put("rc", "-1");
            map.put("msg", "参数错误");
            return map;
        }
        CompanionDogAppraisal c = dao.getByIdentificationFlag(identificationFlag, "0");
        if ((StringUtils.isEmpty(id) && c != null) || (StringUtils.isNotEmpty(id) && c != null && !c.getId().equals(id))) {
            map.put("rc", "-1");
            map.put("msg", "芯片号已使用");
            return map;
        }
        if (StringUtils.isEmpty(orgid)) {
            Org org = (Org) UserUtils.getSession().getAttribute("org");
            if (org != null)
                orgid = org.getId();
        }

        DogBirthCertificate db = dogBirthCertificateService.getByIdentificationFlag(identificationFlag);
        Dog dog = dogService.getByIdentificationFlag(identificationFlag);
        if ("1".equals(chipType)) {
            Long s = customSql(
                    "select count(1) from sys_org_chip where org_id = " + orgid + " and del_flag = '0' AND chip_code IS NOT NULL AND chip_code='" + identificationFlag + "'");

            if (s < 1L) {
                map.put("rc", "-1");
                map.put("msg", "芯片登记不在该门店名下");
                return map;
            }
            //埋置芯片是：芯片登记在该门店名下，且未使用
            // 犬只数据库及出生纸数据库中查重，如重复提示：该芯片号已经登记，请更换其他芯片号
            if (db != null) {
                map.put("rc", "-1");
                map.put("msg", "该芯片号已经登记,请更换其他芯片号");
                return map;
            }
            if (dog != null) {
                map.put("rc", "-1");
                map.put("msg", "该芯片号已经登记,请更换其他芯片号");
                return map;
            }
        }
        if ("2".equals(chipType)) {
            //已有芯片：犬只数据库及出生纸数据库中查重
            if (db != null) {
                map.put("rc", "-1");
                map.put("msg", "该芯片号已存在出生纸数据库中");
                return map;
            }
            if (dog != null) {
                map.put("rc", "-1");
                map.put("msg", "该芯片号已存在出生纸数据库中");
                return map;
            }
        }
        map.put("rc", "0");
        return map;
    }

    public List<CompanionDogAppraisal> findList(CompanionDogAppraisal companionDogAppraisal) {
        return super.findList(companionDogAppraisal);
    }

    public Page<CompanionDogAppraisal> findPage(Page<CompanionDogAppraisal> page, CompanionDogAppraisal companionDogAppraisal) {
        return super.findPage(page, companionDogAppraisal);
    }

    @Transactional(readOnly = false)
    public void save(CompanionDogAppraisal companionDogAppraisal) {
        super.save(companionDogAppraisal);
    }

    @Transactional(readOnly = false)
    public void delete(CompanionDogAppraisal companionDogAppraisal) {
        super.delete(companionDogAppraisal);
    }

    /**
     * 生成订单
     *
     * @param cda
     * @return
     */
    @Transactional(readOnly = false)
    public PaymentOrderDetail buildOrder(CompanionDogAppraisal cda) {
        //build order
        PaymentOrder order = new PaymentOrder();
        Org org = (Org) UserUtils.getSession().getAttribute("org");
        Member member = org.getMember();
        order.setMemberCode(member.getMemberCode());
        order.setMemberName(member.getName());
        order.setAddTime(new Date());
        order.setSource(member.getLoginType());
        //build order detail
        PaymentChargingItem item = paymentChargingItemService.get(COMPANION_DOG_APPRAISAL);
        PaymentOrderDetail detail = new PaymentOrderDetail();
        detail.setAddTime(order.getAddTime());
        detail.setProccessState("0");
        detail.setTotalPrice(item.getPrice());
        detail.setNum("1");
        detail.setPrice(item.getPrice());
        detail.setBusinessIds(cda.getId());
        detail.setBusinessTable("new_pet_passport.companion_dog_appraisal");
        detail.setChargingItemName(item.getName());
        detail.setChargingItemId(item.getId());
        detail.setMemberCode(order.getMemberCode());
        detail.setMemberName(order.getMemberName());

        //保存订单
        restOrderService.saveOrder(order, Double.parseDouble(item.getPrice()), order.getAddTime());
        //save orderDetail

        detail.setOrderCode(order.getOrderCode());
        detail.preInsert();
        paymentOrderDetailDao.insert(detail);

        //更新业务表的订单号
        cda.setRunningNumber(order.getOrderCode());
        this.save(cda);

        return detail;

    }

    /**
     * 生成护照号
     *
     * @param
     * @param
     * @return
     */
    public synchronized Map<String, String> createCabCode(CompanionDogAppraisal companionDogAppraisal) {

        String identificationFlag = companionDogAppraisal.getIdentificationFlag();
        Map<String, String> result = new HashMap<String, String>();
        if (StringUtils.isBlank(identificationFlag)) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "芯片号不能为空");
        }
        if (identificationFlag.length() != 15) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "芯片号格式不正确");
        }
        //芯片号的后六位
        String last6 = identificationFlag.substring(9, identificationFlag.length());

        //查询出未修改前数据
        CompanionDogAppraisal old = dao.get(companionDogAppraisal.getId());
        //如果是修改操作
        if (old != null && StringUtils.isNotBlank(old.getIdentificationFlag())
                && last6.equals(old.getIdentificationFlag().substring(9, identificationFlag.length()))
                && StringUtils.isNotBlank(old.getPassportNo())
                && StringUtils.isNotBlank(old.getCabRegisterCode())) {
            result.put("passportNo", old.getPassportNo());
            result.put("classCode", old.getClassCode());
            result.put("cabRegisterCode", old.getCabRegisterCode());
        } else {
            //如果是添加的操作
//		护照号第三位为后六位的校验位，计算规则为：
//		（护照号第四位*1+护照号第五位*3+护照号第六位*5+护照号第七位*2+护照号第八位*4+护照号第九位*6）除以9的余数，详细公式参照excel表的公式。
            int position4 = Integer.parseInt(last6.substring(0, 1));
            int position5 = Integer.parseInt(last6.substring(1, 2));
            int position6 = Integer.parseInt(last6.substring(2, 3));
            int position7 = Integer.parseInt(last6.substring(3, 4));
            int position8 = Integer.parseInt(last6.substring(4, 5));
            int position9 = Integer.parseInt(last6.substring(5, 6));
            int count = position4 * 1 + position5 * 3 + position6 * 5 + position7 * 2 + position8 * 4 + position9 * 6;
            int position3 = count % 9;
//		护照号第二位（下方标红的位数）为后七位的占用校验位，即：
//		生成该护照号时，如果后七位数字不重复，第二位为0，否则为依次递增
//			非CKU犬只为W
//			非CKU猫只为S
            for (int i = 0; i < 10; i++) {
                String cabRegisterCode = "";
                String passportNo = "N" + i + position3 + last6;
                String classCode = "C" + i + position3 + last6;
                if (StringUtils.isNotBlank(companionDogAppraisal.getPetType()) && "0".equals(companionDogAppraisal.getPetType())) {
                    cabRegisterCode = "W" + i + position3 + last6;
                } else {
                    cabRegisterCode = "S" + i + position3 + last6;
                }
                CompanionDogAppraisal com = dao.getByCabPassport(passportNo);
                if (com == null) {
                    result.put("passportNo", passportNo);
                    result.put("cabRegisterCode", cabRegisterCode);
                    result.put("classCode", classCode);
                    break;
                }
            }

        }

        return result;
    }

    @Transactional(readOnly = false)
    public String identityPrint(String id) {
        CompanionDogAppraisal companionDogAppraisal = dao.get(id);
        if (companionDogAppraisal == null) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "犬只信息错误");
        }
        if (StringUtils.isBlank(companionDogAppraisal.getPassportNo())) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "护照号为空");
        }
        if (StringUtils.isBlank(companionDogAppraisal.getCabRegisterCode())) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "宠爱登记卡号为空");
        }
        if (StringUtils.isBlank(companionDogAppraisal.getIdentificationFlag())) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "芯片号为空");
        }
        if (StringUtils.isBlank(companionDogAppraisal.getAppraisalResult()) && "1".equals(companionDogAppraisal.getAppraisalResult())) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "犬只鉴定未通过");
        }
        if (StringUtils.isBlank(companionDogAppraisal.getPaymentState()) && "2".equals(companionDogAppraisal.getPaymentState())) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "犬只未交费");
        }
        if (StringUtils.isBlank(companionDogAppraisal.getIdentitySticker()) && !"0".equals(companionDogAppraisal.getIdentitySticker())) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "身份贴纸已打印");
        }
        companionDogAppraisal.setIdentitySticker("1");
        companionDogAppraisal.setIdentityPrintTime(new Date());
        dao.update(companionDogAppraisal);
        return "partner/club/identityPrint";

    }

    @Transactional(readOnly = false)
    public String gradePrint(String id) {
        CompanionDogAppraisal companionDogAppraisal = dao.get(id);
        if (companionDogAppraisal == null) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "犬只信息错误");
        }
        if (StringUtils.isBlank(companionDogAppraisal.getPassportNo())) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "护照号为空");
        }
        if (StringUtils.isBlank(companionDogAppraisal.getClassCode())) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "贴纸编号号为空");
        }
        if (StringUtils.isBlank(companionDogAppraisal.getIdentificationFlag())) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "芯片号为空");
        }
        if (StringUtils.isBlank(companionDogAppraisal.getAppraisalResult()) && "1".equals(companionDogAppraisal.getAppraisalResult())) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "犬只鉴定未通过");
        }
        if (StringUtils.isBlank(companionDogAppraisal.getPaymentState()) && "2".equals(companionDogAppraisal.getPaymentState())) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "犬只未交费");
        }
        if (StringUtils.isBlank(companionDogAppraisal.getGradeSticker()) && !"0".equals(companionDogAppraisal.getGradeSticker())) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "等级贴纸已打印");
        }
        companionDogAppraisal.setGradeSticker("1");
        companionDogAppraisal.setGradePrintTime(new Date());
        dao.update(companionDogAppraisal);
        // 确认收入
        saPaymentDetailTotalService.financeConfirmTime(companionDogAppraisal.getRunningNumber());
        return "partner/club/gradePrint";

    }

    @Transactional(readOnly = false)
    public void restIdentityPrint(String id) {
        CompanionDogAppraisal companionDogAppraisal = dao.get(id);
        if (companionDogAppraisal == null) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "犬只信息错误");
        }
        companionDogAppraisal.setIdentitySticker("0");
        dao.update(companionDogAppraisal);
    }

    @Transactional(readOnly = false)
    public void restGradePrint(String id) {
        CompanionDogAppraisal companionDogAppraisal = dao.get(id);
        if (companionDogAppraisal == null) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "犬只信息错误");
        }
        companionDogAppraisal.setGradeSticker("0");
        dao.update(companionDogAppraisal);
    }

    @Transactional(readOnly = false)
    public void afterPay(String businessIds) {
        CompanionDogAppraisal companionDogAppraisal = get(businessIds);
        if (companionDogAppraisal == null) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "犬只信息错误");
        }
        if (StringUtils.isBlank(companionDogAppraisal.getIdentificationFlag())) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "芯片号为空");
        }
        if (StringUtils.isBlank(companionDogAppraisal.getAppraisalResult()) && "1".equals(companionDogAppraisal.getAppraisalResult())) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "犬只鉴定未通过");
        }
        if (StringUtils.isBlank(companionDogAppraisal.getPaymentState()) && "2".equals(companionDogAppraisal.getPaymentState())) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "犬只未交费");
        }
        Map<String, String> cabCode = createCabCode(companionDogAppraisal);
        companionDogAppraisal.setPassportNo(cabCode.get("passportNo"));
        companionDogAppraisal.setCabRegisterCode(cabCode.get("cabRegisterCode"));
        companionDogAppraisal.setClassCode(cabCode.get("classCode"));
        dao.update(companionDogAppraisal);
    }

}