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


import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.api.multishop.constant.ShopStatus;
import com.tmerclub.cloud.api.multishop.vo.ShopDetailVO;
import com.tmerclub.cloud.api.platform.constant.OfflineHandleEventType;
import com.tmerclub.cloud.api.platform.dto.OfflineHandleEventDTO;
import com.tmerclub.cloud.api.platform.feign.OfflineHandleEventFeignClient;
import com.tmerclub.cloud.api.platform.vo.OfflineHandleEventVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.multishop.dto.ShopDetailDTO;
import com.tmerclub.cloud.multishop.service.ShopAllinpayService;
import com.tmerclub.cloud.multishop.service.ShopDetailService;
import com.tmerclub.cloud.multishop.vo.ShopStatusInfoVO;
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.web.bind.annotation.*;

import java.util.Objects;

/**
 * @author lth
 */
@RestController("multishopShopDetailController")
@RequestMapping("/m/applyShop/shopDetail")
@Tag(name = "multishop-店铺信息")
public class ShopDetailController {

    @Autowired
    private ShopDetailService shopDetailService;
    @DubboReference
    private OfflineHandleEventFeignClient offlineHandleEventFeignClient;
    @Autowired
    private ShopAllinpayService shopAllinpayService;

    @PostMapping
    @Operation(summary = "创建店铺", description = "创建店铺")
    public ServerResponseEntity<Void> createShop(@RequestBody @Valid ShopDetailDTO shopDetailDTO) {
        if (!Objects.equals(AuthUserContext.get().getTenantId(), Constant.DEFAULT_SHOP_ID)) {
            throw new LuckException("店铺已存在,不能重复创建");
        }
        this.dealWithUpdateOrCreateInfo(shopDetailDTO);
        shopDetailService.createShop(shopDetailDTO);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "更新店铺基本信息", description = "更新店铺基本信息")
    public ServerResponseEntity<Void> update(@RequestBody @Valid ShopDetailDTO shopDetailDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        if (Objects.equals(shopId, Constant.DEFAULT_SHOP_ID)) {
            throw new LuckException("店铺不存在,无法更新");
        }
        shopDetailDTO.setShopId(shopId);
        this.dealWithUpdateOrCreateInfo(shopDetailDTO);
        shopDetailService.update(shopDetailDTO);
        return ServerResponseEntity.success();
    }

    @PostMapping("/storage")
    @Operation(summary = "存储店铺基本信息", description = "存储店铺基本信息,不存在则新增，已存在则更新")
    public ServerResponseEntity<Void> storage(@RequestBody @Valid ShopDetailDTO shopDetailDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        this.dealWithUpdateOrCreateInfo(shopDetailDTO);
        if (Objects.equals(shopId, Constant.DEFAULT_SHOP_ID)) {
            // 店铺不存在，新增
            shopDetailService.createShop(shopDetailDTO);
        } else {
            // 店铺已存在，更新
            shopDetailDTO.setShopId(shopId);
            shopDetailService.update(shopDetailDTO);
        }
        return ServerResponseEntity.success();
    }

    @GetMapping
    @Operation(summary = "获取店铺基本信息", description = "获取店铺基本信息")
    public ServerResponseEntity<ShopDetailVO> get() {
        Long shopId = AuthUserContext.get().getTenantId();
        if (Objects.equals(shopId, Constant.DEFAULT_SHOP_ID)) {
            // 店铺未创建
            return ServerResponseEntity.success(null);
        }
        ShopDetailVO shopDetailVO = shopDetailService.getByShopId(shopId);
        if (Objects.nonNull(shopDetailVO) && StrUtil.isNotBlank(shopDetailVO.getContactPhone())) {
            shopDetailVO.setContactPhone(PhoneUtil.hideBetween(shopDetailVO.getContactPhone()).toString());
        }
        return ServerResponseEntity.success(shopDetailVO);
    }

    @GetMapping("/get_status_info")
    @Operation(summary = "获取店铺状态信息", description = "获取店铺状态信息")
    public ServerResponseEntity<ShopStatusInfoVO> getShopStatusInfo() {
        Long shopId = AuthUserContext.get().getTenantId();
        ShopDetailVO shopDetailVO = shopDetailService.getByShopId(shopId);
        if (Objects.isNull(shopDetailVO)) {
            throw new LuckException("店铺不存在");
        }
        ShopStatusInfoVO shopStatusInfoVO = new ShopStatusInfoVO();
        shopStatusInfoVO.setShopStatus(shopDetailVO.getShopStatus());
        shopStatusInfoVO.setContractStartTime(shopDetailVO.getContractStartTime());
        shopStatusInfoVO.setContractEndTime(shopDetailVO.getContractEndTime());
        if (Objects.equals(shopDetailVO.getShopStatus(), ShopStatus.OFFLINE.value())) {
            ServerResponseEntity<OfflineHandleEventVO> offlineHandleEventRes = offlineHandleEventFeignClient.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.SHOP.getValue(), shopId, null);
            if (!offlineHandleEventRes.isSuccess()) {
                throw new LuckException(offlineHandleEventRes.getMsg());
            }
            OfflineHandleEventVO offlineHandleEventVO = offlineHandleEventRes.getData();
            if (Objects.nonNull(offlineHandleEventVO)) {
                shopStatusInfoVO.setOfflineReason(offlineHandleEventVO.getOfflineReason());
                shopStatusInfoVO.setOfflineStatus(offlineHandleEventVO.getStatus());
            } else if (shopAllinpayService.getIsAllinpay()) {
                shopStatusInfoVO.setOfflineReason("平台开启通联支付，请重新提交工商信息与财务信息");
            }
        }
        return ServerResponseEntity.success(shopStatusInfoVO);
    }

    @PostMapping("/create_allinpay_member")
    @Operation(summary = "给还没有创建通联账户的商家创建一个", description = "给还没有创建通联账户的商家创建一个")
    public ServerResponseEntity<Void> createAllinpayMemberByShopId() {
        shopDetailService.createAllinpayMemberByShopId(AuthUserContext.get().getTenantId());
        shopDetailService.removeCacheByShopId(AuthUserContext.get().getTenantId());
        return ServerResponseEntity.success();
    }

    @PostMapping("/auditApply")
    @Operation(summary = "店铺重新申请上线", description = "店铺重新申请上线")
    public ServerResponseEntity<Void> auditApply(@RequestBody OfflineHandleEventDTO offlineHandleEventDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        offlineHandleEventDTO.setHandleId(shopId);
        shopDetailService.auditApply(offlineHandleEventDTO);
        return ServerResponseEntity.success();
    }

    /**
     * 处理店铺信息，这些信息商家无法直接修改
     * @param shopDetailDTO
     */
    private void dealWithUpdateOrCreateInfo(ShopDetailDTO shopDetailDTO) {
        if (Objects.isNull(shopDetailDTO)) {
            return;
        }
        shopDetailDTO.setContractEndTime(null);
        shopDetailDTO.setContractStartTime(null);
        shopDetailDTO.setShopStatus(null);
        shopDetailDTO.setType(null);
    }
}
