package com.goafanti.patent.service.impl;

import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.enums.*;
import com.goafanti.common.model.*;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.patent.bo.*;
import com.goafanti.patent.service.PatentInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;

@Service
public class PatentInfoServiceImpl extends BaseMybatisDao<PatentInfoMapper> implements PatentInfoService {
	@Autowired
	private PatentInfoMapper				patentInfoMapper;
	@Autowired
	private UserMapper						userMapper;
	@Autowired
	private PatentRegistrationMapper		patentRegistrationMapper;
	@Autowired
	private PatentCostMapper				patentCostMapper;
	@Autowired
	private PatentLogMapper					patentLogMapper;
	@Autowired
	private OrgIntellectualPropertyMapper	orgIntellectualPropertyMapper;
	@Autowired
	private OrganizationIdentityMapper		organizationIdentityMapper;
	@Override
	public PatentInfo insert(PatentInfo patentInfo) {
		patentInfoMapper.insert(patentInfo);
		return patentInfo;
	}

	@Override
	public int updateByPrimaryKeySelective(PatentInfo patentInfo) {
		return patentInfoMapper.updateByPrimaryKeySelective(patentInfo);
	}

	@Override
	public PatentInfo selectByPrimaryKey(String id) {
		return patentInfoMapper.selectByPrimaryKey(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<PatentInfo> getClientApplyList(String uid, String patentNumber, String patentName,
			Integer patentCatagory, Integer patentState, Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<>();

		if (uid == null) {
			return null;
		} else {
			params.put("uid", uid);
		}

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

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

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

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

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

		if (pageSize == null || pageSize < 0 || pageSize > 10) {
			pageSize = 10;
		}
		return (Pagination<PatentInfo>) findPage("findClientApplyListByPage", "findClentApplyCount", params, pageNo,
				pageSize);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<PatentManageListBo> getManagePatentList(String contractId, Integer serialNumber,
			String patentNumber, String office, Integer locationProvince, String unitName, Integer patentCatagory,
			String patentName, Integer patentState, String[] cDate, String[] pDate, String author, String uid,
			Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<>();
		Date cStart = null;
		Date cEnd = null;
		Date pStart = null;
		Date pEnd = null;

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

		if (cDate != null && cDate.length > 0) {
			try {
				cStart = StringUtils.isBlank(cDate[0]) ? null : DateUtils.parseDate(cDate[0], AFTConstants.YYYYMMDD);
				cEnd = StringUtils.isBlank(cDate[1]) ? null
						: DateUtils.addDays(DateUtils.parseDate(cDate[1], AFTConstants.YYYYMMDD), 1);
			} catch (ParseException e) {
			}
		}
		if (pDate != null && pDate.length > 0) {
			try {
				pStart = StringUtils.isBlank(pDate[0]) ? null : DateUtils.parseDate(pDate[0], AFTConstants.YYYYMMDD);
				pEnd = StringUtils.isBlank(pDate[1]) ? null
						: DateUtils.addDays(DateUtils.parseDate(pDate[1], AFTConstants.YYYYMMDD), 1);
			} catch (ParseException e) {
			}

		}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		if (pageSize == null || pageSize < 0 || pageSize > 1000) {
			pageSize = 10;
		}
		return (Pagination<PatentManageListBo>) findPage("findManagePatentListByPage", "findManagePatentCount", params,
				pageNo, pageSize);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<PatentPendingBo> getManagePendingPaymentList(Integer locationProvince, Integer pageNo,
			Integer pageSize) {
		Map<String, Object> params = new HashMap<>();

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

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

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

		if (pageSize == null || pageSize < 0) {
			pageSize = 10;
		}
		return (Pagination<PatentPendingBo>) findPage("findManagePendingPaymentListByPage",
				"findManagePendingPaymentCount", params, pageNo, pageSize);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<PatentNoticeOfCorrectionBo> getNoticeOfCorrectionList(Date authorizedDate, Integer serialNumber,
			String patentNumber, String office, Integer locationProvince, String unitName, Integer patentCatagory,
			String patentName, Integer patentState, String author, Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<>();

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

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

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

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

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

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

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

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

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

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

		if (author != null && author != "") {
			params.put("author", patentState);
		}

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

		if (pageSize == null || pageSize < 0 || pageSize > 10) {
			pageSize = 10;
		}
		return (Pagination<PatentNoticeOfCorrectionBo>) findPage("findNoticeOfCorrectionListByPage",
				"findNoticeOfCorrectionCount", params, pageNo, pageSize);
	}

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

	@Override
	public PatentInfo savePatentInfo(PatentInfo patentInfo, String salesman) {
		patentInfo.setFounder(salesman);
		patentInfo.setPatentState(PatentInfoStatus.DELIVERD.getCode());
		patentInfo.setPrincipal(TokenManager.getAdminId());
		patentInfo = disposePatentInfoSave(patentInfo);

		PatentLog log = new PatentLog();
		log.setId(UUID.randomUUID().toString());
		log.setPid(patentInfo.getId());
		log.setRecordTime(patentInfo.getRecordTime());
		log.setState(PatentInfoStatus.CREATE.getCode());
		log.setPrincipal(salesman);
		log.setOperator(salesman);
		log.setComment(patentInfo.getPatentDes());
		patentLogMapper.insert(log);

		if (!StringUtils.isBlank(patentInfo.getPatentProryStatementUrl())) {
			OrganizationIdentity oi = organizationIdentityMapper.selectOrgIdentityByUserId(patentInfo.getUid());
			oi.setPatentProryStatementUrl(patentInfo.getPatentProryStatementUrl());
			organizationIdentityMapper.update(oi);
		}
		createNotice(patentInfo, log);

		PatentLog l = new PatentLog();
		l.setId(UUID.randomUUID().toString());
		l.setPid(patentInfo.getId());
		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		l.setRecordTime(now.getTime());
		l.setState(PatentInfoStatus.DELIVERD.getCode());
		l.setPrincipal(TokenManager.getAdminId());
		l.setOperator(salesman);
		patentLogMapper.insert(l);
		createNotice(patentInfo, l);
		return patentInfo;
	}

	@Override
	public void updatePatentInfo(PatentInfo p, PatentLog log, Date recordTime) {

		if (!StringUtils.isBlank(p.getPatentProryStatementUrl())) {
			OrganizationIdentity oi = organizationIdentityMapper.selectOrgIdentityByUserId(p.getUid());
			oi.setPatentProryStatementUrl(p.getPatentProryStatementUrl());
			organizationIdentityMapper.update(oi);
		}

		if (null != log.getState() && recordTime != null && StringUtils.isNotBlank(log.getPrincipal())) {
			log.setId(UUID.randomUUID().toString());
			log.setPid(p.getId());
			log.setRecordTime(recordTime);
			if (TokenManager.getToken() instanceof Admin) {
				log.setOperator(TokenManager.getAdminId());
			}
			if (PatentInfoStatus.getStatus(log.getState()) == PatentInfoStatus.ACCEPT) {
				p.setPatentApplicationDate(recordTime);
			} else if (PatentInfoStatus.getStatus(log.getState()) == PatentInfoStatus.LICENSE) {
				p.setAuthorizedDate(recordTime);
			} else if (PatentInfoStatus.getStatus(log.getState()) == PatentInfoStatus.REVIEWNOTICE) {
				p.setRecordTime(recordTime);
			} else if (PatentInfoStatus.getStatus(log.getState()) == PatentInfoStatus.CORRECTIONNOTICE) {
				p.setRecordTime(recordTime);
			}
			if (PatentInfoStatus.getStatus(log.getState()) != PatentInfoStatus.CIRCULATION) {
				p.setPatentState(log.getState());
			}
			p.setPrincipal(log.getPrincipal());
			patentLogMapper.insert(log);

			if (PatentInfoStatus.getStatus(p.getPatentState()) == PatentInfoStatus.AUTHORIZE) {
				OrgIntellectualProperty o = new OrgIntellectualProperty();
				o.setId(UUID.randomUUID().toString());
				o.setUid(p.getUid());
				o.setPid(p.getId());
				o.setDeletedSign(DeleteStatus.UNDELETE.getCode());
				o.setIntellectualPropertyNumber(p.getPatentNumber());
				o.setIntellectualPropertyName(p.getPatentName());
				o.setCatagory(1);
				o.setObtainWay(1);
				o.setAuthorizationNumber(p.getPatentNumber());
				o.setAuthorizationDate(p.getAuthorizedDate());
				o.setEvaluationCategory((3 == p.getPatentCatagory()) ? 0 : 1);
				o.setType(IntellectualPropertyType.PATENT.getCode());
				o.setPropertyRightUrl(p.getPatentCertificateUrl());
				orgIntellectualPropertyMapper.insert(o);
			}

			if (PatentInfoStatus.getStatus(p.getPatentState()) == PatentInfoStatus.LICENSE) {
				OrgIntellectualProperty o = orgIntellectualPropertyMapper.selectOrgIntellectualPropertyByPid(p.getId());
				if (null != o) {
					Integer i = 0;
					switch (p.getPatentCatagory()) {
					case 0:
						i = 0;
						break;
					case 1:
						i = 2;
						break;
					case 2:
						i = 3;
						break;
					case 3:
						i = 11;
						break;
					}
					o.setCatagory(i);
					o.setAuthorizationDate(p.getAuthorizedDate());
					o.setPropertyRightUrl(p.getPatentCertificateUrl());
					orgIntellectualPropertyMapper.updateByPrimaryKeySelective(o);
				}
			}
			createNotice(p, log);
		}
		patentInfoMapper.updateByPrimaryKeySelective(p);
	}

	@Override
	public void updateNoticeOfCorrection(String pid, Integer patentState) {
		PatentInfo patentInfo = new PatentInfo();
		patentInfo.setId(pid);
		if (patentState == PatentInfoStatus.REVIEWNOTICE.getCode()) {
			patentInfo.setPatentState(PatentInfoStatus.REVIEWREPLY.getCode());
		} else if (patentState == PatentInfoStatus.CORRECTIONNOTICE.getCode()) {
			patentInfo.setPatentState(PatentInfoStatus.CORRECTIONREPLY.getCode());
		}
		patentInfoMapper.updateByPrimaryKeySelective(patentInfo);

		PatentLog patentLog = new PatentLog();
		PatentInfo p = patentInfoMapper.selectByPrimaryKey(pid);
		patentLog.setId(UUID.randomUUID().toString());
		patentLog.setPid(pid);
		patentLog.setState(p.getPatentState());
		patentLog.setOperator(TokenManager.getAdminId());
		patentLog.setPrincipal(p.getPrincipal());

		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		patentLog.setRecordTime(now.getTime());

		patentLogMapper.insert(patentLog);
	}

	@Override
	public PatentInfoDetailBo selectPatentInfoDetail(String id) {
		return patentInfoMapper.selectPatentInfoDetail(id);
	}

	@Override
	public int batchCirculation(String[] ids, String recordTimeFormattedDate, PatentLog pl) {
		Date recordTime = null;
		try {
			recordTime = DateUtils.parseDate(recordTimeFormattedDate, AFTConstants.YYYYMMDDHHMMSS);
		} catch (ParseException e) {
		}
		pl.setRecordTime(recordTime);
		List<PatentLog> p = new ArrayList<PatentLog>();
		List<PatentInfo> list = patentInfoMapper.selectByPrimaryKeys(Arrays.asList(ids));
		if (null != list && list.size() > 0) {
			PatentLog patentLog = null;
			for (PatentInfo patentInfo : list) {
				patentLog = new PatentLog();
				BeanUtils.copyProperties(pl, patentLog);
				patentLog.setId(UUID.randomUUID().toString());
				patentLog.setPid(patentInfo.getId());
				patentLog.setOperator(TokenManager.getAdminId());
				p.add(patentLog);
				if (PatentInfoStatus.CIRCULATION.getCode() != patentLog.getState()) {
					patentInfo.setPatentState(patentLog.getState());
					patentInfoMapper.updateByPrimaryKeySelective(patentInfo);
				}
				createNotice(patentInfo, patentLog);
			}
			return patentLogMapper.batchInsert(p);
		}
		return 0;
	}

	// 专利年费到期
	@Override
	public List<PatentExpireBo> selectExpireRecord() {
		return patentInfoMapper.selectExpireRecord();
	}

	@Override
	public PatentInfo insertPatentInfo(PatentInfo patentInfo, String aid) {
		patentInfo.setPatentState(PatentInfoStatus.CREATE.getCode());
		patentInfo.setPrincipal(aid);
		PatentInfo p = disposePatentInfoSave(patentInfo);

		PatentLog log = new PatentLog();
		log.setId(UUID.randomUUID().toString());
		log.setPid(patentInfo.getId());
		log.setRecordTime(patentInfo.getRecordTime());
		log.setState(PatentInfoStatus.CREATE.getCode());
		log.setPrincipal(aid);
		log.setComment(patentInfo.getPatentDes());
		patentLogMapper.insert(log);

		createNotice(patentInfo, log);
		return p;
	}

	private PatentInfo disposePatentInfoSave(PatentInfo patentInfo) {
		patentInfo.setId(UUID.randomUUID().toString());
		patentInfo.setDeletedSign(DeleteStatus.UNDELETE.getCode());
		patentInfo.setConfirmState(0);

		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		patentInfo.setCreateTime(now.getTime());

		patentInfoMapper.insert(patentInfo);

		PatentRegistration patentRegistration = new PatentRegistration();
		patentRegistration.setId(UUID.randomUUID().toString());
		patentRegistration.setPid(patentInfo.getId());
		patentRegistrationMapper.insert(patentRegistration);

		PatentCost patentCost = new PatentCost();
		patentCost.setId(UUID.randomUUID().toString());
		patentCost.setPid(patentInfo.getId());
		patentCost.setAnnualFeeState(0);
		patentCost.setPaymentState(0);
		patentCostMapper.insert(patentCost);
		return patentInfo;
	}

	@Override
	public List<PatentContractListBo> listContractPatentByContractId(String contractId) {
		return patentInfoMapper.listContractPatentByContractId(contractId);
	}

	//to update 18
	
	@Override
	public void batchInsertContractRecord(Contract contract) {
		/**
		List<PatentInfo> pi = new ArrayList<>();
		List<PatentRegistration> pr = new ArrayList<>();
		List<PatentCost> pc = new ArrayList<>();
		List<PatentLog> pl = new ArrayList<>();
		contract.setPatentStatus(ContractBusinessStatus.CREATE.getCode());
		contractMapper.updateByPrimaryKeySelective(contract);

		for (int i = 0; i < contract.getPatentNum(); i++) {
			PatentInfo p = new PatentInfo();
			PatentLog l = new PatentLog();
			PatentRegistration r = new PatentRegistration();
			PatentCost c = new PatentCost();

			p.setId(UUID.randomUUID().toString());
			p.setUid(contract.getUid());
			p.setContractId(contract.getId());
			p.setDeletedSign(DeleteStatus.UNDELETE.getCode());
			p.setFounder(TokenManager.getAdminId());
			p.setPrincipal(TokenManager.getAdminId());
			p.setPatentState(PatentInfoStatus.CREATE.getCode());
			Calendar now = Calendar.getInstance();
			now.set(Calendar.MILLISECOND, 0);
			p.setCreateTime(now.getTime());
			p.setContacts(contract.getContacts());

			l.setId(UUID.randomUUID().toString());
			l.setPid(p.getId());
			l.setPrincipal(TokenManager.getAdminId());
			l.setOperator(TokenManager.getAdminId());
			l.setRecordTime(now.getTime());
			l.setState(PatentInfoStatus.CREATE.getCode());

			r.setId(UUID.randomUUID().toString());
			r.setPid(p.getId());

			c.setId(UUID.randomUUID().toString());
			c.setPid(p.getId());
			c.setAnnualFeeState(PatentAnnualFeeStatus.UNPAID.getCode());
			c.setPaymentState(PatentPaymentStatus.UNPAID.getCode());
			pi.add(p);
			pr.add(r);
			pc.add(c);
			pl.add(l);
		}
		patentInfoMapper.batchInsert(pi);
		patentRegistrationMapper.batchInsert(pr);
		patentCostMapper.batchInsert(pc);
		patentLogMapper.batchInsert(pl);
		**/
	}
	
	@Override
	public List<PatentAnnualFeeTaskBo> findAnnualFeeTaskBo() {
		return patentInfoMapper.findAnnualFeeTaskBo();
	}

	private void createNotice(PatentInfo p, PatentLog l) {
		PatentInfo info = patentInfoMapper.selectByPrimaryKey(p.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(p.getUid());
		if (null != u) {
			n.setPid(u.getAid());
		}

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

		n.setAid(l.getPrincipal());
		n.setContent("编号" + info.getSerialNumber() + "  " + PatentInfoStatus.getStatus(l.getState()).getDesc());
		n.setNoticeType(NoticeStatus.PATENTINFO.getCode());
	}

}
