package com.ruoyi.web.controller.app;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
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.domain.ValidGroup;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.ss.carousel.service.CarouselService;
import com.ruoyi.ss.room.domain.RoomQuery;
import com.ruoyi.ss.room.domain.RoomVO;
import com.ruoyi.ss.room.service.IRoomAssembler;
import com.ruoyi.ss.room.service.IRoomService;
import com.ruoyi.ss.store.domain.*;
import com.ruoyi.ss.store.service.IStoreAssembler;
import com.ruoyi.ss.store.service.IStoreService;
import com.ruoyi.ss.store.service.IStoreValidator;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 店铺Controller
 * @author qzz
 * 2024/3/5
 */
@Api(tags = "店铺")
@RestController
@RequestMapping("/app/store")
public class AppStoreController extends BaseController {

    @Autowired
    private IStoreService storeService;

    @Autowired
    private IStoreValidator storeValidator;

    @Autowired
    private IStoreAssembler storeAssembler;

    @Autowired
    private CarouselService carouselService;

    @Resource
    public IRoomService roomService;

    @Autowired
    private IRoomAssembler roomAssembler;


    /**
     * 获取店铺详细信息
     */
    @GetMapping(value = "/{storeId}")
    public AjaxResult getStoreInfo(@PathVariable("storeId") Long storeId,String type)
    {
        logger.info("获取店铺详细信息：【storeId={}】", storeId);
        StoreVO storeVO = storeService.selectEStoreByStoreId(storeId);
        ServiceUtil.assertion(storeVO == null, "店铺不存在");
        RoomQuery query = new RoomQuery();
        query.setStoreId(storeId);
        query.setType(type);
        List<RoomVO> eRoomVOS = roomService.selectERoomList(query);// 拼接房间
        roomAssembler.assembleRuleInfo(eRoomVOS); // 拼接套餐
        storeVO.setRoomList(eRoomVOS);
        storeVO.setCarouselList(carouselService.selectSsCarouselListByStoreId(storeVO.getStoreId())); // 轮播图
        return success(storeVO);
    }

    /**
     * 获取店铺详细信息(商家)
     */
    @GetMapping(value = "/mch/{storeId}")
    public AjaxResult getStoreInfo2(@PathVariable("storeId") Long storeId)
    {
        logger.info("获取店铺详细信息(商家)：【storeId={}】", storeId);
        return success(storeService.selectMchStoreByStoreId(storeId));
    }

    /**
     * 开大门
     */
    @GetMapping(value = "/openGate/{storeId}")
    public AjaxResult openGate(@PathVariable("storeId") Long storeId, String isVerify)
    {
        logger.info("开大门：【storeId={}】", storeId);
        // todo 开大门前的校验
        storeValidator.preOpenGate(storeId,isVerify);
        return success(storeService.openGate(storeId,"小程序开大门",true));
    }

    /**
     * 关大门
     */
    @GetMapping(value = "/closeGate/{storeId}")
    public AjaxResult closeGate(@PathVariable("storeId") Long storeId)
    {
        logger.info("关大门：【storeId={}】", storeId);
        return success(storeService.closeGate(storeId,"小程序关大门"));
    }


    /**
     * 客服电话
     */
    @GetMapping(value = "/getServicePhone")
    public AjaxResult getServicePhone(Long storeId)
    {
        logger.info("客服电话：【storeId={}】", storeId);
        return success(storeService.getServicePhone(storeId));
    }

    /**
     * 查看可用门店
     */
    @GetMapping(value = "/getAvailableStores")
    public AjaxResult getAvailableStores(Long storeId)
    {
        logger.info("查看可用门店：【storeId={}】", storeId);
        return success(storeService.getAvailableStores(storeId));
    }

    /**
     * 查询本人店铺列表
     */
    @GetMapping("/list")
    public TableDataInfo list(@Validated StoreQuery store) {
        startPage();
//        PageHelper.orderBy("s.create_time desc");
        store.setMerchantId(getUserId());
        List<StoreVO> list = storeService.selectEStoreList(store);
        // 拼接设备总数量
        storeAssembler.assembleDeviceCount(list);
        // 拼接营收数据
        storeAssembler.assembleRevenue(list);
        // 拼接归属店铺
        storeAssembler.assembleBelongStore(list,getUserId());
        return getDataTable(list);
    }

    /**
     * 新增店铺
     */
    @Log(title = "店铺", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Validated(ValidGroup.Create.class) Store eStore)
    {
        logger.info("新增店铺：【eStore={}】", JSON.toJSONString(eStore));
        return toAjax(storeService.insertEStore(eStore));
    }

    /**
     * 修改店铺
     */
    @Log(title = "店铺", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated(ValidGroup.Update.class)Store eStore)
    {
        return toAjax(storeService.updateEStore(eStore));
    }

    /**
     * 删除店铺
     */
    @Log(title = "店铺", businessType = BusinessType.DELETE)
    @DeleteMapping("/{storeIds}")
    public AjaxResult remove(@PathVariable Long[] storeIds)
    {
        logger.info("删除店铺：【{}】", JSON.toJSONString(storeIds));
        return toAjax(storeService.deleteEStoreByStoreIds(storeIds));
    }

    /**
     * 绑定大门
     */
    @Log(title = "绑定大门", businessType = BusinessType.UPDATE)
    @PutMapping("/bandGate")
    public AjaxResult bandGate(@RequestBody @Validated(ValidGroup.BandGate.class) StoreDTO dto)
    {
        logger.info("绑定大门：【{}】", JSON.toJSONString(dto));
        return toAjax(storeService.bandGate(dto));
    }

    /**
     * 大门权限配置
     */
    @Log(title = "大门权限配置", businessType = BusinessType.UPDATE)
    @PutMapping("/gateAuth")
    public AjaxResult gateAuth(@RequestBody GateAuthDTO dto)
    {
        logger.info("大门权限配置：【{}】", JSON.toJSONString(dto));
        return toAjax(storeService.gateAuth(dto));
    }


//    /**
//     * 申请修改店铺信息
//     * @param data
//     * @return
//     */
//    @ApiOperation("申请修改店铺信息")
//    @PutMapping
//    public AjaxResult edit(@RequestBody @Validated(ValidGroup.FrontUpdate.class) StoreBO data) {
//        StoreVo store = storeService.selectSmStoreById(data.getStoreId());
//        if (!storeValidator.isStoreBelongUser(store, getUserId())) {
//            return error("这不是您的店铺，无法修改");
//        }
//        data = data.filterUpdateByApp();
//        ServiceUtil.assertion(storeValidator.preUpdateByApp(data));
//        return toAjax(storeService.updateApply(data));
//    }
//
//    @ApiOperation("修改店铺配置")
//    @PutMapping("/config")
//    public AjaxResult configStore(@RequestBody @Validated(ValidGroup.FrontUpdate.class) StoreBO data) {
//        StoreVo store = storeService.selectSmStoreById(data.getStoreId());
//        if (!storeValidator.isStoreBelongUser(store, getUserId())) {
//            return error("这不是您的店铺，无法修改");
//        }
//        data = data.filterConfigByApp();
//        return toAjax(storeService.updateSmStore(data));
//    }
//
//    /**
//     * 删除店铺信息
//     * @param storeId
//     * @return
//     */
////    @MchRequired
//    @ApiOperation("删除店铺信息")
//    @DeleteMapping("/{storeId}")
//    public AjaxResult delete(@PathVariable Long storeId) {
//        List<Long> storeIds = Collections.singletonList(storeId);
//        ServiceUtil.assertion(storeValidator.preLogicDelByApp(storeIds));
//        return AjaxResult.success(storeService.logicDel(storeIds));
//    }
//
////    @MchRequired
//    @ApiOperation("申请新增店铺")
//    @PostMapping
//    public AjaxResult add(@RequestBody @Validated(ValidGroup.FrontCreate.class) StoreBO store) {
//        store = store.filterCreateByApp();
//        store.setUserId(getUserId());
//        ServiceUtil.assertion(storeValidator.preCreateByApp(store));
//        return toAjax(storeService.insertAndApply(store));
//    }
//
//
////    @MchRequired
//    @ApiOperation("调整店铺排序")
//    @PutMapping("/changeSort")
//    public AjaxResult changeSort(@RequestBody List<Store> list) {
//        ServiceUtil.assertion(storeValidator.preChangeSortByApp(list));
//        return AjaxResult.success(storeService.changeSort(list));
//    }
//
//    @ApiOperation("获取当前用户店铺列表及其数量")
//    @GetMapping("/listCount")
//    @JsonView(StoreView.ListCount.class)
//    public AjaxResult listCount() {
//        StoreQuery query = new StoreQuery();
//        query.setUserId(getUserId());
//        return AjaxResult.success(storeService.listCount(query));
//    }
//
//    @ApiOperation("获取附近的店铺")
//    @GetMapping("/listNearBy")
//    @JsonView(JsonViewProfile.App.class)
//    @Anonymous
//    public AjaxResult listNearBy(@Validated(ValidGroup.Query.class) StoreQuery query) {
//        query.setShow(true);
//        query.setEnabled(true);
//        List<StoreVo> list = storeService.listNearBy(query);
//        storeAssembler.assembleDeviceCount(list);
//        return success(list);
//    }
//
//    @ApiOperation("获取店铺信息")
//    @GetMapping("/{storeId}")
//    @JsonView(JsonViewProfile.App.class)
//    @Anonymous
//    public AjaxResult getDetail(@PathVariable @ApiParam("店铺ID") Long storeId) {
//        StoreVo store = storeService.selectSmStoreById(storeId);
//        List<StoreVo> list = Collections.singletonList(store);
//        storeAssembler.assembleDeviceCount(list);           // 总设备数量
//        storeAssembler.assembleAvailableDeviceCount(list);  // 可共享设备数量
//        return success(store);
//    }
//
////    @MchRequired
//    @ApiOperation("商户获取店铺信息")
//    @GetMapping("/mch/{storeId}")
//    public AjaxResult getMchDetail(@PathVariable @ApiParam("店铺ID") Long storeId) {
//        ServiceUtil.assertion(!storeValidator.isStoreBelongUser(Collections.singletonList(storeId), getUserId()), "这不是您的店铺，无法查看");
//        StoreVo store = storeService.selectSmStoreById(storeId);
//        List<StoreVo> storeList = Collections.singletonList(store);
//        storeAssembler.assembleDeviceCount(storeList);  // 总设备数量
//        storeAssembler.assembleRevenue(storeList);      // 经营信息
//        return success(store);
//    }
//
////    @MchRequired
//    @ApiOperation("切换默认店铺")
//    @PutMapping("/{storeId}/setDefault")
//    public AjaxResult setDefaultStore(@PathVariable Long storeId) {
//        Long userId = getUserId();
//        ServiceUtil.assertion(storeValidator.preSetDefaultByApp(userId, storeId));
//        return success(storeService.setDefault(userId, storeId));
//    }

}
