package com.goafanti.order.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.goafanti.common.bo.Error;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.dao.TOrderBillMapper;
import com.goafanti.common.dao.TOrderDetailMapper;
import com.goafanti.common.dao.TOrderMapper;
import com.goafanti.common.dao.UserMapper;
import com.goafanti.common.enums.DeleteStatus;

import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.Admin;

import com.goafanti.common.model.TOrder;
import com.goafanti.common.model.TOrderBill;
import com.goafanti.common.model.TOrderDetail;
import com.goafanti.common.model.User;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.JDBCIdGenerator;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.order.bo.BillListBo;
import com.goafanti.order.bo.CommodityDetailBo;
import com.goafanti.order.bo.OperatorActive;
import com.goafanti.order.bo.C2BOrderDetailBo;
import com.goafanti.order.bo.C2COrderDetailBo;
import com.goafanti.order.enums.ActiveState;
import com.goafanti.order.enums.ApprovalState;
import com.goafanti.order.enums.AuditState;
import com.goafanti.order.enums.ChangeState;
import com.goafanti.order.enums.CommodityType;
import com.goafanti.order.enums.LiquidationState;
import com.goafanti.order.enums.OrderAction;
import com.goafanti.order.enums.OrderChannel;
import com.goafanti.order.enums.OrderStage;
import com.goafanti.order.enums.OrderState;
import com.goafanti.order.enums.PayChannel;
import com.goafanti.order.enums.ProjectStage;
import com.goafanti.order.enums.TransactionMode;
import com.goafanti.order.enums.TransactionSubject;
import com.goafanti.order.service.OrderService;

@Service
public class OrderServiceImpl extends BaseMybatisDao<TOrderMapper> implements OrderService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private TOrderMapper tOrderMapper;
	@Autowired
	private TOrderDetailMapper tOrderDetailMapper;
	@Autowired
	private JDBCIdGenerator	idGenerator;
	@Autowired
	private TOrderBillMapper tOrderBillMapper;

	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 = "系统自动生产立项信息，请自行修改或补充";
	
	/*
	 * -------------------------------------------------- APP管理端 --------------------------------------------------------
	 */
	@Override
	public C2COrderDetailBo selectCommodityDetail(String commodityId, Integer commodityType) {
		C2COrderDetailBo bo = new C2COrderDetailBo();
		CommodityDetailBo cdb = tOrderMapper.selectCommodityDetail(commodityId,commodityType);
		try {
			BeanUtils.copyProperties(bo, cdb);
			bo.setOrderNo(String.valueOf(idGenerator.generateId()));
			bo.setCreateTime(DateUtils.formatDate(new Date(),AFTConstants.YYYYMMDDHHMMSS));
			bo.setCommodityType(commodityType);
			if(bo.getCommodityPrice().equals("0"))
				bo.setCommodityPrice("面议");
			else
				bo.setCommodityPrice(bo.getCommodityPrice()+" 万");
			if(StringUtils.isBlank(bo.getFirstPayment())) 
				bo.setFirstPayment("面议");
			else 
				bo.setFirstPayment(bo.getFirstPayment()+" 万");
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		return bo;
	}

	/**
	 * 只能购买一份
	 * 后期规则：自营服务订单 、需求订单、其他订单不能同时加入购物车
	 */
	@Override
	public int addIntention(String orderNo, String commodityId, String commodityMode, Integer commodityQuantity,Integer commodityType, 
			String createTime,String remarks) throws ParseException {
		CommodityDetailBo bo =  tOrderMapper.selectCommodityDetail(commodityId,commodityType);
		BigDecimal commodityPrice = StringUtils.isBlank(bo.getCommodityPrice()) ? DEFAULT_COMMODITY_PRICE 
				: new BigDecimal(Double.valueOf(bo.getCommodityPrice()));
		BigDecimal commodityFirstPayment = StringUtils.isBlank(bo.getCommodityFirstPayment()) ? DEFAULT_FIRST_PAYMENT 
				: new BigDecimal(Double.valueOf(bo.getCommodityFirstPayment()));
		BigDecimal discountPrice = commodityPrice.multiply(new BigDecimal(DEFAULT_COMMODITY_DISCOUNT));
		BigDecimal discountFirstPayment = commodityFirstPayment.multiply(new BigDecimal(DEFAULT_COMMODITY_DISCOUNT));
		TOrder tOrder = new TOrder();
		tOrder.setOrderNo(orderNo);	
		tOrder.setCreater(DEFAULT_ADMIN_ID);
		tOrder.setCreateTime(DateUtils.parseDate(createTime, AFTConstants.YYYYMMDDHHMMSS));
		if(commodityType == CommodityType.DEMAND.getTypeCode()){
			tOrder.setBuyerId(StringUtils.isBlank(bo.getSellerId()) ? DEFAULT_PLATFORM_ID : bo.getSellerId());
			tOrder.setSellerId(TokenManager.getUserId());
		}else{
			tOrder.setBuyerId(TokenManager.getUserId());
			tOrder.setSellerId(StringUtils.isBlank(bo.getSellerId()) ? DEFAULT_PLATFORM_ID : bo.getSellerId());
		}
		tOrder.setOrderType(commodityType);
		tOrder.setBrokerageAmount(discountPrice.multiply(new BigDecimal(DEFAULT_BROKERAGE_PROPORTION)));
		tOrder.setOrderAmount(commodityPrice);
		tOrder.setFirstPayment(commodityFirstPayment);
		tOrder.setSignTotalAmount(discountPrice);
		tOrder.setSignFirstPayment(discountFirstPayment);
		tOrder.setSignBrokerageAmount(discountPrice.multiply(new BigDecimal(DEFAULT_BROKERAGE_PROPORTION)));
		tOrder.setSignWithdrawAmount(discountPrice.subtract(discountPrice.multiply(new BigDecimal(DEFAULT_BROKERAGE_PROPORTION))));
		tOrder.setDeleteSign(DeleteStatus.UNDELETE.getCode());
		tOrder.setOrderChannel(OrderChannel.APP.getCode());
		tOrder.setApproval(ApprovalState.NORMAL.getCode());
		tOrder.setChangeStatus(ChangeState.UNCHANGE.getCode());
		tOrder.setSalesmanId(getSalesmanIdByUid(TokenManager.getAdminId()));
		tOrder.setOrderRemarks(remarks);
		tOrder.setContractType(bo.getCommodityClassify());
		setOrderState(OrderAction.ADD_INTENTION, new BigDecimal(0), tOrder, false);
		
		TOrderDetail tOrderDetail = new TOrderDetail();
		tOrderDetail.setId(UUID.randomUUID().toString());
		tOrderDetail.setOrderNo(orderNo);
		tOrderDetail.setCommodityId(commodityId);
		tOrderDetail.setCommodityName(bo.getCommodityName());
		tOrderDetail.setCommodityMode(StringUtils.isBlank(commodityMode)?DEFAULT_COMMODITY_MODE: commodityMode);
		tOrderDetail.setCommodityType(commodityType);
		tOrderDetail.setCommodityQuantity(commodityQuantity);
		tOrderDetail.setCommodityPrice(commodityPrice);
		tOrderDetail.setCommodityFirstPayment(commodityFirstPayment);
		tOrderDetail.setDiscountPrice(discountPrice);
		tOrderDetail.setDiscountFirstPayment(discountFirstPayment);
		tOrderDetail.setCreateTime(DateUtils.parseDate(createTime, AFTConstants.YYYYMMDDHHMMSS));
		tOrderDetailMapper.insert(tOrderDetail);
		tOrderMapper.insert(tOrder);
		return 1;
	}
	
	/**
	 * 订单状态流转
	 * @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 支付方式
	 * @param FundAudit 流水审核
	 * @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);
	}
	
	@Override
	public int updatePayForFirst(String orderNo, BigDecimal fundAmount,String remarks) {
		TOrder tOrder = tOrderMapper.selectByPrimaryKey(orderNo);
		addFundRecord(orderNo, TokenManager.getUserToken().getNickname(), DEFAULT_PLATFORM_ID, TokenManager.getUserId(), remarks, 
				TransactionSubject.SUPPLY_PAY,PayChannel.UNIONPAY, fundAmount, TransactionMode.OFFLINE, AuditState.WAIT_AUDIT);
		tOrder.setUpdateTime(new Date());
		return tOrderMapper.updateByPrimaryKeySelective(tOrder);
	}

	@Override
	public int updatePayForLast(String orderNo, BigDecimal fundAmount, String remarks) {
		TOrder tOrder = tOrderMapper.selectByPrimaryKey(orderNo);
		addFundRecord(orderNo, TokenManager.getUserToken().getNickname(), DEFAULT_PLATFORM_ID, TokenManager.getUserId(), remarks, 
				TransactionSubject.SUPPLY_PAY,PayChannel.UNIONPAY, fundAmount, TransactionMode.OFFLINE, AuditState.WAIT_AUDIT);
		tOrder.setUpdateTime(new Date());
		return tOrderMapper.updateByPrimaryKeySelective(tOrder);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<C2BOrderDetailBo> selectOrderList(boolean confirm,Integer pageNo,Integer pageSize) {
		Map<String, Object> params = new HashMap<String, Object>();
		Pagination<C2BOrderDetailBo> result = new Pagination<C2BOrderDetailBo>();
		if(!confirm) params.put("orderStatus", OrderState.WAIT_FOR_CONFIRM.getCode()); //购买意向
		params.put("uid", TokenManager.getUserId());
		Pagination<TOrder> data = (Pagination<TOrder>)findPage("selectOrderListByPage", "selectOrderListCount", params, pageNo, pageSize);
		List<TOrder> list = (List<TOrder>)data.getList();
		C2BOrderDetailBo bo = null;
		List<C2BOrderDetailBo> boList = new ArrayList<C2BOrderDetailBo>(); 
		List<CommodityDetailBo> commoditys = null;
		CommodityDetailBo cdb = null;
		if(list.size()>0){
			for(TOrder t:list){
				bo = new C2BOrderDetailBo();
				commoditys = new ArrayList<CommodityDetailBo>();
				bo.setOrderNo(String.valueOf(t.getOrderNo()));
				bo.setOrderRemarks(t.getOrderRemarks());
				bo.setOrderStatus(OrderState.getStatus(t.getOrderStatus()).getDesc());
				bo.setCreateTime(DateUtils.formatDate(t.getCreateTime(),AFTConstants.YYYYMMDDHHMMSS));
				bo.setOrderAmount(String.valueOf(t.getOrderAmount()).equals("0")?"面议":String.valueOf(t.getOrderAmount())+" 万");
				bo.setFirstPayment(String.valueOf(t.getFirstPayment()).equals("0")?"面议":String.valueOf(t.getFirstPayment())+" 万");
				bo.setOperatorActive(setOperatorActive(t));
				List<TOrderDetail> tdList = tOrderMapper.selectOrderCommodity(String.valueOf(t.getOrderNo()));
				for(TOrderDetail tod : tdList ){
					cdb = new CommodityDetailBo();
					cdb.setCommodityPrice(String.valueOf(tod.getCommodityPrice()).equals("0")?"面议":String.valueOf(tod.getCommodityPrice())+" 万");
					cdb.setDiscountPrice(String.valueOf(tod.getDiscountPrice()).equals("0")?"面议":String.valueOf(tod.getDiscountPrice())+" 万");
					cdb.setCommodityId(tod.getCommodityId());
					cdb.setCommodityName(tod.getCommodityName());
					cdb.setCommodityMode(tod.getCommodityMode());
					cdb.setCommodityType(tod.getCommodityType());
					cdb.setCommodityQuantity(tod.getCommodityQuantity());
					commoditys.add(cdb);
				}
				bo.setCommoditys(commoditys);
				boList.add(bo);
			}
		}
		result.setList(boList);
		result.setPageNo(data.getPageNo());
		result.setPageSize(data.getPageSize());
		result.setTotalCount(data.getTotalCount());
		result.setFilterNo(data.getFilterNo());
		return result;
	}

	@Override
	public C2BOrderDetailBo selectOrderDetail(String orderNo) {
		TOrder t = tOrderMapper.selectByPrimaryKey(orderNo);
		C2BOrderDetailBo bo = new C2BOrderDetailBo();
		bo.setOrderNo(String.valueOf(t.getOrderNo()));
		bo.setOrderRemarks(t.getOrderRemarks());
		bo.setOrderStatus(OrderState.getStatus(t.getOrderStatus()).getDesc());
		bo.setCreateTime(DateUtils.formatDate(t.getCreateTime(),AFTConstants.YYYYMMDDHHMMSS));
		bo.setOrderAmount(String.valueOf(t.getOrderAmount()).equals("0")?"面议":String.valueOf(t.getOrderAmount())+" 万");
		bo.setFirstPayment(String.valueOf(t.getFirstPayment()).equals("0")?"面议":String.valueOf(t.getFirstPayment())+" 万");
		bo.setOperatorActive(setOperatorActive(t));
		List<CommodityDetailBo> commoditys = new ArrayList<CommodityDetailBo>();
		CommodityDetailBo cdb = null;
		List<TOrderDetail> tdList = tOrderMapper.selectOrderCommodity(String.valueOf(t.getOrderNo()));
		for(TOrderDetail tod : tdList ){
			cdb = new CommodityDetailBo();
			cdb.setCommodityPrice(String.valueOf(tod.getCommodityPrice()).equals("0")?"面议":String.valueOf(tod.getCommodityPrice())+" 万");
			cdb.setDiscountPrice(String.valueOf(tod.getDiscountPrice()).equals("0")?"面议":String.valueOf(tod.getDiscountPrice())+" 万");
			cdb.setCommodityId(tod.getCommodityId());
			cdb.setCommodityName(tod.getCommodityName());
			cdb.setCommodityMode(tod.getCommodityMode());
			cdb.setCommodityType(tod.getCommodityType());
			cdb.setCommodityQuantity(tod.getCommodityQuantity());
			commoditys.add(cdb);
		}
		bo.setCommoditys(commoditys);
		return bo;
	}

	@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;
	}

	@Override
	@Transactional
	public int updateApplyForWithdraw(String orderNo,String remarks) {
		TOrder tOrder = tOrderMapper.selectByPrimaryKey(orderNo);
		BigDecimal transactionAmount = tOrder.getActuallyTotalAmount().subtract(tOrder.getActuallyBrokerageAmount());
		addFundRecord(orderNo, TokenManager.getUserToken().getNickname(), TokenManager.getUserId(), DEFAULT_PLATFORM_ID, remarks,
				TransactionSubject.SUPPLY_COLLECT, PayChannel.UNIONPAY,transactionAmount,TransactionMode.OFFLINE, AuditState.WAIT_AUDIT);
		setOrderState(OrderAction.APPLY_FOR_WITHDRAW, new BigDecimal(0), tOrder, false);
		tOrder.setUpdateTime(new Date());
		tOrderMapper.updateByPrimaryKeySelective(tOrder);
		return 1;
	}

	@Override
	@Transactional
	public int updateApplyForCancel(String orderNo) {
		TOrder tOrder = tOrderMapper.selectByPrimaryKey(orderNo);
		setOrderState(OrderAction.APPLY_FOR_CANCEL, new BigDecimal(0), tOrder, false);
		tOrder.setUpdateTime(new Date());
		tOrderMapper.updateByPrimaryKeySelective(tOrder);
		return 1;
	}

	/**
	 * 
	 * @param transactionSubject 交易科目
	 * @param transactionAmount 交易金额
	 * @param payeeId 收款人
	 * @param payerId 付款人
	 * @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;
	}

	@Override
	public int updateConfirmIntention(String orderNo, boolean confirm) {
		TOrder tOrder = tOrderMapper.selectByPrimaryKey(orderNo);
		setOrderState(OrderAction.CONFIRM_INTENTION, new BigDecimal(0), tOrder, confirm);
		tOrderMapper.updateByPrimaryKeySelective(tOrder);
		return 1;
	}

	/*
	 * -------------------------------------------------- 后台管理端 --------------------------------------------------------
	 */

	
	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 String getSalesmanIdByUid(String uid){
		User u = userMapper.selectByPrimaryKey(uid);
		if(u!=null&&StringUtils.isBlank(u.getAid())){
			return u.getAid();
		}else{
			return DEFAULT_ADMIN_ID;
		}
	}
	
	@Override
	public int updateApplyForRefund(String orderNo) {
		TOrder tOrder = tOrderMapper.selectByPrimaryKey(orderNo);
		setOrderState(OrderAction.APPLY_FOR_REFUND, new BigDecimal(0), tOrder, false);
		tOrder.setUpdateTime(new Date());
		return tOrderMapper.updateByPrimaryKey(tOrder);
	}

	@Override
	public int updateConfirmRefund(String orderNo,boolean confirm) {
		TOrder tOrder = tOrderMapper.selectByPrimaryKey(orderNo);
		setOrderState(OrderAction.CONFIRM_REFUND, new BigDecimal(0), tOrder, confirm);
		tOrder.setUpdateTime(new Date());
		if(confirm){ //同意退款生成退款流水
			BigDecimal transactionAmount = tOrder.getActuallyTotalAmount().subtract(tOrder.getActuallyBrokerageAmount()).multiply(new BigDecimal(-1)); 
			addFundRecord(orderNo, "平台方", DEFAULT_PLATFORM_ID,TokenManager.getUserId(), "同意退款系统生成流水",
					TransactionSubject.REFUND, PayChannel.UNIONPAY,transactionAmount,TransactionMode.OFFLINE, AuditState.WAIT_AUDIT);
		}
		return tOrderMapper.updateByPrimaryKey(tOrder);
	}

}
