package com.fs.app.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.fs.app.annotation.Login;
import com.fs.common.annotation.DataScope;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyUserService;
import com.fs.store.config.StoreConfig;
import com.fs.store.domain.*;
import com.fs.store.dto.ExpressInfoDTO;
import com.fs.store.dto.StoreOrderProductDTO;
import com.fs.store.enums.OrderLogEnum;
import com.fs.store.enums.ShipperCodeEnum;
import com.fs.store.param.*;
import com.fs.store.service.*;
import com.fs.store.vo.*;
import com.fs.system.service.ISysConfigService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/app/storeOrder")
public class StoreOrderController extends AppBaseController
{

    @Autowired
    private ICompanyUserService companyUserService;
    @Autowired
    private IFsStoreOrderService fsStoreOrderService;
    @Autowired
    private IFsStoreOrderItemService orderItemService;

    @Autowired
    private IFsUserService userService;

    @Autowired
    private IFsStoreOrderStatusService orderStatusService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IFsStoreProductService productService;

    @Autowired
    private IFsStoreProductAttrService attrService;

    @Autowired
    private IFsStoreProductAttrValueService attrValueService;
    @Autowired
    private IFsStoreCartService cartService;

    /**
     * 查询订单列表
     */
    @Login
    @GetMapping("/getOrderList")
    @DataScope(deptAlias = "cu",userAlias = "cu")
    public R getOrderList(FsStoreOrderParam param)
    {
        Integer page=ServletUtils.getParameterToInt("page");
        Integer pageSize=ServletUtils.getParameterToInt("pageSize");
        PageHelper.startPage(page,pageSize);
        param.setCompanyId(getCompanyId());
        List<FsStoreOrderVO> list = fsStoreOrderService.selectFsStoreOrderListVO(param);
        PageInfo<FsStoreOrderVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    /**
     * 获取订单详细信息
     */
    @Login
    @GetMapping(value = "/getOrderById")
    public R getInfo(@RequestParam( value = "id") Long id)
    {
        FsStoreOrder order=fsStoreOrderService.selectFsStoreOrderById(id);
        FsUser user=userService.selectFsUserById(order.getUserId());
        FsStoreOrderItem itemMap=new FsStoreOrderItem();
        itemMap.setOrderId(order.getId());
        List<FsStoreOrderItem> items=orderItemService.selectFsStoreOrderItemList(itemMap);
        FsStoreOrderStatus statusMap=new FsStoreOrderStatus();
        statusMap.setOrderId(order.getId());
        List<FsStoreOrderStatus> logs=orderStatusService.selectFsStoreOrderStatusList(statusMap);
        String json=configService.selectConfigByKey("store.config");
        StoreConfig config= JSONUtil.toBean(json,StoreConfig.class);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(order.getCreateTime());
        calendar.add(Calendar.MINUTE,config.getUnPayTime());
        SimpleDateFormat format = new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String payLimitTime = format.format(calendar.getTime() );
        return R.ok().put("order", order).put("items", items).put("logs",logs).put("user",user).put("payLimitTime",payLimitTime) ;
    }



    @ApiOperation("获取商品列表")
    @GetMapping("/getSalesProducts")
    public R getSalesProducts(FsStoreProductQueryParam param, HttpServletRequest request){
        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);
    }


    @ApiOperation("获取商品详情")
    @GetMapping("/getProductDetails")
    public R getProductDetails(@RequestParam(value="productId") Long productId, HttpServletRequest request){
        FsStoreProductQueryVO product=productService.selectFsStoreProductByIdQuery(productId);
        if(product==null){
            return R.error("商品不存在或已下架");
        }

        List<FsStoreProductAttr> productAttr=attrService.selectFsStoreProductAttrByProductId(product.getProductId());
        List<FsStoreProductAttrValue> productValues=attrValueService.selectFsStoreProductAttrValueByProductId(product.getProductId());
        return R.ok().put("product",product).put("productAttr",productAttr).put("productValues",productValues);
    }

    @Login
    @ApiOperation("添加购物车")
    @PostMapping("/addCart")
    public R addCart(@Validated @RequestBody FsStoreCartParam cartParam, HttpServletRequest request){

        return cartService.addCart(getUserId(Long.parseLong(getUserId())),cartParam);
    }
    @Login
    @ApiOperation("获取购物车列表")
    @GetMapping("/getCarts")
    public R getCarts(HttpServletRequest request){
        List<FsStoreCartVO> carts= cartService.selectFsStoreCartListByUid(getUserId(Long.parseLong(getUserId())));
        return R.ok().put("carts",carts);
    }
    @Login
    @ApiOperation("改变购物车数量")
    @PostMapping("/cartNum")
    public R cartNum(@Validated @RequestBody FsStoreCartNumParam cartParam, HttpServletRequest request){
        return cartService.changeNum(getUserId(Long.parseLong(getUserId())),cartParam);
    }
    @Login
    @ApiOperation("删除购物车")
    @PostMapping("/delCart")
    public R delCart(@Validated @RequestBody FsStoreCartDelParam cartParam, HttpServletRequest request){
        return cartService.delCart(getUserId(Long.parseLong(getUserId())),cartParam);
    }
    @Login
    @ApiOperation("获取商品购物车数量")
    @GetMapping("/getCartCount")
    public R getCartCount(FsStoreCartCountParam param){
        param.setUserId(getUserId(Long.parseLong(getUserId())));
        Integer count=cartService.selectFsStoreCartCount(param);
        return R.ok().put("data", count);
    }
    @Login
    @ApiOperation("制单")
    @GetMapping("/createSalesOrder")
    public R createSalesOrder(@RequestParam("cateIds")String cateIds, HttpServletRequest request){
        CompanyUser companyUser=companyUserService.selectCompanyUserById(Long.parseLong(getUserId()));
        if(companyUser==null||companyUser.getDelFlag().equals("1")){
            return R.error("用户不存在");
        }
        if(!companyUser.getStatus().equals("0")){
            return R.error("用户已禁用");
        }
        return fsStoreOrderService.createSalesOrder(companyUser,cateIds);
    }

    @ApiOperation("改价")
    @GetMapping("/updateSalseOrderMoney")
    public R updateSalseOrderMoney( @RequestParam("createOrderKey")String createOrderKey, @RequestParam("money") BigDecimal money, HttpServletRequest request){
        return fsStoreOrderService.updateSalseOrderMoney(createOrderKey,money);
    }


    @ApiOperation("获取订单")
    @GetMapping("/getSalesOrder")
    public R getSalesOrder(@RequestParam("createOrderKey")String createOrderKey, HttpServletRequest request){
        return fsStoreOrderService.getSalesOrder(createOrderKey);
    }

    @ApiOperation("关联客户")
    @PostMapping("/bindCustomer")
    public R bindCustomer(@RequestBody FsStoreOrderBindCustomerParam param)
    {
        for(Long customerId:param.getCustomerIds()){
            FsStoreOrder order=new FsStoreOrder();
            order.setId(param.getOrderId());
            order.setCustomerId(customerId);
            fsStoreOrderService.updateFsStoreOrder(order);
        }
        return R.ok("操作成功");

    }



}
