package com.goafanti.order.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.goafanti.business.service.BusinessProjectService;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.controller.CertifyApiController;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.customer.bo.BusinessListBo;
import com.goafanti.customer.bo.FollowBusinessBo;
import com.goafanti.order.bo.OrderListBo;
import com.goafanti.order.enums.CommodityType;
import com.goafanti.order.service.OrderService;

@RestController
@RequestMapping(value = "/api/admin/order")
public class AdminOrderApiController extends CertifyApiController {
	@Resource
	private OrderService orderServiceImpl;
	@Resource
	private BusinessProjectService businessProjectServiceImpl;
	
	
	/**
	 * 订单详细
	 * @param orderNo
	 * @return
	 */
	@RequestMapping(value = "/serviceOrderDetail",method = RequestMethod.GET)
	public Result serviceOrderDetail(String orderNo){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "订单编号"));
			return res;
		}
		res.setData(orderServiceImpl.selectServiceOrderDetail(orderNo));
		return res;
	}
	
	
	/**
	 * 签单
	 * @param orderNo
	 * @param signFirstPayment
	 * @param signTotalAmount
	 * @param approval
	 * @param orderRemarks
	 * @return
	 */
	@RequestMapping(value = "/signServiceOrder", method = RequestMethod.POST)
	public Result signServiceOrder(String orderNo,String contractNo,String signFirstPayment,String signTotalAmount,
			String approval,String orderRemarks,String signTime,String contractPictureUrl,String userBusinessList,String uid){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "订单编号", "订单编号"));
			return res;
		}
		if(StringUtils.isBlank(signFirstPayment) || StringUtils.isBlank(signTotalAmount)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "订单金额 和 首付金额", "订单金额 和 首付金额"));
			return res;
		}
		if(null == approval){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "特批状态", "特批状态"));
			return res;
		}
		if(StringUtils.isBlank(contractPictureUrl)){
		res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "合同图片", "合同图片"));
		return res;
		}
		if(StringUtils.isBlank(uid)/* || StringUtils.isBlank(ocbId)*/){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, ""));
			return res;
		}
		orderServiceImpl.updateSignServiceOrder(orderNo,contractNo,signFirstPayment,signTotalAmount,approval,orderRemarks,signTime);
		//自动把签单任务标记成已签单
		JSONArray ja = (JSONArray) JSON.parse(userBusinessList);
		List<BusinessListBo> list = new ArrayList<BusinessListBo>();
		if (ja != null && !ja.isEmpty()) {
			BusinessListBo userBusiness = null;
			for (int idx = 0; idx < ja.size(); idx++) {
				userBusiness = ja.getJSONObject(idx).toJavaObject(BusinessListBo.class);
				list.add(userBusiness);
			}
		}
		FollowBusinessBo fbb = new FollowBusinessBo();
		//fbb.setOcbId(ocbId);
		fbb.setUid(uid);
		fbb.setContactType(AFTConstants.DEFAULT_CONTACT_TYPE);
		fbb.setResult(AFTConstants.DEFAULT_RESULT);
		fbb.setUserBusinessList(list);	
		orderServiceImpl.addBusinessProjectId(fbb);
		return res;
	}
	
	/** 
	 * 订单详情
	 * @param orderNo
	 * @return
	 */
	@RequestMapping(value = "/getServiceOrderDetail", method = RequestMethod.GET)
	public Result getServiceOrderDetail(String orderNo){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "订单编号"));
			return res;
		}
		res.setData(orderServiceImpl.selectServiceOrderDetail(orderNo));
		return res;
	}
	
	/**
	 * 确认意向
	 * @param orderNo
	 * @param confirm
	 * @return
	 */
	@RequestMapping(value="/confirmIntention", method = RequestMethod.POST)
	public Result confirmIntention(String orderNo,boolean confirm){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单编号"));
			return res;
		}
		orderServiceImpl.updateConfirmIntention(orderNo,confirm);
		return res;
	}
	
	/**
	 * 作废订单
	 * @param orderNo
	 * @return
	 */
	@RequestMapping(value = "/revokeOrder", method = RequestMethod.GET)
	public Result revokeOrder(String orderNo){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单编号"));
			return res;
		}
		orderServiceImpl.updateRevokeOrder(orderNo);
		return res;
	}
	
	/**
	 * 模糊查询业务项目
	 * @param businessName
	 * @return
	 */
	@RequestMapping(value = "/getBusinessProjectByName", method = RequestMethod.GET)
	public Result getBusinessProjectByName(String businessName,String cid){
		Result res = new Result();
		res.setData(businessProjectServiceImpl.selectBusinessProjectByName(businessName,cid));
		return res;
	}
	
	/**
	 * 查询业务项目分类
	 * @return
	 */
	@RequestMapping(value="/getBusinessProjectCatalog",method = RequestMethod.GET)
	public Result getBusinessProjectCatalog(){
		Result res = new Result();
		res.setData(businessProjectServiceImpl.selectBusinessProjectCatalog());
		return res;
	}
	
	/**
	 * 获取订单商品信息
	 * @param orderNo
	 * @return
	 */
	@RequestMapping(value = "/getOrderCommodity",method = RequestMethod.GET)
	public Result getOrderCommodity(String orderNo){
		Result res = new Result();
		res.setData(orderServiceImpl.selectOrderCommodity(orderNo));
		return res;
	}
	
	
	/**
	 * 添加订单商品
	 * @param orderNo	
	 * @param commodityId
	 * @param commodityMode
	 * @param commodityQuantity
	 * @param commodityType
	 * @param discountPrice
	 * @param remarks
	 * @return
	 */
	@RequestMapping(value = "/addOrderCommodity",method = RequestMethod.POST)
	public Result addOrderCommodity(String orderNo, String commodityId, String commodityName,String commodityMode, Integer commodityQuantity,Integer commodityType,
			String commodityPrice, String discountPrice,String commodityFirstPayment,String discountFirstPayment,String remarks){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单编号"));
			return res;
		}
		orderServiceImpl.addOrderCommodity(orderNo,commodityId,commodityName,commodityMode,commodityQuantity,commodityType,
				commodityPrice,discountPrice,commodityFirstPayment,discountFirstPayment,remarks);
		return res;
	}
	
	/**
	 * 进入修改商品信息
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/toUpdateOrderCommodity",method = RequestMethod.GET)
	public Result toUpdateOrderCommodity(String id){
		Result res = new Result();
		if(StringUtils.isBlank(id)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","明细ID"));
			return res;
		}
		
		return res;
	}
	
	/**
	 * 修改订单商品
	 * @param detailId
	 * @param orderNo
	 * @param discountPrice
	 * @param discountFirstPayment
	 * @param commodityQuantity
	 * @param remarks
	 * @return
	 */
	@RequestMapping(value = "/updateOrderCommodity", method = RequestMethod.POST)
	public Result updateOrderCommodity(String detailId,String discountPrice,String discountFirstPayment,Integer commodityQuantity,String remarks){
		Result res = new Result();
		if(StringUtils.isBlank(detailId)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","详情编号"));
			return res;
		}
		orderServiceImpl.updateOrderCommodity(detailId,discountPrice, discountFirstPayment,commodityQuantity, remarks);
		return res;
	}
	
	/**
	 * 删除订单商品
	 * @param detailId
	 * @return
	 */
	@RequestMapping(value = "/deleteOrderCommodity",method = RequestMethod.GET)
	public Result deleteOrderCommodity(String detailId){
		Result res = new Result();
		if(StringUtils.isBlank(detailId)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","详情编号"));
			return res;
		}
		orderServiceImpl.deleteOrderCommodity(detailId);
		return res;
	}
	
	/**
	 * 查询分管部门
	 * @return
	 */
	@RequestMapping(value = "/selectMyDeps")
	public Result selectMyDeps(){
		Result res = new Result();
			res.setData(orderServiceImpl.selectMyDeps());
		return res;
	}
	
	
	
	
	
	
	/**
	 * 创建订单
	 * @param uid
	 * @param orderType
	 * @return
	 */
	@RequestMapping(value = "/createOrder",method = RequestMethod.POST)
	public Result createOrder(String uid,Integer orderType,String contractType){
		Result res = new Result();
		if(StringUtils.isBlank(uid)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","客户编号"));
			return res;
		}
		/*if(orderServiceImpl.checkCustomerInformation(uid)){
			res.getError().add(buildError("","请到客户资料-客户资料维护模块完善您的客户信息！"));
			return res;
		}*/
		if(orderType == null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单类型"));
			return res;
		}
		if(orderType != CommodityType.SERVICE.getTypeCode()){
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR,"","暂不支持创建该类型订单"));
			return res;
		}else {
			if(StringUtils.isBlank(contractType)) {
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","业务品类"));
				return res;
			}
		}
		orderServiceImpl.createServiceOrder(uid,orderType,contractType);
		return res;
	}
	

	/** 图片上传 **/
	@RequestMapping(value = "/uploadOrderImg", method = RequestMethod.POST)
	public Result uploadOrderImg(HttpServletRequest req,String sign){
		Result res = new Result();
		res.setData(handleFile(res, "/order_file/", false, req, sign));
		return res;
	}
	
	/** 查询公共订单 **/
	@RequestMapping(value = "/listPublicOrder", method = RequestMethod.POST)
	public Result listPublicOrder(OrderListBo bo,String startDate,String endDate,Integer pageNo, Integer pageSize){
		Result res = new Result();
		res.setData(orderServiceImpl.selectPublicOrder(bo,startDate,endDate,pageNo,pageSize));
		return res;
	}
	
	/** 分配订单到营销员 **/
	@RequestMapping(value = "/appointSalesman", method = RequestMethod.GET)
	public Result appointSalesman(String orderNo,String salesmanId){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单编号"));
			return res;
		}
		if(StringUtils.isBlank(salesmanId)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","指定人员编号"));
			return res;
		}
		orderServiceImpl.updateAppointSalesman(orderNo, salesmanId);
		return res;
	}

	/** 我的结算查询 **/
	@RequestMapping(value = "/listMySettlement", method = RequestMethod.POST)
	public Result listMySettlement(String orderNo, String depId,String buyerName,String salesmanName, String financeName,
			Integer orderStatus,Integer liquidationStatus,Integer approval,String startDate,
			String endDate,Integer pageNo, Integer pageSize){
		Result res = new Result();
		res.setData(orderServiceImpl.selectSettlementList(orderNo, depId, buyerName, salesmanName,
				TokenManager.getAdminId(), financeName, orderStatus, liquidationStatus, approval,null,startDate,endDate, pageNo, pageSize));
		return res;
	}
	
	/** 结算订单管理 **/
	@RequestMapping(value = "/listAllSettlement", method = RequestMethod.POST)
	public Result listAllSettlement(String orderNo, String depId,String buyerName,String salesmanName, String financeName,
			Integer orderStatus,Integer liquidationStatus,Integer approval,Integer isDistributionFinance,String startDate,String endDate,
			Integer pageNo, Integer pageSize){
		Result res = new Result();
		res.setData(orderServiceImpl.selectSettlementList(orderNo, depId, buyerName, salesmanName,
				"", financeName, orderStatus, liquidationStatus, approval,isDistributionFinance, startDate,endDate, pageNo, pageSize));
		return res;
	}
	
	/** 我的订单流水管理 **/
	@RequestMapping(value = "/listMyBill", method = RequestMethod.POST)
	public Result selectMyBillList(String payeeName, String payerName, String depId,
			String salesmanName,String orderNo, Integer confirmSign,Integer deleteSign,Integer pageNo, Integer pageSize){
		Result res = new Result();
		res.setData(orderServiceImpl.selectMyBillList(payeeName, payerName, depId, salesmanName,orderNo, 
				confirmSign, deleteSign, pageNo, pageSize));
		return res;
	}
	

	/** 我的订单流水查询 **/
	@RequestMapping(value = "/queryMyBill", method = RequestMethod.POST)
	public Result queryMyBillList(String payeeName, String payerName, String depId,
			String salesmanName,String orderNo, Integer confirmSign,Integer deleteSign,Integer pageNo, Integer pageSize){
		Result res = new Result();
		res.setData(orderServiceImpl.queryMyBillList(payeeName, payerName, depId, salesmanName,orderNo, 
				confirmSign, deleteSign, pageNo, pageSize));
		return res;
	}
	
	
	/** 所有订单流水查询 **/
	@RequestMapping(value = "/queryAllBill", method = RequestMethod.POST)
	public Result queryAllBill(String payeeName, String payerName, String depId,
			String salesmanName,String financeName,String orderNo, Integer confirmSign,Integer deleteSign, Integer pageNo, Integer pageSize){
		Result res = new Result();
		res.setData(orderServiceImpl.queryAllBillList(payeeName, payerName, depId, salesmanName,financeName, orderNo,confirmSign,deleteSign, pageNo, pageSize));
		return res;
	}
	
	/** 查询流水详情 **/
	@RequestMapping(value = "/selectBillDetail", method = RequestMethod.GET)
	public Result selectBillDetail(String billNo){
		Result res = new Result();
		if(StringUtils.isBlank(billNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","流水编号"));
			return res;
		}
		res.setData(orderServiceImpl.selectBillDetail(billNo));
		return res;
	}
	
	
	/**
	 * 修改流水
	 * @param billNo
	 * @param financialPayNo
	 * @param financialPayTime
	 * @param remarks
	 * @return
	 */
	@RequestMapping(value = "/updateBill", method = RequestMethod.POST)
	public Result updateBill(String billNo,String orderNo, String financialPayNo, String financialPayTime, String remarks){
		Result res = new Result();
		if(StringUtils.isBlank(billNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","流水编号"));
			return res;
		}
		if(StringUtils.isBlank(financialPayNo) || StringUtils.isBlank(financialPayTime)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","财务流水号和财务流水时间"));
			return res;
		}
		orderServiceImpl.updateBill(billNo, orderNo,financialPayNo, financialPayTime, remarks);
		return res;
	}
	
	/**
	 * 订单支付（测试用）
	 * @return
	 */
	@RequestMapping(value = "/testPay",method = RequestMethod.POST)
	public Result testPay(String orderNo,String payAmount){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo) || StringUtils.isBlank(payAmount)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单编号和支付金额"));
			return res;
		}
		orderServiceImpl.updatePayForTest(orderNo, payAmount);
		return res;
	}
	
	/**
	 * 订单退款（测试用）
	 * @param orderNo
	 * @param refundAmount
	 * @return
	 */
	@RequestMapping(value = "/testRefund",method = RequestMethod.POST)
	public Result testRefund(String orderNo,String refundAmount){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo) || StringUtils.isBlank(refundAmount)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单编号和退款金额"));
			return res;
		}
		orderServiceImpl.updateRefundForTest(orderNo, refundAmount);
		return res;
	}
	
	/**
	 * 派单
	 * @param orderNo
	 * @param financeId
	 * @return
	 */
	@RequestMapping(value = "/distributionOrder",method = RequestMethod.POST)
	public Result distributionOrder(String orderNo,String financeId){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo) || StringUtils.isBlank(financeId)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单编号和指定负责人"));
			return res;
		}
		orderServiceImpl.updateDistributionOrder(orderNo,financeId);
		return res;
	}

	/**
	 * 解锁、锁定、作废
	 * @param operatorType
	 * @param orderNo
	 * @return
	 */
	@RequestMapping(value = "/lockOrRevokeOrder",method = RequestMethod.GET)
	public Result lockOrRevokeOrder(String orderNo,Integer operatorType){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo) || operatorType == null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单编号和操作类型"));
			return res;
		}
		orderServiceImpl.updateLockOrRevokeOrder(orderNo,operatorType);
		return res;
	}

	/**
	 * 查询单笔订单流水
	 * @param orderNo
	 * @return
	 */
	@RequestMapping(value= "/getBillByOrderNo", method = RequestMethod.GET)
	public Result getBillByOrderNo(String orderNo){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单编号"));
			return res;
		}
		res.setData(orderServiceImpl.selectBillByOrderNo(orderNo));
		return res;
	}
	
	/**
	 * 确认退款
	 * @param orderNo
	 * @param confirm
	 * @return
	 */
	@RequestMapping(value = "/confirmRefund", method = RequestMethod.GET)
	public Result confirmRefund(String orderNo,boolean confirm){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单编号"));
			return res;
		}
		orderServiceImpl.updateConfirmRefund(orderNo,confirm);
		return res;
	}
	
	

	/**
	 * 发起订单变更(作废)
	 * @param orderNo
	 * @param changeComment
	 * @return
	 */
	@RequestMapping(value = "/addOrderChange",method = RequestMethod.POST)
	public Result addOrderChange(String orderNo,String changeComment,String taskList,String dunList){
		Result res = new Result();
		//此订单变更为原订单变更已经确定不再使用。
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单编号"));
			return res;
		}
		if(StringUtils.isBlank(changeComment)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","变更说明"));
			return res;
		}
		orderServiceImpl.addOrderChange(orderNo,changeComment,taskList,dunList);
		return res;
	}
	
	/**
	 * 查看变更记录
	 * @param orderNo
	 * @return
	 */
	@RequestMapping(value = "/viewOrderChange",method = RequestMethod.GET)
	public Result viewOrderChange(String orderNo){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单编号"));
			return res;
		}
		res.setData(orderServiceImpl.selectOrderChange(orderNo));
		return res;
	}
	
	/**
	 * 删除变更
	 * @param changeId
	 * @return
	 */
	@RequestMapping(value = "/deleteOrderChange",method = RequestMethod.GET)
	public Result deleteOrderChange(String changeId){
		Result res = new Result();
		if(StringUtils.isBlank(changeId)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","变更ID"));
			return res;
		}
		orderServiceImpl.deleteOrderChange(changeId);
		return res;
	}
	
	/**
	 * 更新变更记录
	 * @param changeComment
	 * @param changeStatus
	 * @return
	 */
	@RequestMapping(value = "/updateOrderChange",method = RequestMethod.POST)
	public Result updateOrderChange(String changeId,String changeComment,Integer changeStatus){
		Result res = new Result();
		if(StringUtils.isBlank(changeId)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","变更ID"));
			return res;
		}
		if(changeStatus == null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","变更状态"));
			return res;
		}
		orderServiceImpl.updateOrderChange(changeId,changeComment,changeStatus);
		return res;
	}

	/**
	 * 处理旧项目任务
	 */
	@RequestMapping(value="/addContractTaskLog",method = RequestMethod.GET)
	public Result addContractTaskLog(){
		Result res = new Result();
		orderServiceImpl.addContractTaskLog();
		return res;
	}
}
