package com.fs.app.controller.store;


import com.fs.app.annotation.Login;
import com.fs.app.controller.AppBaseController;
import com.fs.common.core.domain.R;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyUserService;
import com.fs.hisStore.domain.FsStoreOrderScrm;
import com.fs.hisStore.enums.OrderLogEnum;
import com.fs.hisStore.param.FsStoreOrderMoneyByProductParam;
import com.fs.hisStore.param.FsStoreProductQueryParam;
import com.fs.hisStore.service.IFsStoreOrderScrmService;
import com.fs.hisStore.service.IFsStoreOrderStatusScrmService;
import com.fs.hisStore.service.IFsStoreProductScrmService;
import com.fs.hisStore.vo.FsStoreProductListQueryVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Api("销售订单")
@RestController
@RequestMapping(value="/store/app/companyOrder")
public class CompanyOrderScrmController extends AppBaseController {
    @Autowired
    private IFsStoreOrderScrmService orderService;
    @Autowired
    private ICompanyUserService companyUserService;
    @Autowired
    private IFsStoreProductScrmService productService;
    @Autowired
    private IFsStoreOrderStatusScrmService orderStatusService;

    @ApiOperation("获取商品列表")
    @GetMapping("/getSalesProducts")
    public R getSalesProducts(FsStoreProductQueryParam param, HttpServletRequest request){
        // 所属企业过滤
        Long userId = redisCache.getCacheObject("company-user-token:"+param.getToken());
        CompanyUser companyUser = companyUserService.selectCompanyUserById(userId);
        if (Objects.isNull(companyUser)){
            return R.ok().put("data", new ArrayList<>());
        }
        param.setCompanyId(companyUser.getCompanyId());

        PageHelper.startPage(param.getPage(), param.getPageSize());
        param.setIsDisplay(0);
        List<FsStoreProductListQueryVO> productList=productService.selectFsStoreProductListQuery(param);
        PageInfo<FsStoreProductListQueryVO> listPageInfo=new PageInfo<>(productList);
        return R.ok().put("data",listPageInfo);
    }

    @Login
    @ApiOperation("制单")
    @GetMapping("/createSalesOrder")
    public R createSalesOrder(@RequestParam("token")String token,
                              @RequestParam(value = "cateIds", required = false)String cateIds,
                              @RequestParam(value = "orderType",required = false)Integer orderType,
                              @RequestParam(value = "orderMedium",required = false)Integer orderMedium,
                              @RequestParam(value = "isPackage", required = false, defaultValue = "0")Integer isPackage,
                              @RequestParam(value = "packageId", required = false)String packageId,
                              HttpServletRequest request){
        Long userId=redisCache.getCacheObject("company-user-token:"+token);
        if(userId==null){
            return R.error(403,"用户失效");
        }
        CompanyUser companyUser=companyUserService.selectCompanyUserById(userId);
        if(companyUser==null||companyUser.getDelFlag().equals("1")){
            return R.error("用户不存在");
        }
        if(!companyUser.getStatus().equals("0")){
            return R.error("用户已禁用");
        }
        if(isPackage == 0){
            return orderService.createSalesOrder(companyUser,cateIds,orderType,orderMedium);
        } else if(isPackage == 1){
            // 套餐包制单
            if (packageId == null){
                return R.error("套餐包ID不能为空");
            }
            return orderService.createPackageSalesOrder(companyUser,packageId,orderType,orderMedium);
        } else {
            return R.error("参数错误");
        }

    }

    @ApiOperation("改价")
    @GetMapping("/updateSalseOrderMoney")
    public R updateSalseOrderMoney(@RequestParam("token")String token,
                                   @RequestParam("createOrderKey")String createOrderKey,
                                   @RequestParam(value = "money",required = false) BigDecimal money,
                                   @RequestParam(value = "payAmount",required = false) BigDecimal payAmount,
                                   @RequestParam(value = "payType",required = false) Integer payType,
                                   @RequestParam(value = "isPackage",required = false,defaultValue = "0")Integer isPackage,
                                   HttpServletRequest request){
        Long userId=redisCache.getCacheObject("company-user-token:"+token);
        if(userId==null){
            return R.error(403,"用户失效");
        }
        if (money == null){
            money = BigDecimal.ZERO;
        }
        if (payAmount == null){
            payAmount = BigDecimal.ZERO;
        }
        return orderService.updateSalseOrderMoney(createOrderKey,money,payAmount,payType, isPackage);
    }

    @ApiOperation("商品改价")
    @PostMapping("/updateSalesOrderMoneyByProduct")
    public R updateSalesOrderMoneyByProduct(@RequestBody FsStoreOrderMoneyByProductParam param){
        Long userId=redisCache.getCacheObject("company-user-token:"+param.getToken());
        if(userId==null){
            return R.error(403,"用户失效");
        }

        return orderService.updateSalesOrderMoneyByProduct(param);
    }


    @ApiOperation("获取订单")
    @GetMapping("/getSalesOrder")
    public R getSalesOrder(@RequestParam("createOrderKey")String createOrderKey, HttpServletRequest request){
        return orderService.getSalesOrder(createOrderKey);
    }
    @Login
    @ApiOperation("添加用户购物车")
    @GetMapping("/addUserCart")
    public R addUserCart(@RequestParam("createOrderKey")String createOrderKey, HttpServletRequest request){
        return orderService.addUserCart(Long.parseLong(getUserId()),createOrderKey);
    }


    @ApiOperation("改订单价格")
    @GetMapping("/editOrderMoney")
    @Transactional
    public R editOrderMoney(@RequestParam("token")String token,@RequestParam("orderId")Long orderId, @RequestParam("money") BigDecimal money, HttpServletRequest request){
        Long userId=redisCache.getCacheObject("company-user-token:"+token);
        if(userId==null){
            return R.error(403,"用户失效");
        }
        FsStoreOrderScrm order=orderService.selectFsStoreOrderById(orderId);
        if(order.getStatus().equals(0)){
            if(money.compareTo(order.getPayPrice())>0){
                return R.error("金额不能超过订单金额");
            }
            if(money.compareTo(BigDecimal.ZERO)<0){
                return R.error("金额必须大于等于0");
            }
            FsStoreOrderScrm orderMap=new FsStoreOrderScrm();
            orderMap.setId(orderId);
            orderMap.setPayMoney(money);
            orderMap.setPayDelivery(order.getPayPrice().subtract(money));
            if(orderMap.getPayMoney().compareTo(BigDecimal.ZERO)>0&&orderMap.getPayDelivery().compareTo(BigDecimal.ZERO)>0){
                orderMap.setPayType("2");
            }
            else if(orderMap.getPayMoney().compareTo(BigDecimal.ZERO)>0&&orderMap.getPayDelivery().compareTo(BigDecimal.ZERO)==0){
                orderMap.setPayType("1");
            }
            else if(orderMap.getPayMoney().compareTo(BigDecimal.ZERO)==0&&orderMap.getPayDelivery().compareTo(BigDecimal.ZERO)>0){
                orderMap.setPayType("3");
            }
            orderMap.setIsEditMoney(1);
            orderService.updateFsStoreOrder(orderMap);
            orderStatusService.create(orderId, OrderLogEnum.EDIT_ORDER_PRICE.getValue(),
                    OrderLogEnum.EDIT_ORDER_PRICE.getDesc());
            return R.ok("改价成功");
        }
        else{
            return R.error("非法操作");
        }

    }
}
