package com.cku.oa.dog.service;

import com.alibaba.fastjson.JSONObject;
import com.cku.core.ZAErrorCode;
import com.cku.core.ZAException;
import com.cku.oa.dog.dao.DogActivationDao;
import com.cku.oa.dog.dao.DogBirthCertificateDao;
import com.cku.oa.dog.dao.DogChipDao;
import com.cku.oa.dog.entity.DogActivation;
import com.cku.oa.dog.entity.DogBirthCertificate;
import com.cku.oa.dog.entity.DogChip;
import com.cku.oa.finance.service.SaPaymentDetailTotalService;
import com.cku.oa.sys.dao.user.MemberDao;
import com.cku.oa.sys.entity.user.Member;
import com.cku.oa.sys.service.RemindService;
import com.cku.oa.sys.util.ChongaibaoClientUtil;
import com.cku.oa.sys.util.JpushUtil;
import com.cku.oa.sys.util.ZtSmsUtil;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
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 java.util.*;

/**
 * 犬只激活Service
 *
 * @author lgl
 * @version 2018-06-12
 */
@Service
@Transactional(readOnly = true)
public class DogActivationService extends CrudService<DogActivationDao, DogActivation> {

    @Autowired
    private MemberDao memberDao;
    @Autowired
    private DogBirthCertificateDao dogBirthCertificateDao;

    //邮寄后过期时间
    public static final int EXPIRE_DAY = 150;

    @Autowired
    private DogActivationDao dogActivationDao;
    @Autowired
    private RemindService remindService;
    @Autowired
    private DogChipDao dogChipDao;

    @Autowired
    private SaPaymentDetailTotalService saPaymentDetailTotalService;


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

    public List<DogActivation> findList(DogActivation dogActivation) {
        return super.findList(dogActivation);
    }

    public Page<DogActivation> findPage(Page<DogActivation> page, DogActivation dogActivation) {
        return super.findPage(page, dogActivation);
    }

    @Transactional(readOnly = false)
    public void save(DogActivation dogActivation) {
        super.save(dogActivation);
    }

    @Transactional(readOnly = false)
    public void delete(DogActivation dogActivation) {
        if (null != dogActivation && "2".equals(dogActivation.getPaymentState())) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "该记录已缴费，无法删除！");
        }
        super.delete(dogActivation);
    }


    public DogActivation getByBirthCode(String birthCerRegCode) {
        return dogActivationDao.getByBirthCode(birthCerRegCode);
    }

    public void validateBusiness(DogActivation po, String method) {
        DogBirthCertificate dogBirthCertificate = dogBirthCertificateDao.getByBirthCerRegCode(po.getBirthCode());
        //出生纸校验
        validateDogBirthCertificate(dogBirthCertificate);
        //信息校验
        validatInfo(po);
        //价格校验
        validatePrice(po, dogBirthCertificate, "我们无法为您推荐，您将失去在全渠道销售此犬只的机会。请您填写合理的价格");
        if ("POST".equals(method)) {
            //查重
            DogActivation dogActivation = dao.getByBirthCode(po.getBirthCode());
            if (dogActivation != null) {
                throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "请勿重复提交");
            }
        }
    }

    public void validatInfo(DogActivation po) {
        if ("1".equals(po.getState())) {
            if (StringUtils.isBlank(po.getPrice()) || StringUtils.isBlank(po.getCity()) || StringUtils.isBlank(po.getLinkman()) || StringUtils.isBlank(po.getMobile())) {
                throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "您填写的信息不全，请先点击“编辑”，补全信息后再点击推荐");
            }
        }
    }

    public void validateDogBirthCertificate(DogBirthCertificate dogBirthCertificate) {
        DogChip dogChip = dogChipDao.getByBirthCode(dogBirthCertificate.getBirthCerRegCode());
        Date sendDate = dogBirthCertificate.getSendDate();
        if(dogChip == null || !"1".equals(dogChip.getIsAll())){
            if (sendDate != null && sendDate.getTime() > System.currentTimeMillis()) {
                throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "请等待身份识别卡寄出后再办理该业务");
            }
        }
//        if(StringUtils.isBlank(dogBirthCertificate.getActivitionState()) || !"1".equals(dogBirthCertificate.getActivitionState())){
//            DogActivation po = dogActivationDao.getByBirthCode(dogBirthCertificate.getBirthCerRegCode());
//            if (po == null || !"1".equals(po.getReviewState())) {
//                Calendar calendar = Calendar.getInstance();
//                calendar.setTime(sendDate);
//                calendar.add(Calendar.DATE, DogActivationService.EXPIRE_DAY + 1);
//                if (System.currentTimeMillis() > calendar.getTimeInMillis()
//                        && dogBirthCertificate.getCreateDate().getTime() >= DogBirthCertificateService.DOG_ACTIVATION_MILLIS) {
//                    throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "该身份识别卡超期未激活，请到地方俱乐部办理激活");
//                }
//            }
//        }
    }

    public void validatePrice(DogActivation po, DogBirthCertificate dogBirthCertificate, String msg) {
        if ("0".equals(po.getState()) || StringUtils.isBlank(po.getPrice())) {
                return;
        }
        JSONObject params = new JSONObject();
        params.put("dogTypeCode", dogBirthCertificate.getDogBreed());
        String result = ChongaibaoClientUtil.getDogTypePriceSelByDogTypeCode(params);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jo = JSONObject.parseObject(result);
            if (jo.containsKey("data")) {
                JSONObject data = jo.getJSONObject("data");
                double sysMinPrice = data.getDoubleValue("sysMinPrice");
                double sysMaxPrice = data.getDoubleValue("sysMaxPrice");
                double price = Double.parseDouble(po.getPrice());
                if (price < sysMinPrice) {
                    throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "您填写的价格过低，" + msg);
                } else if (price > sysMaxPrice) {
                    throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "您填写的价格过高，" + msg);
                }
            }
            System.out.println(jo.toJSONString());
        }
    }

    public int dogActivationRemind(int dayAfterSend) {
        int totalCount = 0;
        Map<String, Set<String>> map = Maps.newTreeMap();
        //查询数据
        List<DogActivation> dogActivationList = dao.getRemindBirthCode(dayAfterSend, new Date(DogBirthCertificateService.DOG_ACTIVATION_MILLIS));
        for (DogActivation dogActivation : dogActivationList) {
            Set<String> set = map.get(dogActivation.getMemberCode());
            if (set == null) {
                set = new TreeSet<>();
                set.add(dogActivation.getBirthCode());
                map.put(dogActivation.getMemberCode(), set);
            } else {
                set.add(dogActivation.getBirthCode());
            }
        }
        //发送短信
        String expireDate = getExpireDate(dayAfterSend);
        for (Map.Entry<String, Set<String>> entry : map.entrySet()) {
            int count = entry.getValue().size();
            String content = getSmsContent(count, expireDate);
            Member member = memberDao.getByMemberCode(entry.getKey());
            String mobile = member.getSafeMobile();
            if (StringUtils.isBlank(mobile)) {
                mobile = member.getMobile();
            }
            if (sendRemind(member.getMemberCode(), mobile, content)) {
                totalCount++;
            }
            Map<String, String> extraMap = ImmutableMap.of("type", "DOGACTIVATION_GET");
            //推送
            JpushUtil.pushByMemberCode(member.getMemberCode(), content, extraMap);
        }
        return totalCount;
    }

    private String getSmsContent(int count, String date) {
        return "您有" + count + "张新生犬登记卡未激活，请于" + date + "前完成激活，否则会影响您犬只的销售和血统证书办理。";
    }

    private String getExpireDate(int i) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.DATE, EXPIRE_DAY - i);
        int month = calendar.get(Calendar.MONTH) + 1;
        int date = calendar.get(Calendar.DATE);
        return month + "月" + date + "日";
    }

    private boolean sendRemind(String memberCode, String mobile, String content) {
        boolean flag = false;
        try {
            logger.info(content);
            String result = ZtSmsUtil.sendNoteYX(content, mobile);
            if (StringUtils.isNotBlank(result)) {
                logger.info("给会员号为" + memberCode + ",电话为" + mobile + "的会员发送犬只激活提醒短信成功");
                flag = true;
            }
        } catch (Exception e) {
            logger.warn("给会员号为" + memberCode + ",电话为" + mobile + "的会员发送犬只激活提醒短信失败", e);
        }
        return flag;
    }

    /**
     * 激活审核
     *
     * @param id
     * @param frontPicReviewState
     * @param sidePicReviewState
     * @param backPicReviewState
     * @param frontPicRemark
     * @param sidePicRemark
     * @param backPicRemark
     * @param lifePics
     */
    @Transactional(readOnly = false)
    public void saveReview(String id, String frontPicReviewState, String sidePicReviewState, String backPicReviewState,
                           String[] frontPicRemark, String[] sidePicRemark, String[] backPicRemark, String[] lifePics) {
        DogActivation dogActivation = dogActivationDao.get(id);
        if (dogActivation == null) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "无法查询到激活或上架信息！");
        }
        if (dogActivation != null && !dogActivation.getDelFlag().equals("0")) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "无法查询到激活或上架信息！");
        }
        if ("1".equals(dogActivation.getType()) && dogActivation.getReviewState().equals("1")) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "该犬只已经激活！");
        }
        if ("1".equals(dogActivation.getType()) && dogActivation.getReviewState().equals("2")) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "该犬只激活未通过审核！");
        }
        if ("2".equals(dogActivation.getType()) && dogActivation.getUpperReview().equals("1")) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "该犬只已经上架！");
        }
        if ("2".equals(dogActivation.getType()) && dogActivation.getUpperReview().equals("2")) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "该犬只上架未通过审核！");
        }
        dogActivation.setReviewTime(new Date());
        dogActivation.setFrontPicReviewState(frontPicReviewState);
        dogActivation.setSidePicReviewState(sidePicReviewState);
        dogActivation.setBackPicReviewState(backPicReviewState);
        dogActivation.setReviewRemarks("");
        if (lifePics != null && lifePics.length > 0) {
            String lifePic = "";
            for (int i = 0; i < lifePics.length; i++) {
                lifePic += lifePics[i] + ",";
            }
            dogActivation.setLifePic(lifePic);
        }
        if (frontPicRemark != null && frontPicRemark.length > 0) {
            String remark = "";
            for (int i = 0; i < frontPicRemark.length; i++) {
                remark += frontPicRemark[i] + " ";
            }
            dogActivation.setFrontPicRemark(remark);
        }
        if (sidePicRemark != null && sidePicRemark.length > 0) {
            String remark = "";
            for (int i = 0; i < sidePicRemark.length; i++) {
                remark += sidePicRemark[i] + " ";
            }
            dogActivation.setSidePicRemark(remark);
        }
        if (backPicRemark != null && backPicRemark.length > 0) {
            String remark = "";
            for (int i = 0; i < backPicRemark.length; i++) {
                remark += backPicRemark[i] + " ";
            }
            dogActivation.setBackPicRemark(remark);
        }
        String type = dogActivation.getType();
        if("1".equals(type)){
            if ("1".equals(frontPicReviewState) && "1".equals(sidePicReviewState) && "1".equals(backPicReviewState)) {
                dogActivation.setReviewState("1");
                // TODO  财务收入确认时点
//                saPaymentDetailTotalService.financeConfirmTime(dogActivation.getId(), "dog_activation");
            }else{
                dogActivation.setReviewState("2");
            }
            if (dogActivation.getState().equals("1")) {
                dogActivation.setAddTime(new Date());
            }
            dogActivation.setUpperReview("1");
            //更新出生纸表的激活状态
            DogBirthCertificate dogBirthCertificate = dogBirthCertificateDao.getByBirthCerRegCode(dogActivation.getBirthCode());
            dogBirthCertificate.setActivitionState(dogActivation.getReviewState());
            dogBirthCertificateDao.update(dogBirthCertificate);
        }else{
            if ("1".equals(frontPicReviewState) && "1".equals(sidePicReviewState) && "1".equals(backPicReviewState)) {
                dogActivation.setUpperReview("1");
            }else{
                dogActivation.setUpperReview("2");
            }
        }

        super.save(dogActivation);

    }

    /**
     * @param po    数据库记录
     * @param state 上架状态
     * @description: 更新上架时间
     * @author: laiguanglong
     * @date: 2018/7/6 10:06
     */
    public void setAddTime(DogActivation po, String state) {
        //审核通过，数据库中未上架，参数中上架，更新上架时间
        if ("1".equals(po.getReviewState()) && "1".equals(po.getType())
                && "0".equals(po.getState())
                && "1".equals(state)) {
            po.setAddTime(new Date());
        }
        if ("2".equals(po.getType())) {
            po.setAddTime(new Date());
        }
    }

    /**
     * @description: 上架时间大于60天自动下架
     * @author: laiguanglong
     * @date: 2018/7/6 10:12
     */
    public int autoOffSell() {
        return dao.autoOffSell();
    }
    /**
     * @description: 犬只年龄大于24个月自动下架
     * @author: laiguanglong
     * @date: 2018/7/6 10:12
     */
    public int autoStateDown() {
        return dao.autoStateDown();
    }

    public void deleteById(String id) {
        DogActivation dogActivation = get(id);
        if (dogActivation != null) {
            delete(dogActivation);
        }
    }

    @Transactional(readOnly = false)
    public void sendReviewMsg(String dogActivationId) {
        DogActivation dogActivation = get(dogActivationId);
        if (null != dogActivation && "2".equals(dogActivation.getReviewState())) {
            String content = "你提交的激活犬只(登记卡" + dogActivation.getBirthCode() + ")未通过审核，请按照要求重新修改后上传";
            Map<String, String> extraMap = ImmutableMap.of("type", "BIRTHCERTIFICATE_GETLIST1");
            JpushUtil.pushByMemberCode(dogActivation.getMemberCode(), content, extraMap);
            sendRemind(dogActivation.getMemberCode(), dogActivation.getMobile(), content);
            remindService.addMemberRemind(content, dogActivation.getMemberCode());
        }
    }

    @Transactional(readOnly = false)
    public void afterPay(String id) {
        //			会员中心超期激活交费后状态为激活中
        DogActivation dogActivation = dogActivationDao.get(id);
        DogBirthCertificate birthCertificate = dogBirthCertificateDao.getByBirthCerRegCode(dogActivation.getBirthCode());
        if(birthCertificate != null && StringUtils.isNotBlank(birthCertificate.getActivitionState()) && birthCertificate.getActivitionState().equals("3")){
            dogBirthCertificateDao.updateActivationStates(dogActivation.getBirthCode(),"0");
        }else{
            dogBirthCertificateDao.updateActivationStates(dogActivation.getBirthCode(),"1");
        }
    }
}
