package com.ruoyi.web.modules.goods.controller;

import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.web.modules.category.facade.IShopGoodsCategoryFacade;
import com.ruoyi.web.modules.category.service.IPlatformCategoryService;
import com.ruoyi.web.modules.category.support.SellerShopContext;
import com.ruoyi.web.modules.goodsservice.facade.IGoodsServiceFacade;
import com.ruoyi.web.modules.goods.domain.BizGoods;
import com.ruoyi.web.modules.goods.dto.GoodsBatchIdsDTO;
import com.ruoyi.web.modules.goods.dto.GoodsOffShelfDTO;
import com.ruoyi.web.modules.goods.dto.GoodsSaveDTO;
import com.ruoyi.web.modules.goods.exception.GoodsBatchOperationException;
import com.ruoyi.web.modules.goods.service.IGoodsService;
import com.ruoyi.web.modules.freight.facade.IFreightTemplateFacade;
import com.ruoyi.web.modules.freight.vo.FreightTemplateDetailVO;
import com.ruoyi.web.modules.freight.vo.FreightTemplateOptionVO;
import com.ruoyi.web.modules.template.facade.IAttrTemplateFacade;
import com.ruoyi.web.modules.template.vo.AttrTemplateDetailVO;

/**
 * 商家端商品管理
 */
@RestController
@RequestMapping("/agri/seller/goods")
public class SellerGoodsController extends BaseController
{
    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IPlatformCategoryService platformCategoryService;

    @Autowired
    private IShopGoodsCategoryFacade shopGoodsCategoryFacade;

    @Autowired
    private IGoodsServiceFacade goodsServiceFacade;

    @Autowired
    private IAttrTemplateFacade attrTemplateFacade;

    @Autowired
    private IFreightTemplateFacade freightTemplateFacade;

    @PreAuthorize("@ss.hasPermi('agri:seller:goods:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizGoods query)
    {
        startPage();
        return getDataTable(goodsService.selectSellerList(SellerShopContext.getShopId(), query));
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:goods:list') or @ss.hasPermi('agri:seller:goods:add') or @ss.hasPermi('agri:seller:goods:edit')")
    @GetMapping("/categoryOptions")
    public AjaxResult categoryOptions()
    {
        return success(platformCategoryService.selectPlatformLevel2Options());
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:goods:list')")
    @GetMapping("/shopCategoryOptions")
    public AjaxResult shopCategoryOptions(
            @RequestParam(value = "visibleOnly", required = false, defaultValue = "false") boolean visibleOnly)
    {
        return success(shopGoodsCategoryFacade.listOptionsByShopId(SellerShopContext.getShopId(), visibleOnly));
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:goods:list')")
    @GetMapping("/serviceOptions")
    public AjaxResult serviceOptions()
    {
        Map<String, Object> data = new HashMap<>();
        data.put("all", goodsServiceFacade.listAllEnabled());
        data.put("defaultShow", goodsServiceFacade.listDefaultShow());
        return success(data);
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:goods:list') or @ss.hasPermi('agri:seller:goods:add') or @ss.hasPermi('agri:seller:goods:edit')")
    @GetMapping("/attrTemplateOptions")
    public AjaxResult attrTemplateOptions()
    {
        return success(attrTemplateFacade.listOptionsByShopId(SellerShopContext.getShopId()));
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:goods:list') or @ss.hasPermi('agri:seller:goods:add') or @ss.hasPermi('agri:seller:goods:edit')")
    @GetMapping("/attrTemplate/{templateId}")
    public AjaxResult attrTemplateDetail(@PathVariable("templateId") Long templateId)
    {
        AttrTemplateDetailVO detail = attrTemplateFacade.getDetailForGoods(templateId, SellerShopContext.getShopId());
        Map<String, Object> data = new HashMap<>();
        data.put("templateId", detail.getTemplateId());
        data.put("templateName", detail.getTemplateName());
        data.put("attributes", detail.getAttributes());
        data.put("specs", detail.getSpecs());
        return success(data);
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:goods:list') or @ss.hasPermi('agri:seller:goods:add') or @ss.hasPermi('agri:seller:goods:edit')")
    @GetMapping("/freightTemplateOptions")
    public AjaxResult freightTemplateOptions()
    {
        return success(freightTemplateFacade.listOptionsByShopId(SellerShopContext.getShopId()));
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:goods:list') or @ss.hasPermi('agri:seller:goods:add') or @ss.hasPermi('agri:seller:goods:edit')")
    @GetMapping("/freightDefault")
    public AjaxResult freightDefault()
    {
        FreightTemplateOptionVO option = freightTemplateFacade.getDefaultTemplate(SellerShopContext.getShopId());
        if (option == null)
        {
            return success(null);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("freightType", "2");
        data.put("freightTemplateId", option.getTemplateId());
        data.put("templateName", option.getTemplateName());
        data.put("freeFlag", option.getFreeFlag());
        data.put("isDefault", option.getIsDefault());
        return success(data);
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:goods:list') or @ss.hasPermi('agri:seller:goods:add') or @ss.hasPermi('agri:seller:goods:edit')")
    @GetMapping("/freightTemplate/{templateId}")
    public AjaxResult freightTemplateDetail(@PathVariable("templateId") Long templateId)
    {
        FreightTemplateDetailVO detail = freightTemplateFacade.getDetailForGoods(templateId,
                SellerShopContext.getShopId());
        Map<String, Object> data = new HashMap<>();
        data.put("templateId", detail.getTemplateId());
        data.put("templateName", detail.getTemplateName());
        data.put("shipTime", detail.getShipTime());
        data.put("freeFlag", detail.getFreeFlag());
        data.put("pricingType", detail.getPricingType());
        data.put("defaultRule", detail.getDefaultRule());
        data.put("regionRules", detail.getRegionRules());
        return success(data);
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:goods:query')")
    @GetMapping("/{goodsId}")
    public AjaxResult getInfo(@PathVariable("goodsId") Long goodsId)
    {
        return success(goodsService.selectSellerDetail(SellerShopContext.getShopId(), goodsId));
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:goods:add')")
    @Log(title = "商家商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GoodsSaveDTO dto)
    {
        Long goodsId = goodsService.insertSellerGoods(SellerShopContext.getShopId(), dto, getUsername());
        Map<String, Object> data = new HashMap<>();
        data.put("goodsId", goodsId);
        AjaxResult result = AjaxResult.success();
        result.put(AjaxResult.DATA_TAG, data);
        return result;
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:goods:edit')")
    @Log(title = "商家商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GoodsSaveDTO dto)
    {
        goodsService.updateSellerGoods(SellerShopContext.getShopId(), dto, getUsername());
        return success();
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:goods:edit')")
    @Log(title = "商品批量提交上架", businessType = BusinessType.UPDATE)
    @PutMapping("/submit")
    public AjaxResult submitBatch(@RequestBody GoodsBatchIdsDTO dto)
    {
        try
        {
            goodsService.submitGoodsBatch(SellerShopContext.getShopId(), dto, getUsername());
            return success();
        }
        catch (GoodsBatchOperationException e)
        {
            return batchError(e);
        }
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:goods:edit')")
    @Log(title = "商品提交上架", businessType = BusinessType.UPDATE)
    @PutMapping("/{goodsId}/submit")
    public AjaxResult submit(@PathVariable("goodsId") Long goodsId)
    {
        Map<String, Object> data = goodsService.submitGoods(SellerShopContext.getShopId(), goodsId, getUsername());
        AjaxResult result = AjaxResult.success("提交成功");
        result.put(AjaxResult.DATA_TAG, data);
        return result;
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:goods:offshelf')")
    @Log(title = "商家商品批量下架", businessType = BusinessType.UPDATE)
    @PutMapping("/offShelf")
    public AjaxResult offShelfBatch(@RequestBody GoodsOffShelfDTO dto)
    {
        try
        {
            goodsService.offShelfSellerBatch(SellerShopContext.getShopId(), dto, getUsername());
            return success();
        }
        catch (GoodsBatchOperationException e)
        {
            return batchError(e);
        }
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:goods:offshelf')")
    @Log(title = "商家商品下架", businessType = BusinessType.UPDATE)
    @PutMapping("/{goodsId}/offShelf")
    public AjaxResult offShelf(@PathVariable("goodsId") Long goodsId)
    {
        try
        {
            goodsService.offShelfSeller(SellerShopContext.getShopId(), goodsId, getUsername());
            return success();
        }
        catch (GoodsBatchOperationException e)
        {
            return batchError(e);
        }
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:goods:remove')")
    @Log(title = "商家商品删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{goodsIds}")
    public AjaxResult remove(@PathVariable("goodsIds") Long[] goodsIds)
    {
        try
        {
            GoodsBatchIdsDTO dto = new GoodsBatchIdsDTO();
            dto.setGoodsIds(java.util.Arrays.asList(goodsIds));
            goodsService.deleteSellerGoodsBatch(SellerShopContext.getShopId(), dto, getUsername());
            return success();
        }
        catch (GoodsBatchOperationException e)
        {
            return batchError(e);
        }
    }

    private AjaxResult batchError(GoodsBatchOperationException e)
    {
        Map<String, Object> data = new HashMap<>();
        data.put("reasons", e.getReasons());
        AjaxResult result = AjaxResult.error(e.getMessage());
        result.put(AjaxResult.DATA_TAG, data);
        return result;
    }
}
