package com.goafanti.order.controller;


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.common.enums.AttachmentType;
import com.goafanti.common.model.*;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.common.utils.excel.NewExcelUtil;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.order.bo.*;
import com.goafanti.order.enums.ApprovalNewState;
import com.goafanti.order.enums.OrderNewState;
import com.goafanti.order.enums.SalesTypes;
import com.goafanti.order.service.OrderAssistService;
import com.goafanti.order.service.OrderNewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping(value = "/api/admin/newOrder")
public class AdminNewOrderApiController extends CertifyApiController {

	@Autowired
	private OrderNewService orderNewService;
	@Autowired
	private OrderAssistService orderAssistService;
	@Value(value = "${upload.path}")
	private final String	uploadPath			= null;

	/**
	 *
	 * 创建订单、开单、派单
	 *
	 * @param uid 客户编号
	 * @param orderType 订单类型
	 * @param salesType 销售类型
	 * @param channelId 渠道编号
	 * @param other 备注
	 */
	@RequestMapping(value = "/createOrder",method = RequestMethod.POST)
	public Result createOrder(String uid,Integer orderType,Integer userType,
							  Integer salesType,String channelId,String other){
		Result res = new Result();
		if(StringUtils.isBlank(uid)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","客户编号"));
			return res;
		}
		if(orderType == null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单类型"));
			return res;
		}
		if(userType == null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","客户类型"));
			return res;
		}
		if (salesType==null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","销售类型"));
			return res;
		}else{
			if (salesType.equals(SalesTypes.qd.getCode()) ){
				if (StringUtils.isBlank(channelId)){
					res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","销售类型为渠道，渠道客户"));
					return res;
				}
				if (StringUtils.isBlank(other)){
					res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","销售类型为渠道，渠道客户名称"));
					return res;
				}
			}
			if ((salesType.equals(SalesTypes.qt.getCode()) ||salesType.equals(SalesTypes.zjs.getCode()))
					&&StringUtils.isBlank(other)){
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","销售类型为转介绍或者其他，请简单描述"));
				return res;
			}
		}

		res.data(orderNewService.createServiceOrder(uid,userType,orderType, salesType, channelId, other));
		return res;
	}
	/**
	 * 添加项目、新增项目
	 */
	@RequestMapping(value = "/addOrderTask",method = RequestMethod.POST)
	public Result addOrderTask(@RequestBody InputAddTask in){
		Result res = new Result();
		if(StringUtils.isBlank(in.getOrderNo())){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单编号"));
			return res;
		}
		if (in.getOrderNo()!=null&&orderNewService.checkOrderMain(in)) {
			res.getError().add(buildError("订单主要任务已存在","订单主要任务已存在"));
			return res;
		}
		return res.data(orderNewService.addOrderTask(in));
	}


	/**
	 * 修改项目(营销员)
	 */
	@RequestMapping(value = "/updateOrderTask",method = RequestMethod.POST)
	public Result updateOrderTask(InputAddTask t){
		Result res=new Result();
		if(null==t.getId()){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","项目编号"));
			return res;
		}
		if (t.getOrderNo()!=null&&orderNewService.checkOrderMain(t)) {
			res.getError().add(buildError("订单主要任务已存在","订单主要任务已存在"));
			return res;
		}
		return res.data(orderNewService.updateOrderTask(t));
	}

	/**
	 * 删除订单项目
	 */
	@RequestMapping(value = "/deleteOrderTask",method = RequestMethod.POST)
	public Result deleteOrderTask(Integer id){
		Result res = new Result();
		if(id==null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","项目编号"));
			return res;
		}
		return res.data(orderNewService.delectOrderTask(id));
	}

	/**
	 * 删除订单
	 */
	@RequestMapping(value = "/deleteOrderNew",method = RequestMethod.POST)
	public Result deleteOrderNew(String orderNo){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单编号"));
			return res;
		}
		int i=orderNewService.deleteOrderNew(orderNo);
		if (i==-1) {
			res.getError().add(buildError("订单未达删除条件","订单未达删除条件"));
			return res;
		}
		return res.data(i);
	}

	/**
	 * 获取订单项目信息
	 * @param type   分类 0 所有  1通过审核
	 * @param orderNo 订单编号
	 */
	@RequestMapping(value = "/getOrderTask",method = RequestMethod.GET)
	public Result getOrderTask(String orderNo,Integer type){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单编号"));
			return res;
		}
		res.setData(orderNewService.selectOrderTask(orderNo,type));
		return res;
	}

	/**
	 * 提交订单、发起订单
	 */
	@RequestMapping(value = "/submitOrder",method = RequestMethod.POST)
	public Result SubmitOrder(TOrderNewWithBLOBs t,String signDate){
		Result res = new Result();
		if(orderNewService.chekeProcessStatus(t.getOrderNo())){
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "审核状态错误","审核状态错误"));
			return res;
		}
		return updateServiceOrder( t, 1, signDate);
	}

	/**
	 * 修改订单
	 */
	@RequestMapping(value = "/updateServiceOrderNew",method = RequestMethod.POST)
	public Result updateServiceOrder(TOrderNewWithBLOBs t,Integer isSubmit,String signDate){
		Result res = new Result();
		if (null == isSubmit) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "提交状态"));
			return res;
		}
		if (isSubmit == 1) {
			if (StringUtils.isBlank(t.getOrderNo())) {
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "订单编号"));
				return res;
			}
			if (null == t.getTotalAmount() || null == t.getFirstAmount()) {
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "订单金额 和 首付金额"));
				return res;
			}
			if (StringUtils.isBlank(t.getContractPictureUrl())) {
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "合同图片"));
				return res;
			}
			if (StringUtils.isBlank(t.getContacts())||StringUtils.isBlank(t.getContactMobile())){
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "联系人与电话"));
				return res;
			}else {
				if (!StringUtils.isContainChinese(t.getContacts())){
					res.getError().add(buildError("联系人名称必须是中文。"));
					return res;
				}
				if (!StringUtils.isContactMobile(t.getContactMobile())){
					res.getError().add(buildError(ErrorConstants.MOBILE_PATTERN_ERROR));
					return res;
				}
			}
			if (orderNewService.checkORderTask(t.getOrderNo())) {
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "主项目"));
				return res;
			}
			if (orderNewService.checkOrderAmount(t)) {
				res.getError().add(buildError( "总金额、项目金额总计、催款金额总计必须一致"));
				return res;
			}
		}
		if (StringUtils.isNotBlank(signDate)) {
			t.setSignTime(DateUtils.StringToDate(signDate,"yyyy-MM-dd"));
		}
		res.setData(orderNewService.updateServiceOrder(t,isSubmit));
		return res;
	}

	/**
	 * 订单详情
	 */
	@RequestMapping(value = "/getOrderNewDetail", method = RequestMethod.GET)
	public Result getOrderNewDetail(String orderNo){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "订单编号","订单编号"));
			return res;
		}
		res.setData(orderNewService.getOrderNewDetail(orderNo));
		return res;
	}


	/**
	 * 订单审核列表
	 */
	@RequestMapping(value = "/getProcessName", method = RequestMethod.GET)
	public Result getProcessName(String orderNo){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "订单编号","订单编号"));
			return res;
		}
		res.setData(orderNewService.getProcessName(orderNo));
		return res;
	}

	@RequestMapping(value = "/updateSalesType",method = RequestMethod.POST)
	public Result updateSalesType(TOrderNew in ){
		Result res = new Result();
		if(StringUtils.isBlank(in.getOrderNo())){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "订单编号"));
			return res;
		}
		if (in.getSalesType().equals(SalesTypes.qd.getCode()) ){
			if (StringUtils.isBlank(in.getChannelId())){
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","销售类型为渠道，渠道客户"));
				return res;
			}
			if (StringUtils.isBlank(in.getOther())){
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","销售类型为渠道，渠道客户名称"));
				return res;
			}
		}
		if ((in.getSalesType().equals(SalesTypes.qt.getCode()) ||in.getSalesType().equals(SalesTypes.zjs.getCode()))
				&&StringUtils.isBlank(in.getOther())){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","销售类型为转介绍或者其他，请简单描述"));
			return res;
		}
		res.data(orderNewService.updateSalesType(in));
		return res;

	}

	/**
	 * 收款截点编辑
	 */
	@RequestMapping(value = "/createOrderDun", method = RequestMethod.POST)
	public Result createOrderDun(String orderDun,String orderNo){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "订单编号","订单编号"));
			return res;
		}
		res.setData(orderNewService.createOrderDun(orderDun,orderNo));
		return res;
	}

	/**
	 * 查看订单收款截点
	 */
	@RequestMapping(value = "/selectOrderDun", method = RequestMethod.GET)
	public Result selectOrderDun(String orderNo){
		Result res = new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "订单编号","订单编号"));
			return res;
		}
		res.setData(orderNewService.selectOrderDun(orderNo));
		return res;
	}

	/**
	 * 		订单列表
	 *  specially 0 个人 1 营销员管理 2 驳回 3 特批 4 咨询师管理 5部门订单查询 6客服查询 7统计签单订单 8客户订单列表 9 复审订单 10 营销经理 11运营保障 12 公出最大值待审核
	 *  distribution （咨询师管理列表 0 未分配 1部分 2全部
	 *  amountStatus  0 10万元以下 1 10万~20万 2 20万~30万 3 30万~40万  4 40万以上
	 */
	@RequestMapping(value="/orderNewList", method = RequestMethod.GET)
	public Result orderNewList(InputOrderNewListBo in){
		Result res=new Result();
		res.data(orderNewService.orderNewList(in));
		return res;
	}

	/**
	 * 		订单列表导出文件(压缩包)
	 *  specially 0 个人 1 营销员管理 2 驳回 3 特批 4 咨询师管理 5部门订单查询 6客服查询 7统计签单订单 8客户订单列表 9 复审订单 10 营销经理
	 *  distribution （咨询师管理列表 0 未分配 1部分 2全部
	 *  amountStatus  0 10万元以下 1 10万~20万 2 20万~30万 3 30万~40万  4 40万以上
	 */
	@RequestMapping(value="/orderNewListDownload", method = RequestMethod.GET)
	public Result orderNewListDownload(InputOrderNewListBo in,HttpServletResponse response){
		Result res =new Result();
		if(!TokenManager.hasRole(AFTConstants.SUPERADMIN)){
			res.getError().add(buildError("合同图片只允许超管导出！"));
			return res;
		}
		orderNewService.orderNewListDownload(in,response);
		return res;
	}

	/**
	 * 销售来源订单列表
	 */
	@RequestMapping(value="/statistics/orderList", method = RequestMethod.GET)
	public Result orderNewList(InputStatisticsOrderList in ){
		Result res=new Result();
		res.data(orderNewService.statisticsOrderList(in));
		return res;
	}


	/**
	 * 订单审核 营销管理员审核
	 */
	@RequestMapping(value="/auditOrderNew", method = RequestMethod.POST)
	public Result auditOrderNew(String orderNo,Integer orderStatus,String reason){
		Result res=new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "订单编号","订单编号"));
			return res;
		}
		if(orderStatus==null||(orderStatus!=OrderNewState.QDSHTG.getCode()&&orderStatus!=OrderNewState.QDSHJJ.getCode())||
				orderNewService.chekeOrderStatus(orderNo)){
			res.getError().add(buildError( "审核状态错误","审核状态错误"));
			return res;
		}
		if (orderStatus==OrderNewState.QDSHJJ.getCode()&&StringUtils.isBlank(reason)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"驳回原因", "驳回原因"));
			return res;
		}
		return res.data(orderNewService.updateOrderNew(orderNo,orderStatus,reason,0,null));
	}


	/**
	 * 订单审核 运营保障审核
	 * @param orderNo 订单编号
	 * @param type 0拒绝 1通过
	 * @param reason 说明
	 */
	@RequestMapping(value="/operationGuaranteeAudit", method = RequestMethod.POST)
	public Result operationGuaranteeAudit(String orderNo,Integer type,String reason){
		Result res=new Result();
		if(StringUtils.isBlank(orderNo)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "订单编号","订单编号"));
			return res;
		}
		if (type==null||(type!=0&&type!=1)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"审核状态", "审核状态"));
			return res;
		}
		if (StringUtils.isBlank(reason)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"驳回原因", "驳回原因"));
			return res;
		}
		return res.data(orderNewService.addOperationGuaranteeAudit(orderNo,type,reason));
	}


	/**
	 * 催款统计列表
	 * @param newStatus 0旧催款 1新催款
	 * @param specially 0查看自己 1查看别人
	 */
	@RequestMapping(value="/dunOrderNewList", method = RequestMethod.GET)
	public Result dunOrderNewList(String name,String orderNo,String contractNo,String starTime,String endTime,Integer specially,String aid,
			String adminName,String deps,Integer newStatus,Integer approval,Integer amountStatus,Integer memberType,
								  Integer pageNo,Integer pageSize){
		Result res=new Result();
		res.data(orderNewService.dunOrderNewList(name, orderNo,contractNo, starTime, endTime,specially,aid,  adminName, deps,newStatus,
				approval,amountStatus,memberType,pageNo, pageSize));
		return res;
	}

	/**
	 * 催款统计列表
	 */
	@RequestMapping(value="/arrearsDunList", method = RequestMethod.GET)
	public Result arrearsDunList(InputArrearsDunListBo in){
		Result res=new Result();
		res.data(orderNewService.arrearsDunList(in));
		return res;
	}

	/**
	 * 新增催款记录
	 */
	@RequestMapping(value="/createDunLog", method = RequestMethod.POST)
	public Result createDunLog(String dunId,String dumTime,String remarks,String attUrl){
		Result res=new  Result();
		if (StringUtils.isBlank(dunId)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "催款ID","催款ID"));
			return res;
		}
		if (StringUtils.isBlank(dumTime)||StringUtils.isBlank(remarks)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "时间与描述","时间与描述"));
			return res;
		}
		res.data(orderNewService.createDunLog(dunId, dumTime, remarks,attUrl));
		return res;
	}

	/**
	 * 催款记录查询
	 */
	@RequestMapping(value="/selectDunLogList", method = RequestMethod.GET)
	public Result selectDunLogList(String dunId){
			Result res=new Result();
			if (StringUtils.isBlank(dunId)) {
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "催款ID","催款ID"));
				return res;
			}
			res.data(orderNewService.selectDunLogList(dunId));
			return res;
	}

	/**
	 * 订单退单
	 */
	@RequestMapping(value="/addOrderRefund", method = RequestMethod.POST)
	public Result addOrderRefund(TOrderRefundWithBLOBs t){
			Result res=new Result();
			if (StringUtils.isBlank(t.getOrderNo())) {
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "订单编号","订单编号"));
				return res;
			}
			if(StringUtils.isBlank(t.getContractUrl())||StringUtils.isBlank(t.getApplicationUrl())){
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "合同与申请表","合同与申请表"));
				return res;
			}
			if (StringUtils.isBlank(t.getReason())) {
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "退单原因","退单原因"));
				return res;
			}
			if(orderNewService.checkOderSettlementAmount(t.getOrderNo())){
				res.getError().add(buildError( "未达退单条件","未达退单条件"));
				return res;
			}
			res.data(orderNewService.addOrderRefund(t));
			return res;
	}

	/**
	 * 退单详情
	 */
	@RequestMapping(value="/orderRefundDetail", method = RequestMethod.GET)
	public Result OrderRefund(String id){
			Result res=new Result();
			if (StringUtils.isBlank(id)) {
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "退单编号","退单编号"));
				return res;
			}
			res.data(orderNewService.orderRefundDetail(id));
			return res;
	}

	/**
	 * 订单退单
	 */
	@RequestMapping(value="/updateOrderRefund", method = RequestMethod.POST)
	public Result updateOrderRefund(TOrderRefundWithBLOBs t){
			Result res=new Result();
			if (null==t.getId()) {
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "退单编号","退单编号"));
				return res;
			}
			if(StringUtils.isBlank(t.getContractUrl())||StringUtils.isBlank(t.getApplicationUrl())){
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "合同与申请表","合同与申请表"));
				return res;
			}
			if (StringUtils.isBlank(t.getReason())) {
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "退单原因","退单原因"));
				return res;
			}
			res.data(orderNewService.updateOrderRefund(t));
			return res;
	}

	/**
	 * 审批特批订单
	 * @param orderNo
	 * @return
	 */
	@RequestMapping(value = "/approvalOrder",method = RequestMethod.POST)
	public Result approvalOrder(String orderNo,Integer confirm,String reason){
		Result res = new Result();
		if (StringUtils.isBlank(orderNo)||confirm==null) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "订单编号和审批","订单编号和审批"));
			return res;
		}
		if (confirm==ApprovalNewState.TPBH.getCode()&&StringUtils.isBlank(reason)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"驳回原因", "驳回原因"));
			return res;
		}
		if (orderNewService.chekeApprovalOrderStatus(orderNo)) {
			res.getError().add(buildError( "审核状态错误","审核状态错误"));
			return res;
		}
		return res.data(orderNewService.updateApprovalOrder(orderNo,confirm,reason));
	}

	/**
	 * 退单列表
	 */
	@RequestMapping(value="/orderRefundList", method = RequestMethod.GET)
	public Result orderRefundList(String name,String orderNo,String starTime,String endTime,Integer specially,Integer pageNo,Integer pageSize){
		Result res=new Result();
		res.data(orderNewService.orderRefundList(name, orderNo, starTime, endTime,specially, pageNo, pageSize));
		return res;
	}

	/**
	 * 订单结单
	 */
	@RequestMapping(value="/OrderOver", method = RequestMethod.GET)
	public Result updateOrderOver(String orderNo){
		Result res=new Result();
		if (StringUtils.isBlank(orderNo)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "订单编号","订单编号"));
			return res;
		}
		int i=orderNewService.updateOrderOver(orderNo);
		if (i==-1) {
			res.getError().add(buildError("不符合结单条件","不符合结单条件"));
			return res;
		}
		res.setData(i);
		return res;
	}

	/**
	 * 咨询师驳回订单
	 */
	@RequestMapping(value = "/technicianBackOrder", method = RequestMethod.POST)
	public Result technicianBackOrder(String orderNo,String reason){
		Result res = new Result();
		if (StringUtils.isBlank(reason)){
			res.getError().add(buildError("请输入驳回原因","请输入驳回原因"));
			return res;
		}
		int i=orderNewService.updatetechnicianBackOrder(orderNo, reason);
		if (i==-1) {
			res.getError().add(buildError("不符合驳回条件","不符合驳回条件"));
			return res;
		}
		return res;
	}

	/**
	 * 财务订单转交
	 */
	@RequestMapping(value = "/updateFinance", method= RequestMethod.GET)
	public Result updateFinance(String orderNo,String newFinance) {
		Result res = new Result();
		orderNewService.updateFinance( orderNo, newFinance);
		return res;
	}

	/**
	 * 查看订单日志
	 */
	@RequestMapping(value ="/selectOrderLog", method=RequestMethod.GET)
	public Result selectOrderLog (String orderNo) {
		Result res=new Result();
		if (StringUtils.isBlank(orderNo)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "订单编号","订单编号"));
			return res;
		}
		res.data(orderNewService.selectOrderLog(orderNo));
		return res;
	}

	/** 退单文件上传 **/
	@RequestMapping(value = "/uploadRefundOrderFile", method = RequestMethod.POST)
	public Result uploadRefundOrderFile(HttpServletRequest req,String sign){
		Result res = new Result();
		//order_refund_file
		res.setData(handleFile(res, "/order_refund_file/", false, req, sign));
		return res;
	}

	/**
	 * 催款日志文件上传
	 */
	@RequestMapping(value = "/uploadDunLogFile", method = RequestMethod.POST)
	public Result uploadDunLogFileResult(HttpServletRequest req, String sign) {
		Result res = new Result();
		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.DUN_LOG_ATTACHMENT) {
			res.setData(handleFiles(res, "/dun_log_attachment/", false, req, sign, TokenManager.getAdminId()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 催款列表下载
	 * @throws IOException
	 */
	@RequestMapping(value = "/exportOrderDunData", method = RequestMethod.GET)
	public Result exportOrderDunData(String name,String orderNo,String contractNo,String starTime,String endTime,Integer specially, String aid,String adminName,
			String depId,Integer newStatus,Integer approval,Integer amountStatus,Integer memberType,
									 Integer pageNo,Integer pageSize){
		return orderNewService.exportOrderDunData( name, orderNo,contractNo, starTime, endTime,specially, aid, adminName, depId,newStatus
				, approval, amountStatus, memberType,pageNo, pageSize);
	}

	/**
	 * 	项目列表下载
	 * @throws IOException
	 */
	@RequestMapping(value = "/exportOrderTaskData", method = RequestMethod.GET)
	public Result exportOrderTaskData(String orderNo,Integer type,HttpServletResponse response){
		List<TOrderTaskBo> list=orderNewService.selectOrderTask(orderNo,type);
		NewExcelUtil<TOrderTaskBo>excel=new NewExcelUtil<>(TOrderTaskBo.class);
		 return  excel.exportExcel(list,"订单项目列表",response);
	}

	/**
	 * 	催款信息下载
	 * @throws IOException
	 */
	@RequestMapping(value = "/exportArrearsDunListData", method = RequestMethod.GET)
	public Result exportArrearsDunListData(InputArrearsDunListBo in,HttpServletResponse response){
		@SuppressWarnings("unchecked")
		List<OutArrearsDunListBo> list=(List<OutArrearsDunListBo>) orderNewService.arrearsDunList(in).getList();
		NewExcelUtil<OutArrearsDunListBo>excel=new NewExcelUtil<>(OutArrearsDunListBo.class);
		return  excel.exportExcel(list,"欠款催款列表",response);
	}

	/**
	 * 	签单统计表
	 * @throws IOException
	 */
	@RequestMapping(value = "/statisticsList", method = RequestMethod.GET)
	public Result statisticsList(InputStatistics in){
		List<OutStatisticsList> result = orderNewService.statisticsList(in);
		ListSort(result,in.getSort());
		return res().data(result);
	}

	private void ListSort(List<OutStatisticsList> result,Integer sort) {
		if (sort==null||sort==0){
			result.sort(Comparator.comparing(OutStatisticsList::getTotal).reversed());
		}else if (sort==1){
			result.sort(Comparator.comparing(OutStatisticsList::getQuantity).reversed());
		} else {
			result.sort(Comparator.comparing(OutStatisticsList::getCounts).reversed());
		}
	}

	/**
	 * 	签单统计表
	 * @throws IOException
	 */
	@RequestMapping(value = "/statisticsListExprot", method = RequestMethod.GET)
	public Result statisticsListExprot(InputStatistics in){
		List<OutStatisticsList>  list =orderNewService.statisticsList(in);
		ListSort(list,in.getSort());
		NewExcelUtil<OutStatisticsList> excelUtil=new NewExcelUtil<>(OutStatisticsList.class);
		StringBuffer sb=new StringBuffer("搜索条件=》");
		if (in.getDepName()!=null)sb=sb.append("部门：").append(in.getDepName()).append(",");
		if(in.getProvinceName()!=null)sb=sb.append("省份：").append(in.getProvinceName()).append(",");
		if(in.getSort()!=null){
			sb=sb.append("排序：");
			if (in.getSort()==0)sb=sb.append("按签单额");
			else if (in.getSort()==1)sb=sb.append("按签单总量");
			else if (in.getSort()==2)sb=sb.append("按签单人数");
			sb=sb.append(",");
		}
		if (in.getStartCreate()!=null&&in.getEndCreate()!=null){
			sb=sb.append("下单时间：").append(in.getStartCreate()).append("~").append(in.getEndCreate()).append(",");
		}
		if (in.getStartSign()!=null&&in.getEndSign()!=null){
			sb=sb.append("合同时间：").append(in.getStartSign()).append("~").append(in.getEndSign()).append(",");
		}
		return excelUtil.exportExcel(list,"签单统计表",uploadPath,sb.substring(0,sb.toString().length()-1));
	}

	/**
	 * 	省份签单统计表
	 * 	a.total_amount>0.5,1,if(a.total_amount>0 and a.order_type=1,0.5,0)
	 * 	签单金额大于0.5万计做一个订单，小于0.5，如果是科技项目计做0.5单，其他计算成0单
	 * @throws IOException
	 */
	@RequestMapping(value = "/provinceStatisticsList", method = RequestMethod.GET)
	public Result provinceStatisticsList(InputStatistics in){
		List<OutProvinceStatisticsList> out = orderNewService.provinceStatisticsList(in);
		ProvinceListSort(out,in.getSort());
		return res().data(out);
	}

	private void ProvinceListSort(List<OutProvinceStatisticsList> out, Integer sort) {
		if (sort==null||sort==0){
			out.sort(Comparator.comparing(OutProvinceStatisticsList::getTotal).reversed());
		}else if (sort==1){
			out.sort(Comparator.comparing(OutProvinceStatisticsList::getQuantity).reversed());
		}
	}

	/**
	 * 	签单统计表
	 * @throws IOException
	 */
	@RequestMapping(value = "/provinceStatisticsListExprot", method = RequestMethod.GET)
	public Result provinceStatisticsListExprot(InputStatistics in){
		List<OutProvinceStatisticsList>  list =orderNewService.provinceStatisticsList(in);
		ProvinceListSort(list,in.getSort());
		NewExcelUtil<OutProvinceStatisticsList> excelUtil=new NewExcelUtil<>(OutProvinceStatisticsList.class);
		StringBuffer sb=new StringBuffer("搜索条件=》");
		if (in.getDepName()!=null)sb=sb.append("部门：").append(in.getDepName()).append(",");
		if(in.getProvinceName()!=null)sb=sb.append("省份：").append(in.getProvinceName()).append(",");
		if(in.getSort()!=null){
			sb=sb.append("排序：");
			if (in.getSort()==0)sb=sb.append("按签单额");
			else if (in.getSort()==1)sb=sb.append("按签单总量");
			else if (in.getSort()==2)sb=sb.append("按签单人数");
			sb=sb.append(",");
		}
		if (in.getStartCreate()!=null&&in.getEndCreate()!=null){
			sb=sb.append("下单时间：").append(in.getStartCreate()).append("~").append(in.getEndCreate()).append(",");
		}
		if (in.getStartSign()!=null&&in.getEndSign()!=null){
			sb=sb.append("合同时间：").append(in.getStartSign()).append("~").append(in.getEndSign()).append(",");
		}
		return excelUtil.exportExcel(list,"签单省份统计表",uploadPath,sb.substring(0,sb.toString().length()-1));
	}

	/**
	 * 新增协单人员
	 * @param in
	 * @return
	 */
	@RequestMapping(value = "/addAssist",method = RequestMethod.POST)
	public Result addAssist(TOrderAssist in){
		Result res = new Result();
		if (in.getAid()==null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,ErrorConstants.PARAM_EMPTY_ERROR,"协单人"));
			return res;
		}
		if (in.getOrderNo()==null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,ErrorConstants.PARAM_EMPTY_ERROR,"订单编号"));
			return res;
		}
		int i=orderAssistService.addAssistCheck(in);
		if (i==-1){
			res.getError().add(buildError(ErrorConstants.PARAM_BEING_ERROR,ErrorConstants.PARAM_BEING_ERROR,"协单人员"));
			return res;
		}
		return res.data(orderAssistService.addAssist(in));
	}

	/**
	 * 删除订单协单人员
	 * @return
	 */
	@RequestMapping(value = "/deleteAssist",method = RequestMethod.POST)
	public Result deleteAssist(Integer id){
		Result res = new Result();
		if (id==null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,ErrorConstants.PARAM_EMPTY_ERROR,"协单人"));
			return res;
		}
		return res.data(orderAssistService.deleteAssist(id));
	}

	/**
	 * 协单人员列表
	 * @return
	 */
	@RequestMapping(value = "/assistList",method = RequestMethod.GET)
	public Result assistList(String orderNo){
		Result res = new Result();
		if (orderNo==null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,ErrorConstants.PARAM_EMPTY_ERROR,"订单编号"));
			return res;
		}
		return res.data(orderAssistService.assistList(orderNo));
	}


	/**
	 * 新增订单上门服务
	 * @param in
	 * @return
	 */
	@RequestMapping(value = "/addOrderService",method = RequestMethod.POST)
	public Result addOrderService(TOrderServiceBo in){
		Result res = new Result();
		if (in.getServiceTimes()==null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,ErrorConstants.PARAM_EMPTY_ERROR,"服务时间"));
			return res;
		}
		if (in.getOrderNo()==null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,ErrorConstants.PARAM_EMPTY_ERROR,"订单编号"));
			return res;
		}
		return res.data(orderAssistService.addOrderService(in));
	}

	/**
	 * 删除订单上门服务
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/deleteOrderService",method = RequestMethod.POST)
	public Result deleteOrderService(Integer id){
		Result res = new Result();
		if (id==null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,ErrorConstants.PARAM_EMPTY_ERROR,"服务编号"));
			return res;
		}

		return res.data(orderAssistService.deleteOrderService(id));
	}

	/**
	 * 订单上门服务列表
	 * @return
	 */
	@RequestMapping(value = "/orderServiceList",method = RequestMethod.GET)
	public Result orderServiceList(String orderNo){
		Result res = new Result();
		if (orderNo==null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,ErrorConstants.PARAM_EMPTY_ERROR,"订单编号"));
			return res;
		}
		return res.data(orderAssistService.orderServiceList(orderNo));
	}


	@RequestMapping(value = "/updateOrderUrl",method = RequestMethod.POST)
	public Result updateOrderUrl(String orderNo,String contractPictureUrl,String agreementUrl,String serviceContent){
		Result res = new Result();
		if (!TokenManager.hasRole(AFTConstants.SUPERADMIN)){
			res.getError().add(buildError("只有超级管理员能直接修改"));
			return res;
		}
		return res.data(orderNewService.updateOrderUrl(orderNo,contractPictureUrl,agreementUrl,serviceContent));
	}

	/**
	 * 修改订单的标签
	 * @param orderNo  订单编号，可传多个逗号隔开
	 * @param tag   标签 0=默认，1=待处理，2=待派单，3=暂不处理，4=已过期，5=已作废
	 * @return
	 */
	@RequestMapping(value = "/updateTag",method = RequestMethod.POST)
	public Result updateTag(String orderNo,Integer tag){
		Result res=new Result();
		if (orderNo==null){
			res.getError().add(buildErrorMessageParams(ErrorConstants.PARAM_EMPTY_ERROR,"订单编号"));
			return res;
		}
		if (tag==null){
			res.getError().add(buildErrorMessageParams(ErrorConstants.PARAM_EMPTY_ERROR,"项目标签"));
			return res;
		}
		return res.data(orderNewService.updateTag(orderNo,tag));
	}


	/**
	 * 修改用户是否入群
	 * @param us
	 * @return
	 */
	@RequestMapping(value = "/updateAddGroupChat",method = RequestMethod.POST)
	public Result updateAddGroupChat(TOrderMid us) {
		Result res =new Result();
		if(us.getOrderNo()==null) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "订单编号"));
		}
		res.data(orderNewService.updateAddGroupChat(us));
		return res;
	}



}
