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


import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.account.dao.TraderAccountDao;
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.vo.DistributionGoodsVo;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
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.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


import com.sifang.modules.flowpath.entity.BondApply;
import com.sifang.modules.flowpath.dao.BondApplyDao;

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

/**
 *  保证金调整申请
 * * @version
 */
@Component
@Transactional(readOnly = true)
public class BondApplyService extends BaseService {

	@Autowired
	private BondApplyDao bondApplyDao;

	@Autowired
	private ProcessFlowableService flowableService;

	@Autowired
	TaskService taskService;

	@Autowired
	private TraderAccountDao accountDao;


	public void applyList(LayuiPage<Record> page, Map<String, String> map){
		User user = UserUtils.getUser();
		String traderId = "";
		if (User.USER_TYPE_KJ.equals(user.getUserType()) || User.USER_TYPE_ADVISOR.equals(user.getUserType())) {  //代理商
			traderId = CrmUtils.getUserRelId(user);
		} else if (User.USER_TYPE_WXG.equals(user.getUserType())) {
			//平台人员
			EmployeRoleUtils.getUserDataAuthority(user.getId(),map);
		}
		map.put("traderIds",traderId);
		bondApplyDao.applyList(page,map,user);
	}
	/*查询保证金账户-账户明细中明细*/
	public List<Record> getDetailByTraderId(Map<String, String> map){
		User user = UserUtils.getUser();
		String traderId = "";
		if (User.USER_TYPE_KJ.equals(user.getUserType()) || User.USER_TYPE_ADVISOR.equals(user.getUserType())) {  //代理商
			traderId = CrmUtils.getUserRelId(user);
		} else if (User.USER_TYPE_WXG.equals(user.getUserType())) {
			//平台人员
			EmployeRoleUtils.getUserDataAuthority(user.getId(),map);
		}
		map.put("traderIds",traderId);
		return bondApplyDao.accountDetailList(map,user);
	}
	public Record getDetailById(String id){
		return bondApplyDao.getDetailById(id);
	}

	@Transactional(rollbackFor = Exception.class)
	public void saveBondAdjustApply(DistributionGoodsVo vo){
		logger.info(">>>>>>>>>>>>>>>saveBondAdjustApply  vo:{}",vo);
		User user = UserUtils.getUser();
		String userName= user.getUserName();
		Date date=new Date();
		BondApply apply;

		if(com.sifang.modules.sys.common.utils.StringUtil.isBlank(vo.getId())){
			apply=new BondApply();
			apply.setApplyNumber(PlantformUtils.getOrderNumber());
			apply.setDepartmentId(user.getDepartmentId());
			apply.setDepartmentName(user.getDepartmentName());
		}else{
			apply=bondApplyDao.getByApplyId(vo.getId());
			if(com.sifang.modules.sunshine.SystemSetting.utils.StringUtil.equalsAny(apply.getStatus(), BondApplyConstant.APPLYSTATUS_ONE,BondApplyConstant.APPLYSTATUS_TWO,BondApplyConstant.APPLYSTATUS_THREE)){
				throw new RuntimeException("该申请状态不允许修改!");
			}
		}
		apply.setTraderId(vo.getTraderId());
		apply.setAdjustType(vo.getAdjustType());
		apply.setAmount(vo.getAmount());
		apply.setVoucher(vo.getVoucher());
		apply.setRemarks(vo.getRemarks());
		apply.setCreateBy(user.getId());
		apply.setCreateName(userName);
		apply.setCreateTime(date);

		if(StringUtil.isBlank(vo.getId())){

			/*Record phe=accountDao.getXsByTraderVsAccount(apply.getTraderId(),"1"); //获取标准授信额的 系数
			if(phe==null){
				throw new RuntimeException("请先设置标准授信额系数");
			}

			Record phe2=accountDao.getXsByTraderVsAccount(apply.getTraderId(),"2");  //可授信额上限 系数
			if(phe2==null){
				throw new RuntimeException("请先设置可授信额上限系数");
			}*/

			apply.setId(IdGen.uuid());
			Record rd = FormUtils.getdefLatest(FormUtils.MARGIN_ADJUSTMENT_APPLICATION);
			if(rd == null){
				throw  new RuntimeException("流程未定义，不可发布申请");
			}
			String traderName=CrmUtils.getTraderNameById(apply.getTraderId());
			String processName="保证金调整申请-"+userName+'-'+ DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss")+"("+traderName+")";
			String processInstanceId=flowableService.startProcessFlowable(user,apply.getId(),rd,FormUtils.MARGIN_ADJUSTMENT_APPLICATION,date,userName,vo.getRemarks(),processName,apply.getTraderId());
			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"));
			logger.info(">>>>>>>>>>>>>>saveBondAdjustApply>>>>>>>>>taskName:{}",taskName);
		}else if(StringUtil.isNotBlank(apply.getProcessInstanceId())){
			Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
			flowableService.approveTask2(task,"编辑后提交",apply.getId(),user, FormUtils.MARGIN_ADJUSTMENT_APPLICATION);
		}
		apply.setStatus(BondApplyConstant.APPLYSTATUS_ONE);
		bondApplyDao.save(apply);
	}

	//删除申请
	@Transactional(rollbackFor = Exception.class)
	public void deleteBondAdjustApply(String id){
		logger.info(">>>>>>>>>>>>>deleteBondAdjustApply  id:{}",id);
		User user = UserUtils.getUser();
		String userName= user.getUserName();
		//修改申请状态
		BondApply apply=bondApplyDao.getByApplyId(id);
		if(StringUtil.equalsAny(apply.getStatus(), BondApplyConstant.APPLYSTATUS_ONE,BondApplyConstant.APPLYSTATUS_TWO,BondApplyConstant.APPLYSTATUS_THREE)){
			throw new RuntimeException("申请状态不允许删除!");
		}

		apply.setStatus(BondApplyConstant.APPLYSTATUS_FOUR);
		bondApplyDao.save(apply);
		//删除流程
		flowableService.deleteApplication(apply.getId(),apply.getProcessInstanceId(),userName,apply.getStatus(),FormUtils.MARGIN_ADJUSTMENT_APPLICATION);
	}

	//审核通过
	@Transactional(rollbackFor = Exception.class)
	public void examineBondAdjustApplyApprove(String id,String taskId,String content){
		logger.info(">>>>>>>>>>>>>examineBondAdjustApplyApprove  id:{},task:{}",id,taskId);
		User user = UserUtils.getUser();
		BondApply apply=bondApplyDao.getByApplyId(id);
		Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
		flowableService.approveTask2(task,content,apply.getId(),user, FormUtils.MARGIN_ADJUSTMENT_APPLICATION);
	}

	//驳回
	@Transactional(rollbackFor = Exception.class)
	public void rejectBondAdjustApplyTask(String id,String taskId,String content){
		logger.info(">>>>>>>>>>>>>rejectBondAdjustApplyTask  id:{},task:{}",id,taskId);
		User user = UserUtils.getUser();
		BondApply apply=bondApplyDao.getByApplyId(id);
		/*apply.setStatus(BondApplyConstant.APPLYSTATUS_TWO);*/
		apply.setContent(content);
		apply.setExamineOpinion(content);
		bondApplyDao.save(apply);
		Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
		flowableService.rejectTask2(task,content,id,user,FormUtils.MARGIN_ADJUSTMENT_APPLICATION,apply.getCreateBy());
	}

	//代理商准入的时候，有保证金，加入一条保证金明细
	public void saveBondApply(BigDecimal bondAmount,String traderId){
		BondApply apply=new BondApply();
		apply.setId(IdGen.uuid());
		apply.setApplyNumber(PlantformUtils.getOrderNumber());
		apply.setTraderId(traderId);
		apply.setAdjustType("1");
		apply.setAmount(bondAmount);
		apply.setRemarks("代理商准入，初始保证金金额");
		apply.setCreateTime(new Date());
		apply.setStatus("3");
		bondApplyDao.save(apply);
	}

}
