/**
 */
package com.sifang.modules.flowpath.service;

import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.contract.dao.TraderContractTemplateDao;
import com.sifang.modules.contract.entity.TraderContractTemplate;
import com.sifang.modules.esign.cn.tsign.hz.exception.EsignDemoException;
import com.sifang.modules.esign.service.ESignFileService;
import com.sifang.modules.esign.service.ESignSignService;
import com.sifang.modules.esign.utils.BeanUtils;
import com.sifang.modules.esign.utils.ConvertUpMoney;
import com.sifang.modules.esign.vo.ComponentVo;
import com.sifang.modules.esign.vo.FileVo;
import com.sifang.modules.flowpath.dao.TraderAgentDao;
import com.sifang.modules.flowpath.dao.TraderApplyAgentDao;
import com.sifang.modules.flowpath.entity.TraderAgent;
import com.sifang.modules.flowpath.entity.TraderApplyAgent;
import com.sifang.modules.sunshine.SystemSetting.dao.TraderDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 代理商审批代理信息Service
 * @author lzp
 * @version 
 */
@Component
@Transactional(readOnly = true)
public class TraderAgentService extends BaseService {

	@Autowired
	private TraderAgentDao traderAgentDao;

	@Value("${img.domain}")
	private String URL;

	@Autowired
	private TraderContractTemplateDao templateDao;
	@Autowired
	private TraderDao traderDao;
	
	public TraderAgent get(String id) {
		return traderAgentDao.get(id);
	}

	
	@Transactional(readOnly = true)
	public void save(TraderAgent traderApplyAgent) {
		traderAgentDao.save(traderApplyAgent);
	}
	
	@Transactional(readOnly = true)
	public void delete(String id) {
		traderAgentDao.deleteById(id);
	}



	public String  inviteSign(String id) throws EsignDemoException {
		User user = UserUtils.getUser();
		TraderAgent agent = traderAgentDao.get(id);
		//获取模板

		TraderContractTemplate template = templateDao.getByHql("from TraderContractTemplate where status='0' and type='1' ");
		if(template == null){
			throw new BusinessException("请先维护合同模板");
		}
		if(StringUtil.isBlank(agent.getSignFlowId())){
			CrmTrader trader = traderDao.get(agent.getTraderId());
			List<Record> list = Db.find("SELECT * FROM `crm_sign_file` where form ='1'");
			List<ComponentVo> componentS = Lists.newArrayList();
			for(Record rd :list){
				ComponentVo vo = new ComponentVo();
				String key = rd.getStr("component_key");
				if("1".equals(rd.getStr("type"))){
					if("bond".equals(key)){
						BigDecimal bond = trader.getBond();
						vo.setComponentKey(key);
						vo.setComponentValue(bond.divide(new BigDecimal(10000),4,BigDecimal.ROUND_DOWN));
						String macAmount = ConvertUpMoney.toChinese(trader.getBond().toString());
						ComponentVo max = new ComponentVo();
						max.setComponentKey("macAmount");
						max.setComponentValue(macAmount);
						componentS.add(max);
					}else {
						//代理商信息
						String eomValue = (String) BeanUtils.getValueByStringField(trader,key);
						if(StringUtil.isNotBlank(eomValue)){
							vo.setComponentKey(key);
							vo.setComponentValue(eomValue);
						}
					}
				}else{
					String eomValue = (String) BeanUtils.getValueByStringField(agent,key);
					if(StringUtil.isNotBlank(eomValue)){
						vo.setComponentKey(key);
						vo.setComponentValue(eomValue);
					}
				}
				componentS.add(vo);
			}
			ComponentVo vo1 = new ComponentVo();
			vo1.setComponentKey("userName");
			vo1.setComponentValue(user.getUserName());
			componentS.add(vo1);
			ComponentVo year = new ComponentVo();
			year.setComponentKey("year");
			year.setComponentValue(DateUtils.getYear());
			componentS.add(year);
			ComponentVo mmo = new ComponentVo();
			mmo.setComponentKey("month");
			mmo.setComponentValue(DateUtils.getMonth());
			componentS.add(mmo);
			ComponentVo day = new ComponentVo();
			day.setComponentKey("day");
			day.setComponentValue(DateUtils.getDay());
			componentS.add(day);
			ComponentVo com1 = new ComponentVo();
			com1.setComponentKey("actualContacts1");
			com1.setComponentValue(trader.getActualContacts());
			componentS.add(com1);
			ComponentVo code = new ComponentVo();
			code.setComponentKey("actualIdCcode");
			code.setComponentValue(trader.getActualIdCode()	);
			componentS.add(code);

			ComponentVo img = new ComponentVo();
			img.setComponentKey("idImg");
			img.setComponentValue(URL+trader.getSfzzmfyjImg());
			componentS.add(img);
			//未邀请，流程ID为空
			FileVo fileVo = ESignFileService.createByDocTemplate(template.getDocTemplateId(),"代理商加盟合作协议",componentS);
			agent.setFileId(fileVo.getFileId());
			//基于文件发起签署---获取到流程ID
			String signFlow=ESignSignService.createByFile(fileVo.getFileId(),"代理商加盟合作协议",trader,agent.getId(),user.getId());
			agent.setSignFlowId(signFlow);
			//根据流程ID获取签署链接
			Map<String,String> remap =ESignSignService.signUrl(signFlow,trader.getTelephone(),"");
			logger.info("签署====================== :{}",remap);
		/*	StringBuilder contextString = new StringBuilder("尊敬的" + trader.getActualContacts()
					+ "，您好！能辉光伏邀请您签署合同。点击进入"+remap.get("shortUrl"));*/
			agent.setContractUrl(remap.get("url"));
			traderAgentDao.save(agent);
			//Map<String, Object> result = SfSmsNUtils.sendBatchMsg(trader.getTelephone(), contextString.toString(), "能辉光伏", "", SfSmsNUtils.SMS_TYPE_A);

			return remap.get("shortUrl");
		}else{
			throw new EsignDemoException("合同签署中，不要重复邀请!");
		}
	}

	
}
