package cn.newfeifan.mall.sale.controller.admin.shop;

import cn.newfeifan.mall.module.enums.ErrorCodeConstants;
import cn.newfeifan.mall.module.system.api.user.dto.AdminUserRespDTO;
import cn.newfeifan.mall.module.system.controller.admin.user.vo.user.UserRespVO;
import cn.newfeifan.mall.sale.controller.admin.merchant.vo.MerchantRespVO;
import cn.newfeifan.mall.sale.controller.admin.shop.vo.ShopPageReqVO;
import cn.newfeifan.mall.sale.controller.admin.shop.vo.ShopRespVO;
import cn.newfeifan.mall.sale.controller.admin.shop.vo.ShopSaveReqVO;
import cn.newfeifan.mall.sale.dal.dataobject.merchant.MerchantDO;
import cn.newfeifan.mall.sale.dal.redis.ShopMessage;
import cn.newfeifan.mall.sale.service.merchant.MerchantService;
import cn.newfeifan.mall.sale.service.shop.ShopService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.newfeifan.mall.framework.common.pojo.PageParam;
import cn.newfeifan.mall.framework.common.pojo.PageResult;
import cn.newfeifan.mall.framework.common.pojo.CommonResult;
import cn.newfeifan.mall.framework.common.util.object.BeanUtils;

import static cn.newfeifan.mall.framework.common.pojo.CommonResult.error;
import static cn.newfeifan.mall.framework.common.pojo.CommonResult.success;

import cn.newfeifan.mall.framework.excel.core.util.ExcelUtils;

import cn.newfeifan.mall.framework.operatelog.core.annotations.OperateLog;

import static cn.newfeifan.mall.framework.operatelog.core.enums.OperateTypeEnum.*;
import static cn.newfeifan.mall.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.newfeifan.mall.module.enums.ErrorCodeConstants.MERCHANT_NOT_EXISTS;

import cn.newfeifan.mall.sale.dal.dataobject.shop.ShopDO;

@Tag(name = "管理后台 - 店铺")
@RestController
@RequestMapping("/sale/shop")
@Validated
public class ShopController {


    @Resource
    private MerchantService merchantService;

    @Resource
    private ShopService shopService;

    @PostMapping("/create")
    @Operation(summary = "创建店铺")
    @PreAuthorize("@ss.hasPermission('sale:shop:create')")
    public CommonResult<Long> createShop(@Valid @RequestBody ShopSaveReqVO createReqVO) {
        return success(shopService.createShop(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新店铺")
    @PreAuthorize("@ss.hasPermission('sale:shop:update')")
    public CommonResult<Boolean> updateShop(@Valid @RequestBody ShopSaveReqVO updateReqVO) {
        shopService.updateShop(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除店铺")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('sale:shop:delete')")
    public CommonResult<Boolean> deleteShop(@RequestParam("id") Long id) {
        shopService.deleteShop(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得店铺")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('sale:shop:query')")
    public CommonResult<ShopRespVO> getShop(@RequestParam("id") Long id) {
        ShopDO shop = shopService.getShop(id);
        return success(BeanUtils.toBean(shop, ShopRespVO.class));
    }


    @GetMapping("/getAllShop")
    @Operation(summary = "获得商户下所有店铺")
    @Parameter(name = "merId", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('sale:merchant:query')")
    public CommonResult<List<ShopRespVO>> getMerchantAllShop(@RequestParam("merId") Long merId) {
        // 获取所有店铺
        List<ShopRespVO> shops = shopService.getMerchantAllShop(merId);
        return success(shops);
    }


    @GetMapping("/getAllUser")
    @Operation(summary = "获取店铺下的所有人员列表")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('sale:merchant:query')")
    public CommonResult<List<UserRespVO>> getAllUser(@RequestParam("id") Long id) {
        // 获取所有店铺
        List<UserRespVO> shops = shopService.getAllUser(id);
        return success(shops);
    }


    @GetMapping("/getAllUserByMer")
    @Operation(summary = "获取商户下的所有人员列表")
    @Parameter(name = "merId", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('sale:merchant:query')")
    public CommonResult<List<UserRespVO>> getAllUserByMer(@RequestParam("merId") Long merId) {
        // 获取所有店铺
        List<ShopRespVO> shops = shopService.getMerchantAllShop(merId);
        if (shops.isEmpty()) {
            return success(Collections.emptyList());
        }
        List<Long> shopIds = shops.stream().map(ShopRespVO::getId).collect(Collectors.toList());
        List<UserRespVO> userRespVOS = shopService.getAllUser(shopIds);
        return success(userRespVOS);
    }


    @GetMapping("/page")
    @Operation(summary = "获得店铺分页")
    @PreAuthorize("@ss.hasPermission('sale:shop:query')")
    public CommonResult<PageResult<ShopRespVO>> getShopPage(@Valid ShopPageReqVO pageReqVO) {
        PageResult<ShopDO> pageResult = shopService.getShopPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, ShopRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出店铺 Excel")
    @PreAuthorize("@ss.hasPermission('sale:shop:export')")
    @OperateLog(type = EXPORT)
    public void exportShopExcel(@Valid ShopPageReqVO pageReqVO,
                                HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ShopDO> list = shopService.getShopPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "店铺.xls", "数据", ShopRespVO.class,
                BeanUtils.toBean(list, ShopRespVO.class));
    }

    @PutMapping("/change_shop")
    @Operation(summary = "切换店铺")
    @PreAuthorize("@ss.hasPermission('sale:merchant:query')")
    public CommonResult<Boolean> changeShop(@RequestParam("shopId") Long shopId) {
        shopService.changeShop(getLoginUserId(),shopId);
        return success(true);
    }


    @PutMapping("/get_current_shop")
    @Operation(summary = "获取当前店铺ID")
    @PreAuthorize("@ss.hasPermission('sale:merchant:query')")
    public CommonResult<ShopMessage> getCurrentShop() {
        return success(shopService.getCurrentShop(getLoginUserId()));
    }

    @GetMapping("/getAllShopByUserId")
    @Operation(summary = "获取当前用户下的所有店铺")
    @Parameter(name = "merId", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('sale:merchant:query')")
    public CommonResult<List<ShopRespVO>> getAllShopByUserId() {
        // 获取所有店铺
        List<ShopRespVO> shops = shopService.getAllShopByUserId(getLoginUserId());
        return success(shops);
    }


}