package com.ghy.web.controller.order;

import com.ghy.common.core.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.utils.StringUtils;
import com.ghy.customer.domain.Customer;
import com.ghy.customer.service.CustomerService;
import com.ghy.goods.service.GoodsService;
import com.ghy.order.domain.OrderMaster;
import com.ghy.order.request.AppOrderRequest;
import com.ghy.order.service.OrderDetailService;
import com.ghy.order.service.OrderMasterService;
import com.ghy.payment.service.FinancialDetailService;
import com.ghy.payment.service.FinancialMasterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author clunt
 * 下单接口
 */
@Controller
@RequestMapping("/order")
public class OrderController extends BaseController {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderMasterService orderMasterService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private FinancialMasterService financialMasterService;

    @Autowired
    private FinancialDetailService financialDetailService;


    @PostMapping("/server/app")
    @ResponseBody
    public AjaxResult appOrder(@RequestBody AppOrderRequest appOrderRequest){
        // 校验用户信息
        Customer customer = customerService.selectByCustomerId(appOrderRequest.getCustomerId());
        if(StringUtils.isNull(customer)){
            return AjaxResult.error("用户不存在!");
        }
        // 校验商品信息(库存)
        boolean flag = goodsService.checkStore(appOrderRequest.getGoodsList());
        if(!flag){
            return AjaxResult.error("库存不足!");
        }
        // 计算商品费用
        BigDecimal totalPay = goodsService.calculate(appOrderRequest.getGoodsList());
        // 生成主单
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setCode(orderMasterService.createOrderCode());
        orderMaster.setOrderType(1);
        orderMaster.setOrderStatus(0);
        orderMaster.setCustomerId(appOrderRequest.getCustomerId());
        orderMaster.setPayStatus(0);
        orderMaster.setCreateTime(new Date());
        orderMasterService.insertOrderMaster(orderMaster);
        //TODO 生成财务主单

        //TODO 生成细单

        //TODO 生成财务细单(含分销等.)

        return AjaxResult.success(orderMaster);
    }

}
