package com.goafanti.order.controller;


import com.goafanti.admin.service.AttachmentService;
import com.goafanti.common.bo.Error;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.controller.CertifyApiController;
import com.goafanti.common.enums.AttachmentType;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.Attachment;
import com.goafanti.common.model.TOrderBillNew;
import com.goafanti.common.utils.LoggerUtils;
import com.goafanti.common.utils.excel.NewExcelUtil;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.order.bo.OrderListBo;
import com.goafanti.order.bo.ReceivablesListBo;
import com.goafanti.order.bo.TOrderInvoiceBo;
import com.goafanti.order.bo.TemporaryReceivablesBo;
import com.goafanti.order.enums.ApprovalTypeEnums;
import com.goafanti.order.service.FundManageOrderService;
import com.goafanti.order.service.OrderBillService;
import com.goafanti.order.service.OrderInvoiceService;
import com.goafanti.order.service.OrderReceivablesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

	@Resource
	private OrderReceivablesService orderReceivablesService;
	@Resource
	private AttachmentService	attachmentService;
	@Resource
	private OrderBillService	orderBillService;
	@Resource
	private OrderInvoiceService	orderInvoiceService;
	@Resource
	private FundManageOrderService	fundManageOrderService;
	@Value(value = "${upload.path}")
	private String					uploadPath			= null;
	/**
	 * 	新增预计回款信息
	 * @param t
	 * @return
	 */
	@RequestMapping(value = "/addReceivables",method = RequestMethod.POST)
	public Result addReceivables(TemporaryReceivablesBo t){
		Result res = new Result();
		res=inputCheck(t, res);
		if (!res.getError().isEmpty()) {
			return res;
		}
		res.data(orderReceivablesService.addReceivables(t));
		return res;
	}

	private Result inputCheck(TemporaryReceivablesBo t, Result res) {
		if(StringUtils.isBlank(t.getOrderNo())){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","订单编号编号"));
			return res;
		}
		if(t.getAmount() == null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","收款金额"));
			return res;
		}
		if(t.getReceivablesTimes() == null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","收款时间"));
			return res;
		}
		return res;
	}
	/**
	 * 	修改预计回款
	 */
	@RequestMapping(value = "/updateReceivables",method = RequestMethod.POST)
	public Result updateReceivables(TemporaryReceivablesBo t){
		Result res = new Result();
		res=inputCheck(t, res);
		if (!res.getError().isEmpty()) {
			return res;
		}
		res.data(orderReceivablesService.updateReceivables(t));
		return res;
	}
	/**
	 * 	删除预计回款
	 * @param ids	逗号隔开的id
	 * @param type	0 多个  1全部
	 * @return
	 */
	@RequestMapping(value = "/deleteReceivables",method = RequestMethod.POST)
	public Result deleteReceivables(String ids,Integer type){
		Result res = new Result();
		if(type==null) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","删除类型"));
			return res;
		}else if (type==0) {
			if(null==ids) {
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"","id或删除量"));
				return res;
			}
			res.data(orderReceivablesService.deleteReceivables(ids));
		} else {
			res.data(orderReceivablesService.deleteAllReceivables());
		}
		return res;
	}

	@RequestMapping(value ="/listReceivables",method = RequestMethod.GET)
	public Result listReceivables(ReceivablesListBo rl,Integer status,String adminName,String adminDeps,String orderDeps,
								  Integer mergeStatus,Integer pageSize,Integer pageNo){
		Result res = new Result();
		Map<String, Object>map =new HashMap<>();
		//列表数据
		map.put("pagination", orderReceivablesService.listReceivables(  rl,status,adminName,  adminDeps, orderDeps,mergeStatus, pageSize, pageNo));
		//统计数据
		map.put("count",orderReceivablesService.getCountlistReceivables(  rl,status,adminName,  adminDeps, orderDeps,mergeStatus));
		res.data(map);
		return res;
	}
	/**
	 * 	处理批量导入(批量回款)
	 *
	 *
	 */
	@RequestMapping(value ="/batchImport",method = RequestMethod.POST)
	public Result batchImport(Integer mergeStatus){
		LoggerUtils.debug(getClass(), "=========================开始批量导入===================");
		Result res = new Result();
		int i=0;
		i=orderReceivablesService.batchImport( mergeStatus);
		if (i==-1) {
			throw new BusinessException(new Error("未找到正确的回款信息。"));
		}
		return res;
	}

	/**
	 * 	下载回款批量导入Excel模板
     *
     * @param response
     * @return
     */
    @RequestMapping(value = "/downloadTemplate", method = RequestMethod.GET)
    public Result downloadTemplateFile(HttpServletResponse response, String sign) {
        Result res = new Result();
        AttachmentType attachmentType = AttachmentType.getField(sign);
        if (attachmentType == AttachmentType.RECEIVABLES_TEMPLATE) {
            String fileName = "";
            Attachment af = attachmentService.selectByReceivbles(sign);
            if (null == af) {
                res.getError().add(buildError(ErrorConstants.FILE_NON_EXISTENT, "", "找不到文件！"));
            } else {
                String path = af.getFilePath();
                String suffix = path.substring(path.lastIndexOf("."));
                fileName = AttachmentType.RECEIVABLES_TEMPLATE.getDesc() + suffix;
                downloadFile(response, fileName, path);
            }
        } else {
            res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
        }
        return res;
    }
	/**
	 * 	Excel批量导入回款
     *
     * @return
     */
    @RequestMapping(value = "/import" , method = RequestMethod.POST)
    public Result importTemplate(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
    	Result res=new Result();
    	//判断文件是否存在
        if(null == file){
      	  res.getError().add(buildError("文件不存在！","文件不存在！"));
      	  return res;
        }
    	String fileName = file.getOriginalFilename();
    	if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
        	  res.getError().add(buildError("格式不正确","格式不正确"));
        	  return res;
          }
    	orderReceivablesService.batchListReceivables(file);
         res.data(1);
    	return res;
    }

    /**
	 * 	导出回款
     *
     * @return
     */
    @RequestMapping(value = "/exportReceivables" , method = RequestMethod.GET)
    public Result exportReceivables(OrderListBo o,Integer pageSize ,Integer pageNo)  {
    	if (pageSize==null)pageSize=99999;
    	o.setOrderStatus(2);//营销管理员审核通过
    	@SuppressWarnings("unchecked")
    	Pagination<OrderListBo> p=(Pagination<OrderListBo>) fundManageOrderService.financeList(o, pageNo, pageSize).get("pagination");
		@SuppressWarnings("unchecked")
		List<OrderListBo> list=(List<OrderListBo>)p.getList() ;
		for (OrderListBo e : list) {
			if (e.getType()!=null){
				String[] split = e.getType().split(",");
				StringBuilder str=new StringBuilder();
				int index = 1;
				for (int i = 1; i < 9; i++) {
					for (String s : split) {
						if (index ==Integer.parseInt(s)){
							if (ApprovalTypeEnums.QT.getCode().equals(Integer.parseInt(s))){
								str.append(ApprovalTypeEnums.getDesc(s))
										.append("(").append(e.getTypeExplain()).append(")")
										.append(",");
							}else {
								str.append(ApprovalTypeEnums.getDesc(s)).append(",");
							}
						}
					}
					index++;
					if (index==8)index=0;
				}
				if(str.length()>0)e.setType(str.substring(0,str.length()-1));
			}
		}
    	NewExcelUtil<OrderListBo>excel=new NewExcelUtil<>(OrderListBo.class);
		 return  excel.exportExcel(list,"订单回款列表",uploadPath);
    }

    /**
	 * 	导出开票
     *
     * @param response
     * @return
     */
    @RequestMapping(value = "/exportInvoice" , method = RequestMethod.GET)
    public Result exportInvoice(HttpServletResponse response,String orderNo,Integer pageSize ,Integer pageNo)  {
    	if (pageSize==null)pageSize=99999;
		@SuppressWarnings("unchecked")
    	List<TOrderInvoiceBo>list=(List<TOrderInvoiceBo>) orderInvoiceService.salesmanOrderInvoiceList( orderNo, pageNo,pageSize).getList();
    	NewExcelUtil<TOrderInvoiceBo>excel=new NewExcelUtil<>(TOrderInvoiceBo.class);
		 return  excel.exportExcel(list,"订单"+orderNo+"开票列表",response);
    }
    /**
	 * 	导出流水
     *
     * @param response
     * @return
     */
    @RequestMapping(value = "/exportMyBill" , method = RequestMethod.GET)
    public Result exportMyBill(HttpServletResponse response, TOrderBillNew billNew,Integer pageSize ,Integer pageNo)  {
    	if (pageSize==null)pageSize=99999;
    	@SuppressWarnings("unchecked")
		List<TOrderBillNew>list=(List<TOrderBillNew>) orderBillService.myBillList(billNew,pageNo, pageSize).getList();
    	NewExcelUtil<TOrderBillNew>excel=new NewExcelUtil<>(TOrderBillNew.class);
		 return  excel.exportExcel(list,"订单流水列表",response);
    }

	@RequestMapping(value = "/waitingMerge",method = RequestMethod.POST)
	public Result waitingMerge(String ids){
		Result res=new Result();
		if (ids==null||ids.isEmpty()){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"回款编号"));
			return res;
		}
		res.data(orderReceivablesService.pushWaitingMerge(ids));
		return res;
	}

	/**
	 * 匹配
	 * @param value 匹配数据值
	 * @return
	 */
	@RequestMapping(value = "/matchingOrderNo",method = RequestMethod.GET)
	public Result matchingOrderNo(String value){
		Result res=new Result();
		if (value==null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"数据值"));
			return res;
		}
		res.data(orderReceivablesService.matchingOrderNo(value));
		return res;
	}

	/**
	 * 匹配
	 * @param value 匹配数据值
	 * @return
	 */
	@RequestMapping(value = "/matchingUser",method = RequestMethod.GET)
	public Result matchingUser(String value){
		Result res=new Result();
		if (value==null){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"数据值"));
			return res;
		}
		res.data(orderReceivablesService.matchingUser(value));
		return res;
	}



}
