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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.q7link.openapi.model.*;
import com.sifang.modules.customer.utils.EmployeRoleUtils;
import com.sifang.modules.flowable.service.ProcessFlowableService;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.flowpath.constant.BondApplyConstant;
import com.sifang.modules.flowpath.dao.BondApplyDao;
import com.sifang.modules.flowpath.dao.TraderAgentDao;
import com.sifang.modules.flowpath.dao.TraderApplyAgentDao;
import com.sifang.modules.flowpath.entity.TraderApplyAgent;
import com.sifang.modules.flowpath.vo.TraderApplyVo;
import com.sifang.modules.q7link.utils.OpenapiTemplate;
import com.sifang.modules.sunshine.SystemSetting.dao.CrmPlatformEmpDao;
import com.sifang.modules.sunshine.SystemSetting.dao.DepartmentSettingDao;
import com.sifang.modules.sunshine.SystemSetting.dao.SiteInformationDao;
import com.sifang.modules.sunshine.SystemSetting.dao.TraderDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmDepartment;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmPlatformEmployee;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
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 com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.flowable.task.api.Task;
import org.flowable.engine.TaskService;
import com.sifang.modules.flowpath.entity.TraderApply;
import com.sifang.modules.flowpath.dao.TraderApplyDao;

import java.util.*;

import static com.sifang.modules.q7link.utils.Q7linkUtils.getSdkRequestConfig;
import static com.sifang.modules.q7link.utils.Q7linkUtils.openapi;

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

	@Autowired
	private TraderApplyDao traderApplyDao;

	@Autowired
	private TraderApplyAgentDao applyAgentDao;

	@Autowired
	private TraderAgentDao agentDao;

	@Autowired
	private DepartmentSettingDao departmentSettingDao;

	@Autowired
	private CrmPlatformEmpDao platformEmpDao;

	@Autowired
	private TraderDao traderDao;


	@Autowired
	private SiteInformationDao siteInformationDao;

	@Autowired
	TaskService taskService;
	@Autowired
	private ProcessFlowableService flowableService;

	@Autowired
	private TraderService traderService;



	public TraderApply get(String id) {
		return traderApplyDao.get(id);
	}

	public LayuiPage<Record> findtraderApplyList(LayuiPage<Record> page, Map<String, String> map){
		User user = UserUtils.getUser();
		if (User.USER_TYPE_WXG.equals(user.getUserType())) {
			//平台人员
			EmployeRoleUtils.getUserDataAuthority(user.getId(),map);
		} if (User.USER_TYPE_WXG.equals(user.getUserType())) {
			//平台人员
			EmployeRoleUtils.getUserDataAuthority(user.getId(),map);
		}
		List<Record> list = traderApplyDao.findApplyList(page,map,user);
		page.setData(list);
		page.setCount(traderApplyDao.findApplyCount(map,user));
		return page;
	}
	
	@Transactional(readOnly = false,rollbackFor = Exception.class)
	public void add(TraderApplyVo vo) {

		User user = UserUtils.getUser();
		TraderApply apply;
		CrmDepartment dep = departmentSettingDao.get(user.getDepartmentId());
		if(dep ==null && !user.getLoginName().equals("system")){
			throw new BusinessException("当前用户无操作权限");
		}
		Date date = new Date();

		if(StringUtil.isBlank(vo.getTraderId())){
			String loginName = vo.getLoginName().trim();
			vo.setLoginName(loginName);
			if (siteInformationDao.getExistsLoginName(vo.getLoginName())) {
				throw new BusinessException("登录账号已存在");
			}

		}
		if (!(traderDao.checkNameExists(vo.getName(), vo.getTraderId()) && traderApplyDao.checkNameExists(vo.getName(), vo.getId(), vo.getTraderId()))) {
			throw new BusinessException("代理商名称已存在");
		}


		//获取当前业务人员信息
		CrmPlatformEmployee emp = platformEmpDao.findByUserId(user.getId());
		String userName = emp.getName();
		if(StringUtils.isNotBlank(vo.getId())){
			apply = traderApplyDao.get(vo.getId());
			apply.setUpdateBy(user.getId());
			apply.setUpdater(emp.getName());
			apply.setUpdateTime(date);
			//删除明细
			Db.update("DELETE  FROM `crm_trader_apply_agent` WHERE `trader_apply_id` =?",vo.getId());
		}else{
			apply = new TraderApply();
			apply.setDepartmentId(user.getDepartmentId());
			if(!user.getLoginName().equals("system")){
				apply.setDepartmentName(dep.getName());
				apply.setCreator(emp.getName());
			}
			apply.setCreateBy(user.getId());
			apply.setCreateTime(date);
		}
		setAssignment(vo,apply);

		apply.setStatus(vo.getStatus());
		if(StringUtil.isBlank(vo.getId())){
			apply.setId(IdGen.uuid());
			//提交流程
			Record rd = FormUtils.getdefLatest(FormUtils.AGENT_ADMISSION_APPLICATION);
			if(rd == null){
				throw  new RuntimeException("流程未定义，不可发布申请");
			}
			//启动流程
			String processName="代理商准入申请-"+user.getUserName()+'-'+ DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss")+"("+apply.getName()+")";
			String processInstanceId=flowableService.startProcessFlowable2(user,apply.getId(),rd, FormUtils.AGENT_ADMISSION_APPLICATION,date,userName,vo.getRemarks(),processName,apply.getProvince(),apply.getCity());
			apply.setProcessInstanceId(processInstanceId);
			apply.setProcessDefId(rd.getStr("id"));
			String taskName=FormUtils.getOneStepTaskName(rd.getStr("id"));
			apply.setTaskName(taskName);
			apply.setOperateUserIds(user.getId()+","+rd.getStr("oneAuditUseId"));
			traderApplyDao.save(apply);
		}else if(StringUtil.isNotBlank(apply.getProcessInstanceId())){
			traderApplyDao.save(apply);
			Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
			flowableService.approveTask2(task,"编辑后提交",apply.getId(),user, FormUtils.AGENT_ADMISSION_APPLICATION);
		}
		List<TraderApplyAgent> agentList = vo.getAgentList();
		for(TraderApplyAgent agent:agentList){
			agent.setTraderApplyId(apply.getId());
		}
		applyAgentDao.save(agentList);


	}

	@Transactional(readOnly = false,rollbackFor = Exception.class)
	public void save(TraderApplyVo vo, String from) {
		if ("2".equals(from) && cheackTraderChange(vo)) {
			logger.info("代理商修改操作——无修改内容或仅修改备注");
			return;
		}
		User user = UserUtils.getUser();
		TraderApply apply;
		CrmDepartment dep = departmentSettingDao.get(user.getDepartmentId());
		if(dep ==null && !user.getLoginName().equals("system")){
			throw new BusinessException("当前用户无操作权限");
		}
		Date date = new Date();

		if(StringUtil.isBlank(vo.getTraderId())){
			String loginName = vo.getLoginName().trim();
			vo.setLoginName(loginName);
			if (siteInformationDao.getExistsLoginName(vo.getLoginName())) {
				throw new BusinessException("登录账号已存在");
			}

		}
		if (!(traderDao.checkNameExists(vo.getName(), vo.getTraderId()) && traderApplyDao.checkNameExists(vo.getName(), vo.getId(), vo.getTraderId()))) {
			throw new BusinessException("代理商名称已存在");
		}

		//获取当前业务人员信息
		CrmPlatformEmployee emp = platformEmpDao.findByUserId(user.getId());
		if(StringUtils.isNotBlank(vo.getId())){
			apply = traderApplyDao.get(vo.getId());
			apply.setUpdateBy(user.getId());
			apply.setUpdater(emp.getName());
			apply.setUpdateTime(date);
			//删除明细
		//	Db.update("DELETE  FROM `crm_trader_apply_agent` WHERE `trader_apply_id` =?",vo.getId());
		}else{
			apply = new TraderApply();
			apply.setDepartmentId(user.getDepartmentId());
			if(!user.getLoginName().equals("system")){
				apply.setDepartmentName(dep.getName());
				apply.setCreator(emp.getName());
			}
			apply.setCreateBy(user.getId());
			apply.setCreateTime(date);
		}
		setAssignment(vo,apply);

		apply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
		apply.setTaskName("已完成");
		String qqCompanyCode = null; // 为null 表示需要生成企企客户信息，为''表示不处理，为有效值表示需要同步企企修改客户名称
		CrmTrader oldData;

		// 新增代理商时，需要同步到企企 生成客户信息
		// 修改代理商信息 需要获取企企的客户编码 用户同步最新的代理商名称至企企

			oldData = traderDao.get(apply.getTraderId());
			if (oldData != null) {
				if(!oldData.getName().equals(apply.getName())){
					Db.update(" update crm_customer_entry set create_trader_name = ? where create_trader_id = ? ",apply.getName(),apply.getTraderId());
					Db.update(" update crm_customer_entry set trader_name = ? where distributor_id = ? ",apply.getName(),apply.getTraderId());
					qqCompanyCode = oldData.getQqCompanyCode();
				}
			}

		traderService.addTraderByApply(apply);
		if(StringUtils.isNotBlank(qqCompanyCode)){
			OpenapiTemplate.updateTradeToQQ(apply.getName(),qqCompanyCode);
		}

	}
	public List<Record> findAgentList(String applyId){
		return applyAgentDao.findAgentList(applyId);
	}

	public List<Record> findAgentListByTraderId(String traderId){
		return agentDao.findAgentListByTraderId(traderId);
	}


	/**
	 * 审核通过
	*/
	public void examineTraderApply(String id,String taskId,String content){
		logger.info(">>>>>>>>>>>>>examineDistributionGoodsApprove  id:{},task:{}",id,taskId);
		User user = UserUtils.getUser();
		TraderApply apply=traderApplyDao.get(id);
		Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
		flowableService.approveTask2(task,content,apply.getId(),user, FormUtils.AGENT_ADMISSION_APPLICATION);
	}

	/**
	* 驳回
	*/
	public void rejectTask(String id,String taskId,String content){
		logger.info(">>>>>>>>>>>>>rejectTask  id:{},task:{}",id,taskId);
		User user = UserUtils.getUser();
		TraderApply apply=traderApplyDao.get(id);
		apply.setContent(content);
		traderApplyDao.save(apply);
		Task task=taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();;
		flowableService.rejectTask2(task,content,id,user,FormUtils.AGENT_ADMISSION_APPLICATION,apply.getCreateBy());
	}


	public void setAssignment(TraderApplyVo vo,TraderApply apply){
		apply.setName(vo.getName());
		apply.setContacts(vo.getContacts());
		apply.setProvince(vo.getProvince());
		apply.setCity(vo.getCity());
		apply.setArea(vo.getArea());
		apply.setAddress(vo.getAddress());
		apply.setMobile(vo.getMobile());
		apply.setActualContacts(vo.getActualContacts());
		apply.setTelephone(vo.getTelephone());
		apply.setBond(vo.getBond());
		apply.setActualIdCode(vo.getActualIdCode());
		apply.setBankName(vo.getBankName());
		apply.setBankCode(vo.getBankCode());
		apply.setTaxNumber(vo.getTaxNumber());
		apply.setLicenseImg(vo.getLicenseImg());
//		apply.setIdFrontImg(vo.getIdFrontImg());
//		apply.setIdOppositeImg(vo.getIdOppositeImg());
		apply.setRemarks(vo.getRemarks());
		apply.setTakeDeliveryProvince(vo.getTakeDeliveryProvince());
		apply.setTakeDeliveryCity(vo.getTakeDeliveryCity());
		apply.setTakeDeliveryArea(vo.getTakeDeliveryArea());
		apply.setTakeDeliveryAddress(vo.getTakeDeliveryAddress());
		apply.setLoginName(vo.getLoginName());
		apply.setPassword(vo.getPassword());
		apply.setTraderId(vo.getTraderId());
		apply.setQqjyglwtsImg(vo.getQqjyglwtsImg());
		apply.setBzjdkpzImg(vo.getBzjdkpzImg());
		apply.setSfzzmfyjImg(vo.getSfzzmfyjImg());
		apply.setSfzfmfyjImg(vo.getSfzfmfyjImg());
		apply.setDlszrsqbImg(vo.getDlszrsqbImg());
		apply.setQqProjectCode(vo.getQqProjectCode());
		apply.setQqProjectName(vo.getQqProjectName());
		apply.setWarehouseTake(vo.getWarehouseTake());
		apply.setWarehouseTakeMobile(vo.getWarehouseTakeMobile());
		if(vo.getBondLimit()!=null){
			apply.setBondLimit(vo.getBondLimit());
		}
	}
	
	@Transactional(readOnly = false,rollbackFor = Exception.class)
	public void delete(String id) {
		TraderApply apply = traderApplyDao.get(id);
		if(!"0".equals(apply.getStatus()) && !"2".equals(apply.getStatus())){
			throw new BusinessException("当前数据不满足删除条件");
		}
		User user = UserUtils.getUser();
		String userName= CrmUtils.getUserXM(user);
		apply.setStatus(BondApplyConstant.APPLYSTATUS_FOUR);
		traderApplyDao.save(apply);
		//删除流程
		flowableService.deleteApplication(apply.getId(),apply.getProcessInstanceId(),userName,apply.getStatus(), FormUtils.AGENT_ADMISSION_APPLICATION);
	}

	//代理商修改操作校验是否有改动
	public boolean cheackTraderChange(TraderApplyVo vo){
		//判断是否为代理商修改
		if(StringUtil.isBlank(vo.getTraderId())){
			return false;
		}
		String traderId = vo.getTraderId();
		CrmTrader trader = traderDao.get(traderId);
		boolean changeFlag = true;
		//代理商名称
		if (!Objects.equals(trader.getName(),vo.getName())) {
			changeFlag = false;
		}
		//业务联系人
		if (!Objects.equals(trader.getContacts(),vo.getContacts())) {
			changeFlag = false;
		}
		//业务联系人电话
		if (!Objects.equals(trader.getMobile(),vo.getMobile())) {
			changeFlag = false;
		}
		//企业实控人
		if (!Objects.equals(trader.getActualContacts(),vo.getActualContacts())) {
			changeFlag = false;
		}
		//企业实控人联系电话
		if (!Objects.equals(trader.getTelephone(),vo.getTelephone())) {
			changeFlag = false;
		}
		//保证金
		if (!Objects.equals(trader.getBond(),vo.getBond())) {
			changeFlag = false;
		}
		//实控人身份证号
		if (!Objects.equals(trader.getActualIdCode(),vo.getActualIdCode())) {
			changeFlag = false;
		}
		//开户银行
		if (!Objects.equals(trader.getBankName(),vo.getBankName())) {
			changeFlag = false;
		}
		//银行账号
		if (!Objects.equals(trader.getBankCode(),vo.getBankCode())) {
			changeFlag = false;
		}
		//企业信用统一编码
		if (!Objects.equals(trader.getTaxNumber(),vo.getTaxNumber())) {
			changeFlag = false;
		}
		//营业执照
		if (!Objects.equals(trader.getLicenseImg(),vo.getLicenseImg())) {
			changeFlag = false;
		}
		//实控人身份证正面
		if (!Objects.equals(trader.getIdFrontImg(),vo.getIdFrontImg())) {
			changeFlag = false;
		}
		//实控人身份证反面
		if (!Objects.equals(trader.getIdOppositeImg(),vo.getIdOppositeImg())) {
			changeFlag = false;
		}
		//代理商地址
		if (!Objects.equals(trader.getProvince(),vo.getProvince())) {
			changeFlag = false;
		}
		if (!Objects.equals(trader.getCity(),vo.getCity())) {
			changeFlag = false;
		}
		if (!Objects.equals(trader.getArea(),vo.getArea())) {
			changeFlag = false;
		}
		if (!Objects.equals(trader.getAddress(),vo.getAddress())) {
			changeFlag = false;
		}
		//收货地址
		if (!Objects.equals(trader.getTakeDeliveryProvince(),vo.getTakeDeliveryProvince())) {
			changeFlag = false;
		}
		if (!Objects.equals(trader.getTakeDeliveryCity(),vo.getTakeDeliveryCity())) {
			changeFlag = false;
		}
		if (!Objects.equals(trader.getTakeDeliveryArea(),vo.getTakeDeliveryArea())) {
			changeFlag = false;
		}
		if (!Objects.equals(trader.getTakeDeliveryAddress(),vo.getTakeDeliveryAddress())) {
			changeFlag = false;
		}
		if (!Objects.equals(trader.getQqProjectCode(),vo.getQqProjectCode())) {
			changeFlag = false;
		}

		List<TraderApplyAgent> agentList = vo.getAgentList();
		Long cnt = agentDao.findCount(traderId);
//		if (agentList.size() != cnt) {
//			changeFlag = false;
//		}
		//备注
		if (!Objects.equals(trader.getRemarks(),vo.getRemarks())) {
			//仅修改备注不用生成申请记录
			if (changeFlag) {
				trader.setRemarks(vo.getRemarks());
				traderDao.save(trader);
			}
		}
		return changeFlag;
	}

}
