package com.goafanti.cognizance.service.impl;

import com.goafanti.cognizance.bo.*;
import com.goafanti.cognizance.service.OrgCognizanceService;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.enums.*;
import com.goafanti.common.model.*;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class OrgCognizanceServiceImpl extends BaseMybatisDao<OrgCognizanceMapper> implements OrgCognizanceService {
	@Autowired
	private OrgCognizanceMapper				orgCognizanceMapper;
	@Autowired
	private OrgCognizanceLogMapper			orgCognizanceLogMapper;
	@Autowired
	private OrganizationIdentityMapper		organizationIdentityMapper;
	@Autowired
	private OrgCognizanceProportionMapper	orgCognizanceProportionMapper;
	@Autowired
	private UserMapper						userMapper;
	@Autowired
	private CopyrightInfoMapper				copyrightInfoMapper;
	@Autowired
	private PatentInfoMapper				patentInfoMapper;
	@Autowired
	private TechProjectMapper				techProjectMapper;

	@Override
	public OrgCognizance insert(OrgCognizance c) {
		orgCognizanceMapper.insert(c);
		return c;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<CognizanceBo> listCognizance(String contractId, String uid, String unitName,
			Integer locationProvince, Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<>();

		if (TokenManager.getToken() instanceof Admin && !TokenManager.hasRole(AFTConstants.SUPERADMIN)) {
			params.put("principal", TokenManager.getAdminId());
		}

		if (!StringUtils.isBlank(contractId)) {
			params.put("contractId", contractId);
		}

		if (!StringUtils.isBlank(unitName)) {
			params.put("unitName", unitName);
		}

		if (!StringUtils.isBlank(uid)) {
			params.put("uid", uid);
		}

		if (null != locationProvince) {
			params.put("locationProvince", locationProvince);
		}

		if (pageNo == null || pageNo < 0) {
			pageNo = 1;
		}

		if (pageSize == null || pageSize < 0 || pageSize > 10) {
			pageSize = 10;
		}
		return (Pagination<CognizanceBo>) findPage("findCognizanceBoByPage", "findCognizanceBoCount", params, pageNo,
				pageSize);
	}

	@Override
	public CognizanceDetailBo selectCognizanceDetailBo(String uid, String cid, Integer year) {
		CognizanceDetailBo cog = new CognizanceDetailBo();

		CognizanceOrgInfoBo orgInfo = orgCognizanceMapper.selectCognizanceOrgInfoBoByUidAndCid(uid, cid);
		if (null != orgInfo) {
			cog.setUid(null == orgInfo.getUid() ? "" : orgInfo.getUid());
			cog.setCid(null == orgInfo.getCid() ? "" : orgInfo.getCid());
			cog.setUnitName(null == orgInfo.getUnitName() ? "" : orgInfo.getUnitName());
			cog.setOrgCode(null == orgInfo.getOrgCode() ? "" : orgInfo.getOrgCode());
			cog.setPostalAddress(null == orgInfo.getPostalAddress() ? "" : orgInfo.getPostalAddress());
			cog.setContacts(null == orgInfo.getContacts() ? "" : orgInfo.getContacts().toString());// 联系人
			cog.setTechnicalField1(null == orgInfo.getTechnicalField1() ? 0 : orgInfo.getTechnicalField1());
			cog.setTechnicalField2(null == orgInfo.getTechnicalField2() ? 0 : orgInfo.getTechnicalField2());
			cog.setTechnicalField3(null == orgInfo.getTechnicalField3() ? 0 : orgInfo.getTechnicalField3());
			cog.setBasicResearchCost(
					null == orgInfo.getBasicResearchCost() ? new BigDecimal(0) : orgInfo.getBasicResearchCost());
			cog.setAccident(null == orgInfo.getAccident() ? 0 : orgInfo.getAccident());
			cog.setLargeOrder(null == orgInfo.getLargeOrder() ? 0 : orgInfo.getLargeOrder());
			cog.setYear(orgInfo.getYear());
			cog.setCertificateNumber(orgInfo.getCertificateNumber());
		}

		CognizanceResearchCostBo researchCost = orgCognizanceMapper.selectCognizanceResearchCostBoByUidAndYear(year,
				uid);
		if (null != researchCost) {
			cog.setResearchCost(
					null == researchCost.getResearchCost() ? new BigDecimal(0) : researchCost.getResearchCost());
			cog.setTerritory(null == researchCost.getTerritory() ? new BigDecimal(0) : researchCost.getTerritory());
		}

		CognizanceManageCostBo manageCost = orgCognizanceMapper.selectCognizanceManageCostBoByUidAndYear(year, uid);
		if (null != manageCost) {
			cog.setNetAsset1(null == manageCost.getNetAsset1() ? new BigDecimal(0) : manageCost.getNetAsset1());
			cog.setNetAsset2(null == manageCost.getNetAsset2() ? new BigDecimal(0) : manageCost.getNetAsset2());
			cog.setNetAsset3(null == manageCost.getNetAsset3() ? new BigDecimal(0) : manageCost.getNetAsset3());
			cog.setSalesRevenue1(
					null == manageCost.getSalesRevenue1() ? new BigDecimal(0) : manageCost.getSalesRevenue1());
			cog.setSalesRevenue2(
					null == manageCost.getSalesRevenue2() ? new BigDecimal(0) : manageCost.getSalesRevenue2());
			cog.setSalesRevenue3(
					null == manageCost.getSalesRevenue3() ? new BigDecimal(0) : manageCost.getSalesRevenue3());
			cog.setGrossProfit1(
					null == manageCost.getGrossProfit1() ? new BigDecimal(0) : manageCost.getGrossProfit1());
			cog.setGrossProfit2(
					null == manageCost.getGrossProfit2() ? new BigDecimal(0) : manageCost.getGrossProfit2());
			cog.setGrossProfit3(
					null == manageCost.getGrossProfit3() ? new BigDecimal(0) : manageCost.getGrossProfit3());
		}
		Integer firstCatagory = orgCognizanceMapper.findFirstCatagory(year, uid);
		Integer secondCatagory = orgCognizanceMapper.findSecondCatagory(year, uid);
		OrgHumanResource ohr = orgCognizanceMapper.findFirmAndTechTotal(year, uid);
		BigDecimal totalRevenue = orgCognizanceMapper.findTotalRevenue(year, uid);
		/*
		 * CognizanceCatagoryBo catagory =
		 * orgCognizanceMapper.selectCognizanceCatagoryBoByUidAndYear(year,
		 * uid); if (null != catagory) {
		 */
		cog.setFirstCatagory(null == firstCatagory ? 0 : firstCatagory);
		cog.setSecondCatagory(null == secondCatagory ? 0 : secondCatagory);
		if (null != ohr) {
			cog.setFirmTotal(null == ohr.getFirmTotal() ? 0 : ohr.getFirmTotal());
			cog.setTechTotal(null == ohr.getTechTotal() ? 0 : ohr.getTechTotal());
		} else {
			cog.setFirmTotal(0);
			cog.setTechTotal(0);
		}
		cog.setTotalRevenue(null == totalRevenue ? new BigDecimal(0) : totalRevenue);
		// }

		BigDecimal revenue = orgCognizanceMapper.selectLastYearRevenueByUidAndYear(year, uid); // 上年度销售收入
		cog.setLastYearRevenue(null == revenue ? new BigDecimal(0) : revenue);
		return cog;
	}

	@Override
	public CognizanceOrgInfoBo selectCognizanceOrgInfoBoByUidAndCid(String uid, String cid) {
		return orgCognizanceMapper.selectCognizanceOrgInfoBoByUidAndCid(uid, cid);
	}

	@Override
	public CognizanceResearchCostBo selectCognizanceResearchCostBoByUidAndYear(Integer year, String uid) {
		return orgCognizanceMapper.selectCognizanceResearchCostBoByUidAndYear(year, uid);
	}

	@Override
	public CognizanceManageCostBo selectCognizanceManageCostBoByUidAndYear(Integer year, String uid) {
		return orgCognizanceMapper.selectCognizanceManageCostBoByUidAndYear(year, uid);
	}

	@Override
	public CognizanceCatagoryBo selectCognizanceCatagoryBoByUidAndYear(Integer year, String uid) {
		return orgCognizanceMapper.selectCognizanceCatagoryBoByUidAndYear(year, uid);
	}

	@Override
	public BigDecimal selectLastYearRevenueByUidAndYear(Integer year, String uid) {
		return orgCognizanceMapper.selectLastYearRevenueByUidAndYear(year, uid);
	}

	@Override
	public int updateByPrimaryKeySelective(OrgCognizance cog) {
		return orgCognizanceMapper.updateByPrimaryKeySelective(cog);
	}

	@Override
	public OrgCognizance selectCognizanceByUidAndYear(Integer year, String uid) {
		return orgCognizanceMapper.selectCognizanceByUidAndYear(year, uid);
	}

	@Override
	public int deleteByPrimaryKey(List<String> id) {
		return orgCognizanceMapper.batchDeleteByPrimaryKey(id);
	}

	@Override
	public void updateCognizance(OrgCognizance cog, OrgCognizanceLog log, Date recordTime, String aid) {
		if (null != log.getState() && null != recordTime && StringUtils.isNotBlank(cog.getUid())
				&& StringUtils.isNotBlank(log.getPrincipal())) {
			log.setRecordTime(recordTime);
			cog.setTechPrincipal(log.getPrincipal());
			OrganizationIdentity o = organizationIdentityMapper.selectOrgIdentityByUserId(cog.getUid());
			o.setTechPrincipal(null == cog.getTechPrincipal() ? "" : cog.getTechPrincipal());
			if (OrgCognizanceStatus.getStatus(cog.getState()) == OrgCognizanceStatus.DELIVERD) {
				cog.setCreateTime(recordTime);
			} else if (OrgCognizanceStatus.getStatus(cog.getState()) == OrgCognizanceStatus.ACCEPT) {
				cog.setAcceptDate(recordTime);
			} else if (OrgCognizanceStatus.getStatus(cog.getState()) == OrgCognizanceStatus.ISSUING) {
				cog.setIssuingDate(recordTime);
				o.setCertificateNumber(
						StringUtils.isBlank(cog.getCertificateNumber()) ? "" : cog.getCertificateNumber());
				o.setIssuingDate(recordTime);
				o.setCogContacts(null == cog.getContacts() ? null : cog.getContacts());
				organizationIdentityMapper.update(o);
			}

			if (OrgCognizanceStatus.getStatus(cog.getState()) == OrgCognizanceStatus.CIRCULATION) {
				cog.setState(OrgCognizanceStatus.DELIVERD.getCode());
			}

			log.setId(UUID.randomUUID().toString());
			log.setCid(cog.getId());
			log.setOperator(aid);
			orgCognizanceLogMapper.insert(log);

			createNotice(cog, log);

		}
		orgCognizanceMapper.updateByPrimaryKeySelective(cog);
	}

	@Override
	public OrgCognizance saveCognizance(OrgCognizance c, String salesman) {
		c.setState(OrgCognizanceStatus.DELIVERD.getCode());
		c.setFounder(salesman);
		c = disposeCognizanceSave(c);

		OrgCognizanceLog log = new OrgCognizanceLog();
		log.setId(UUID.randomUUID().toString());
		log.setCid(c.getId());
		log.setRecordTime(c.getRecordTime());
		log.setState(c.getState());
		log.setPrincipal(salesman);
		log.setOperator(salesman);
		log.setComment(c.getComment());
		orgCognizanceLogMapper.insert(log);

		createNotice(c, log);

		OrgCognizanceProportion ocp = orgCognizanceProportionMapper.selectByUid(c.getUid());
		if (null == ocp) {
			OrgCognizanceProportion o = new OrgCognizanceProportion();
			o.setId(UUID.randomUUID().toString());
			o.setUid(c.getUid());
			orgCognizanceProportionMapper.insert(o);
		} else {
			orgCognizanceProportionMapper.updateByPrimaryKeySelective(disposeProportion(ocp));
		}

		OrgCognizanceLog l = new OrgCognizanceLog();
		l.setId(UUID.randomUUID().toString());
		l.setCid(c.getId());
		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		l.setRecordTime(now.getTime());
		l.setState(c.getState());
		l.setPrincipal(TokenManager.getAdminId());
		l.setOperator(salesman);
		orgCognizanceLogMapper.insert(l);

		createNotice(c, l);
		return c;
	}

	private OrgCognizance disposeCognizanceSave(OrgCognizance c) {
		c.setId(UUID.randomUUID().toString());
		c.setDeletedSign(DeleteStatus.UNDELETE.getCode());
		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		c.setRecordTime(now.getTime());
		c.setCreateTime(now.getTime());
		orgCognizanceMapper.insert(c);
		return c;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<CultivationListBo> listCultivation(String uid, Integer province, String unitName, Integer pageNo,
			Integer pageSize) {
		Map<String, Object> params = new HashMap<>();

		if (!StringUtils.isBlank(unitName)) {
			params.put("unitName", unitName);
		}

		if (!StringUtils.isBlank(uid)) {
			params.put("uid", uid);
		}

		if (null != province) {
			params.put("province", province);
		}

		if (pageNo == null || pageNo < 0) {
			pageNo = 1;
		}

		if (pageSize == null || pageSize < 0) {
			pageSize = 10;
		}
		return (Pagination<CultivationListBo>) findPage("findCultivationListByPage", "findCultivationCount", params,
				pageNo, pageSize);
	}

	@Override
	public OrgCognizance selectByPrimaryKey(String id) {
		return orgCognizanceMapper.selectByPrimaryKey(id);
	}

	@Override
	public Integer selectLatelyRecordYear(String uid) {
		return orgCognizanceMapper.selectLatelyRecordYear(uid);
	}

	@Override
	public BusinessCountBo countBusiness(String uid, Integer year) {
		BusinessCountBo bcb = new BusinessCountBo();
		bcb.setUid(uid);
		bcb.setCopyrightDone(copyrightInfoMapper.countCopyrightDone(uid, year));
		bcb.setCopyrightUndone(copyrightInfoMapper.countCopyrightUnDone(uid, year));
		bcb.setPatentDone(patentInfoMapper.countPatentDone(uid, year));
		bcb.setPatentUndone(patentInfoMapper.countPatentUndone(uid, year));
		bcb.setTechProjectDone(techProjectMapper.countTechProjectDone(uid, year));
		bcb.setTechProjectUndone(techProjectMapper.countTechProjectUndone(uid, year));
		return bcb;
	}

	private OrgCognizanceProportion disposeProportion(OrgCognizanceProportion o) {
		o.setAbility(ProportionStatus.UNFINISHED.getCode());
		o.setAchievement(ProportionStatus.UNFINISHED.getCode());
		o.setActivity(ProportionStatus.UNFINISHED.getCode());
		o.setActivityCost(ProportionStatus.UNFINISHED.getCode());
		o.setFinance(ProportionStatus.UNFINISHED.getCode());
		o.setHonorDatum(ProportionStatus.UNFINISHED.getCode());
		o.setHumanResource(ProportionStatus.UNFINISHED.getCode());
		o.setInstitution(ProportionStatus.UNFINISHED.getCode());
		o.setIntellectualProperty(ProportionStatus.UNFINISHED.getCode());
		o.setRatepay(ProportionStatus.UNFINISHED.getCode());
		o.setStandard(ProportionStatus.UNFINISHED.getCode());
		o.setTechProject(ProportionStatus.UNFINISHED.getCode());
		return o;
	}

	private void createNotice(OrgCognizance cog, OrgCognizanceLog l) {
		OrgCognizance info = orgCognizanceMapper.selectByPrimaryKey(cog.getId());

		Notice n = new Notice();
		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		n.setId(UUID.randomUUID().toString());
		n.setCreateTime(now.getTime());
		n.setReaded(NoticeReadStatus.UNREAD.getCode());

		User u = userMapper.queryById(cog.getUid());
		if (null != u) {
			n.setPid(u.getAid());
		}

		n.setUid(cog.getUid());
		n.setRid(cog.getId());

		n.setYear(cog.getYear());

		n.setAid(l.getPrincipal());
		n.setContent("编号" + info.getSerialNumber() + "  " + OrgCognizanceStatus.getStatus(l.getState()).getDesc());
		n.setNoticeType(NoticeStatus.COGNIZANCE.getCode());
		// noticeMapper.insert(n);
	}

	@Override
	public OrgCognizance insertCognizance(OrgCognizance c, String aid) {
		c.setState(OrgCognizanceStatus.CREATE.getCode());
		c = disposeCognizanceSave(c);

		OrgCognizanceLog log = new OrgCognizanceLog();
		log.setId(UUID.randomUUID().toString());
		log.setCid(c.getId());
		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		log.setRecordTime(now.getTime());
		log.setState(OrgCognizanceStatus.CREATE.getCode());
		log.setPrincipal(aid);
		log.setComment(c.getComment());
		orgCognizanceLogMapper.insert(log);

		createNotice(c, log);
		return c;

	}

	@Override
	public List<CognizanceContractBo> selectContractCognizanceByContractId(String contractId) {
		return orgCognizanceMapper.selectContractCognizanceByContractId(contractId);
	}
	
	//to update 18
	@Override
	public void insertContractRecord(Contract c) {
		/*OrgCognizance oc = new OrgCognizance();
		oc.setId(UUID.randomUUID().toString());
		oc.setUid(c.getUid());
		oc.setContacts(c.getContacts());
		oc.setContractId(c.getId());
		oc.setYear(c.getCognizanceYear());
		oc.setDeletedSign(DeleteStatus.UNDELETE.getCode());
		oc.setState(OrgCognizanceStatus.CREATE.getCode());
		oc.setTechPrincipal(TokenManager.getAdminId());
		oc.setFounder(TokenManager.getAdminId());
		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		oc.setRecordTime(now.getTime());
		oc.setCreateTime(now.getTime());
		
		OrgCognizanceLog ocl = new OrgCognizanceLog();
		ocl.setId(UUID.randomUUID().toString());
		ocl.setCid(oc.getId());
		ocl.setPrincipal(TokenManager.getAdminId());
		ocl.setOperator(TokenManager.getAdminId());
		ocl.setRecordTime(now.getTime());
		ocl.setState(OrgCognizanceStatus.CREATE.getCode());

		orgCognizanceMapper.insert(oc);
		orgCognizanceLogMapper.insert(ocl);

		c.setCognizanceStatus(ContractBusinessStatus.CREATE.getCode());
		contractMapper.updateByPrimaryKeySelective(c);*/
	}

}
