package com.goafanti.copyright.service.impl;

import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.CopyrightInfoMapper;
import com.goafanti.common.dao.CopyrightLogMapper;
import com.goafanti.common.dao.OrgIntellectualPropertyMapper;
import com.goafanti.common.dao.UserMapper;
import com.goafanti.common.enums.CopyrightStatus;
import com.goafanti.common.enums.IntellectualPropertyType;
import com.goafanti.common.enums.NoticeReadStatus;
import com.goafanti.common.enums.NoticeStatus;
import com.goafanti.common.model.*;
import com.goafanti.copyright.bo.CopyrightContractListBo;
import com.goafanti.copyright.bo.CopyrightInfoDetail;
import com.goafanti.copyright.bo.CopyrightInfoSummary;
import com.goafanti.copyright.bo.CopyrightLogBo;
import com.goafanti.copyright.service.CopyrightInfoService;
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.apache.commons.lang3.time.DateUtils;
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 CopyrightInfoServiceImpl extends BaseMybatisDao<CopyrightInfoMapper> implements CopyrightInfoService {
	@Autowired
	private CopyrightInfoMapper				copyrightInfoMapper;
	@Autowired
	private CopyrightLogMapper				copyrightLogMapper;
	@Autowired
	private OrgIntellectualPropertyMapper	orgIntellectualPropertyMapper;
	@Autowired
	private UserMapper						userMapper;
	@Override
	public CopyrightInfo insert(CopyrightInfo copyrightInfo, String aid) {
		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		copyrightInfo.setCreateTime(now.getTime());
		copyrightInfo.setStatus(CopyrightStatus.CREATE.getCode());
		CopyrightLog log = new CopyrightLog();
		log.setCid(copyrightInfo.getId());
		log.setRecordTime(copyrightInfo.getCreateTime());
		log.setComment(copyrightInfo.getComment());
		log.setPrincipal(aid);
		log.setStatus(copyrightInfo.getStatus());
		copyrightInfoMapper.insertSelective(copyrightInfo);
		copyrightLogMapper.insertSelective(log);
		createNotice(copyrightInfo, log);
		return copyrightInfo;
	}

	@Override
	public void updateByPrimaryKeySelective(CopyrightInfo copyrightInfo, CopyrightLog copyrightLog) {
		if (copyrightLog.getRecordTime() != null && copyrightLog.getStatus() != null
				&& copyrightLog.getPrincipal() != null) {
			copyrightLogMapper.insertSelective(copyrightLog);

			createNotice(copyrightInfo, copyrightLog);

			if (CopyrightStatus.getStatus(copyrightLog.getStatus()) == CopyrightStatus.ACCEPT) {
				copyrightInfo.setAcceptTime(copyrightLog.getRecordTime());
			} else if (CopyrightStatus.getStatus(copyrightLog.getStatus()) == CopyrightStatus.DELIVERD) {
				copyrightInfo.setCreateTime(copyrightLog.getRecordTime());
			} else if (CopyrightStatus.getStatus(copyrightLog.getStatus()) == CopyrightStatus.AUTHORIZED) {
				copyrightInfo.setAuthorizedDate(copyrightLog.getRecordTime());
				OrgIntellectualProperty o = new OrgIntellectualProperty();
				o.setId(UUID.randomUUID().toString());
				o.setUid(copyrightInfo.getUid());
				o.setPid(copyrightInfo.getId());
				o.setDeletedSign(0);
				o.setIntellectualPropertyNumber(copyrightInfo.getCopyrightNumber());
				o.setIntellectualPropertyName(copyrightInfo.getCopyrightName());
				o.setCatagory(4);
				o.setObtainWay(1);
				o.setAuthorizationNumber(copyrightInfo.getCopyrightNumber());
				o.setAuthorizationDate(copyrightInfo.getAuthorizedDate());
				o.setEvaluationCategory(1);
				o.setType(IntellectualPropertyType.COPYRIGHT.getCode());
				o.setPropertyRightUrl(copyrightInfo.getCertificateUrl());
				orgIntellectualPropertyMapper.insert(o);
			} else if (CopyrightStatus.getStatus(copyrightLog.getStatus()) == CopyrightStatus.CIRCULATION) {
				copyrightInfo.setStatus(CopyrightStatus.DELIVERD.getCode());
			}
		} else {
			copyrightInfo.setStatus(null);
		}
		copyrightInfoMapper.updateByPrimaryKeySelective(copyrightInfo);
	}

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

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<CopyrightInfo> listCopyrightInfo(String contractId, Integer province, String unitName,
			String copyrightName, CopyrightStatus status, String[] createTime, String[] acceptTime, String[] authTime,
			Integer pageNo, Integer pageSize) {
		return (Pagination<CopyrightInfo>) findPage("findListByPage", "findListCount", buildListParams(contractId,
				province, unitName, copyrightName, status, createTime, acceptTime, authTime, pageNo, pageSize, null),
				pageNo, pageSize);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<CopyrightInfoSummary> listMyCopyrightInfo(String contractId, Integer province, String unitName,
			String copyrightName, CopyrightStatus status, String[] createTime, String[] acceptTime, String[] authTime,
			Integer pageNo, Integer pageSize, String uid) {
		return (Pagination<CopyrightInfoSummary>) findPage("findListByPage", "findListCount",
				buildListParams(contractId, province, unitName, copyrightName, status, createTime, acceptTime, authTime,
						pageNo, pageSize, uid),
				pageNo, pageSize);
	}

	private Map<String, Object> buildListParams(String contractId, Integer province, String unitName,
			String copyrightName, CopyrightStatus status, String[] createTime, String[] acceptTime, String[] authTime,
			Integer pageNo, Integer pageSize, String uid) {
		Map<String, Object> params = new HashMap<>();

		if (TokenManager.getAdminToken() != null && !TokenManager.hasRole(AFTConstants.SUPERADMIN)) {
			params.put("principal", TokenManager.getAdminId());
		}
		if (null != province) {
			params.put("province", province);
		}
		if (StringUtils.isNotBlank(contractId)) {
			params.put("contractId", contractId);
		}
		if (StringUtils.isNotBlank(unitName)) {
			params.put("unitName", unitName);
		}
		if (StringUtils.isNotBlank(uid)) {
			params.put("unitId", uid);
		}
		if (StringUtils.isNotBlank(copyrightName)) {
			params.put("copyrightName", copyrightName);
		}
		if (status != CopyrightStatus.OTHER) {
			params.put("status", status.getCode());
		}
		if (createTime != null) {
			try {
				if (createTime.length > 0 && StringUtils.isNotBlank(createTime[0])) {
					params.put("createStartTime", DateUtils.parseDate(createTime[0], AFTConstants.YYYYMMDD));
				}
				if (createTime.length > 1 && StringUtils.isNotBlank(createTime[1])) {
					params.put("createEndTime",
							DateUtils.addDays(DateUtils.parseDate(createTime[1], AFTConstants.YYYYMMDD), 1));
				}
			} catch (ParseException e) {
			}
		}
		if (acceptTime != null) {
			try {
				if (acceptTime.length > 0 && StringUtils.isNotBlank(acceptTime[0])) {
					params.put("acceptStartTime", DateUtils.parseDate(acceptTime[0], AFTConstants.YYYYMMDD));
				}
				if (acceptTime.length > 1 && StringUtils.isNotBlank(acceptTime[1])) {
					params.put("acceptEndTime",
							DateUtils.addDays(DateUtils.parseDate(acceptTime[1], AFTConstants.YYYYMMDD), 1));
				}
			} catch (ParseException e) {
			}
		}
		if (authTime != null) {
			try {
				if (authTime.length > 0 && StringUtils.isNotBlank(authTime[0])) {
					params.put("authStartTime", DateUtils.parseDate(authTime[0], AFTConstants.YYYYMMDD));
				}
				if (authTime.length > 1 && StringUtils.isNotBlank(authTime[1])) {
					params.put("authEndTime",
							DateUtils.addDays(DateUtils.parseDate(authTime[1], AFTConstants.YYYYMMDD), 1));
				}
			} catch (ParseException e) {
			}
		}
		return params;
	}

	@Override
	public CopyrightInfo selectByPrimaryKey(String id) {
		return copyrightInfoMapper.selectByPrimaryKey(id);
	}

	@Override
	public CopyrightInfoDetail findByPrimaryKey(String id) {
		return copyrightInfoMapper.findByPrimaryKey(id);
	}

	@Override
	public List<CopyrightLogBo> findLogsByPrimaryKey(String id) {
		return copyrightLogMapper.findByCopyrightId(id);
	}

	@Override
	public void updateByPrimaryKey(CopyrightInfo copyrightInfo) {
		copyrightInfoMapper.updateByPrimaryKey(copyrightInfo);
	}

	@Override
	public int batchCirculation(String[] ids, String recordTimeFormattedDate, CopyrightLog cl) {
		Date recordTime = null;
		try {
			recordTime = DateUtils.parseDate(recordTimeFormattedDate, AFTConstants.YYYYMMDDHHMMSS);
		} catch (ParseException e) {
		}
		cl.setRecordTime(recordTime);
		List<CopyrightLog> log = new ArrayList<CopyrightLog>();
		List<CopyrightInfo> list = copyrightInfoMapper.selectByPrimaryKeys(Arrays.asList(ids));
		if (null != list && list.size() > 0) {
			CopyrightLog copyrightLog = null;
			for (CopyrightInfo copyrightInfo : list) {
				copyrightLog = new CopyrightLog();
				BeanUtils.copyProperties(cl, copyrightLog);
				copyrightLog.setId(UUID.randomUUID().toString());
				copyrightLog.setCid(copyrightInfo.getId());
				copyrightLog.setOperator(TokenManager.getAdminId());
				log.add(copyrightLog);
				if (CopyrightStatus.CIRCULATION.getCode() != copyrightLog.getStatus()) {
					copyrightInfo.setStatus(copyrightLog.getStatus());
					copyrightInfoMapper.updateByPrimaryKeySelective(copyrightInfo);
				}
				createNotice(copyrightInfo, copyrightLog);
			}
			return copyrightLogMapper.batchInsert(log);
		}
		return 0;
	}

	@Override
	public CopyrightInfo saveCopyright(CopyrightInfo copyrightInfo, String salesman) {
		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		copyrightInfo.setCreateTime(now.getTime());
		copyrightInfo.setFounder(salesman);
		copyrightInfo.setStatus(CopyrightStatus.DELIVERD.getCode());
		copyrightInfo.setPrincipal(TokenManager.getAdminId());

		CopyrightLog log = new CopyrightLog();
		log.setCid(copyrightInfo.getId());
		log.setRecordTime(copyrightInfo.getCreateTime());
		log.setComment(copyrightInfo.getComment());
		log.setOperator(salesman);
		log.setPrincipal(salesman);
		log.setStatus(CopyrightStatus.CREATE.getCode());

		copyrightInfoMapper.insertSelective(copyrightInfo);
		copyrightLogMapper.insertSelective(log);
		createNotice(copyrightInfo, log);

		CopyrightLog l = new CopyrightLog();
		l.setCid(copyrightInfo.getId());
		l.setRecordTime(now.getTime());
		l.setOperator(salesman);
		l.setPrincipal(TokenManager.getAdminId());
		l.setStatus(CopyrightStatus.DELIVERD.getCode());
		copyrightLogMapper.insertSelective(l);
		createNotice(copyrightInfo, l);
		return copyrightInfo;
	}

	@Override
	public List<CopyrightContractListBo> listContractCopyrightByContractId(String contractId) {
		return copyrightInfoMapper.listContractCopyrightByContractId(contractId);
	}

	//to update 18
	@Override
	public void batchInsertContractRecord(Contract contract) {
		/**
		contract.setCopyrightStatus(ContractBusinessStatus.CREATE.getCode());
		contractMapper.updateByPrimaryKeySelective(contract);

		List<CopyrightInfo> ci = new ArrayList<>();
		List<CopyrightLog> cl = new ArrayList<>();
		CopyrightInfo c = null;
		CopyrightLog l = null;
		for (int i = 0; i < contract.getCopyrightNum(); i++) {
			c = new CopyrightInfo();
			l = new CopyrightLog();
			c.getId();
			c.setUid(contract.getUid());
			c.setContact(contract.getContacts());
			c.setContractId(contract.getId());
			c.setStatus(CopyrightStatus.CREATE.getCode());
			c.setPrincipal(TokenManager.getAdminId());
			c.setFounder(TokenManager.getAdminId());
			Calendar now = Calendar.getInstance();
			now.set(Calendar.MILLISECOND, 0);
			c.setCreateTime(now.getTime());
			c.setDeleteSign(DeleteStatus.UNDELETE.getCode());

			l.getId();
			l.setCid(c.getId());
			l.setStatus(CopyrightStatus.CREATE.getCode());
			l.setOperator(TokenManager.getAdminId());
			l.setOperator(TokenManager.getAdminId());
			l.setRecordTime(now.getTime());

			ci.add(c);
			cl.add(l);
		}
		copyrightInfoMapper.batchInsert(ci);
		copyrightLogMapper.batchInsert(cl);
		**/
	}

	private void createNotice(CopyrightInfo c, CopyrightLog l) {
		CopyrightInfo info = copyrightInfoMapper.selectByPrimaryKey(c.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(c.getUid());
		if (null != u) {
			n.setPid(u.getAid());
		}

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

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

}
