package com.ym.mec.biz.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.TeacherContractsDao;
import com.ym.mec.biz.dal.entity.TeacherContracts;
import com.ym.mec.biz.service.TeacherContractsService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.common.tenant.TenantContextHolder;
import com.ym.mec.thirdparty.lingxinpay.ContractSignService;

@Service
public class TeacherContractsServiceImpl extends BaseServiceImpl<Long, TeacherContracts> implements TeacherContractsService {

	private static final Logger logger = LoggerFactory.getLogger(TeacherContractsServiceImpl.class);

	@Autowired
	private TeacherContractsDao teacherContractsDao;

	@Autowired
	private ContractSignService contractSignService;

	@Override
	public BaseDAO<Long, TeacherContracts> getDAO() {
		return teacherContractsDao;
	}

	@Override
	public TeacherContracts queryByUserId(Integer userId) {
		return teacherContractsDao.queryByUserId(userId);
	}

	@Override
	@Transactional
	public boolean sign(SysUser user) {

		if (StringUtils.isBlank(user.getRealName()) || StringUtils.isBlank(user.getIdCardNo())) {
			throw new BizException("请先实名认证");
		}

		TeacherContracts teacherContracts = new TeacherContracts();
		teacherContracts.setUserId(user.getId());
		teacherContracts.setCreateTime(new Date());
		teacherContracts.setType(null);
		teacherContracts.setTenantId(TenantContextHolder.getTenantId());
		teacherContracts.setSerialNo(user.getId() + "_" + System.currentTimeMillis());

		teacherContractsDao.insert(teacherContracts);

		contractSignService.signContract(user.getRealName(), user.getIdCardNo(), user.getPhone(), teacherContracts.getSerialNo());

		return true;
	}

	@Override
	public boolean callback(String jsonStr) {
		JSONObject jsonObject = JSONObject.parseObject(jsonStr);

		String serialNo = (String) JSONPath.eval(jsonObject, "$.content.serialNo");

		TeacherContracts teacherContracts = teacherContractsDao.queryBySerialNo(serialNo);
		if (teacherContracts == null) {
			return true;
		}

		if (StringUtils.equals("F", jsonObject.getString("return_code"))) {
			teacherContractsDao.delete(teacherContracts.getId());
			logger.error("老师签署协议回调异常：{}", jsonObject.getString("return_message"));
			return true;
		}

		String contractResultNo = (String) JSONPath.eval(jsonObject, "$.content.contractResultNo");
		String contractUrl = (String) JSONPath.eval(jsonObject, "$.content.contractUrl");

		teacherContracts.setContractNo(contractResultNo);
		teacherContracts.setUrl(contractUrl);
		teacherContractsDao.update(teacherContracts);

		return true;
	}

	@Override
	public void queryTeacherContractSignStatus() {
		
		List<TeacherContracts> updateList = new ArrayList<TeacherContracts>();
		
		List<TeacherContracts> teacherContractsList = teacherContractsDao.queryNotUrlList();
		
		if(teacherContractsList != null && teacherContractsList.size() > 0){
			for(TeacherContracts teacherContracts : teacherContractsList){
				String url = contractSignService.querySignContractResult(teacherContracts.getSerialNo());
				if(StringUtils.isNoneBlank(url)){
					teacherContracts.setUrl(url);
					updateList.add(teacherContracts);
				}else{
					teacherContractsDao.delete(teacherContracts.getId());
				}
			}
			
			if(updateList.size() > 0){
				teacherContractsDao.batchUpdate(updateList);
			}
		}
		
	}

}