package com.goafanti.order.service.impl;

import com.goafanti.common.bo.Error;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.enums.DeleteStatus;
import com.goafanti.common.enums.UserLockReleaseStatus;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.*;
import com.goafanti.common.utils.AsyncUtils;
import com.goafanti.common.utils.BeanUtilsExt;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.customer.bo.BusinessListBo;
import com.goafanti.customer.bo.FollowBusinessBo;
import com.goafanti.customer.bo.LockingReleaseBo;
import com.goafanti.order.bo.BillListBo;
import com.goafanti.order.bo.OperatorActive;
import com.goafanti.order.bo.OrderChangeBo;
import com.goafanti.order.bo.OrderListBo;
import com.goafanti.order.enums.*;
import com.goafanti.order.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends BaseMybatisDao<TOrderMapper> implements OrderService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private TOrderNewMapper tOrderNewMapper;

	@Autowired
	private TOrderBillMapper tOrderBillMapper;
	@Autowired
	private DepartmentMapper departmentMapper;
	@Autowired
	private ContractMapper contractMapper;
	@Autowired
	private ContractTaskMapper contractTaskMapper;
	@Autowired
	private TOrderChangeMapper tOrderChangeMapper;
	@Autowired
	private TmpTableMapper tmpTableMapper;
	@Autowired
	private AdminMapper adminMapper;
	@Autowired
	private AsyncUtils	asyncUtils;
	@Autowired
	private ContractTaskLogMapper contractTaskLogMapper;
	@Autowired
	private BusinessProjectMapper businessProjectMapper;
	@Autowired
	private UserLockReleaseMapper userLockReleaseMapper;
	@Autowired
	UserRoleMapper	userRoleMapper;
	@Autowired
	private UserBusinessMapper	userBusinessMapper;
	@Autowired
	private UserFollowMapper	userFollowMapper;
	@Autowired
	private UserFollowBusinessMapper	userFollowBusinessMapper;

	@Value(value = "${mobileRemindCodeTemplate}")
	private String					mobileRemindCodeTemplate	= null;

	@Value(value = "${accessKey}")
	private String					accessKey			= null;

	@Value(value = "${accessSecret}")
	private String					accessSecret		= null;

	private final BigDecimal DEFAULT_FIRST_PAYMENT = new BigDecimal(0);//默认首付价格
	private final BigDecimal DEFAULT_COMMODITY_PRICE = new BigDecimal(0);//默认单价
	private final String DEFAULT_PLATFORM_ID = "0"; //平台默认id
	private final String DEFAULT_ADMIN_ID = "1"; //默认管理员
	private final double DEFAULT_BROKERAGE_PROPORTION = 0; //佣金比例
	private final double DEFAULT_COMMODITY_DISCOUNT = 1; //折扣比例
	private final String DEFAULT_COMMODITY_MODE = "NO_MODE"; //暂无规格
	private final String DEFUALT_SET_UP_COMMENT = "系统自动生产立项信息，请自行修改或补充";





	/**
	 * 订单状态流转
	 * @param orderAction
	 * @param changeAmount
	 * @param tOrder
	 * @param confrim
	 */
	public void setOrderState(OrderAction orderAction,BigDecimal changeAmount,TOrder tOrder,boolean confrim){
		BigDecimal initial = new BigDecimal(0);
		checkOrder(tOrder);
		if(orderAction == OrderAction.ADD_INTENTION){ //添加意向订单
			tOrder.setOrderStatus(OrderState.WAIT_FOR_CONFIRM.getCode());
			tOrder.setLiquidationStatus(LiquidationState.WAIT_PAY_FIRST_BALANCE.getCode());
//			tOrder.setOrderStage(OrderStage.INTENTION.getCode());
			/** 意向阶段 **/
			/** 跟单阶段 **/
			/** 合同阶段 **/
			/** 项目阶段 **/
			tOrder.setProjectStage(ProjectStage.NOT_SATISFY_CONDITION.getCode());
			tOrder.setLiquidationStatus(LiquidationState.WAIT_PAY_FIRST_BALANCE.getCode());
			tOrder.setActuallyFirstPayment(initial);
			tOrder.setActuallyBrokerageAmount(initial);
			tOrder.setActuallyTotalAmount(initial);
			tOrder.setActuallyWithdrawAmount(initial);
		}else if(orderAction == OrderAction.CONFIRM_INTENTION){ //确认意向订单 (用户确认)
			if(tOrder.getOrderStatus() != OrderState.WAIT_FOR_CONFIRM.getCode()){
				throw new BusinessException(new Error(ErrorConstants.NOT_ACCORD_WITH_NEXT,"确认意向订单"));
			}
			if (confrim) {
				tOrder.setOrderStatus(OrderState.WAIT_FOR_SIGN.getCode()); // 卖家同意
//				tOrder.setOrderStage(OrderStage.FOLLOWING.getCode());
			} else {
				tOrder.setOrderStatus(OrderState.SELLER_REFUSE_BEFORE_SIGNL.getCode()); // 买家拒绝
			}
		}else if(orderAction == OrderAction.CONFIRM_PAY_FOR_FIRST){ // 支付首付(审核流水)
			if(tOrder.getLiquidationStatus() != LiquidationState.WAIT_PAY_FIRST_BALANCE.getCode()){
				throw new BusinessException(new Error(ErrorConstants.NOT_ACCORD_WITH_NEXT,""));
			}
			int boundary = tOrder.getActuallyFirstPayment().add(changeAmount).compareTo(tOrder.getSignFirstPayment());
			int boundary2 = tOrder.getActuallyTotalAmount().add(changeAmount).compareTo(tOrder.getSignTotalAmount());
			if(boundary2 == 1){
				throw new BusinessException(new Error(ErrorConstants.PAY_BEYOND_SIGN,"支付首付款"));
			}else if(boundary2 == 0){ //全付清
				tOrder.setActuallyTotalAmount(tOrder.getSignTotalAmount());
				tOrder.setActuallyFirstPayment(tOrder.getSignFirstPayment());
				tOrder.setLiquidationStatus(LiquidationState.ALREADY_PAY.getCode());
				if(tOrder.getProjectStage() == ProjectStage.NOT_SATISFY_CONDITION.getCode())
					tOrder.setProjectStage(ProjectStage.WAIT_SET_UP.getCode());
			}else if(boundary == 1){ //超过首付未达尾款
				tOrder.setActuallyTotalAmount(tOrder.getActuallyTotalAmount().add(changeAmount));
				tOrder.setActuallyFirstPayment(tOrder.getSignFirstPayment());
				tOrder.setLiquidationStatus(LiquidationState.WAIT_PAY_LAST_BALANCE.getCode());
				if(tOrder.getProjectStage() == ProjectStage.NOT_SATISFY_CONDITION.getCode())
					tOrder.setProjectStage(ProjectStage.WAIT_SET_UP.getCode());
			}else if(boundary == -1){ //首付待付清
				tOrder.setActuallyTotalAmount(tOrder.getActuallyTotalAmount().add(changeAmount));
				tOrder.setActuallyFirstPayment(tOrder.getActuallyFirstPayment().add(changeAmount));
			}else if(boundary == 0){ //首付已结清
				tOrder.setActuallyTotalAmount(tOrder.getActuallyTotalAmount().add(changeAmount));
				tOrder.setActuallyFirstPayment(tOrder.getSignFirstPayment());
				tOrder.setLiquidationStatus(LiquidationState.WAIT_PAY_LAST_BALANCE.getCode());
				if(tOrder.getProjectStage() == ProjectStage.NOT_SATISFY_CONDITION.getCode())
					tOrder.setProjectStage(ProjectStage.WAIT_SET_UP.getCode());
			}
		}else if(orderAction == OrderAction.CONFIRM_PAY_FOR_LAST){ //支付尾款 (审核流水)
			if(tOrder.getLiquidationStatus() != LiquidationState.WAIT_PAY_LAST_BALANCE.getCode()){
				throw new BusinessException(new Error(ErrorConstants.NOT_ACCORD_WITH_NEXT,"支付尾款"));
			}
			int boundary = tOrder.getActuallyTotalAmount().add(changeAmount).compareTo(tOrder.getSignTotalAmount());
			if(boundary == 1){
				throw new BusinessException(new Error(ErrorConstants.PAY_BEYOND_SIGN,"支付尾款"));
			}else if(boundary == -1){
				tOrder.setActuallyTotalAmount(tOrder.getActuallyTotalAmount().add(changeAmount));
			}else if(boundary == 0){
				tOrder.setActuallyTotalAmount(tOrder.getSignTotalAmount());
				tOrder.setLiquidationStatus(LiquidationState.ALREADY_PAY.getCode());
			}
		}else if(orderAction == OrderAction.APPLY_FOR_WITHDRAW){ //提现申请
			if(tOrder.getOrderStatus() != OrderState.ALREADY_SIGN.getCode()
					|| tOrder.getLiquidationStatus() != LiquidationState.ALREADY_PAY.getCode()
					|| tOrder.getActuallyTotalAmount().doubleValue() <= 0){
				throw new BusinessException(new Error(ErrorConstants.NOT_ACCORD_WITH_NEXT,"等待提现"));
			}
			tOrder.setLiquidationStatus(LiquidationState.WAIT_FOR_WITHDRAW.getCode());
		}else if(orderAction == OrderAction.CONFIRM_WITHDRAW){ //提现确认 (审核员先审核流水)
			if(tOrder.getOrderStatus() != OrderState.ALREADY_SIGN.getCode()
					|| tOrder.getLiquidationStatus() != LiquidationState.WAIT_FOR_WITHDRAW.getCode()
					|| tOrder.getActuallyTotalAmount().doubleValue() <= 0){
				throw new BusinessException(new Error(ErrorConstants.NOT_ACCORD_WITH_NEXT,"确认提现"));
			}
			tOrder.setLiquidationStatus(LiquidationState.ALREADY_WITHDRAW.getCode());
			tOrder.setActuallyWithdrawAmount(tOrder.getActuallyWithdrawAmount().add(changeAmount));
		}else if(orderAction == OrderAction.APPLY_FOR_CANCEL){ //取消订单
			boolean flag = true;
			if(tOrder.getOrderStatus() != OrderState.WAIT_FOR_CONFIRM.getCode()
					&& tOrder.getOrderStatus() != OrderState.WAIT_FOR_SIGN.getCode()){
				flag = false;
			}
			if(tOrder.getLiquidationStatus() != LiquidationState.WAIT_PAY_FIRST_BALANCE.getCode()
					&& tOrder.getLiquidationStatus() != LiquidationState.WAIT_PAY_LAST_BALANCE.getCode()
					&& tOrder.getLiquidationStatus() != LiquidationState.ALREADY_PAY.getCode()){
				flag = false;
			}
			if(!flag) throw new BusinessException(new Error(ErrorConstants.NOT_ACCORD_WITH_NEXT,"取消订单"));
			if(TokenManager.getToken() instanceof Admin){
				if(!tOrder.getSellerId().equals(DEFAULT_PLATFORM_ID))
					throw new BusinessException(new Error(ErrorConstants.NOT_ACCORD_WITH_NEXT,"取消订单"));
				if(tOrder.getOrderStatus() == OrderState.WAIT_FOR_CONFIRM.getCode())
					tOrder.setOrderStatus(OrderState.SELLER_REFUSE_BEFORE_SIGNL.getCode());
				if( tOrder.getOrderStatus() == OrderState.WAIT_FOR_SIGN.getCode())
					tOrder.setOrderStatus(OrderState.SELLER_CANCEL_AFTER_SIGN.getCode());
			}else if(TokenManager.getToken() instanceof User){
				if(TokenManager.getUserId().equals(tOrder.getSellerId())){
					if(tOrder.getOrderStatus() == OrderState.WAIT_FOR_CONFIRM.getCode())
						tOrder.setOrderStatus(OrderState.SELLER_REFUSE_BEFORE_SIGNL.getCode());
					if( tOrder.getOrderStatus() == OrderState.ALREADY_SIGN.getCode())
						tOrder.setOrderStatus(OrderState.SELLER_CANCEL_AFTER_SIGN.getCode());
				}else if(TokenManager.getUserId().equals(tOrder.getBuyerId())){
					if(tOrder.getOrderStatus() == OrderState.WAIT_FOR_CONFIRM.getCode())
						tOrder.setOrderStatus(OrderState.BUYER_CANCEL_BEFORE_SIGN.getCode());
					if( tOrder.getOrderStatus() == OrderState.ALREADY_SIGN.getCode())
						tOrder.setOrderStatus(OrderState.BUYER_CANCEL_AFTER_SIGN.getCode());
				}
			}
		}else if(orderAction == OrderAction.APPLY_FOR_REFUND){ //退款申请
			boolean	flag = true;
			if(tOrder.getOrderStatus() != OrderState.BUYER_CANCEL_BEFORE_SIGN.getCode()
					&& tOrder.getOrderStatus() != OrderState.BUYER_CANCEL_AFTER_SIGN.getCode()
					&& tOrder.getOrderStatus() != OrderState.SELLER_REFUSE_BEFORE_SIGNL.getCode()
					&& tOrder.getOrderStatus() != OrderState.SELLER_CANCEL_AFTER_SIGN.getCode()){
				flag = false;
			}
			if(tOrder.getChangeStatus() == ChangeState.CHANGING.getCode()) flag = true; // Add 2018/4/9 if normal order in changing can refund
			if(tOrder.getLiquidationStatus() == LiquidationState.WAIT_FOR_REFUND_CONFIRM.getCode()
					|| tOrder.getLiquidationStatus() == LiquidationState.REFUSE_REFUND.getCode()
					|| tOrder.getLiquidationStatus() == LiquidationState.AGREE_REFUND.getCode()
					|| tOrder.getLiquidationStatus() == LiquidationState.COMPLETE_REFUND.getCode()){
				flag = false;
			}
			if(tOrder.getActuallyTotalAmount().doubleValue() <= 0)
				flag = false;
			if(!flag) throw new BusinessException(new Error(ErrorConstants.NOT_ACCORD_WITH_NEXT,"申请退款"));
			tOrder.setLiquidationStatus(LiquidationState.WAIT_FOR_REFUND_CONFIRM.getCode());
		}else if(orderAction == OrderAction.CONFIRM_REFUND){ //退款确认
			boolean flag = true;
			if(tOrder.getOrderStatus() != OrderState.BUYER_CANCEL_BEFORE_SIGN.getCode()
					&& tOrder.getOrderStatus() != OrderState.BUYER_CANCEL_AFTER_SIGN.getCode()
					&& tOrder.getOrderStatus() != OrderState.SELLER_REFUSE_BEFORE_SIGNL.getCode()
					&& tOrder.getOrderStatus() != OrderState.SELLER_CANCEL_AFTER_SIGN.getCode()){
				flag = false;
			}
			if(tOrder.getChangeStatus() == ChangeState.CHANGING.getCode()) flag = true; // Add 2018/4/9 if normal order in changing can refund
			if(tOrder.getLiquidationStatus() != LiquidationState.WAIT_FOR_REFUND_CONFIRM.getCode())
				flag = false;
			if(tOrder.getActuallyTotalAmount().doubleValue() <= 0)
				flag = false;
			if(confrim) {
				if(!flag) throw new BusinessException(new Error(ErrorConstants.NOT_ACCORD_WITH_NEXT,"同意退款"));
				tOrder.setLiquidationStatus(LiquidationState.AGREE_REFUND.getCode());
			}else{
				if(!flag) throw new BusinessException(new Error(ErrorConstants.NOT_ACCORD_WITH_NEXT,"拒绝退款"));
				tOrder.setLiquidationStatus(LiquidationState.REFUSE_REFUND.getCode());
			}
		}else if(orderAction == OrderAction.COMPLETE_REFUND){ //完成退款
			boolean flag = true;
			if(tOrder.getOrderStatus() != OrderState.BUYER_CANCEL_BEFORE_SIGN.getCode()
					&& tOrder.getOrderStatus() != OrderState.BUYER_CANCEL_AFTER_SIGN.getCode()
					&& tOrder.getOrderStatus() != OrderState.SELLER_REFUSE_BEFORE_SIGNL.getCode()
					&& tOrder.getOrderStatus() != OrderState.SELLER_CANCEL_AFTER_SIGN.getCode()){
				flag = false;
			}
			if(tOrder.getChangeStatus() == ChangeState.CHANGING.getCode()) flag = true; // Add 2018/4/9 if normal order in changing can refund
			if(tOrder.getLiquidationStatus() != LiquidationState.AGREE_REFUND.getCode())
				flag = false;
			if(tOrder.getActuallyTotalAmount().doubleValue() <= 0)
				flag = false;
			if(!flag) throw new BusinessException(new Error(ErrorConstants.NOT_ACCORD_WITH_NEXT,"申请退款"));
			tOrder.setActuallyTotalAmount(tOrder.getActuallyTotalAmount().add(changeAmount));
			int boundary = tOrder.getActuallyTotalAmount().compareTo(tOrder.getSignTotalAmount());
			if(boundary == 0) {
				tOrder.setLiquidationStatus(LiquidationState.COMPLETE_REFUND.getCode()); //完成退款
			}else if(boundary == 1){
				tOrder.setLiquidationStatus(LiquidationState.AGREE_REFUND.getCode()); //需要再退款
			}else if(boundary == -1){
				throw new BusinessException(new Error(ErrorConstants.REFUND_BEYOND_SIGN,"退款")); //超过退款金额
			}
		}
	}


	/**
	 * 设置按钮状态
	 * @param tOrder
	 * @return
	 */
	private OperatorActive setOperatorActive(TOrder tOrder){
		OperatorActive active = new OperatorActive();
		if(tOrder.getDeleteSign() == ActiveState.ABOLISH.getCode())
			return active;
		if(tOrder.getDeleteSign() == ActiveState.LOCKING.getCode()) {
			active.setApplyUnLock(true);
			return active;
		}
		if (TokenManager.getToken() instanceof User) {
			active.setConfirmPayForFirst(false);
			active.setConfirmPayForLast(false);
			active.setConfirmWithdraw(false);
			active.setCompleteRefund(false);
			active.setApplyLock(false);
			active.setApplyUnLock(false);
			active.setApplyRevoke(false);
			active.setApplySign(false);
			if (TokenManager.getUserId().equals(tOrder.getBuyerId())) { // 买方
				active.setApplyForWithdraw(false);
				if (tOrder.getOrderStatus() == OrderState.WAIT_FOR_CONFIRM.getCode()) {
					/** 需求订单 开始 **/
					if (tOrder.getOrderType() == CommodityType.DEMAND.getTypeCode()) {
						active.setConfirmIntention(true);
						active.setRefuseIntention(true);
					} else {
						active.setConfirmIntention(false);
						active.setRefuseIntention(false);
					}
					/** 需求订单 结束 **/
				} else {
					active.setConfirmIntention(false);
					active.setRefuseIntention(false);
				}
				if ((tOrder.getOrderStatus() == OrderState.WAIT_FOR_SIGN.getCode() || tOrder.getOrderStatus() == OrderState.ALREADY_SIGN.getCode())
						&& tOrder.getLiquidationStatus() == LiquidationState.WAIT_PAY_FIRST_BALANCE.getCode()) {
					active.setPayForFirst(true); //支付首付
				} else {
					active.setPayForFirst(false); //支付首付
				}
				if ((tOrder.getOrderStatus() == OrderState.WAIT_FOR_SIGN.getCode() || tOrder.getOrderStatus() == OrderState.ALREADY_SIGN.getCode())
						&& tOrder.getLiquidationStatus() == LiquidationState.WAIT_PAY_LAST_BALANCE.getCode()) {
					active.setPayForLast(true); //支付尾款
				} else {
					active.setPayForLast(false); //支付尾款
				}
				boolean flag = true;
				if(tOrder.getOrderStatus() != OrderState.WAIT_FOR_CONFIRM.getCode()
						&& tOrder.getOrderStatus() != OrderState.WAIT_FOR_SIGN.getCode()){
					flag = false;
				}
				if(tOrder.getLiquidationStatus() != LiquidationState.WAIT_PAY_FIRST_BALANCE.getCode()
						&& tOrder.getLiquidationStatus() != LiquidationState.WAIT_PAY_LAST_BALANCE.getCode()
						&& tOrder.getLiquidationStatus() != LiquidationState.ALREADY_PAY.getCode()){
					flag = false;
				}
				active.setApplyForCancel(flag); //申请取消
				flag = true;
				if(tOrder.getOrderStatus() != OrderState.BUYER_CANCEL_BEFORE_SIGN.getCode()
						&& tOrder.getOrderStatus() != OrderState.BUYER_CANCEL_AFTER_SIGN.getCode()
						&& tOrder.getOrderStatus() != OrderState.SELLER_REFUSE_BEFORE_SIGNL.getCode()
						&& tOrder.getOrderStatus() != OrderState.SELLER_CANCEL_AFTER_SIGN.getCode()){
					flag = false;
				}
				if(tOrder.getLiquidationStatus() == LiquidationState.WAIT_FOR_REFUND_CONFIRM.getCode()
						|| tOrder.getLiquidationStatus() == LiquidationState.REFUSE_REFUND.getCode()
						|| tOrder.getLiquidationStatus() == LiquidationState.AGREE_REFUND.getCode()
						|| tOrder.getLiquidationStatus() == LiquidationState.COMPLETE_REFUND.getCode()){
					flag = false;
				}
				if(tOrder.getActuallyTotalAmount().doubleValue() <= 0)
					flag = false;
				active.setApplyForRefund(flag); //申请退款
			}else if(TokenManager.getUserId().equals(tOrder.getSellerId())){ //卖方
				active.setPayForFirst(false);
				active.setPayForLast(false);
				active.setApplyForRefund(false);
				if (tOrder.getOrderStatus() == OrderState.WAIT_FOR_CONFIRM.getCode()) {
					/** 需求订单 开始 **/
					if (tOrder.getOrderType() == CommodityType.DEMAND.getTypeCode()) {
						active.setConfirmIntention(false);
						active.setRefuseIntention(false);
					} else {
						active.setConfirmIntention(true);
						active.setRefuseIntention(true);
					}
					/** 需求订单 结束 **/
				} else {
					active.setConfirmIntention(false);
					active.setRefuseIntention(false);
				}
				boolean flag = true;
				if(tOrder.getOrderStatus() != OrderState.WAIT_FOR_SIGN.getCode()){
					flag = false;
				}
				if(tOrder.getLiquidationStatus() != LiquidationState.WAIT_PAY_FIRST_BALANCE.getCode()
						&& tOrder.getLiquidationStatus() != LiquidationState.WAIT_PAY_LAST_BALANCE.getCode()
						&& tOrder.getLiquidationStatus() != LiquidationState.ALREADY_PAY.getCode()){
					flag = false;
				}
				active.setApplyForCancel(flag); //申请取消
				flag = true;
				if(tOrder.getOrderStatus() != OrderState.BUYER_CANCEL_BEFORE_SIGN.getCode()
						&& tOrder.getOrderStatus() != OrderState.BUYER_CANCEL_AFTER_SIGN.getCode()
						&& tOrder.getOrderStatus() != OrderState.SELLER_REFUSE_BEFORE_SIGNL.getCode()
						&& tOrder.getOrderStatus() != OrderState.SELLER_CANCEL_AFTER_SIGN.getCode()){
					flag = false;
				}
				if(tOrder.getLiquidationStatus() != LiquidationState.WAIT_FOR_REFUND_CONFIRM.getCode())
					flag = false;
				if(tOrder.getActuallyTotalAmount().doubleValue() <= 0)
					flag = false;
				active.setAgreeRefund(flag); //同意退款
				active.setRefuseRefund(flag); //拒绝退款
				if (tOrder.getOrderStatus() == OrderState.ALREADY_SIGN.getCode()
						&& tOrder.getLiquidationStatus() == LiquidationState.ALREADY_PAY.getCode()
						&& tOrder.getActuallyTotalAmount().doubleValue() > 0) {
					active.setApplyForWithdraw(true); //申请提现
				} else {
					active.setApplyForWithdraw(false); //申请提现
				}
			}else{
				active.setPayForFirst(false);
				active.setPayForLast(false);
				active.setConfirmIntention(false);
				active.setRefuseIntention(false);
				active.setApplyForCancel(false);
				active.setApplyForRefund(false);
				active.setAgreeRefund(false);
				active.setRefuseRefund(false);
				active.setApplyForWithdraw(false);
			}
		}
		if (TokenManager.getToken() instanceof Admin) {
			active.setPayForFirst(false);
			active.setPayForLast(false);
			active.setApplyForWithdraw(false);
			active.setApplyForRefund(false);
			if (tOrder.getSellerId().equals(DEFAULT_PLATFORM_ID)) { // 平台作为卖方
				if (tOrder.getOrderStatus() == OrderState.WAIT_FOR_CONFIRM.getCode()) {
					active.setConfirmIntention(true);
					active.setRefuseIntention(true);
				} else {
					active.setConfirmIntention(false);
					active.setRefuseIntention(false);
				}
				boolean flag = true;
				if(tOrder.getOrderStatus() != OrderState.WAIT_FOR_SIGN.getCode()){
					flag = false;
				}
				if(tOrder.getLiquidationStatus() != LiquidationState.WAIT_PAY_FIRST_BALANCE.getCode()
						&& tOrder.getLiquidationStatus() != LiquidationState.WAIT_PAY_LAST_BALANCE.getCode()
						&& tOrder.getLiquidationStatus() != LiquidationState.ALREADY_PAY.getCode()){
					flag = false;
				}
				active.setApplyForCancel(flag); //申请取消
				flag = true;
				if(tOrder.getOrderStatus() != OrderState.BUYER_CANCEL_BEFORE_SIGN.getCode()
						&& tOrder.getOrderStatus() != OrderState.BUYER_CANCEL_AFTER_SIGN.getCode()
						&& tOrder.getOrderStatus() != OrderState.SELLER_REFUSE_BEFORE_SIGNL.getCode()
						&& tOrder.getOrderStatus() != OrderState.SELLER_CANCEL_AFTER_SIGN.getCode()){
					flag = false;
				}
				if(tOrder.getLiquidationStatus() != LiquidationState.WAIT_FOR_REFUND_CONFIRM.getCode())
					flag = false;
				if(tOrder.getActuallyTotalAmount().doubleValue() <= 0)
					flag = false;
				active.setAgreeRefund(flag); //同意退款
				active.setRefuseRefund(flag); //拒绝退款
			} else {
				active.setConfirmIntention(false); //确认意向
				active.setRefuseIntention(false); //拒绝意向
				active.setApplyForCancel(false); //申请取消
				active.setAgreeRefund(false); //同意退款
				active.setRefuseRefund(false); //拒绝退款
			}
		}
		//平台方作为中间方 确认首付 - 尾款 - 提现 - 退款
		if(tOrder.getOrderStatus() == OrderState.WAIT_FOR_SIGN.getCode()
				&& tOrder.getLiquidationStatus() == LiquidationState.WAIT_PAY_FIRST_BALANCE.getCode()){
			active.setConfirmPayForFirst(true);
		}else{
			active.setConfirmPayForFirst(false);
		}
		if(tOrder.getOrderStatus() == OrderState.WAIT_FOR_SIGN.getCode()
				&& tOrder.getLiquidationStatus() == LiquidationState.WAIT_PAY_FIRST_BALANCE.getCode()){
			active.setConfirmPayForLast(true);
		}else{
			active.setConfirmPayForLast(false);
		}
		if(tOrder.getOrderStatus() == OrderState.ALREADY_SIGN.getCode()
				&& tOrder.getLiquidationStatus() == LiquidationState.WAIT_FOR_WITHDRAW.getCode()){
			active.setConfirmWithdraw(true);
		}else{
			active.setConfirmWithdraw(false);
		}
		boolean flag = true;
		if(tOrder.getOrderStatus() != OrderState.BUYER_CANCEL_BEFORE_SIGN.getCode()
				&& tOrder.getOrderStatus() != OrderState.BUYER_CANCEL_AFTER_SIGN.getCode()
				&& tOrder.getOrderStatus() != OrderState.SELLER_REFUSE_BEFORE_SIGNL.getCode()
				&& tOrder.getOrderStatus() != OrderState.SELLER_CANCEL_AFTER_SIGN.getCode()){
			flag = false;
		}
		if(flag && tOrder.getActuallyTotalAmount().doubleValue() == 0
				&& tOrder.getDeleteSign() == DeleteStatus.UNDELETE.getCode()){
			active.setApplyRevoke(true); //作废
		}else{
			active.setApplyRevoke(false); //作废
		}
		if(tOrder.getLiquidationStatus() != LiquidationState.AGREE_REFUND.getCode())
			flag = false;
		if(tOrder.getActuallyTotalAmount().doubleValue() <= 0)
			flag = false;
		active.setCompleteRefund(flag); //完成退款
		flag = true;
		if(tOrder.getOrderStatus() != OrderState.WAIT_FOR_SIGN.getCode())
			flag = false;
		active.setApplySign(flag); //签单
		if(tOrder.getDeleteSign() == DeleteStatus.UNDELETE.getCode()){
			active.setApplyLock(true);
		}else{
			active.setApplyLock(false);
		}
		if(tOrder.getDeleteSign() == DeleteStatus.LOCKING.getCode()){
			active.setApplyUnLock(true);
		}else{
			active.setApplyUnLock(false);
		}
		return active;
	}


	/**
	 * 添加流水记录
	 * @param orderNo 订单编号
	 * @param creater 创建人
	 * @param payeeId 收款人
	 * @param payerId 付款人
	 * @param remarks 附言
	 * @param transactionSubject 交易科目
	 * @param payChannel 支付渠道
	 * @param transactionMode 支付方式
	 * @return
	 */
	public int addFundRecord(String orderNo,String creater,String payeeId,String payerId,String remarks,TransactionSubject transactionSubject,PayChannel payChannel,
			BigDecimal transactionAmount,TransactionMode transactionMode,AuditState auditState){
		TOrderBill bill = new TOrderBill();
		bill.setBillNo(UUID.randomUUID().toString().replace("-", ""));
		bill.setConfirmSign(auditState.getCode());
		bill.setCreater(creater);
		bill.setDeleteSign(Boolean.FALSE);
		bill.setOrderNo(orderNo);
		bill.setTransactionAmount(transactionAmount);
		bill.setPayeeId(payeeId);
		bill.setPayerId(payerId);
		bill.setRemarks(remarks);
		bill.setTransactionAmount(transactionAmount);
		bill.setTransactionMode(transactionMode.getCode());
		bill.setTransactionSubject(transactionSubject.getCode());
		bill.setTransactionChannel(payChannel.getCode());
		bill.setCreateTime(new Date());
		return tOrderBillMapper.insert(bill);
	}







	@SuppressWarnings("unchecked")
	@Override
	public Pagination<BillListBo> selectOrderBillList(String orderNo,Integer pageNo,Integer pageSize) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(orderNo != null) params.put("orderNo", orderNo);
		params.put("uid", TokenManager.getUserId());
		Pagination<BillListBo> data = (Pagination<BillListBo>)findPage("selectOrderBillByPage","selectOrderBillCount", params, pageNo, pageSize);
		List<BillListBo> list = (List<BillListBo>)data.getList();
		if(list.size()>0){
			for(BillListBo bo:list){
				bo.setBusinessDesc(setBusinessDesc(bo.getTransactionSubject(),bo.getTransactionAmount()));
			}
		}
		data.setList(list);
		return data;
	}





	/**
	 *
	 * @param transactionSubject 交易科目
	 * @param transactionAmount 交易金额
	 * @return
	 */
	private String setBusinessDesc(Integer transactionSubject,BigDecimal transactionAmount){
		String result = "";
		if(transactionSubject == TransactionSubject.SUPPLY_COLLECT.getCode() || transactionSubject == TransactionSubject.REFUND.getCode()){
			result =  "收入-"+transactionAmount;
		}else if(transactionSubject == TransactionSubject.SUPPLY_PAY.getCode()){
			result =  "支出-"+transactionAmount;
		}
		return result;
	}


	/*
	 * -------------------------------------------------- 后台管理端 --------------------------------------------------------
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Pagination<OrderListBo> selectServiceOrder(OrderListBo bo,String startDate,String endDate,Integer intention,Integer formal,
			Integer pageNo, Integer pageSize) {
		Map<String,Object> params = disposeParams(bo,startDate,endDate);
		if(!TokenManager.hasRole(AFTConstants.SUPERADMIN))
			params.put("salesmanId", TokenManager.getAdminId());
		if((1 == intention && 0 == formal) || ( 0 == intention && 1 == formal)){
			params.put("intention", intention);
			params.put("formal", formal);
		}else if(0 == intention && 0 == formal){
			return new Pagination<OrderListBo>();
		}
		Pagination<OrderListBo> data = (Pagination<OrderListBo>)findPage("selectServiceOrderByPage","selectServiceOrderCount",
				params, pageNo, pageSize);
		TOrder tOrder = null;
		List<OrderListBo> list = (List<OrderListBo>)data.getList();
		for(OrderListBo olb:list){
			tOrder = new TOrder();
			try {
				BeanUtilsExt.copyProperties(tOrder, olb);
				tOrder.setActuallyTotalAmount(olb.getActuallyTotalAmount());
			} catch (InvocationTargetException | IllegalAccessException e) {
				e.printStackTrace();
			}
			olb.setActive(setOperatorActive(tOrder));
		}
		data.setList(list);
		return data;
	}

	private Map<String,Object> disposeParams(OrderListBo bo,String startDate,String endDate){
		Map<String,Object> params = new HashMap<>();
		if(StringUtils.isNotBlank(bo.getBuyerName())) params.put("buyerName", bo.getBuyerName());
		if(StringUtils.isNotBlank(bo.getOrderNo())) params.put("orderNo", bo.getOrderNo());
		if(null!=bo.getApproval()) params.put("approval", bo.getApproval());
		if(StringUtils.isNotBlank(bo.getSalesmanName())) params.put("salesmanName", bo.getSalesmanName());
		if(StringUtils.isNotBlank(startDate)) params.put("startDate", startDate +" 00:00:00");
		if(StringUtils.isNotBlank(endDate)) params.put("endDate", endDate + "23:59:59");
		if(bo.getOrderStatus() != null) params.put("orderStatus", bo.getOrderStatus());
		if(bo.getLiquidationStatus() != null) params.put("liquidationStatus", bo.getLiquidationStatus());
		if(bo.getProjectStage() != null) params.put("projectStage", bo.getProjectStage());
		if(bo.getOrderChannel() != null) params.put("orderChannel", bo.getOrderChannel());

		return params;
	}







	public void checkOrder(TOrder tOrder){
		if(tOrder == null)
			 throw new BusinessException(new Error(ErrorConstants.ORDER_NOT_EXIST, "" ,""));
		if(tOrder.getDeleteSign() == ActiveState.ABOLISH.getCode())
			 throw new BusinessException(new Error(ErrorConstants.ORDER_ALREADY_FREEZE, tOrder.getOrderNo(),""));
		if(tOrder.getDeleteSign() == ActiveState.LOCKING.getCode())
			 throw new BusinessException(new Error(ErrorConstants.ORDER_ALREADY_REVOKE, tOrder.getOrderNo(),""));
	}



	private void lockProject(BusinessListBo ub) {
		UserLockRelease ulr= new UserLockRelease();
			ulr.setId(UUID.randomUUID().toString());
			ulr.setType(1);
			ulr.setAid(TokenManager.getAdminId());
			ulr.setBusinessProjectId(ub.getBusinessProjectId());
			SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
			try {
				if (null==ub.getCreateTime()) {
					ulr.setLockTime(new Date());
				}else {
					ulr.setLockTime(sdf.parse(ub.getCreateTime()));
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
			ulr.setStatus(UserLockReleaseStatus.LOCKED.getCode());
			ulr.setUid(ub.getUid());
			userLockReleaseMapper.insert(ulr);
		}

	@SuppressWarnings("unused")
	private void releaseProject(List<LockingReleaseBo> releaseList){
		if(releaseList != null && releaseList.size()>0){
			UserLockRelease ulr = null;
			for(LockingReleaseBo bo : releaseList){
				ulr = new UserLockRelease();
				ulr.setId(bo.getId());
				ulr.setStatus(UserLockReleaseStatus.RELEASE.getCode());
				userLockReleaseMapper.updateByPrimaryKeySelective(ulr);
			}

		}
	}






	@Override
	public List<Department> selectMyDeps(){
		if(TokenManager.hasRole(AFTConstants.SUPERADMIN) || TokenManager.hasRole(AFTConstants.APPROVAL_DECISION))
			return departmentMapper.selectAllDeps();
		else
			return selectCurrentDep(TokenManager.getAdminId());
	}

	private List<Department> selectSubDeps(List<Department> allData,List<Department> superData){
		List<Department> subData = new ArrayList<>();
		String superIds = "";
		for(Department om : superData){
			if(!om.getId().equals(om.getSuperId())){
				superIds += om.getId() + ",";
			}
		}
		if(StringUtils.isNotBlank(superIds)) subData = departmentMapper.selectSubDepsList(superIds.substring(0, superIds.length()-1));
		if(subData != null && subData.size()>0) {
			allData.addAll(subData);
			selectSubDeps(allData,subData);
		}
		return allData;
	}

	private List<Department> selectCurrentDep(String managerId){
		List<Department> allData = new ArrayList<Department>();
		List<Department> superData = departmentMapper.selectSubDepsList(managerId);
		if(superData != null && superData.size()>0){
			allData.addAll(superData);
		}
		selectSubDeps(allData,superData);
		return allData;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<OrderListBo> selectDepServiceOrder(OrderListBo bo, String startDate, String endDate,
			Integer intention, Integer formal, String depIds,Integer pageNo, Integer pageSize) {
		Map<String,Object> params = disposeParams(bo,startDate,endDate);
		if(StringUtils.isNotBlank(depIds)) {
			if(!TokenManager.hasRole(AFTConstants.SUPERADMIN) && !TokenManager.hasRole(AFTConstants.APPROVAL_DECISION)){
				params.put("depIds","'" + depIds.replace(",", "','") + "'");
			}else{
				if(!depIds.contains(",")) params.put("depIds","'" + depIds + "'");
			}

		}else{
			if(!TokenManager.hasRole(AFTConstants.SUPERADMIN) && !TokenManager.hasRole(AFTConstants.APPROVAL_DECISION))
				return new Pagination<OrderListBo>();
		}
		if((1 == intention && 0 == formal) || ( 0 == intention && 1 == formal)){
			params.put("intention", intention);
			params.put("formal", formal);
		}else if(0 == intention && 0 == formal){
			return new Pagination<OrderListBo>();
		}
		Pagination<OrderListBo> data = (Pagination<OrderListBo>)findPage("selectServiceOrderByPage","selectServiceOrderCount",
				params, pageNo, pageSize);
		TOrder tOrder = null;
		List<OrderListBo> list = (List<OrderListBo>)data.getList();
		for(OrderListBo olb:list){
			tOrder = new TOrder();
			try {
				BeanUtilsExt.copyProperties(tOrder, olb);
				tOrder.setActuallyTotalAmount(olb.getActuallyTotalAmount());
			} catch (InvocationTargetException | IllegalAccessException e) {
				e.printStackTrace();
			}
			olb.setActive(setOperatorActive(tOrder));
		}
		data.setList(list);
		return data;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<OrderListBo> selectApprovalServiceOrder(OrderListBo bo, String startDate, String endDate,
			String depIds,Integer approvalHistory, Integer pageNo, Integer pageSize) {
		Map<String,Object> params = disposeParams(bo,startDate,endDate);
		if(StringUtils.isNotBlank(depIds)) {
			params.put("depIds", "'" + depIds + "'");
		}else{
			if(!TokenManager.hasRole(AFTConstants.SUPERADMIN) && !TokenManager.hasRole(AFTConstants.APPROVAL_DECISION))
				return new Pagination<OrderListBo>();
		}
		if(approvalHistory != null){
			params.put("approvalHistory", approvalHistory);
		}
		if(StringUtils.isNotBlank(bo.getBuyerName())) params.put("buyerName", bo.getBuyerName());
		if(bo.getOrderType() != null) params.put("orderType", bo.getOrderType());
		if(bo.getOrderChannel() != null) params.put("orderChannel", bo.getOrderChannel());
		if(bo.getOrderStatus() != null) params.put("orderStatus", bo.getOrderStatus());
		if(StringUtils.isNotBlank(startDate)) params.put("startDate", startDate);
		if(StringUtils.isNotBlank(endDate)) params.put("endDate", endDate);
		params.put("deleteStatus", 1);
		return  (Pagination<OrderListBo>)findPage("selectServiceOrderByPage","selectServiceOrderCount",
				params, pageNo, pageSize);
	}



	@SuppressWarnings("unchecked")
	@Override
	public Pagination<OrderListBo> selectPublicOrder(OrderListBo bo,String startDate,String endDate,Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<String,Object>();
		if(StringUtils.isNotBlank(bo.getBuyerName())) params.put("buyerName", bo.getBuyerName());
		if(bo.getOrderType() != null) params.put("orderType", bo.getOrderType());
		if(bo.getOrderChannel() != null) params.put("orderChannel", bo.getOrderChannel());
		if(bo.getOrderStatus() != null) params.put("orderStatus", bo.getOrderStatus());
		if(StringUtils.isNotBlank(startDate)) params.put("startDate", startDate);
		if(StringUtils.isNotBlank(endDate)) params.put("endDate", endDate);
		return (Pagination<OrderListBo>)findPage("selectPublicOrderByPage","selectPublicOrderCount",
				params, pageNo, pageSize);
	}



	@SuppressWarnings("unchecked")
	@Override
	public Pagination<OrderListBo> selectSettlementList(String orderNo, String depId,String buyerName,String salesmanName,
			String financeId,String financeName,Integer orderStatus,Integer liquidationStatus,Integer approval,Integer isDistributionFinance,
			String startDate,String endDate,Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(orderNo)) params.put("orderNo", orderNo);
		if(StringUtils.isNotBlank(depId)) params.put("depId", depId);
		if(StringUtils.isNotBlank(buyerName)) params.put("buyerName", buyerName);
		if(StringUtils.isNotBlank(salesmanName)) params.put("salesmanName", salesmanName);
		if(StringUtils.isNotBlank(financeId)) params.put("financeId", financeId);
		if(StringUtils.isNotBlank(financeName)) params.put("financeName", financeName);
		if(orderStatus != null) params.put("orderStatus", orderStatus);
		if(liquidationStatus != null) params.put("liquidationStatus", liquidationStatus);
		if(approval != null) params.put("approval", approval);
		if(isDistributionFinance != null) params.put("isDistributionFinance", isDistributionFinance);
		if(StringUtils.isNotBlank(startDate)) params.put("startDate", startDate);
		if(StringUtils.isNotBlank(endDate)) params.put("endDate", endDate);
		return (Pagination<OrderListBo>)findPage("selectSettlementByPage","selectSettlementCount", params, pageNo, pageSize);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<BillListBo> selectMyBillList(String payeeName, String payerName, String depId,
			String salesmanName,String orderNo, Integer confirmSign,Integer deleteSign, Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(payeeName)) params.put("payeeName", payeeName);
		if(StringUtils.isNotBlank(payerName)) params.put("payerName", payerName);
		if(StringUtils.isNotBlank(depId)) params.put("depId", depId);
		if(StringUtils.isNotBlank(salesmanName)) params.put("salesmanName", salesmanName);
		if(StringUtils.isNotBlank(orderNo)) params.put("orderNo", orderNo);
		if(confirmSign != null) params.put("confirmSign", confirmSign);
		if(deleteSign != null) params.put("deleteSign", deleteSign);
		/** 特殊处理字段开始 **/
		if(!TokenManager.hasRole(AFTConstants.SUPERADMIN)){
			params.put("isFinance", 1);
		}
		params.put("aid", TokenManager.getAdminId());
		/** 特殊处理字段结束 **/
		return (Pagination<BillListBo>)findPage("selectBillByPage","selectBillCount", params, pageNo, pageSize);
	}


	@SuppressWarnings("unchecked")
	@Override
	public Pagination<BillListBo> queryMyBillList(String payeeName, String payerName, String depId,
			String salesmanName,String orderNo, Integer confirmSign,Integer deleteSign, Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(payeeName)) params.put("payeeName", payeeName);
		if(StringUtils.isNotBlank(payerName)) params.put("payerName", payerName);
		if(StringUtils.isNotBlank(depId)) params.put("depId", depId);
		if(StringUtils.isNotBlank(salesmanName)) params.put("salesmanName", salesmanName);
		if(StringUtils.isNotBlank(orderNo)) params.put("orderNo", orderNo);
		if(confirmSign != null) params.put("confirmSign", confirmSign);
		if(deleteSign != null) params.put("deleteSign", deleteSign);
		/** 特殊处理字段开始 **/
		if(!TokenManager.hasRole(AFTConstants.SUPERADMIN)){
			params.put("isFinance", 0);
		}
		params.put("aid", TokenManager.getAdminId());
		/** 特殊处理字段结束 **/
		return (Pagination<BillListBo>)findPage("selectBillByPage","selectBillCount", params, pageNo, pageSize);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<BillListBo> queryAllBillList(String payeeName, String payerName, String depId,
			String salesmanName ,String financeName, String orderNo, Integer confirmSign,Integer deleteSign,Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(payeeName)) params.put("payeeName", payeeName);
		if(StringUtils.isNotBlank(payerName)) params.put("payerName", payerName);
		if(StringUtils.isNotBlank(depId)) params.put("depId", depId);
		if(StringUtils.isNotBlank(salesmanName)) params.put("salesmanName", salesmanName);
		if(StringUtils.isNotBlank(financeName)) params.put("financeName", financeName);
		if(orderNo != null) params.put("orderNo", orderNo);
		if(confirmSign != null) params.put("confirmSign", confirmSign);
		if(deleteSign != null) params.put("deleteSign", deleteSign);
		Pagination<BillListBo> data = (Pagination<BillListBo>)findPage("selectBillByPage","selectBillCount", params, pageNo, pageSize);
		List<BillListBo> list = (List<BillListBo>)data.getList();
		if(list.size()>0){
			for(BillListBo bo:list){
				bo.setBusinessDesc(setBusinessDesc(bo.getTransactionSubject(),bo.getTransactionAmount()));
			}
		}
		data.setList(list);
		return data;
	}




	@Override
	public int updateBill(String billNo,String orderNo, String financialPayNo, String financialPayTime, String remarks) {
		TOrderBill bill = new TOrderBill();
		bill.setBillNo(billNo);
		bill.setOrderNo(orderNo);
		bill.setFinancialPayNo(financialPayNo);
		try {
			bill.setFinancialPayTime(DateUtils.parseDate(financialPayTime, AFTConstants.YYYYMMDDHHMMSS));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		bill.setRemarks(remarks);
		return tOrderBillMapper.updateByPrimaryKeySelective(bill);
	}





	@SuppressWarnings("unchecked")
	@Override
	public Pagination<OrderListBo> listSetUpServiceOrder(String buyerName,String salesmanName, String financeName,
			String depId,Integer approval, Integer pageNo, Integer pageSize) {
		Map<String,Object> params = new HashMap<String,Object>();
		if(StringUtils.isNotBlank(buyerName))
			params.put("buyerName", buyerName);
		if(StringUtils.isNotBlank(salesmanName))
			params.put("salesmanName", salesmanName);
		if(StringUtils.isNotBlank(financeName))
			params.put("financeName",financeName);
		if(StringUtils.isNotBlank(depId))
			params.put("depId", depId);
		if(approval != null)
			params.put("approval", approval);
		return  (Pagination<OrderListBo>)findPage("selectSetUpServiceOrderByPage","selectSetUpServiceOrderCount",
				params, pageNo, pageSize);
	}













	private String getSalesmanIdByUid(String uid){
		User u = userMapper.queryById(uid);
		if(u!=null&&StringUtils.isBlank(u.getAid())){
			return u.getAid();
		}else{
			return DEFAULT_ADMIN_ID;
		}
	}






	@Override
	public List<OrderChangeBo> selectOrderChange(String orderNo) {
		return tOrderChangeMapper.selectOrderChange(orderNo);
	}






	@Override
	public int updateRepairData() {
		List<TmpTable> tmpData = tmpTableMapper.selectAll();
		int taskDistribution = TaskDistributionState.NOT_DISTRIBUTION.getCode();
		for(TmpTable tt: tmpData){
			if(tt.getAllCount() == tt.getDisCount())
				taskDistribution = TaskDistributionState.ALL_DISTRIBUTION.getCode();
			else if(tt.getAllCount() > tt.getDisCount() && tt.getDisCount() != 0)
				taskDistribution = TaskDistributionState.PART_DISTRIBUTION.getCode();
			else if(tt.getAllCount() > tt.getDisCount() && tt.getDisCount() == 0)
				taskDistribution = TaskDistributionState.NOT_DISTRIBUTION.getCode();
			contractMapper.updateRepairData(tt.getOrderNo(),taskDistribution);
		}
		return 1;
	}




	private void MobileNotice(List<String> targetIds, TOrder tOrder) {


	}

	@Override
	public void addContractTaskLog() {
		List<ContractTask> list=contractTaskMapper.selectlistContractTask();
		Admin aa=adminMapper.selectAdminName(AFTConstants.DEFAULT_INITIATOR);
		Admin ab=adminMapper.selectAdminName(AFTConstants.CONSULTANT_MANAGER);
		for (ContractTask ct : list) {
			ContractTaskLog c=new ContractTaskLog();
			c.setId(UUID.randomUUID().toString());
			c.setContractTaskId(ct.getId());
			c.setTaskReceiver(ab.getId());
			c.setTaskAllocator(aa.getId());
			c.setCreateTime(new Date());
			contractTaskLogMapper.insert(c);
			if (StringUtils.isNotBlank(ct.getTaskReceiver())&&!ct.getTaskReceiver().equals(ab.getId())) {
				 c=new ContractTaskLog();
				c.setId(UUID.randomUUID().toString());
				c.setContractTaskId(ct.getId());
				c.setTaskReceiver(ct.getTaskReceiver());
				c.setTaskAllocator(ab.getId());
				c.setCreateTime(new Date());
				contractTaskLogMapper.insert(c);
			}

		}


	}



	@Override
	public int addBusinessProjectId(FollowBusinessBo fbb) {
		//if(fbb.getUserBusinessList().size()<1) throw new BusinessException(new Error(ErrorConstants.AT_LEAST_A_BUSINESS,"",""));
		//更新跟进记录表
		SimpleDateFormat format = new SimpleDateFormat(AFTConstants.YYYYMMDDHHMMSS);
		fbb.setFollowTime(format.format(new Date()));
		UserFollow userFollow = new UserFollow();
		String followId = UUID.randomUUID().toString();
		userFollow.setId(followId);
		userFollow.setAid(TokenManager.getAdminId());
		userFollow.setContactType(Integer.parseInt(fbb.getContactType()));
		userFollow.setEffective(DeleteStatus.UNDELETE.getCode());
		userFollow.setCreateTime(new Date());
		userFollow.setOcbId(fbb.getOcbId());
		userFollow.setResult(fbb.getResult());
		userFollow.setUid(fbb.getUid());
		int followCount = userBusinessMapper.selectFollowCountByUAid(fbb.getUid(), TokenManager.getAdminId()) + 1;
		userFollow.setFollowCount(followCount);
		userFollowMapper.insert(userFollow);
		//检查客户锁定情况
		if(fbb.getUserBusinessList().size()>0){
			String ufbId = "";
			UserBusiness userBusiness = null;
			UserFollowBusiness userFollowBusiness = null;
			for(BusinessListBo ub: fbb.getUserBusinessList()){
				userBusiness = new UserBusiness();
				userFollowBusiness = new UserFollowBusiness();
				ufbId = UUID.randomUUID().toString();
				if (ub.getFollowSituation()==5) {//如果改成已签合同，则锁定业务
						if (StringUtils.isNotBlank(fbb.getUid())) ub.setUid(fbb.getUid());
						userLockReleaseMapper.updateProject(fbb.getUid(), TokenManager.getAdminId(), ub.getBusinessProjectId());
						lockProject(ub);//锁定客户业务
					}
					String ubId = UUID.randomUUID().toString();
					//更新业务表
					userBusiness.setId(ubId);
					userBusiness.setBusinessProjectId(ub.getBusinessProjectId());
					try {
						userBusiness.setCreateTime(format.parse(fbb.getFollowTime()));
						userBusiness.setUpdateTime(format.parse(fbb.getFollowTime()));
					} catch (ParseException e) {
						e.printStackTrace();
					}
					userBusiness.setCustomerStatus(ub.getCustomerStatus());
					userBusiness.setFollowSituation(ub.getFollowSituation());
					userBusiness.setUid(fbb.getUid());
					userBusiness.setAid(TokenManager.getAdminId());
					userBusiness.setRemarks(ub.getRemarks());
					userBusinessMapper.insert(userBusiness);
					//更新业务中间表
					userFollowBusiness.setBusinessId(ubId);
					userFollowBusiness.setCustomerStatus(ub.getCustomerStatus());
					userFollowBusiness.setFollowSituation(ub.getFollowSituation());
					userFollowBusiness.setId(ufbId);
					userFollowBusiness.setFollowId(followId);
					userFollowBusiness.setRemarks(ub.getRemarks());
					userFollowBusiness.setBusinessProjectId(ub.getBusinessProjectId());
					userFollowBusinessMapper.insert(userFollowBusiness);
				}

			}


		return 1;
	}

	@Override
	@Transactional
	public  int pushOrderImg(String orderNo, String imageUrl,String sign) {
		TOrderNew tOrderNew = tOrderNewMapper.queryById(orderNo);
		TOrderNew newOrder=new TOrderNew();
		newOrder.setOrderNo(orderNo);
		StringBuffer str=new StringBuffer();
		if (sign.equals(OrderImgEnums.CONTRACT.getCode())){
			if (StringUtils.isNotBlank(tOrderNew.getContractPictureUrl())){
				str=str.append(tOrderNew.getContractPictureUrl()).append(",").append(imageUrl);
			}else {
				str=str.append(imageUrl);
			}
			newOrder.setContractPictureUrl(str.toString());
		}else if (sign.equals(OrderImgEnums.SUPPLEMENT.getCode())){
			if (StringUtils.isNotBlank(tOrderNew.getAgreementUrl())){
				str=str.append(tOrderNew.getAgreementUrl()).append(",").append(imageUrl);
			}else {
				str=str.append(imageUrl);
			}
			newOrder.setAgreementUrl(str.toString());
		}else if (sign.equals(OrderImgEnums.CONTENT.getCode())){
			if (StringUtils.isNotBlank(tOrderNew.getServiceContent())){
				str=str.append(tOrderNew.getServiceContent()).append(",").append(imageUrl);
			}else {
				str=str.append(imageUrl);
			}
			newOrder.setServiceContent(str.toString());
		}else {
			return 0;
		}
		return tOrderNewMapper.update(newOrder);
	}



	@Override
	public int deleteOrderImg(String fileName,String orderNo, String sign) {
		TOrderNew tOrderNew = tOrderNewMapper.queryById(orderNo);
		TOrderNew newOrder=new TOrderNew();
		newOrder.setOrderNo(orderNo);
		StringBuffer str=new StringBuffer();
		List<String >list=new ArrayList<>();
		if (sign.equals(OrderImgEnums.CONTRACT.getCode())){
			if (tOrderNew.getContractPictureUrl()!=null){
				String[] ss=tOrderNew.getContractPictureUrl().split(",");
				list=Arrays.stream(ss).filter(e ->!e.equals(fileName)).collect(Collectors.toList());
			}
			if (list.size()<1){
				newOrder.setContractPictureUrl("");
			}else {
				for (String s : list) {
					str=str.append(s).append(",");
				}
				newOrder.setContractPictureUrl(str.substring(0,str.length()-1));
			}
		}else if (sign.equals(OrderImgEnums.SUPPLEMENT.getCode())){
			if (tOrderNew.getAgreementUrl()!=null){
				String[] ss=tOrderNew.getAgreementUrl().split(",");
				list=Arrays.stream(ss).filter(e ->!e.equals(fileName)).collect(Collectors.toList());
			}
			if (list.size()<1){
				newOrder.setAgreementUrl("");
			}else {
				for (String s : list) {
					str=str.append(s).append(",");
				}
				newOrder.setAgreementUrl(str.substring(0,str.length()-1));
			}

		}else if (sign.equals(OrderImgEnums.CONTENT.getCode())){
			if (tOrderNew.getServiceContent()!=null){
				String[] ss=tOrderNew.getServiceContent().split(",");
				list=Arrays.stream(ss).filter(e ->!e.equals(fileName)).collect(Collectors.toList());
			}
			if (list.size()<1){
				newOrder.setServiceContent("");
			}else {
				for (String s : list) {
					str=str.append(s).append(",");
				}
				newOrder.setServiceContent(str.substring(0,str.length()-1));
			}

		}else {
			return 0;
		}
		return tOrderNewMapper.update(newOrder);
	}


}
