package com.yonge.cooleshow.portal.controller.open;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.enums.ApiErrorCode;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.mall.common.api.CommonPage;
import com.yonge.cooleshow.mall.common.api.CommonResult;
import com.yonge.cooleshow.mall.common.courier.domain.CourierInfo;
import com.yonge.cooleshow.mall.common.courier.service.CourierService;
import com.yonge.cooleshow.mbg.mapper.PmsSkuStockMapper;
import com.yonge.cooleshow.mbg.model.OmsOrderCourier;
import com.yonge.cooleshow.mbg.model.PmsProduct;
import com.yonge.cooleshow.portal.domain.OmsOrderDetail;
import com.yonge.cooleshow.portal.domain.PmsPortalProductDetail;
import com.yonge.cooleshow.portal.dto.*;
import com.yonge.cooleshow.portal.service.OmsOrderCourierService;
import com.yonge.cooleshow.portal.service.OmsPortalOrderService;
import com.yonge.cooleshow.portal.service.PmsPortalProductService;
import com.yonge.toolset.base.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/open")
@Api(tags = "开放权限接口-分享")
public class OpenShareController extends BaseController {
    private final static Logger log = LoggerFactory.getLogger(OpenShareController.class);

    @Autowired
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private PmsPortalProductService portalProductService;

    @Autowired
    private PmsSkuStockMapper skuStockMapper;

    @Autowired
    private OmsOrderCourierService orderCourierService;

    @Autowired
    private OmsPortalOrderService portalOrderService;

    @Autowired
    private CourierService courierService;

    @ApiOperation(value = "老师商品分享分润")
    @PostMapping(value="/productProfit")
    @ResponseBody
    public CommonResult<ShareProductVo> shareProductProfit(@RequestBody ShareProfitParam param) {
        SysUser sysUser = sysUserFeignService.queryUserById(param.getUserId());
        if (sysUser == null  || sysUser.getId() == null) {
            return CommonResult.failed("用户信息获取失败");
        }
        HttpResponseResult<String> client = sysUserFeignService.client();
        if (client.getStatus()) {
            if (!StringUtil.isEmpty(client.getData()) && "teacher".equals(client.getData())) {
                return CommonResult.success(portalProductService.shareProductProfit(sysUser, param.getBizId()));
            }
        } else {
            return CommonResult.success(portalProductService.shareProductProfit(sysUser, param.getBizId()));
        }
        return CommonResult.failed("分享功能暂未开放");
    }



    @ApiOperation(value = "快递信息回调")
    @PostMapping(value="/courierCallback", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    @ResponseBody
    public Object courierCallback( String param) {
        log.info("快递信息回调：{}",param);

        JSONObject jsonObject = JSON.parseObject(param);
        String data = jsonObject.getString("lastResult");
        CourierInfo courierInfos = courierService.getCourierInfos(data);

        // 保存快递信息
        orderCourierService.updateCourierInfo(courierInfos);
        Map<String,Object> result = new HashMap<>();
        result.put("result",true);
        result.put("returnCode","200");
        result.put("message","成功");

        return result;
    }


    @ApiOperation(value = "综合搜索、筛选、排序")
    @RequestMapping(value = "/product/search", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<CommonPage<PmsProduct>> search(@RequestBody ProductSearch search) {
        List<PmsProduct> productList = portalProductService.search(search.getKeyword(),search.getBrandId(),search.getProductCategoryId(),
                                                                   search.getProductAttributeCategoryId(), search.getPageNum(), search.getPageSize(), search.getSort());
        return CommonResult.success(CommonPage.restPage(productList));
    }

    @ApiOperation("获取商品列表下拉条件")
    @RequestMapping(value = "/search/condition", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<ProductSearchConditionVo> searchCondition() {
        ProductSearchConditionVo list = portalProductService.searchCondition();
        return CommonResult.success(list);
    }

    @ApiOperation("获取前台商品详情")
    @RequestMapping(value = "/product/detail/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<PmsPortalProductDetail> detail(@PathVariable Long id) {
        PmsPortalProductDetail productDetail = portalProductService.detail(id);
        return CommonResult.success(productDetail);
    }

    @PostMapping(value = "/product/queryNameMap", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public CommonResult<Map<Long,String>> queryNameMap(@RequestBody List<Long> goodsIds) {
        return CommonResult.success(portalProductService.queryNameMap(goodsIds));

    }


    /**
     * 商品库存查询
     * @param goodsSkuId 商品存储Id
     * @return String
     */
    @GetMapping(value = "/product/stocks/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public R<Integer> productStocks(@PathVariable(name = "id") Long goodsSkuId) {
        log.info("商品库存查询 skuId:{}",goodsSkuId);
        return R.ok(portalProductService.getProductStockAndSkuStock(goodsSkuId));

    }

    @PostMapping(value = "/product/stocksLock/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public R<Boolean> productStocksLock(@PathVariable(name = "id") Long goodsSkuId, @RequestParam("lockState") Boolean lockState) {
        log.info("商品库存锁定 goodsSkuId:{},lockState:{}",goodsSkuId,lockState);
        return R.ok(portalProductService.lockStock(goodsSkuId,lockState));

    }

    /**
     * 查询商品订单状态
     * @param orderNo 订单编号
     * @return String
     */
    @GetMapping(value = "/product/orderStatus/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public R<Boolean> productOrderStatus(@PathVariable(name = "id") String orderNo){
        log.info("查询商品订单状态:{}",orderNo);
        OmsOrderDetail detail = portalOrderService.detail(orderNo);

        return R.restResult(detail.getStatus().equals(1), ApiErrorCode.SUCCESS);
    }


    /**
     * 设置商品退款
     *
     * @param orderNo 订单编号
     * @return String
     */
    @GetMapping(value = "/product/orderRefund/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public R<Boolean> productOrderRefund(@PathVariable(name = "id") String orderNo) {

        log.info("设置订单退款：{}",orderNo);
        return R.restResult(portalOrderService.jmeduOrderRefund(orderNo), ApiErrorCode.SUCCESS);
    }


    /**
     * 查询商品订单生成
     * @param order ProductWrapper.OrderCreate
     * @return String
     */
    @PostMapping(value = "/product/orderCreate", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public R<Boolean> productOrderCreate(@RequestBody OrderCreate order) {

        log.info("创建管乐团订单：{}",JSON.toJSONString(order));

        portalOrderService.jmeduProductOrderCreate(order);


        return R.ok(true);
    }



    /**
     * 查询订单快递信息
     * @return
     */
    @GetMapping(value = "/product/orderCourier/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public R<OmsOrderCourier> productOrderCourier(@PathVariable(name = "id") String orderNo) {
        log.info("查询订单快递信息 : {}",orderNo);
        return R.ok(portalOrderService.productOrderCourier(orderNo));

    }





    /**
     * 锁定/解锁 sku
     *
     */
    @GetMapping(value = "/product/lockSku/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public R<Boolean> productOrderCourier(@PathVariable(name = "id") Long skuId,@RequestParam("platform") String platform,@RequestParam("lockState") Boolean lockState) {
        log.info("锁定/解锁 skuId : {},platform:{},lockState:{}",skuId,platform,lockState);
        return R.restResult(portalOrderService.lockSku(skuId,platform,lockState), ApiErrorCode.SUCCESS);

    }
}
