package com.yami.shop.platform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.model.ShopCategory;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.param.CategoryProductDTO;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.R;
import com.yami.shop.security.platform.model.YamiSysUser;
import com.yami.shop.security.platform.util.SecurityUtils;
import com.yami.shop.service.IShopCategoryService;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.utils.SmqjhUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 门店前台类目管理控制器
 *
 * @author YourName
 * @since 2025-09-XX
 */
@Slf4j
@RestController
@RequestMapping("/platform/shopCategory")
@Api(tags = "门店前台类目管理接口")
@AllArgsConstructor
public class ShopCategoryController {

    private final IShopCategoryService shopCategoryService;
    private final ShopDetailService shopDetailService;
    private final SmqjhUtil smqjhUtil;

    /**
     * 分页查询门店前台类目列表
     *
     * @param pageParam    分页参数
     * @param shopCategory 查询条件
     * @return 分页结果
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页查询门店前台类目列表", notes = "分页查询门店前台类目列表")
    public R<IPage<ShopCategory>> page(PageParam<ShopCategory> pageParam, ShopCategory shopCategory) {
        IPage<ShopCategory> page = shopCategoryService.page(
                pageParam,
                new LambdaQueryWrapper<ShopCategory>()
                        .like(shopCategory.getName() != null, ShopCategory::getName, shopCategory.getName())
                        .eq(shopCategory.getShopId() != null, ShopCategory::getShopId, shopCategory.getShopId())
                        .eq(shopCategory.getIsDelete() != null, ShopCategory::getIsDelete, shopCategory.getIsDelete())
                        .orderByDesc(ShopCategory::getId)
        );
        return R.SUCCESS(page);
    }

    /**
     * 获取未删除的门店前台类目列表
     *
     * @return 门店前台类目列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "获取未删除的门店前台类目列表", notes = "获取未删除的门店前台类目列表")
    public R<List<ShopCategory>> list(
            @RequestParam(required = false) Long shopId,
            @RequestParam(required = false) String name) {
        if (shopId == null) {
            return R.FAIL("门店不能为空！");
        }
        return R.SUCCESS(shopCategoryService.treeShopCategory(shopId, name));
    }


    /**
     * 导出门店前台类目导入模板
     */
    @GetMapping("/exportTemplate")
    @ApiOperation(value = "导出门店前台类目导入模板", notes = "导出门店前台类目导入模板")
    public void exportTemplate(HttpServletResponse response) {
        try {
            shopCategoryService.exportTemplate(response);
        } catch (Exception e) {
            log.error("导出模板失败：", e);
            throw new RuntimeException("导出模板失败：" + e.getMessage());
        }
    }

    /**
     * 导入门店前台类目
     */
    @PostMapping("/import")
    @ApiOperation(value = "导入门店前台类目", notes = "导入门店前台类目")
    public R importCategory(@RequestParam("file") MultipartFile file) {
        YamiSysUser sysUser = SecurityUtils.getSysUser();
        shopCategoryService.importCategory(file, sysUser.getUserId());
        return R.SUCCESS();
    }


    /**
     * 根据ID获取门店前台类目详情
     *
     * @param id 门店前台类目ID
     * @return 门店前台类目详情
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID获取门店前台类目详情", notes = "根据ID获取门店前台类目详情")
    @ApiImplicitParam(name = "id", value = "门店前台类目ID", required = true, dataType = "Long", paramType = "path")
    public R<ShopCategory> getById(@PathVariable Long id) {
        ShopCategory shopCategory = shopCategoryService.getById(id);
        if (shopCategory == null || shopCategory.getIsDelete() == 1) {
            return R.FAIL("门店前台类目不存在");
        }
        return R.SUCCESS(shopCategory);
    }

    /**
     * 新增门店前台类目
     *
     * @param shopCategory 门店前台类目信息
     * @return 操作结果
     */
    @PostMapping
    @ApiOperation(value = "新增门店前台类目", notes = "新增门店前台类目")
    public R<Void> save(@Valid @RequestBody ShopCategory shopCategory) {
        // 设置默认值
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());
        String random = String.valueOf((int) (Math.random() * 10000));
        shopCategory.setCode("F" + date + random);
        shopCategory.setIsDelete(0);

        ShopDetail shopDetailByShopId = shopDetailService.getShopDetailByShopId(shopCategory.getShopId());
        shopCategory.setHbShopId(shopDetailByShopId.getHbStationId());
        shopCategoryService.save(shopCategory);
        return R.SUCCESS();
    }

    /**
     * 修改门店前台类目
     *
     * @param shopCategory 门店前台类目信息
     * @return 操作结果
     */
    @PutMapping
    @ApiOperation(value = "修改门店前台类目", notes = "修改门店前台类目")
    public R update(@Valid @RequestBody ShopCategory shopCategory) {
        if (shopCategory.getId() == null) {
            return R.FAIL("ID不能为空");
        }

        // 检查是否存在
        ShopCategory dbShopCategory = shopCategoryService.getById(shopCategory.getId());
        if (dbShopCategory == null) {
            return R.FAIL("门店前台类目不存在");
        }
        shopCategoryService.updateById(shopCategory);


        ShopCategory dbShopCategory1 = shopCategoryService.getById(shopCategory.getId());
        try {
            String syncUrl = smqjhUtil.getSmqjhPmsUrl() + "/syncShopCategoryData";
            log.info("推送url: {}",syncUrl);
            // 将frontCategory对象作为JSON放入请求体
            String response = com.yami.shop.common.util.HttpUtil.post(syncUrl, dbShopCategory1);
            log.info("推送frontCategory到同步服务器结果: {}", response);
        } catch (Exception e) {
            log.error("推送frontCategory到同步服务器失败: {}", e.getMessage(), e);
        }

        return R.SUCCESS();
    }

    /**
     * 删除门店前台类目（逻辑删除）
     *
     * @param id 门店前台类目ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除门店前台类目", notes = "删除门店前台类目（逻辑删除）")
    @ApiImplicitParam(name = "id", value = "门店前台类目ID", required = true, dataType = "Long", paramType = "path")
    public R<Void> delete(@PathVariable Long id) {
        shopCategoryService.delete(id);
        return R.SUCCESS();

    }


}
