package com.cku.oa.breeder.service;

import com.cku.core.ZAErrorCode;
import com.cku.core.ZAException;
import com.cku.oa.breeder.dao.StudDogDao;
import com.cku.oa.breeder.entity.StudDog;
import com.cku.oa.dog.dao.DogBirthCertificateDao;
import com.cku.oa.dog.dao.DogDao;
import com.cku.oa.dog.dao.DogNewbornDao;
import com.cku.oa.dog.entity.Dog;
import com.cku.oa.dog.entity.DogPedigreeCertifiedChange;
import com.cku.oa.dog.service.DogPedigreeCertifiedChangeService;
import com.cku.oa.show.dao.ChampionLoginDao;
import com.cku.oa.show.dao.ShowResultsDao;
import com.cku.oa.show.dao.ShowResultsDdzDao;
import com.cku.oa.show.dao.ShowScoreDao;
import com.cku.oa.sys.entity.user.Member;
import com.cku.oa.sys.util.MemberUtil;
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;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 种公信息Service
 *
 * @author lgl
 * @version 2017-10-13
 */
@Service
@Transactional(readOnly = true)
public class StudDogService extends CrudService<StudDogDao, StudDog> {

    @Autowired
    private DogBirthCertificateDao dogBirthCertificateDao;
    @Autowired
    private ShowResultsDao showResultsDao;
    @Autowired
    private ShowResultsDdzDao showResultsDdzDao;
    @Autowired
    private ChampionLoginDao championLoginDao;
    @Autowired
    private ShowScoreDao showScoreDao;
    @Autowired
    private DogDao dogDao;
    @Autowired
    private DogNewbornDao dogNewbornDao;
    @Autowired
    private DogPedigreeCertifiedChangeService dogPedigreeCertifiedChangeService;
    @Autowired
    private BlacklistService blacklistService;
    @Autowired
    private  StudDogDao studDogDao;

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

    public List<StudDog> findList(StudDog studDog) {
        return super.findList(studDog);
    }

    public Page<StudDog> findPage(Page<StudDog> page, StudDog studDog) {
        return super.findPage(page, studDog);
    }

    @Transactional(readOnly = false)
    public void save(StudDog studDog) {
        super.save(studDog);
    }

    @Transactional(readOnly = false)
    public void delete(StudDog studDog) {
        super.delete(studDog);
    }

    public String getAge(Date birthdate) {
        if(birthdate==null){
            return "";
        }
        StringBuilder dogAge = new StringBuilder();
        int monthAge = getMonthAge(new Date(), birthdate);
        if (monthAge / 12 > 0) {
            dogAge.append(monthAge / 12).append("岁");
            if (monthAge % 12 != 0) {
                dogAge.append(monthAge % 12).append("个月");
            }
        } else {
            dogAge.append(monthAge % 12).append("个月");
        }
        return dogAge.toString();
    }

    public boolean isAgeOneToTen(Date birthdate) {
        if(birthdate==null){
            return false;
        }
        boolean flag = true;
        int monthAge = getMonthAge(new Date(), birthdate);
        if (monthAge < 12 || monthAge > 120) {
            flag = false;
        }
        return flag;
    }

    public int getMonthAge(Date date, Date birthdate) {
        Calendar dateCalendar = Calendar.getInstance();
        Calendar birthdateCalendar = Calendar.getInstance();
        dateCalendar.setTime(date);
        birthdateCalendar.setTime(birthdate);
        int monthAge = dateCalendar.get(Calendar.MONTH)
                - birthdateCalendar.get(Calendar.MONTH);
        if (dateCalendar.get(Calendar.YEAR) != birthdateCalendar
                .get(Calendar.YEAR)) {
            monthAge = (dateCalendar.get(Calendar.YEAR) - birthdateCalendar
                    .get(Calendar.YEAR)) * 12 + monthAge;
        }
        birthdateCalendar.add(Calendar.MONTH, monthAge);
        if (birthdateCalendar.getTime().after(dateCalendar.getTime())) {
            monthAge = monthAge - 1;
        }
        return monthAge;
    }

    private String getloginType(String pedigreeCertified) {
        String[] loginTypeArray = getloginTypeArray(pedigreeCertified);
        String result = DictUtils.getDictLabel(loginTypeArray[0], "stud_dog_label", "");
        if (StringUtils.isNotBlank(result)) {
            result += "," + DictUtils.getDictLabel(loginTypeArray[1], "stud_dog_label", "");
        } else {
            result = DictUtils.getDictLabel(loginTypeArray[1], "stud_dog_label", "");
        }
        return result;
    }

    public String[] getloginTypeArray(String pedigreeCertified) {
        String[] loginTypeArray = {"", ""};
        List<String> loginTypeList = championLoginDao.getLoginTypeByPedigreeCertified(pedigreeCertified);
        for (String loginType : loginTypeList) {
            if ("1".equals(loginType)
                    || "2".equals(loginType)
                    || "3".equals(loginType)
                    || "4".equals(loginType)
                    || "5".equals(loginType)
                    || "7".equals(loginType)) {
                if (!"7".equals(loginType) || "7".equals(loginType) && StringUtils.isBlank(loginTypeArray[1])) {
                    loginTypeArray[1] = loginType;
                }
            } else if ("6".equals(loginType)) {
                loginTypeArray[0] = loginType;
            }
        }
        return loginTypeArray;
    }

    /**
     * @description: 获年龄
     * @author: laiguanglong
     * @date: 2017/10/26 14:28
     */
    public String getAge(String dogId) {
        String age = "0";
        Dog dog = dogDao.get(dogId);
        if (dog == null) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "犬id有误");
        }
        if (dog.getBirthdate() == null) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "犬生日为空");
        }
        int monthAge = getMonthAge(new Date(), dog.getBirthdate());
        if (monthAge / 12 > 0) {
            age = (monthAge / 12) + "";
        }
        return age;
    }

    @Cacheable(value = "fiveMinuteCache", key = "#dog.id + 'findById'")
    public JSONObject studDogOtherInfo(Dog dog) {
        JSONObject data = new JSONObject();
        HashMap<String, Map<String, Object>> childGenderCountMap = dogBirthCertificateDao.getChildGenderCountMapByFdogPedigreeCertified(dog.getPedigreeCertifiedCode());
        String maleDogCount = "0";
        String femaleDogCount = "0";
        for (Map.Entry<String, Map<String, Object>> entry : childGenderCountMap.entrySet()) {
            if ("1".equals(entry.getKey())) {
                maleDogCount = entry.getValue().get("count").toString();
            } else if ("2".equals(entry.getKey())) {
                femaleDogCount = entry.getValue().get("count").toString();
            }
        }
        data.put("maleDogCount", getString(maleDogCount));
        data.put("femaleDogCount", getString(femaleDogCount));
        //种犬成绩
        //中国冠军登录和世界冠军登录
        String loginType = getloginType(dog.getPedigreeCertifiedCode());
        data.put("loginType", loginType);
        //当年冠军积分排行
        String rank = showScoreDao.getRankByPedigreeCertified(dog.getPedigreeCertifiedCode());
        data.put("bestYear", getString("2017"));
        String bestRank = getString(rank);
        //只显示前10的排名
        if (StringUtils.isNotBlank(bestRank) && Integer.parseInt(bestRank) > 10) {
            bestRank = "";
        }
        data.put("bestRank", bestRank);
        //BIS和BISS数量
        int bisCount = showResultsDao.getBisCountByPedigreeCertified(dog.getPedigreeCertifiedCode());
        int bissCount = showResultsDdzDao.getBissCountByPedigreeCertified(dog.getPedigreeCertifiedCode());
        data.put("bisCount", getString(bisCount == 0 ? "" : bisCount + ""));
        data.put("bissCount", getString(bissCount == 0 ? "" : bissCount + ""));
        //子代成绩
        HashMap<String, Map<String, Object>> childLoginTypeCountMap = championLoginDao.getChildLoginTypeCountMapByFdogPedigreeCertified(dog.getPedigreeCertifiedCode());
        String comLoginCount = "";
        String tongLoginCount = "";
        String yinLoginCount = "";
        String jinLoginCount = "";
        String superLoginCount = "";
        String worldLoginCount = "";
        String youngLoginCount = "";
        for (Map.Entry<String, Map<String, Object>> entry : childLoginTypeCountMap.entrySet()) {
            String count = entry.getValue().get("count").toString();
            if ("1".equals(entry.getKey()) && !"0".equals(count)) {
                comLoginCount = count;
            } else if ("2".equals(entry.getKey()) && !"0".equals(count)) {
                tongLoginCount = count;
            } else if ("3".equals(entry.getKey()) && !"0".equals(count)) {
                yinLoginCount = count;
            } else if ("4".equals(entry.getKey()) && !"0".equals(count)) {
                jinLoginCount = count;
            } else if ("5".equals(entry.getKey()) && !"0".equals(count)) {
                superLoginCount = count;
            } else if ("6".equals(entry.getKey()) && !"0".equals(count)) {
                worldLoginCount = count;
            } else if ("7".equals(entry.getKey()) && !"0".equals(count)) {
                youngLoginCount = count;
            }
        }
        data.put("comLoginCount", comLoginCount);
        data.put("tongLoginCount", tongLoginCount);
        data.put("yinLoginCount", yinLoginCount);
        data.put("jinLoginCount", jinLoginCount);
        data.put("superLoginCount", superLoginCount);
        data.put("worldLoginCount", worldLoginCount);
        data.put("youngLoginCount", youngLoginCount);
        return data;
    }

    @Cacheable(value = "fiveMinuteCache")
    public List<String> getDogBreedList() {
        return dao.getDogBreedList();
    }

    public void dogChangeInfo(StudDog po, Member member) {
        po.setAge(getAge(po.getDogId()));
        DogPedigreeCertifiedChange dogPedigreeCertifiedChange = dogPedigreeCertifiedChangeService.getByDogId(po.getDogId());
        po.setDogPedigreeCertifiedChangeId(dogPedigreeCertifiedChange == null ? "" : dogPedigreeCertifiedChange.getId());
        String dogNewbornCount = dogNewbornDao.getCountByMalePedigreeCertified(po.getPedigreeCertified());
        po.setDogNewbornCount(dogNewbornCount);
    }

    /**
     * @description: 种公信息发布及修改业务校验
     * @author: laiguanglong
     * @date: 2018/1/16 10:11
     */
    public void validateBusiness(StudDog po) {
        //价格不能超过30000
        double price = Double.parseDouble(po.getPrice());
        if (price > 30000) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "已超过宠爱王国最高限额：30000元");
        }
        //专业有效会员
        Member member = UserUtils.getLoginMember();
        if (!(MemberUtil.isProfessionalMember(member) && MemberUtil.isActiveMember(member))) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "仅限有限专业会员发布种犬信息");
        }
        //不在黑名单中
        if (blacklistService.isInBlacklist(member.getMemberCode(), "stud_dog")) {
            throw new ZAException(ZAErrorCode.ZA_VALID_FAILED, "您的发布权限已被取消，如有疑问，请致电宠爱王国客服！");
        }
    }

    private String getString(String str) {
        return str == null ? "" : str;
    }
    public void updateMemberCode(String memberCode, String dogId) {
        StudDog stuDog =  studDogDao.getByDogId(dogId);
        if(stuDog != null){
            studDogDao.updateMemberCode(memberCode,dogId);
        }
    }
}