package com.cool.store.dao;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.constants.RedisConstant;
import com.cool.store.entity.CloseStoreAccountInfoDO;
import com.cool.store.mapper.CloseStoreAccountInfoMapper;
import com.cool.store.utils.RedisUtilPool;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @Author suzhuhong
 * @Date 2025/9/22 16:54
 * @Version 1.0
 */
@Repository
@RequiredArgsConstructor
public class CloseStoreAccountInfoDAO {
    private final CloseStoreAccountInfoMapper closeStoreAccountInfoMapper;
    private final RedisUtilPool redisUtilPool;

    /**
     * 根据闭店申请id查询
     * @param closeStoreId 闭店申请id
     * @return 账号列表
     */
    public List<CloseStoreAccountInfoDO> getByCloseStoreId(Long closeStoreId) {
        return closeStoreAccountInfoMapper.select(CloseStoreAccountInfoDO.builder().closeStoreId(closeStoreId).build());
    }

    /**
     * 根据主键id查询
     * @param id 主键id
     * @return 账号信息
     */
    public CloseStoreAccountInfoDO getById(Long id) {
        return closeStoreAccountInfoMapper.selectByPrimaryKey(id);
    }

    /**
     * 修改账号状态
     * @param id 主键id
     * @param status 状态
     */
    public void updateStatus(Long id, Integer status) {
        closeStoreAccountInfoMapper.updateByPrimaryKeySelective(CloseStoreAccountInfoDO.builder().id(id).status(status).build());
    }

    /**
     * 初始化数据
     * @param closeStoreId 闭店申请id
     */
    public void init(Long closeStoreId) {
        String accountInitJson = redisUtilPool.getString(RedisConstant.CLOSE_STORE_ACCOUNT_INIT);
        List<CloseStoreAccountInfoDO> accountList = JSONObject.parseArray(accountInitJson, CloseStoreAccountInfoDO.class);
        accountList.forEach(v -> v.setCloseStoreId(closeStoreId));
        closeStoreAccountInfoMapper.insertBatch(accountList);
    }

    /**
     * 是否存在未关闭的账号
     * @param closeStoreId 闭店申请id
     * @return 是否存在
     */
    public boolean existNotCloseAccount(Long closeStoreId) {
        Example example = new Example(CloseStoreAccountInfoDO.class);
        example.createCriteria()
                .andEqualTo("closeStoreId", closeStoreId)
                .andNotEqualTo("status", 2);
        return closeStoreAccountInfoMapper.selectCountByExample(example) > 0;
    }
}
