package com.czg.service.account.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjUtil;
import com.czg.account.dto.ShopBranchDTO;
import com.czg.account.entity.ShopConfig;
import com.czg.account.entity.ShopInfo;
import com.czg.account.enums.BranchDataSyncMethodEnum;
import com.czg.account.enums.ShopTypeEnum;
import com.czg.account.param.ShopBranchParam;
import com.czg.account.service.ShopBranchService;
import com.czg.constants.SystemConstants;
import com.czg.exception.CzgException;
import com.czg.product.service.ShopSyncService;
import com.czg.sa.StpKit;
import com.czg.service.account.mapper.ShopConfigMapper;
import com.czg.service.account.mapper.ShopInfoMapper;
import com.czg.utils.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 分店管理Service实现类
 *
 * @author tankaikai
 * @since 2025-04-07 14:20
 */
@Slf4j
@Service
public class ShopBranchServiceImpl implements ShopBranchService {

    @Resource
    private ShopConfigMapper shopConfigMapper;
    @Resource
    private ShopInfoMapper shopInfoMapper;
    @DubboReference
    private ShopSyncService shopSyncService;


    @Override
    public Page<ShopBranchDTO> findPage(ShopBranchParam param) {
        PageHelper.startPage(PageUtil.buildPageHelp());
        List<ShopBranchDTO> branchList = shopConfigMapper.findBranchList(param);
        return PageUtil.convert(new PageInfo<>(branchList));
    }

    @Override
    public void settingDataSyncMethod(Long shopId, String dataSyncMethod) {
        ShopInfo shopInfo = shopInfoMapper.selectOneById(shopId);
        if (shopInfo == null) {
            throw new CzgException("店铺不存在");
        }
        ShopConfig shopConfig = shopConfigMapper.selectOneById(shopInfo.getId());
        if (shopConfig == null) {
            throw new CzgException("店铺配置信息不存在");
        }
        if (ShopTypeEnum.ONLY.getValue().equals(shopInfo.getShopType())) {
            throw new CzgException("单店不支持设置数据同步方式");
        }
        if (ObjUtil.defaultIfNull(shopInfo.getIsHeadShop(), SystemConstants.OneZero.ZERO) == SystemConstants.OneZero.ZERO) {
            throw new CzgException("非主店不能设置数据同步方式");
        }
        boolean contains = BranchDataSyncMethodEnum.checkValue(dataSyncMethod);
        if (!contains) {
            throw new CzgException("非法的数据同步方式值");
        }
        shopConfig.setBranchDataSyncMethod(dataSyncMethod);
        shopConfigMapper.update(shopConfig);
    }

    @Override
    public void dataSyncEnable(Long branchShopId) {
        Long shopId = StpKit.USER.getShopId(0L);
        ShopInfo shopInfo = shopInfoMapper.selectOneById(shopId);
        if (shopInfo == null) {
            throw new CzgException("主店铺不存在");
        }
        ShopConfig shopConfig = shopConfigMapper.selectOneById(shopInfo.getId());
        if (shopConfig == null) {
            throw new CzgException("主店铺配置信息不存在");
        }
        if (ShopTypeEnum.ONLY.getValue().equals(shopInfo.getShopType())) {
            throw new CzgException("数据错误：主店铺类型为单店");
        }
        if (ObjUtil.defaultIfNull(shopInfo.getIsHeadShop(), 0) == SystemConstants.OneZero.ZERO) {
            throw new CzgException("数据错误：当前店铺不是主店");
        }
        ShopInfo branchShop = shopInfoMapper.selectOneByQuery(QueryWrapper.create().eq(ShopInfo::getMainId, shopInfo.getId()).eq(ShopInfo::getId, branchShopId));
        if (branchShop == null) {
            throw new CzgException("对应的分店信息不存在");
        }
        if (ShopTypeEnum.ONLY.getValue().equals(branchShop.getShopType())) {
            throw new CzgException("数据错误：分店店铺类型错误");
        }
        ShopConfig branchConfig = shopConfigMapper.selectOneById(branchShop.getId());
        branchConfig.setIsEnableProdSync(SystemConstants.OneZero.ONE);
        branchConfig.setIsEnableConsSync(SystemConstants.OneZero.ONE);
        branchConfig.setIsEnableVipSync(SystemConstants.OneZero.ONE);
        shopConfigMapper.update(branchConfig);
        long sysUserId = StpKit.USER.getLoginIdAsLong();
        ThreadUtil.execAsync(() -> {
            ThreadUtil.safeSleep(3000L);
            log.info("开始同步，店铺id：{}，分店id：{} 操作人Id:{}", shopId, branchShop.getId(), sysUserId);
            // 同步商品和耗材
            shopSyncService.sync(shopId, branchShop.getId(), sysUserId);
            log.info("同步结束，店铺id：{}，分店id：{} 操作人Id:{}", shopId, branchShop.getId(), sysUserId);
        });
    }

    @Override
    public void accountEnable(Long branchShopId) {
        Long shopId = StpKit.USER.getShopId(0L);
        ShopInfo shopInfo = shopInfoMapper.selectOneById(shopId);
        if (shopInfo == null) {
            throw new CzgException("主店铺不存在");
        }
        ShopConfig shopConfig = shopConfigMapper.selectOneById(shopInfo.getId());
        if (shopConfig == null) {
            throw new CzgException("主店铺配置信息不存在");
        }
        if (ShopTypeEnum.ONLY.getValue().equals(shopInfo.getShopType())) {
            throw new CzgException("数据错误：主店铺类型为单店");
        }
        if (ObjUtil.defaultIfNull(shopInfo.getIsHeadShop(), 0) == SystemConstants.OneZero.ZERO) {
            throw new CzgException("数据错误：当前店铺不是主店");
        }
        ShopInfo branchShop = shopInfoMapper.selectOneByQuery(QueryWrapper.create().eq(ShopInfo::getMainId, shopInfo.getId()).eq(ShopInfo::getId, branchShopId));
        if (branchShop == null) {
            throw new CzgException("对应的分店信息不存在");
        }
        if (ShopTypeEnum.ONLY.getValue().equals(branchShop.getShopType())) {
            throw new CzgException("数据错误：分店店铺类型错误");
        }
        ShopConfig branchConfig = shopConfigMapper.selectOneById(branchShop.getId());
        branchConfig.setIsAllowAccountLogin(SystemConstants.OneZero.ONE);
        shopConfigMapper.update(branchConfig);
    }

    @Override
    public void accountDisable(Long branchShopId) {
        Long shopId = StpKit.USER.getShopId(0L);
        ShopInfo shopInfo = shopInfoMapper.selectOneById(shopId);
        if (shopInfo == null) {
            throw new CzgException("主店铺不存在");
        }
        ShopConfig shopConfig = shopConfigMapper.selectOneById(shopInfo.getId());
        if (shopConfig == null) {
            throw new CzgException("主店铺配置信息不存在");
        }
        if (ShopTypeEnum.ONLY.getValue().equals(shopInfo.getShopType())) {
            throw new CzgException("数据错误：主店铺类型为单店");
        }
        if (ObjUtil.defaultIfNull(shopInfo.getIsHeadShop(), 0) == SystemConstants.OneZero.ZERO) {
            throw new CzgException("数据错误：当前店铺不是主店");
        }
        ShopInfo branchShop = shopInfoMapper.selectOneByQuery(QueryWrapper.create().eq(ShopInfo::getMainId, shopInfo.getId()).eq(ShopInfo::getId, branchShopId));
        if (branchShop == null) {
            throw new CzgException("对应的分店信息不存在");
        }
        if (ShopTypeEnum.ONLY.getValue().equals(branchShop.getShopType())) {
            throw new CzgException("数据错误：分店店铺类型错误");
        }
        ShopConfig branchConfig = shopConfigMapper.selectOneById(branchShop.getId());
        branchConfig.setIsAllowAccountLogin(SystemConstants.OneZero.ZERO);
        shopConfigMapper.update(branchConfig);
    }

    @Override
    public boolean isAllowAccountLogin(Long branchShopId) {
        ShopConfig shopConfig = shopConfigMapper.selectOneById(branchShopId);
        if (shopConfig == null) {
            return true;
        }
        if (shopConfig.getMainId() == null) {
            return true;
        }
        if (shopConfig.getIsAllowAccountLogin() == SystemConstants.OneZero.ONE) {
            return true;
        }
        return false;
    }
}
