package com.org.hktshop.controller.order;

import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.org.hktshop.base.BaseResult;
import com.org.hktshop.controller.BaseController;
import com.org.hktshop.controller.pay.AlipayController;
import com.org.hktshop.controller.pay.WxpayController;
import com.org.hktshop.entity.Page;
import com.org.hktshop.entity.order.HktOrder;
import com.org.hktshop.entity.order.HktOrderRefund;
import com.org.hktshop.entity.user.HktUser;
import com.org.hktshop.service.aliyun.AliyunSmsService;
import com.org.hktshop.service.order.HktOrderRefundService;
import com.org.hktshop.service.order.HktOrderService;
import com.org.hktshop.utils.DateUtil;
import com.org.hktshop.utils.HttpCode;
import com.org.hktshop.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hotking03
 */
@RestController
@RequestMapping("/refund")
public class HktOrderRefundController extends BaseController {
    @Autowired
    private AlipayController alipayController;

    @Autowired
    private HktOrderService hktOrderService;

    @Autowired
    private WxpayController wxpayController;

    @Autowired
    private HktOrderRefundService hktOrderRefundService;

    @Autowired
    private AliyunSmsService aliyunSmsService;

    @Value("${refund_mobile}")
    private String refundMobile;

    @PostMapping("/applyOrderRefund")
    @ApiOperation(value = "申请退款订单", notes = "申请退款订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "outTrandeNo", value = "订单编号", required = true),
            @ApiImplicitParam(name = "refundMsg", value = "退款原因"),
            @ApiImplicitParam(name = "refundAmount", value = "退款金额", required = true),
            @ApiImplicitParam(name = "code", value = "验证码", required = true)
    })
    public Object applyOrderRefund(HttpServletRequest request, @RequestBody HktOrderRefund hktOrderRefund) {
          try {

              QuerySendDetailsResponse querySendDetailsResponse = aliyunSmsService.querySendDetails(refundMobile);
              String code = aliyunSmsService.queryCode(querySendDetailsResponse);

              if(StringUtils.isNull(hktOrderRefund.getCode())){
                  return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"验证码不能为空");
              }

              if(!code.equalsIgnoreCase(hktOrderRefund.getCode())){
                  return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"验证码错误");
              }

//              HktUser user = (HktUser) request.getSession().getAttribute("OpUser");
              if(StringUtils.isNull(hktOrderRefund.getOutTrandeNo())){
                  return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"订单号不能为空");
              }

              if(StringUtils.isNull(hktOrderRefund.getRefundAmount())){
                  return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"退款金额不能为空");
              }
              HktOrder findOrder = new HktOrder();
              findOrder.setOutTrandeNo(hktOrderRefund.getOutTrandeNo());
              HktOrder hktOrder = hktOrderService.getHktOrder(findOrder);
              if(hktOrder == null){
                  return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"不存在的订单号");
              }
              if(!"2".equals(hktOrder.getPayStatus())){
                  return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"该订单不能申请退款");
              }
              if(!"0".equals(hktOrder.getReturnStatus())){
                  return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"该订单已退款，不能重复退款");
              }
              if(hktOrderRefund.getRefundAmount() > (Double.parseDouble(hktOrder.getTotalAmount()) - Double.parseDouble(hktOrder.getShippingPrice()))){
                  return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"退款金额不能大于订单金额");
              }
              hktOrderRefund.setCreateTime(DateUtil.getDateTime());
//              hktOrderRefund.setUserId(user.getId());
              hktOrderRefund.setOutRefundNo(StringUtils.getUUID().replace("-",""));
              hktOrderRefund.setTotalAmount(Double.parseDouble(hktOrder.getTotalAmount()));
              hktOrderRefund.setOrderId(hktOrder.getId());
              hktOrderRefund.setTrandeNo(hktOrder.getOrderSn());
              hktOrderRefund.setUserId(hktOrder.getUserId());
              if("微信".equals(hktOrder.getPayName())){
                  wxpayController.wxPayRefund(hktOrderRefund);
              }else {
                  alipayController.appliyRefund(hktOrderRefund);
              }
              return BaseResult.success();
          }catch (Exception e){
              logger.info("退款订单错误：error={}",e.toString());
              return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMsg());
          }
    }


    @PostMapping("/queryList")
    @ApiOperation(value = "申请退款订单", notes = "申请退款订单")
    public Object queryListByPage(@RequestBody HktOrderRefund hktOrderRefund) {
        try {
            Page<HktOrderRefund> page = hktOrderRefundService.queryListByPage(hktOrderRefund);
            return BaseResult.successWithData(page);
        }catch (Exception e){
            logger.info("退款订单列表查询：error={}",e.toString());
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMsg());
        }
    }

    @PostMapping("/sendSMS")
    @ApiOperation(value = "发送验证码", notes = "发送验证码")
    public BaseResult sendSms() {
        try {
            boolean flag = aliyunSmsService.sendSms(refundMobile, null, null);
            if (flag) {
                return BaseResult.success();
            }
        } catch (Exception e) {
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode());
        }
        return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode());
    }

    @PostMapping("/refundOrder")
    @ApiOperation(value = "申请退款订单", notes = "申请退款订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "outTrandeNo", value = "订单编号", required = true),
            @ApiImplicitParam(name = "code", value = "验证码", required = true),
            @ApiImplicitParam(name = "refundMsg", value = "退款原因")
    })
    public Object refundOrder(@RequestBody HktOrderRefund hktOrderRefund) {
        try {

            QuerySendDetailsResponse querySendDetailsResponse = aliyunSmsService.querySendDetails(refundMobile);
            String code = aliyunSmsService.queryCode(querySendDetailsResponse);

            if(StringUtils.isNull(hktOrderRefund.getCode())){
                return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"验证码不能为空");
            }

            if(!code.equalsIgnoreCase(hktOrderRefund.getCode())){
                return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"验证码错误");
            }

//              HktUser user = (HktUser) request.getSession().getAttribute("OpUser");
            if(StringUtils.isNull(hktOrderRefund.getOutTrandeNo())){
                return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"订单号不能为空");
            }

            HktOrder findOrder = new HktOrder();
            findOrder.setOrderSn(hktOrderRefund.getOutTrandeNo());
            HktOrder hktOrder = hktOrderService.getHktOrder(findOrder);
            findOrder.setId(hktOrder.getId());
            findOrder.setOrderStatus("4");
            findOrder.setReturnStatus("1");
            hktOrderService.updateHktOrder(findOrder);
            return BaseResult.success();
        }catch (Exception e){
            logger.info("退款订单错误：error={}",e.toString());
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMsg());
        }
    }


    @PostMapping("/updateReturnOrder")
    @ApiOperation(value = "修改退款订单", notes = "修改退款订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true)
    })
    public Object updateReturnOrder(@RequestBody HktOrderRefund hktOrderRefund) {
        try {
            hktOrderRefundService.updateReturnOrder(hktOrderRefund);
            return BaseResult.success();
        }catch (Exception e){
            logger.info("修改退款订单：error={}",e.toString());
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMsg());
        }
    }

    @PostMapping("/cusumerApply")
    @ApiOperation(value = "客户申请退款订单", notes = "客户申请退款订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "trandeNo", value = "订单编号", required = true)
    })
    public Object cusumerApply(@RequestBody HktOrderRefund hktOrderRefund) {
        try {
            hktOrderRefundService.cusumerApply(hktOrderRefund);
            return BaseResult.success();
        }catch (Exception e){
            logger.info("申请退款错误：error={}",e.toString());
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMsg());
        }
    }

}
