
package com.tmerclub.cloud.multishop.controller.platform;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.PhoneUtil;
import com.tmerclub.cloud.api.auth.constant.SysTypeEnum;
import com.tmerclub.cloud.api.auth.dto.AuthAccountDTO;
import com.tmerclub.cloud.api.auth.feign.AccountFeignClient;
import com.tmerclub.cloud.api.auth.vo.AuthAccountVO;
import com.tmerclub.cloud.api.multishop.constant.ShopStatus;
import com.tmerclub.cloud.api.multishop.vo.ShopDetailVO;
import com.tmerclub.cloud.api.platform.constant.OfflineHandleEventStatus;
import com.tmerclub.cloud.api.platform.dto.OfflineHandleEventDTO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ResponseEnum;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.util.BeanUtil;
import com.tmerclub.cloud.multishop.constant.IsPreferred;
import com.tmerclub.cloud.multishop.dto.*;
import com.tmerclub.cloud.multishop.service.ShopDetailService;
import com.tmerclub.cloud.multishop.vo.ShopHeadInfoVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 店铺详情
 *
 * @author tmerclub
 * @date 2020-12-05 15:50:25
 */
@RestController("platformShopDetailController")
@RequestMapping("/p/shopDetail")
@Tag(name = "platform-店铺信息")
public class ShopDetailController {

    @Value("${tmerclub.expose.operation.auth:}")
    private Boolean permission;

    @Autowired
    private ShopDetailService shopDetailService;
    @DubboReference
    private AccountFeignClient accountFeignClient;

    @GetMapping("/page")
    @Operation(summary = "分页查询", description = "分页查询")
    public ServerResponseEntity<PageVO<ShopDetailVO>> getShopAuditingPage(PageDTO pageDTO, ShopDetailDTO shopDetailDTO) {
        if (!Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId())) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        return ServerResponseEntity.success(shopDetailService.page(pageDTO, shopDetailDTO));
    }

    @GetMapping("/info")
    @Operation(summary = "获取店铺基本信息", description = "获取店铺基本信息")
    public ServerResponseEntity<ShopDetailVO> getInfo(@RequestParam Long shopId) {
        ShopDetailVO shopDetailVO = shopDetailService.getByShopId(shopId);
        shopDetailVO.setContactPhone(PhoneUtil.hideBetween(shopDetailVO.getContactPhone()).toString());
        ServerResponseEntity<AuthAccountVO> responseEntity = accountFeignClient.getAccountInfoByTenantId(shopId, SysTypeEnum.MULTISHOP.value());
        if (responseEntity.isSuccess() && Objects.nonNull(responseEntity.getData())) {
            AuthAccountVO authAccountVO = responseEntity.getData();
            shopDetailVO.setMerchantAccount(PhoneUtil.hideBetween(authAccountVO.getPhone()).toString());
            shopDetailVO.setAccountStatus(authAccountVO.getStatus());
        }
        return ServerResponseEntity.success(shopDetailVO);
    }

    /**
     * 新建店铺
     */
    @PostMapping("/create_shop")
    @Operation(summary = "新建店铺", description = "新建店铺")
    public ServerResponseEntity<Void> createShop(@RequestBody ShopCreateInfoDTO shopCreateInfoDTO) {
        shopDetailService.platformCreateShop(shopCreateInfoDTO);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "编辑店铺基本信息", description = "编辑店铺基本信息")
    public ServerResponseEntity<Void> editShop(@RequestBody ShopDetailDTO shopDetailDTO) {
        if (Objects.isNull(shopDetailDTO.getShopId())) {
            throw new LuckException("店铺id不能为空");
        }
        shopDetailService.update(shopDetailDTO);
        return ServerResponseEntity.success();
    }

    @PutMapping("/update_signing_info")
    @Operation(summary = "更新店铺签约信息", description = "更新店铺签约信息")
    public ServerResponseEntity<Void> updateSigningInfo(@RequestBody @Valid ShopSigningInfoDTO shopSigningInfoDTO) {
        if (Objects.isNull(shopSigningInfoDTO.getShopId())) {
            throw new LuckException("店铺id不能为空");
        }
        shopDetailService.updateSigningInfo(shopSigningInfoDTO);
        return ServerResponseEntity.success();
    }

    @PutMapping("/update_shop_preferred")
    @Operation(summary = "当前店铺为优选，则取消优选;不是优选，则设置为优选", description = "当前店铺为优选，则取消优选;不是优选，则设置为优选")
    public ServerResponseEntity<Void> updateShopPreferred(@RequestParam("shopId") Long shopId) {
        ShopDetailVO shopDetailVO = shopDetailService.getByShopId(shopId);
        shopDetailVO.setIsPreferred(Objects.equals(shopDetailVO.getIsPreferred(), IsPreferred.YES.value()) ? IsPreferred.NO.value() : IsPreferred.YES.value());
        shopDetailService.update(BeanUtil.map(shopDetailVO, ShopDetailDTO.class));
        return ServerResponseEntity.success();
    }

    @PutMapping("/updatePassword")
    @Operation(summary = "更新店铺商家的登陆密码", description = "更新店铺商家的登陆密码")
    public ServerResponseEntity<Void> updatePassword(@RequestBody ShopAccountDTO shopAccountDTO) {
        // 暂时的home的店铺id
        Long home = 4L;
        if (Objects.equals(shopAccountDTO.getShopId(), home) && BooleanUtil.isFalse(permission)) {
            throw new LuckException("暂无权限修改该用户账号信息");
        }
        ServerResponseEntity<AuthAccountVO> merchantInfoByTenantId = accountFeignClient.getAccountInfoByTenantId(shopAccountDTO.getShopId(), SysTypeEnum.MULTISHOP.value());
        if (!merchantInfoByTenantId.isSuccess()) {
            throw new LuckException("服务异常");
        }
        AuthAccountVO authAccountVO = merchantInfoByTenantId.getData();
        authAccountVO.setPassword(shopAccountDTO.getPassword());
        accountFeignClient.update(BeanUtil.map(authAccountVO, AuthAccountDTO.class));
        return ServerResponseEntity.success();
    }

    @PutMapping("/offline")
    @Operation(summary = "下线店铺", description = "下线店铺")
    public ServerResponseEntity<Void> offline(@RequestBody OfflineHandleEventDTO offlineHandleEventDTO) {
        Long sysUserId = AuthUserContext.get().getUserId();
        ShopDetailVO shopDetailVO = shopDetailService.getByShopId(offlineHandleEventDTO.getHandleId());
        if (Objects.isNull(shopDetailVO)) {
            throw new LuckException("未找到该店铺信息");
        }
        if (!Objects.equals(shopDetailVO.getShopStatus(), ShopStatus.OPEN.value()) && !Objects.equals(shopDetailVO.getShopStatus(), ShopStatus.STOP.value())) {
            throw new LuckException("店铺不处于营业或者停业状态,不能进行下线");
        }
        shopDetailService.offline(shopDetailVO, offlineHandleEventDTO.getOfflineReason(), sysUserId);
        return ServerResponseEntity.success();
    }

    @GetMapping("/count_by_shop_status")
    @Operation(summary = "根据店铺状态查询店铺数量", description = "根据店铺状态查询店铺数量")
    public ServerResponseEntity<Long> countByShopStatus(@RequestParam(value = "shopStatus", required = false, defaultValue = "3") Integer shopStatus) {
        Long countByShopStatus = shopDetailService.countByShopStatus(shopStatus);
        return ServerResponseEntity.success(countByShopStatus);
    }

    @PostMapping("/online_audit")
    @Operation(summary = "店铺违规下线，重新申请上线审核", description = "店铺违规下线，重新申请上线审核")
    public ServerResponseEntity<Void> onlineAudit(@RequestBody OfflineHandleEventDTO offlineHandleEventDTO) {
        shopDetailService.onlineAudit(offlineHandleEventDTO);
        return ServerResponseEntity.success();
    }

    @PostMapping("/online_open_shop")
    @Operation(summary = "店铺违规下线，平台直接上线店铺", description = "开通通联支付可用")
    public ServerResponseEntity<Void> onlineOpenShop(@RequestBody OfflineHandleEventDTO offlineHandleEventDTO) {
        offlineHandleEventDTO.setStatus(OfflineHandleEventStatus.AGREE_BY_PLATFORM.getValue());
        shopDetailService.onlineOpenShop(offlineHandleEventDTO);
        return ServerResponseEntity.success();
    }

    @GetMapping("/search_shops")
    @Operation(summary = "platform搜索店铺", description = "根据店铺名称搜索店铺")
    public ServerResponseEntity<PageVO<ShopHeadInfoVO>> searchShops(PageDTO pageDTO, ShopSearchDTO shopSearchDTO) {
        PageVO<ShopHeadInfoVO> shopPage = shopDetailService.renovationShopPage(pageDTO, shopSearchDTO, SysTypeEnum.PLATFORM.value());
        return ServerResponseEntity.success(shopPage);
    }
}
