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.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.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();
        if (UserTypeUtil.CUSTOMERS_TYPE.equals(userType)) {
            return AjaxResult.error(HttpStatus.ERROR_STATUS, "大客户不支持退款");
        }
        String amount = StringUtils.valueOf(map.get("amount"));
        if (StringUtils.isEmpty(amount)) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "退款金额不能为空");
        } else {
            if (new BigDecimal(1).compareTo(new BigDecimal(amount)) == 1) {
                return AjaxResult.error(HttpStatus.NOT_NULL, "退款金额不能少于1元");
            }
        }
        //用户信息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, "用户信息不能为空");
        }
        String type = StringUtils.valueOf(map.get("type"));
        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("/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(1).compareTo(new BigDecimal(amount)) == 1) {
                return R.fail("退款金额不能少于1元");
            }
        }
        //用户信息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"));
        }
    }





}
