package com.app.controller.api;

import com.app.annotation.platform.OperationLog;
import com.app.dto.PageResult;
import com.app.dto.Result;
import com.app.dto.SearchDto;
import com.app.dto.SearchPageDto;
import com.app.dto.order.OpenCourseOrderDto;
import com.app.dto.order.operation.GenerateOrderDto;
import com.app.dto.wx.PrePayDto;
import com.app.entity.basics.OpenCourse;
import com.app.entity.order.OpenCourseShoppingCar;
import com.app.service.basics.OpenCourseService;
import com.app.service.order.OpenCourseOrderService;
import com.app.service.order.OpenCourseShoppingCarService;
import com.app.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.Optional;

@Api(description = "开课 - 订单")
@Slf4j
@Validated
@RestController("ApiOpenCourseOrderController")
@RequestMapping("/api/open-course-order")
public class OpenCourseOrderController {

    @Autowired
    private OpenCourseService openCourseService;

    @Autowired
    private OpenCourseShoppingCarService openCourseShoppingCarService;

    @Autowired
    private OpenCourseOrderService openCourseOrderService;

    @OperationLog("更新 - 生产选课单订单")
    @ApiOperation(value = "[选课单] - 生成订单")
    @PostMapping("/generate")
    public ResponseEntity<Result<OpenCourseOrderDto>> generate(@Valid @RequestBody GenerateOrderDto generateOrderDto) {
        String accountId = "";
        if (generateOrderDto.getOpenCourseIdList().size() == 0) {
            throw new RuntimeException("没有选中课程");
        }

        /* 判断[开课]是否满足条件 */
        for (String openCourseId : generateOrderDto.getOpenCourseIdList()) {
            Optional<OpenCourse> optional = openCourseService.findById(openCourseId);
            if (optional.isPresent()) {
                OpenCourse _openCourse = optional.get();
                if (!DateUtil.between(_openCourse.getSignUpStartTime(), _openCourse.getSignUpEndTime(), new Date()) || _openCourse.getFreeCourseNumber() <= 0) {
                    return new ResponseEntity(new Result().serverError("课程已过报名时间或名额已满"), HttpStatus.OK);
                }

                /* 校验当前[课程]是否在选课单上，[在]就不加入[选课单]、[不在]就加入[选课单] */
                if (generateOrderDto.getIsFast()) {
                    OpenCourseShoppingCar _car = openCourseShoppingCarService.find(openCourseId, accountId, generateOrderDto.getAccountChildId());
                    if(!Optional.ofNullable(_car).isPresent()) {
                        openCourseShoppingCarService.save(openCourseId, accountId, generateOrderDto.getAccountChildId());
                    }
                }
            }
        }

        return new ResponseEntity(new Result().ok(openCourseOrderService.generate(generateOrderDto, accountId)), HttpStatus.OK);
    }

    @ApiOperation(value = "订单-预支付[微信支付]")
    @PostMapping("/pre-pay")
    public ResponseEntity<Result<PrePayDto>> wxPrePay(HttpServletRequest request, @RequestBody SearchDto param) {
        String accountId = "";
        String openId = "";

        PrePayDto prePayDto = openCourseOrderService.payToStart(accountId, openId, param.getId());
        if (StringUtils.isEmpty(prePayDto.getPaySign())) {
            return new ResponseEntity(new Result().serverError(), HttpStatus.OK);
        } else {
            return new ResponseEntity(new Result().ok(prePayDto), HttpStatus.OK);
        }
    }

    @ApiOperation(value = "订单-免费支付[零元订单]")
    @PostMapping("/free-pre-pay")
    public ResponseEntity<Result<PrePayDto>> freePrePay(HttpServletRequest request, @RequestBody SearchDto param) {
        String accountId = "";
        String openId = "";

        PrePayDto prePayDto = openCourseOrderService.payToStart(accountId, openId, param.getId());
        if (StringUtils.isEmpty(prePayDto.getPaySign())) {
            return new ResponseEntity(new Result().serverError(), HttpStatus.OK);
        } else {
            return new ResponseEntity(new Result().ok(prePayDto), HttpStatus.OK);
        }
    }

    @ApiOperation(value = "查询[我的订单]")
    @PostMapping("/page")
    public ResponseEntity<Result<PageResult<OpenCourseOrderDto>>> page(@Valid @RequestBody SearchPageDto params) {
        String accountId = "";
        return new ResponseEntity(new Result().ok(openCourseOrderService.page(accountId, params.getPage(), params.getSize())), HttpStatus.OK);
    }

    @ApiOperation(value = "查询[我的订单]详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单标识", dataType = "String", paramType = "path", required = true, defaultValue = "")
    })
    @GetMapping("/{id}")
    public ResponseEntity<Result<OpenCourseOrderDto>> find(@NotBlank @PathVariable("id") String orderId) {
        String accountId = "";
        return new ResponseEntity(new Result().ok(openCourseOrderService.find(orderId, accountId)), HttpStatus.OK);
    }

    @OperationLog("删除 - 我的订单")
    @ApiOperation(value = "删除[我的订单]")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "id", value = "开课标识", dataType = "String", paramType = "path", required = true, defaultValue = "")
    )
    @DeleteMapping("/{id}")
    public ResponseEntity<Result> delete(@PathVariable("id") String id) {
        String accountId = "";
        // add by 梁展鹏 20200921 不知道为什么会有家长支付费用后，还会删除订单的操作!?!?!?
        // openCourseOrderService.delete(id, userDetails.getAccountId());
        return new ResponseEntity(new Result().ok(), HttpStatus.OK);
    }

}
