package com.cool.store.dao;

import cn.hutool.core.collection.CollStreamUtil;
import com.alibaba.excel.util.CollectionUtils;
import com.cool.store.entity.CloseStoreAuditRecordDO;
import com.cool.store.enums.close.CloseStoreAuditStatusEnum;
import com.cool.store.enums.close.RecordTypeEnum;
import com.cool.store.mapper.CloseStoreAuditRecordMapper;
import com.cool.store.request.close.store.CloseStoreQueryRequest;
import com.cool.store.vo.close.store.CloseStoreInfoListVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author suzhuhong
 * @Date 2025/9/22 16:52
 * @Version 1.0
 */
@Repository
public class CloseStoreAuditRecordDAO {

    @Resource
    private CloseStoreAuditRecordMapper closeStoreAuditRecordMapper;


    /**
     * 提交新增记录
     * @param closeStoreId
     * @param userId
     * @return
     */
    public int addSubmitRecord(Long closeStoreId, String userId, String userName) {
        CloseStoreAuditRecordDO closeStoreAuditRecordDO = CloseStoreAuditRecordDO.builder()
                .closeStoreId(closeStoreId)
                .recordType(RecordTypeEnum.CLOSE_STORE_RECORD_TYPE_10.getRecordType())
                .actionRemark("")
                .finishTaskTime(new Date())
                .receiveTaskTime(new Date())
                .handlerUserId(userId)
                .handlerUserName(userName)
                .auditStatus(CloseStoreAuditStatusEnum.PASS.getStatus())
                .handlerUserIds(getUserIds(Collections.singletonList(userId)))
                .build();
        return closeStoreAuditRecordMapper.insertSelective(closeStoreAuditRecordDO);
    }

    /**
     * 提交审批记录
     * @param closeStoreId
     * @param userIdList
     * @return
     */
    public int addApproveRecord(Long closeStoreId, List<String> userIdList) {
        CloseStoreAuditRecordDO closeStoreAuditRecordDO = CloseStoreAuditRecordDO.builder()
                .closeStoreId(closeStoreId)
                .recordType(RecordTypeEnum.CLOSE_STORE_RECORD_TYPE_20.getRecordType())
                .receiveTaskTime(new Date())
                .handlerUserIds(getUserIds(userIdList))
                .auditStatus(CloseStoreAuditStatusEnum.PENDING.getStatus())
                .build();
        return closeStoreAuditRecordMapper.insertSelective(closeStoreAuditRecordDO);
    }

    private String getUserIds(List<String> userIds) {
        String userIdStr = userIds.stream()
                .filter(StringUtils::isNotBlank)
                .distinct()
                .collect(Collectors.joining(","));
        return "," + userIdStr + ",";
    }

    /**
     * 首次发起流程 添加审批记录
     */
    public void addRecord(Long closeStoreId, String userId, String userName, List<String> userIdList) {
        //新增提交审批
        addSubmitRecord(closeStoreId, userId, userName);
        //新增审批记录
        addApproveRecord(closeStoreId, userIdList);
    }

    /**
     * 审批记录更新
     * @param closeStoreAuditRecordDO
     */
    public void updateRecord(CloseStoreAuditRecordDO closeStoreAuditRecordDO) {
        closeStoreAuditRecordMapper.updateByPrimaryKeySelective(closeStoreAuditRecordDO);
    }


    /**
     * 流程记录列表
     * @param closeStoreId
     * @return
     */
    public List<CloseStoreAuditRecordDO> getRecordListByCloseStoreId(Long closeStoreId) {
        if (closeStoreId == null){
            return new ArrayList<>();
        }
        return closeStoreAuditRecordMapper.getRecordListByCloseStoreId(closeStoreId);
    }

    /**
     * 根据id查询审批记录
     * @param id 审批记录id
     * @return 审批记录
     */
    public CloseStoreAuditRecordDO getById(Long id) {
        return closeStoreAuditRecordMapper.selectByPrimaryKey(id);
    }

    /**
     * 删除待处理的审批记录
     * @param closeStoreId 闭店申请id
     */
    public void deletePendingRecord(Long closeStoreId) {
        Example example = new Example(CloseStoreAuditRecordDO.class);
        example.createCriteria()
                .andEqualTo("closeStoreId", closeStoreId)
                .andEqualTo("auditStatus", CloseStoreAuditStatusEnum.PENDING.getStatus())
                .andEqualTo("deleted", 0);
        closeStoreAuditRecordMapper.updateByExampleSelective(CloseStoreAuditRecordDO.builder().deleted(1).build(), example);
    }

    /**
     * 查询权限下的闭店申请审批记录
     * @param request 闭店申请查询Request
     * @param userId 用户id
     * @param isAdmin 是管理员权限
     * @return 闭店申请记录列表VO列表
     */
    public PageInfo<CloseStoreInfoListVO> getCloseStoreAuditList(CloseStoreQueryRequest request, String userId, Boolean isAdmin) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CloseStoreInfoListVO> list = closeStoreAuditRecordMapper.getCloseStoreAuditList(request, userId, isAdmin);
        return new PageInfo<>(list);
    }

    /**
     * 根据闭店申请id查询审批记录
     * @param closeStoreId 闭店申请id
     * @return 审批记录列表
     */
    public List<CloseStoreAuditRecordDO> getListByCloseStoreId(Long closeStoreId) {
        Example example = new Example(CloseStoreAuditRecordDO.class);
        example.createCriteria()
                .andEqualTo("closeStoreId", closeStoreId)
                .andEqualTo("deleted", 0);
        example.setOrderByClause("id ASC");
        return closeStoreAuditRecordMapper.selectByExample(example);
    }

    /**
     * 获取待处理的审批记录
     * @param closeStoreId 闭店申请id
     * @return 闭店申请审批记录
     */
    public CloseStoreAuditRecordDO getPendingAuditRecord(Long closeStoreId) {
        Example example = new Example(CloseStoreAuditRecordDO.class);
        example.createCriteria()
                .andEqualTo("closeStoreId", closeStoreId)
                .andEqualTo("auditStatus", CloseStoreAuditStatusEnum.PENDING.getStatus())
                .andEqualTo("deleted", 0);
        return closeStoreAuditRecordMapper.selectOneByExample(example);
    }

    /**
     * 获取待处理的审批记录
     * @param closeStoreIds 闭店申请id列表
     * @return 闭店申请id->审批记录id
     */
    public Map<Long, Long> getPendingAuditIdByCloseStoreIds(List<Long> closeStoreIds) {
        if (CollectionUtils.isEmpty(closeStoreIds)) {
            return Collections.emptyMap();
        }
        Example example = new Example(CloseStoreAuditRecordDO.class);
        example.createCriteria()
                .andIn("closeStoreId", closeStoreIds)
                .andEqualTo("auditStatus", CloseStoreAuditStatusEnum.PENDING.getStatus())
                .andEqualTo("deleted", 0);
        List<CloseStoreAuditRecordDO> list = closeStoreAuditRecordMapper.selectByExample(example);
        return CollStreamUtil.toMap(list, CloseStoreAuditRecordDO::getCloseStoreId, CloseStoreAuditRecordDO::getId);
    }
}
