package org.dromara.zhishu.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import cn.dev33.satoken.annotation.SaIgnore;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.zhishu.domain.ShopGoodsRejection;
import org.dromara.zhishu.domain.vo.PlatformIdUpdateVO;
import org.dromara.zhishu.service.IRunningTaskByShopService;
import org.dromara.zhishu.service.ShopGoodsRejectionService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.zhishu.domain.vo.ShopGoodsPublishedVo;
import org.dromara.zhishu.domain.bo.ShopGoodsPublishedBo;
import org.dromara.zhishu.service.IShopGoodsPublishedService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 记录已发布书籍
 *
 * @author yxy
 * @date 2025-04-11
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/zhishu/shopGoodsPublished")
public class ShopGoodsPublishedController extends BaseController {

    private final IShopGoodsPublishedService shopGoodsPublishedService;

    private final IRunningTaskByShopService runningTaskByShopService;


    /**
     * 查询记录已发布书籍列表
     */
    @SaCheckPermission("zhishu:shopGoodsPublished:list")
    @GetMapping("/list")
    public TableDataInfo<ShopGoodsPublishedVo> list(ShopGoodsPublishedBo bo, PageQuery pageQuery) {
        // 获取当前登录用户的ID
        Long userId = LoginHelper.getUserId();
        bo.setCreateBy(userId);
        return shopGoodsPublishedService.selectDataList(bo, pageQuery);
    }

    @SaIgnore
    @GetMapping("/pddAdd/{platformId}/{goodsId}/{shopId}/{userId}")
    public void pddAdd(@PathVariable("platformId") String platformId,
                       @PathVariable("goodsId") String goodsId,
                       @PathVariable("shopId") String shopId,
                       @PathVariable("userId") String userId) {
        ShopGoodsPublishedBo shopGoodsPublishedBo = new ShopGoodsPublishedBo();
        shopGoodsPublishedBo.setPlatformId(platformId);
        shopGoodsPublishedBo.setShopGoodsId(goodsId);
        shopGoodsPublishedBo.setShopId(shopId);
        shopGoodsPublishedBo.setCreateBy(Long.parseLong(userId));
        shopGoodsPublishedBo.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        shopGoodsPublishedBo.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        shopGoodsPublishedService.insertByBo(shopGoodsPublishedBo);
    }

    /**
     * 导出记录已发布书籍列表
     */
    @SaCheckPermission("zhishu:shopGoodsPublished:export")
    @Log(title = "记录已发布书籍", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(ShopGoodsPublishedBo bo, HttpServletResponse response) {
        List<ShopGoodsPublishedVo> list = shopGoodsPublishedService.queryList(bo);
        ExcelUtil.exportExcel(list, "记录已发布书籍", ShopGoodsPublishedVo.class, response);
    }

    /**
     * 获取记录已发布书籍详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("zhishu:shopGoodsPublished:query")
    @GetMapping("/{id}")
    public R<ShopGoodsPublishedVo> getInfo(@NotNull(message = "主键不能为空")
                                           @PathVariable Long id) {
        return R.ok(shopGoodsPublishedService.queryById(id));
    }

    /**
     * 新增记录已发布书籍
     */
    @SaCheckPermission("zhishu:shopGoodsPublished:add")
    @Log(title = "记录已发布书籍", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody ShopGoodsPublishedBo bo) {
        return toAjax(shopGoodsPublishedService.insertByBo(bo));
    }

    /**
     * 修改记录已发布书籍
     */
    @SaCheckPermission("zhishu:shopGoodsPublished:edit")
    @Log(title = "记录已发布书籍", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ShopGoodsPublishedBo bo) {
        return toAjax(shopGoodsPublishedService.updateByBo(bo));
    }

    /**
     * 删除记录已发布书籍
     *
     * @param ids 主键串
     */
    @SaCheckPermission("zhishu:shopGoodsPublished:remove")
    @Log(title = "记录已发布书籍", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(shopGoodsPublishedService.deleteWithValidByIds(List.of(ids), true));
    }

    @SaCheckPermission("zhishu:shopGoodsPublished:remove")
    @Log(title = "记录已发布书籍删除全部", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeAll")
    public Map removeAll(Long shopId){
        Map map = new HashMap();
        String msg = shopGoodsPublishedService.deleteAll(shopId);
        if(msg.contains("成功")){
            map.put("code",200);
        }else{
            map.put("code",500);
        }
        map.put("msg",msg);
        return map;
    }

    /**
     * 根据店铺Id查询商品列表
     */
    @PostMapping("/getListByShopId")
    @SaIgnore
    public List<ShopGoodsPublishedVo> getListByShopId(Long shopId, @RequestBody List<String> platformIds) {
        return shopGoodsPublishedService.selectGoodsListByShopId(shopId, platformIds);
    }

    /**
     * 根据店铺Id查询商品列表
     */
    @GetMapping("/getListByShopId")
    @SaIgnore
    public List<ShopGoodsPublishedVo> getListByShopId(Long shopId) {
        return shopGoodsPublishedService.selectGoodsListByShopId(shopId);
    }

    /**
     * 商品发布驳回-类目修改cat_id
     */
    @GetMapping("/uodateCatId")
    @SaIgnore
    public Boolean uodateCatId(String shopType, Long mallId, String platformId) {
        return shopGoodsPublishedService.uodateCatId(shopType, mallId, platformId);
    }

    /**
     * 根据店铺Id和商品Id删除失败的商品
     */
    @GetMapping("/delShopGoodsPublished")
    @SaIgnore
    public Boolean delShopGoodsPublished(String shopType, Long mallId, String platformId, String rejectComment) {
        return shopGoodsPublishedService.delShopGoodsPublished(shopType, mallId, platformId, rejectComment);
    }

    /**
     * 更新孔网商品id
     */
    @PostMapping("/batchUpdateKfzPlatformId")
    @SaIgnore
    public R batchUpdateKfzPlatformId(@RequestBody List<PlatformIdUpdateVO> platformIdUpdateVOList) {
        shopGoodsPublishedService.batchUpdateKfzPlatformId(platformIdUpdateVOList);
//        System.out.println("platformIdUpdateVOList:" + JSON.toJSONString(platformIdUpdateVOList));
        return R.ok();
    }

    /**
     * 根据店铺Id和商品Id删除失败的商品
     */
    @GetMapping("/insertShopGoodsPublishedlog")
    @SaIgnore
    public void insertShopGoodsPublishedlog(String shopType, Long mallId, String platformId, String offshelftime) {
         shopGoodsPublishedService.insertLog(shopType, mallId, platformId, offshelftime);
    }


    /**
     * 已发布商品记录校验店铺商品
     */
    @PostMapping("/verifyShopGoodsPublished")
    public R<Void> verifyShopGoodsPublished(String shopId){
        // 异步执行耗时任务
        CompletableFuture.runAsync(() -> {
            shopGoodsPublishedService.verifyShopGoodsPublished(shopId);
        });
        return R.ok("任务已提交，请前往任务列表查询结果");
    }

}
