package com.xhpc.payment.controller;

import com.xhpc.common.api.UserTypeService;
import com.xhpc.common.core.annotation.NoRepeatSubmit;
import com.xhpc.common.core.constant.HttpStatus;
import com.xhpc.common.core.constant.StatusConstants;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.utils.StringUtils;
import com.xhpc.common.core.web.controller.BaseController;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.core.web.page.TableDataInfo;
import com.xhpc.common.log.annotation.Log;
import com.xhpc.common.log.enums.BusinessType;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.common.util.UserTypeUtil;
import com.xhpc.payment.domain.XhpcRefundAudit;
import com.xhpc.payment.service.IXhpcCommonPayment;
import com.xhpc.payment.service.IXhpcRefundOrderService;
import com.xhpc.system.api.model.LoginUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/refund/order")
@Api(value = "退款订单接口", tags = "退款订单接口")
public class XhpcRefundOrderController extends BaseController {

    @Autowired
    private IXhpcRefundOrderService iXhpcRefundOrderService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IXhpcCommonPayment xhpcCommonPayment;
    @Autowired
    private UserTypeService userTypeService;

    /**
     * 申请退款
     *
     * @return
     */
    @Log(title = "申请退款", businessType = BusinessType.INSERT)
    @NoRepeatSubmit
    @PostMapping("/checkOut")
    @ApiOperation(value = "申请退款")
    public AjaxResult enterpriseCheckOut(HttpServletRequest request, @RequestBody Map<String, Object> map) {

        LoginUser loginUser = tokenService.getLoginUser(request);
        Long userid = loginUser.getUserid();
        Integer userType = loginUser.getUserType();
        String tenantId = loginUser.getTenantId();
//        Long userid = 1L;
//        Integer userType =0;
//        String tenantId = "000000";
        if (UserTypeUtil.CUSTOMERS_TYPE.equals(userType)) {
            return AjaxResult.error(HttpStatus.ERROR_STATUS, "大客户不支持退款");
        }
        String amount = StringUtils.valueOf(map.get("amount"));
        String type = StringUtils.valueOf(map.get("type"));
        if (StringUtils.isEmpty(amount)) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "退款金额不能为空");
        } else {
            if("1".equals(type)){
                if (new BigDecimal(0.3).compareTo(new BigDecimal(amount)) == 1) {
                    return AjaxResult.error(HttpStatus.NOT_NULL, "微信平台规定退款金额不能少于0.3元");
                }
            }
        }
        //用户信息id
        String userId = StringUtils.valueOf(map.get("userId"));
        if (StringUtils.isEmpty(userId)) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "用户信息不能为空");
        }
        //openid
        String openid = StringUtils.valueOf(map.get("openid"));
        if (StringUtils.isEmpty(userId)) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "用户信息不能为空");
        }

        if (StringUtils.isEmpty(type)) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "退款渠道不能为空");
        }
        //是否有实时数据
        int i = iXhpcRefundOrderService.countXhpcRealTimeOrder(userid, userType, tenantId);
        if (i > 0) {
            return AjaxResult.error(1103, "车辆正在充电,不能退款");
        }
        // 是否有异常订单
        int j = iXhpcRefundOrderService.countXhpcChargeOrder(userid, userType, tenantId);
        if (j > 0) {
            return AjaxResult.error(1103, "你有异常订单未解决，请拨打客服电话进行解决");
        }
        //生成退款订单
        String orderOutNumber = StringUtils.numFormat(userid, Integer.parseInt(type),
                StatusConstants.FLOWING_WATER_REFUND_TYPE);
        String remark = StringUtils.valueOf(map.get("remark"));
        return iXhpcRefundOrderService.addRefundOrder("" + userid, BigDecimal.valueOf(Double.parseDouble(amount)), type,
                orderOutNumber, openid, remark, userType, tenantId);
    }

    /**
     * 退款订单详情
     *
     * @param refundOrderId
     * @return
     */
    @GetMapping("/info")
    @ApiOperation(value = "退款订单详情")
    public AjaxResult info(@RequestParam Long refundOrderId) {
        return AjaxResult.success(iXhpcRefundOrderService.info(refundOrderId));
    }

    /**
     * 通过用户id查询未完成退款订单
     *
     * @param userId
     * @return
     */
    @GetMapping("/getNotRefundOrder")
    @ApiOperation(value = "用户id查询未完成退款订单")
    public AjaxResult getNotRefundOrder(HttpServletRequest request, @RequestParam Long userId) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        Long userid = loginUser.getUserid();
        Integer userType = loginUser.getUserType();
        String tenantId = loginUser.getTenantId();
        return AjaxResult.success(iXhpcRefundOrderService.getNotRefundOrder(userid,userType,tenantId));
    }

    /**
     * 退款订单页列表
     */
    //@PreAuthorize(hasPermi = "refund:order:page")
    @GetMapping("/page")
    public TableDataInfo page(String phone, String refundOrderNumber, String status, String createTimeStart, String createTimeEnd,Integer type,Integer source,Integer userId) {
        startPage();
        List<Map<String, Object>> list = iXhpcRefundOrderService.page(phone, refundOrderNumber, status, createTimeStart, createTimeEnd,type,source,userId);
        return getDataTable(list);
    }



    @PostMapping("/export")
    public void export(HttpServletResponse response,
                       String phone,
                       String refundOrderNumber,
                       String status,
                       String createTimeStart,
                       String createTimeEnd,
                       Integer type,
                       Integer source,
                       Integer userId) throws IOException {
        iXhpcRefundOrderService.export(response, phone, refundOrderNumber, status, createTimeStart, createTimeEnd,type,source,userId);

    }


    /**
     * 统计
     */
    @GetMapping("/sumMoney")
    @ApiOperation(value = "退款统计订单")
    public AjaxResult sumMoney(String phone, String refundOrderNumber, String status, String createTimeStart, String createTimeEnd,Integer type) {
        return AjaxResult.success(iXhpcRefundOrderService.sumMoney(phone, refundOrderNumber, status, createTimeStart, createTimeEnd,type));
    }

    @GetMapping("/sumUserMoney")
    @ApiOperation(value = "退款统计订单")
    public AjaxResult sumUserMoney(String phone, String refundOrderNumber, String status, String createTimeStart, String createTimeEnd,Integer type,Integer userId) {
        return AjaxResult.success(iXhpcRefundOrderService.sumUserMoney(phone, refundOrderNumber, status, createTimeStart, createTimeEnd,type,userId));
    }
    /**
     * 自动申请退款
     */
    @GetMapping("/orderCheckOut")
    @ApiOperation(value = "订单自动退款")
    public R orderCheckOut(@RequestParam(value = "amount") String amount,@RequestParam(value = "openid") String openid,@RequestParam(value = "source") Integer source,@RequestParam(value = "type") String type,@RequestParam(value = "userId") String userId,@RequestParam(value = "tenantId")String tenantId,@RequestParam(value = "remark")String remark) {
        logger.info("-------------");
        logger.info("进入自动申请退款");
        logger.info("-------------");
        if (UserTypeUtil.CUSTOMERS_TYPE.equals(source)) {
            return R.fail("大客户不支持退款");
        }
        if (StringUtils.isEmpty(amount)) {
            return R.fail("退款金额不能为空");
        } else {
            if (new BigDecimal(0.3).compareTo(new BigDecimal(amount)) == 1) {
                return R.fail("退款金额不能少于0.3元");
            }
        }
        //用户信息id
        if (StringUtils.isEmpty(userId)) {
            return R.fail("用户信息不能为空");
        }
        //openid
        if (StringUtils.isEmpty(userId)) {
            return R.fail("用户信息不能为空");
        }
        if (StringUtils.isEmpty(type)) {
            return R.fail("退款渠道不能为空");
        }
        //是否有实时数据
        Long userid = Long.valueOf(userId);
        // 是否有异常订单
        int j = iXhpcRefundOrderService.countXhpcChargeOrder(userid, source, tenantId);
        if (j > 0) {
            return R.fail("你有异常订单未解决，请拨打客服电话进行解决");
        }
        //生成退款订单
        String orderOutNumber = StringUtils.numFormat(userid, Integer.parseInt(type),
                StatusConstants.FLOWING_WATER_REFUND_TYPE);

        AjaxResult ajaxResult = iXhpcRefundOrderService.addRefundOrder("" + userid, BigDecimal.valueOf(Double.parseDouble(amount)), type,
                orderOutNumber, openid, remark, source, tenantId);
        if("200".equals(ajaxResult.get("code"))){
            return R.ok();
        }else{
            return R.fail(ajaxResult.get("msg"));
        }
    }

     @Scheduled(cron = "0 0/5 * * * ? ")
    public void administratorReview(){
        logger.info("++++++++++++每5分，扫描一次，在管理员审核状态中，用户金额为0时，去掉该记录++++++++++++++++");
        try {
            List<Map<String, Object>> list = iXhpcRefundOrderService.administratorReview();
            if(list !=null && list.size()>0){
                for (int i = 0; i <list.size() ; i++) {
                    Map<String, Object> map = list.get(i);
                    if(map.get("balance") !=null && new BigDecimal(0).compareTo(new BigDecimal(map.get("balance").toString()))==0){
                        iXhpcRefundOrderService.updateXhpcRefundOrder(Long.valueOf(map.get("refundOrderId").toString()));
                    }else if(new BigDecimal(0).compareTo(new BigDecimal(map.get("balance").toString()))< 0){
                        //修改请求数据
                        iXhpcRefundOrderService.updateXhpcRefundOrderBalance(Long.valueOf(map.get("refundOrderId").toString()),map.get("balance").toString());
                    }
                }
            }
        }catch (Exception e){
            logger.info("++++++++++++管理员审核异常++++++++++++++++");
            e.printStackTrace();
            //后期可以增加短信通知
        }
    }

    //没在充电中、异常订单
    //没十分钟查询一下，审核失败的订单，当用户有金额时，且对应不上，订单删除，生成新的订单
    //金额对应的上，重新审核
    @Scheduled(cron = "0 0/10 * * * ? ")
    public void abnormalPaymentOrder(){
        logger.info("++++++++++++每5分，扫描一次，在管理员审核状态中，用户金额为0时，去掉该记录++++++++++++++++");
        try {
            List<Map<String, Object>> list = iXhpcRefundOrderService.administratorReview();
            if(list !=null && list.size()>0){
                for (int i = 0; i <list.size() ; i++) {
                    Map<String, Object> map = list.get(i);
                    if(map.get("balance") !=null && new BigDecimal(0).compareTo(new BigDecimal(map.get("balance").toString()))==0){
                        iXhpcRefundOrderService.updateXhpcRefundOrder(Long.valueOf(map.get("refundOrderId").toString()));
                    }
                }
            }
        }catch (Exception e){
            logger.info("++++++++++++管理员审核异常++++++++++++++++");
            e.printStackTrace();
            //后期可以增加短信通知
        }
    }






    /**
     * 云快充充电完成自动退款
     */
    @GetMapping("/cycOrderCheckOut")
    @ApiOperation(value = "云快充充电完成自动退款")
    public AjaxResult cycOrderCheckOut(@RequestParam(value = "amount") String amount,@RequestParam(value = "source") Integer source,@RequestParam(value = "userId") String userId,@RequestParam(value = "tenantId")String tenantId){
        if (UserTypeUtil.CUSTOMERS_TYPE.equals(source)) {
            return AjaxResult.error("大客户不支持退款");
        }
        if (StringUtils.isEmpty(amount)) {
            return AjaxResult.error("退款金额不能为空");
        } else {
            if (new BigDecimal(0.3).compareTo(new BigDecimal(amount)) == 1) {
                return AjaxResult.error("退款金额不能少于0.3元");
            }
        }
        //用户信息id
        if (StringUtils.isEmpty(userId)) {
            return AjaxResult.error("用户信息不能为空");
        }
        //openid
        if (StringUtils.isEmpty(userId)) {
            return AjaxResult.error("用户信息不能为空");
        }
        //是否有实时数据
        Long userid = Long.valueOf(userId);
        // 是否有异常订单
        int j = iXhpcRefundOrderService.countXhpcChargeOrder(userid, source, tenantId);
        if (j > 0) {
            return AjaxResult.error("你有异常订单未解决，请拨打客服电话进行解决");
        }

        //生成退款订单
        String orderOutNumber = StringUtils.numFormat(userid, 1,
                StatusConstants.FLOWING_WATER_REFUND_TYPE);

        AjaxResult ajaxResult = iXhpcRefundOrderService.addCycRefundOrder("" + userid, BigDecimal.valueOf(Double.parseDouble(amount)), "0", orderOutNumber,source, tenantId);
        return ajaxResult;
    }


}
