package cn.quantgroup.customer.rest;

import cn.quantgroup.customer.aop.OperateLog;
import cn.quantgroup.customer.rest.param.vcc.OfflineRepaySubmitParam;
import cn.quantgroup.customer.rest.param.vcc.UserPreRepayInfoQuery;
import cn.quantgroup.customer.rest.vo.JsonResult;
import cn.quantgroup.customer.service.IVccService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/vcc")
public class VccRest {

    @Autowired
    private IVccService vccService;

    /**
     * 查询用户的待还款信息
     * @param query
     * @return
     */
    @PostMapping("/offline_pre_repay/query_page")
    @OperateLog(moduleName = "查询用户的待还款信息")
    public JsonResult queryPage(@RequestBody @Valid UserPreRepayInfoQuery query, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return JsonResult.buildErrorStateResult(bindingResult.getFieldError().getField() + ":" + bindingResult.getFieldError().getDefaultMessage());
        }
        log.info("queryPage | 开始用户待还款查询，param={}",query);
        if (StringUtils.isBlank(query.getBillId()) && StringUtils.isBlank(query.getPhone())
         && StringUtils.isBlank(query.getUserId()) && StringUtils.isBlank(query.getOrderNo())){
            log.error("queryPage | 请求参数userId，phone，billId，orderNo不能同时为空");
            return JsonResult.buildErrorStateResult("请求参数userId，phone，billId，orderNo不能同时为空");
        }
        try {
            JsonResult jsonResult = vccService.queryPage(query);
            log.info("queryPage | 结束用户待还款查询，param={}",query);
            return jsonResult;
        } catch (Exception e){
            log.error("queryPage | 用户待还款查询发生异常",e);
            return JsonResult.buildErrorStateResult("用户待还款查询发生异常:"+ e.getMessage());
        }
    }

    /**
     * 查询分期账单的详情
     * @param uniqueId
     * @param repayType
     * @return
     */
    @GetMapping("/pre_repay_cal/detail")
    @OperateLog(moduleName = "查询分期账单的详情")
    public JsonResult repayPlanDetail(@NotNull String uniqueId,@NotNull Integer repayType){
        log.info("repayPlanDetail | 查询用户分期的详情及试算详情，uniqueId={},repayType={}",uniqueId,repayType);
        try {
            JsonResult jsonResult = vccService.queryRepayCalDetail(uniqueId,repayType);
            log.info("repayPlanDetail | 结束查询用户分期的详情及试算详情，uniqueId={},repayType={}",uniqueId,repayType);
            return jsonResult;
        } catch (Exception e){
            log.error("repayPlanDetail | 查询用户分期的详情及试算详情发生异常",e);
            return JsonResult.buildErrorStateResult("查询用户分期的详情及试算详情发生异常:"+e.getMessage());
        }
    }

    /**
     * 保存线下还款的申请记录
     * @param request
     * @param param
     * @return
     */
    @PostMapping("/offline_repay/save_submit")
    @OperateLog(moduleName = "保存线下还款的申请记录")
    public JsonResult saveSubmit(HttpServletRequest request, @RequestBody@Valid OfflineRepaySubmitParam param,BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return JsonResult.buildErrorStateResult(bindingResult.getFieldError().getField() + ":" + bindingResult.getFieldError().getDefaultMessage());
        }
        if (param.getRepayType() == 1){
            if (CollectionUtils.isEmpty(param.getList())){
                return JsonResult.buildErrorStateResult("还款月还账单时，账单不能为空");
            }
        }else {
            if (StringUtils.isBlank(param.getUniqueId())){
                return JsonResult.buildErrorStateResult("提前结清时单号不能为空");
            }
            if (Objects.isNull(param.getCurrTerm())){
                return JsonResult.buildErrorStateResult("提前结清开始期数不能为空");
            }
        }

        log.info("saveSubmit | 开始保存线下还款的申请记录,param={}",param);
        try {
            String token = request.getHeader("x-auth-token");
            vccService.saveSubmitRecord(param,token);
            log.info("saveSubmit | 保存线下还款的申请记录成功,param={}",param);
            return JsonResult.buildSuccessResult("请求成功",null);
        } catch (Exception e){
            log.error("saveSubmit | 保存线下还款提交申请时发生异常",e);
            return JsonResult.buildErrorStateResult("保存线下还款提交申请时发生异常:"+e.getMessage());
        }
    }

    /**
     * 审批回显提交的线下还款申请记录
     * @param serialNo
     * @return
     */
    @GetMapping("/offline_repay/approval")
    @OperateLog(moduleName = "审批回显提交的线下还款申请记录")
    public JsonResult approval(@NotNull String serialNo){
        log.info("approval | 开始点击审批按钮查询信息，serialNo={}",serialNo);
        try {
            OfflineRepaySubmitParam param = vccService.approvalQuery(serialNo);
            log.info("approval | 点击审批按钮查询信息成功，serialNo={}",serialNo);
            return JsonResult.buildSuccessResult("请求成功",param);
        } catch (Exception e){
            log.error("approval | 点击审批按钮查询信息时发生异常",e);
            return JsonResult.buildErrorStateResult("点击审批按钮查询信息时发生异常:",e.getMessage());
        }
    }

    /**
     * 查看审批流水记录
     * @param serialNo
     * @return
     */
    @GetMapping("/approval/detail")
    @OperateLog(moduleName = "查看审批流水记录")
    public JsonResult queryApprovalRecord(@NotNull String serialNo){
        log.info("queryApprovalRecord | 开始查看审批流水记录,serialNo={}",serialNo);
        try {
            JsonResult jsonResult = vccService.queryApprovalRecord(serialNo);
            log.info("queryApprovalRecord | 查看审批流水记录成功,serialNo={}",serialNo);
            return jsonResult;
        } catch (Exception e){
            log.error("queryApprovalRecord | 查询审批流水时发生异常",e);
            return JsonResult.buildErrorStateResult("查询审批流水时发生异常:"+e.getMessage());
        }
    }

    /**
     * 审批结果：通过/拒绝
     * @param request
     * @param serialNo
     * @param remark
     * @param status
     * @return
     */
    @GetMapping("/approval/result")
    @OperateLog(moduleName = "审批结果：通过/拒绝")
    public JsonResult approvalResult(HttpServletRequest request,@NotNull String serialNo,String remark,@NotNull Integer status){
        log.info("approvalResult | 开始提交审批结果,serialNo={},remark={},status={}",serialNo,remark,status);
        try {
            String token = request.getHeader("x-auth-token");
            vccService.approvalResult(serialNo,remark,status,token);
            log.info("approvalResult | 提交审批结果成功,serialNo={},remark={},status={}",serialNo,remark,status);
            return JsonResult.buildSuccessResult("请求成功",null);
        }catch (Exception e){
            log.error("approvalResult | 通过/拒绝审批时发生异常",e);
            return JsonResult.buildErrorStateResult("通过/拒绝审批时发生异常:"+ e.getMessage());
        }
    }

    /**
     * 上传打款凭证
     * @param file
     * @return
     */
    @PostMapping("/offline_repay_file/upload")
    @OperateLog(moduleName = "上传打款凭证")
    public JsonResult fileUpload (MultipartFile file){
        log.info("fileUpload | 开始上传打款凭证");
        try {
            Map<String, String> map = vccService.fileUpload(file);
            log.info("fileUpload | 上传打款凭证成功map={}",map);
            return JsonResult.buildSuccessResult("请求成功",map);
        }catch (Exception e){
            log.error("fileUpload | 文件上传时发生异常",e);
            return JsonResult.buildErrorStateResult("文件上传时发生异常:"+e.getMessage());
        }
    }

    /**
     * 查询线下还款的申请记录
     * @param query
     * @return
     */
    @PostMapping("/approval/query_applly_record")
    @OperateLog(moduleName = "查询线下还款的申请记录")
    public JsonResult queryApplyRecord(@RequestBody@Valid UserPreRepayInfoQuery query,BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return JsonResult.buildErrorStateResult(bindingResult.getFieldError().getField() + ":" + bindingResult.getFieldError().getDefaultMessage());
        }
        if (StringUtils.isBlank(query.getBillId()) && StringUtils.isBlank(query.getPhone())
                && StringUtils.isBlank(query.getUserId()) && StringUtils.isBlank(query.getOrderNo())){
            log.error("queryPage | 请求参数userId，phone，billId，orderNo不能同时为空");
            return JsonResult.buildErrorStateResult("请求参数userId，phone，billId，orderNo不能同时为空");
        }
        log.info("queryApplyRecord | 开始查看线下还款的申请记录,param={}",query);
        try {
            JsonResult jsonResult = vccService.queryApplyRecord(query);
            log.info("queryApplyRecord | 查看线下还款的申请记录成功,param={}",query);
            return jsonResult;
        }catch (Exception e){
            log.error("queryApplyRecord | 查询线下还款申请记录时发生异常",e);
            return JsonResult.buildErrorStateResult("查询线下还款申请记录时发生异常:"+e.getMessage());
        }
    }
}
