package cn.iocoder.yudao.module.inspection.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.core.text.Convert;
import cn.iocoder.yudao.module.core.text.ServletUtils;
import cn.iocoder.yudao.module.partner.service.IPartnerWorkerService;
import cn.iocoder.yudao.module.payment.service.OrderInfoService;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.iocoder.yudao.module.inspection.service.AppInspectionPartnerService;
import cn.iocoder.yudao.module.partner.entity.PartnerWorker;
import cn.iocoder.yudao.module.payment.entity.OrderInfo;
import cn.iocoder.yudao.module.shop.entity.ShopMallPartners;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.iocoder.yudao.module.core.controller.BaseController;
import cn.iocoder.yudao.module.inspection.entity.ShopInspectionGoods;
import cn.iocoder.yudao.module.inspection.service.IShopInspectionGoodsService;


/**
 * 检测商品Controller
 *
 * @author ruoyi
 * @date 2023-07-08
 */
@RestController
@RequestMapping("/admin-api/system/inspectionGoods")
public class ShopInspectionGoodsController extends BaseController
{
    @Autowired
    private IShopInspectionGoodsService shopInspectionGoodsService;
    @Autowired
    @Lazy
    private AppInspectionPartnerService appInspectionPartnerService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private IPartnerWorkerService partnerWorkerService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    /**
     * 查询检测商品列表
     */
//    @PreAuthorize("@ss.hasPermi('system:inspectionGoods:list')")
    @GetMapping("/listSystem")
    public CommonResult listSystem(ShopInspectionGoods shopInspectionGoods,
                                   @RequestParam(value = "pageNum" ,required = false ,defaultValue = "1") Integer pageNum,
                                   @RequestParam(value ="pageSize" ,required = false ,defaultValue = "10") Integer pageSize)
    {
        Page<ShopInspectionGoods> page = new Page<>(pageNum, pageSize);
        IPage<ShopInspectionGoods> list = shopInspectionGoodsService.listSystem(page,shopInspectionGoods);
        return success(list);
    }

    /**
     * 查询检测商品列表
     */
    @GetMapping("/listPartnerGoods")
    public CommonResult listPartnerGoods(ShopInspectionGoods shopInspectionGoods,
                                         @RequestParam(value = "pageNum" ,required = false ,defaultValue = "1") Integer pageNum,
                                         @RequestParam(value ="pageSize" ,required = false ,defaultValue = "10") Integer pageSize) throws Exception {
        ShopMallPartners one = appInspectionPartnerService.shopInfoByUserId();
        shopInspectionGoods.setPartnerId(one.getPartnerId().intValue());
        Page<ShopInspectionGoods> page = new Page<>(pageNum, pageSize);
        IPage<ShopInspectionGoods> list = shopInspectionGoodsService.listPartnerGoods(page,shopInspectionGoods);
        return success(list);
    }

    /**
     * 分页查询所有数据
     *
     * @return 所有数据
     */
    @GetMapping("/categoryList")
    public CommonResult categoryList() throws Exception {
        return success( shopInspectionGoodsService.categoryList());
    }

    /**
     * 商家发布商品
     *
     * @return 所有数据
     */
    @PostMapping("/partnerAddGoods")
    public CommonResult partnerAddGoods(@RequestBody ShopInspectionGoods shopInspectionGoods) throws Exception {
        shopInspectionGoodsService.partnerAddGoods(shopInspectionGoods);
        return success();
    }



    /**
     * 商品详细信息
     */
    @GetMapping("/partnerGoodsDetail")
    public CommonResult partnerGoodsDetail(Long goodsId) throws Exception {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        LambdaQueryWrapper<ShopMallPartners> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopMallPartners::getUserId,loginUser.getId()).eq(ShopMallPartners::getType,"jc").last("limit 1");
        ShopMallPartners one = appInspectionPartnerService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(one)){
            throw new Exception("您不是商户");
        }

        return   success(appInspectionPartnerService.goodsDetail(goodsId));
    }

    /**
     * 修改商品
     */
    @PostMapping("/partnerEditGoods")
    public CommonResult partnerEditGoods(@RequestBody ShopInspectionGoods goods) throws Exception {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        LambdaQueryWrapper<ShopMallPartners> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopMallPartners::getUserId,loginUser.getId()).eq(ShopMallPartners::getType,"jc").last("limit 1");
        ShopMallPartners one = appInspectionPartnerService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(one)){
            throw new Exception("您不是商户");
        }
        goods.setPartnerId(one.getPartnerId().intValue());
        appInspectionPartnerService.editGoods(goods);
        return   success();
    }
    /**
     * 上下架
     */
    @PostMapping("/partnerChangeListing")
    public CommonResult partnerChangeListing(Long goodsId) throws Exception {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        LambdaQueryWrapper<ShopMallPartners> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopMallPartners::getUserId,loginUser.getId()).eq(ShopMallPartners::getType,"jc").last("limit 1");
        ShopMallPartners one = appInspectionPartnerService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(one)){
            throw new Exception("您不是商户");
        }
        appInspectionPartnerService.changeListing(goodsId);
        return   success();
    }
    /**
     * 删除商品
     */
    @PostMapping("/partnerDelGoods")
    public CommonResult partnerDelGoods(Long goodsId) throws Exception {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        LambdaQueryWrapper<ShopMallPartners> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopMallPartners::getUserId,loginUser.getId()).eq(ShopMallPartners::getType,"jc").last("limit 1");
        ShopMallPartners one = appInspectionPartnerService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(one)){
            throw new Exception("您不是商户");
        }
        appInspectionPartnerService.delGoods(goodsId);
        return   success();
    }

    /**
     * 查询检测订单列表
     */
    @GetMapping("/partnerOrderListSystem")
    public CommonResult<IPage<?>> partnerOrderListSystem(OrderInfo shopInspectionOrder,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) throws Exception {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(user.getId());
        List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);
        List<String> roles = roleList.stream().map(RoleDO::getCode).collect(Collectors.toList());

        ShopMallPartners partner  = new ShopMallPartners();
        if (roles.contains("jcshop")){
            LambdaQueryWrapper<ShopMallPartners> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(ShopMallPartners::getUserId,user.getId()).eq(ShopMallPartners::getType,"jc").eq(ShopMallPartners::getIsBanned,"0");
            partner = appInspectionPartnerService.getOne(queryWrapper);
            if (ObjectUtil.isEmpty(partner)){
                return error();
            }
        }else if (roles.contains("jcworker")){
            LambdaQueryWrapper<PartnerWorker> queryWrapperWork =new LambdaQueryWrapper<>();
            queryWrapperWork.eq(PartnerWorker::getUserId,user.getId());
            PartnerWorker worker = partnerWorkerService.getOne(queryWrapperWork);
            if (ObjectUtil.isEmpty(worker)){
                return error();
            }
            partner.setPartnerId(worker.getPartnerId());
        }
        shopInspectionOrder.setPartnerId(partner.getPartnerId());
        shopInspectionOrder.setValidationTime(new Date());
        Page<OrderInfo> page = new Page<>(pageNo, pageSize);
        return CommonResult.success(orderInfoService.queryListPage(shopInspectionOrder,page));
    }



    /**
     * 获取检测商品详细信息
     */
    @GetMapping(value = "/getByIdSystem")
    public CommonResult getByIdSystem(@RequestParam("id") Long id)
    {
        return success(shopInspectionGoodsService.selectShopInspectionGoodsById(id));
    }

    /**
     * 新增检测商品
     */
//    @PreAuthorize("@ss.hasPermi('system:inspectionGoods:add')")
    @PostMapping("/add")
    public CommonResult add(@RequestBody ShopInspectionGoods shopInspectionGoods)
    {
        shopInspectionGoods.setIsListing("1");
        return toAjax(shopInspectionGoodsService.insertShopInspectionGoods(shopInspectionGoods));
    }

    /**
     * 修改检测商品
     */
//    @PreAuthorize("@ss.hasPermi('system:inspectionGoods:edit')")
    @PostMapping("/edit")
    public CommonResult edit(@RequestBody ShopInspectionGoods shopInspectionGoods)
    {
        return toAjax(shopInspectionGoodsService.updateShopInspectionGoods(shopInspectionGoods));
    }

    /**
     * 审核检测商品
     */
//    @PreAuthorize("@ss.hasPermi('system:inspectionGoods:edit')")
    @PostMapping("/examine")
    public CommonResult examine(@RequestBody ShopInspectionGoods shopInspectionGoods)
    {
        return toAjax(shopInspectionGoodsService.examine(shopInspectionGoods));
    }

    /**
     * 删除检测商品
     */
//    @PreAuthorize("@ss.hasPermi('system:inspectionGoods:remove')")
    @PostMapping("/del")
    public CommonResult remove(@RequestParam("idList") Long[] ids)
    {
        return toAjax(shopInspectionGoodsService.deleteShopInspectionGoodsByIds(ids));
    }

    @GetMapping("/listWx")
    public CommonResult listWx(ShopInspectionGoods shopInspectionGoods,
                               @RequestParam(value = "pageNum" ,required = false ,defaultValue = "1") Integer pageNum,
                               @RequestParam(value ="pageSize" ,required = false ,defaultValue = "10") Integer pageSize)
    {
        Page<ShopInspectionGoods> page = new Page<>(pageNum, pageSize);
        IPage<ShopInspectionGoods> list = shopInspectionGoodsService.selectShopInspectionGoodsListWx(page,shopInspectionGoods);
        return success(list);
    }
    /**
     * 获取检测商品详细信息
     */
    @GetMapping(value = "/{id}")
    public CommonResult getInfo(@PathVariable("id") Long id)
    {
        return success(shopInspectionGoodsService.selectShopInspectionGoodsById(id));
    }

    /**
     * 获取当前商家的商品信息
     */
    @GetMapping("/partnerGoodsListTree")
    public CommonResult partnerGoodsListTree() throws Exception {
        ShopMallPartners partners = appInspectionPartnerService.shopInfo();
        return success(shopInspectionGoodsService.partnerGoodsListTree(partners.getPartnerId()));
    }


    /**
     * 获取当前商家的商品信息
     */
    @GetMapping("/partnerGoodsListCol")
    public CommonResult partnerGoodsListCol() throws Exception {
        ShopMallPartners partners = appInspectionPartnerService.shopInfo();
        return success(shopInspectionGoodsService.partnerGoodsListCol(partners.getPartnerId()));
    }


}
