package com.cool.store.dao;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.constants.RedisConstant;
import com.cool.store.entity.CloseStoreFileInfoDO;
import com.cool.store.enums.close.FileStatusEnum;
import com.cool.store.mapper.CloseStoreFileInfoMapper;
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:53
 * @Version 1.0
 */
@Repository
@RequiredArgsConstructor
public class CloseStoreFileInfoDAO {
    private final CloseStoreFileInfoMapper closeStoreFileInfoMapper;
    private final RedisUtilPool redisUtilPool;

    /**
     * 批量更新
     * @param list 实体列表
     * @return boolean
     */
    public boolean updateBatch(List<CloseStoreFileInfoDO> list) {
        return closeStoreFileInfoMapper.updateBatch(list) > 0;
    }

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

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

    /**
     * 提交材料
     */
    public Boolean updateFile(Long id, String urls, Integer receivedFile) {
        return closeStoreFileInfoMapper.updateFile(id, urls, receivedFile) > 0;
    }

    /**
     * 根据闭店申请id将所有资料状态改为审批中
     */
    public void updateAllFileStatus(Long closeStoreId) {
        Example example = new Example(CloseStoreFileInfoDO.class);
        example.createCriteria()
                .andEqualTo("closeStoreId", closeStoreId);
        closeStoreFileInfoMapper.updateByExampleSelective(CloseStoreFileInfoDO.builder().fileStatus(FileStatusEnum.APPROVING.getStatus()).build(), example);
    }

    public void updateSelective(CloseStoreFileInfoDO closeStoreFileInfoDO) {
        closeStoreFileInfoMapper.updateByPrimaryKeySelective(closeStoreFileInfoDO);
    }

    public CloseStoreFileInfoDO getById(Long id) {
        return closeStoreFileInfoMapper.selectByPrimaryKey(id);
    }

    /**
     * 更新材料状态为审批状态
     * @param closeStoreId 闭店申请id
     */
    public void updateFileStatusToApproveStatus(Long closeStoreId) {
        closeStoreFileInfoMapper.updateFileStatusToApproveStatus(closeStoreId);
    }
}
