package com.goafanti.order.controller;






import java.util.HashMap;
import java.util.Map;

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

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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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.order.bo.OrderListBo;
import com.goafanti.order.bo.ReceivablesListBo;
import com.goafanti.order.bo.TemporaryReceivablesBo;
import com.goafanti.order.service.OrderBillService;
import com.goafanti.order.service.OrderReceivablesService;

@RestController
@RequestMapping(value = "/api/admin/receivables")
public class AdminOrderReceivablesApiController extends CertifyApiController {
	
	@Resource
	private OrderReceivablesService orderReceivablesService;
	@Resource
	private AttachmentService	attachmentService;
	@Resource
	private OrderBillService	orderBillService;
	/**
	 * 	新增预计回款信息
	 * @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 adminDepId,String orderDepId,Integer pageSize,Integer pageNo){
		Result res = new Result();
		Map<String, Object>map =new HashMap<>();
		//列表数据
		map.put("pagination", orderReceivablesService.listReceivables(  rl,status,adminName,  adminDepId, orderDepId, pageSize, pageNo));
		//统计数据
		map.put("count",orderReceivablesService.getCountlistReceivables(  rl,status,adminName,  adminDepId, orderDepId));
		res.data(map);
		return res;
	}
	/**
	 * 	处理批量导入(批量回款)
	 * 
	 * 
	 */
	@RequestMapping(value ="/batchImport",method = RequestMethod.POST)
	public Result batchImport(){
		LoggerUtils.debug(getClass(), "=========================开始批量导入===================");
		Result res = new Result();
		int i=0;
		i=orderReceivablesService.batchImport();
		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批量导入回款
     * 
     * @param response
     * @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;
    }
    
    /**
	 * 	导出回款
     * 
     * @param response
     * @return
     */
    @RequestMapping(value = "/exportReceivables" , method = RequestMethod.GET)
    public Result exportReceivables(HttpServletResponse response,OrderListBo o,Integer pageSize ,Integer pageNo)  {
    	Result res=new Result();
			try {
				orderReceivablesService.exportReceivables( response, o,pageSize,pageNo);
			} catch (Exception e) {
				res.getError().add(buildError("格式不正确"));
				e.printStackTrace();
				return res;
			}
         res.data(1); 
    	return res;
    }
    
    /**
	 * 	导出开票
     * 
     * @param response
     * @return
     */
    @RequestMapping(value = "/exportInvoice" , method = RequestMethod.GET)
    public Result exportInvoice(HttpServletResponse response,String orderNo,Integer pageSize ,Integer pageNo)  {
    	Result res=new Result();
			try {
				orderReceivablesService.exportInvoice( response, orderNo,pageSize,pageNo);
			} catch (Exception e) {
				res.getError().add(buildError("格式不正确"));
				e.printStackTrace();
				return res;
			}
         res.data(1); 
    	return res;
    }
    /**
	 * 	导出流水
     * 
     * @param response
     * @return
     */
    @RequestMapping(value = "/exportMyBill" , method = RequestMethod.GET)
    public Result exportMyBill(HttpServletResponse response, TOrderBillNew billNew,Integer pageSize ,Integer pageNo)  {
    	Result res=new Result();
			try {
				orderReceivablesService.exportMyBill( response, billNew,pageSize,pageNo);
			} catch (Exception e) {
				res.getError().add(buildError("格式不正确"));
				e.printStackTrace();
				return res;
			}
         res.data(1); 
    	return res;
    }
}
