package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.StoreStaffConfig;
import shop.alien.entity.store.excelVo.StoreInfoExpiredRecordsExcelVo;
import shop.alien.entity.store.excelVo.StoreStaffConfigExcelVo;
import shop.alien.entity.store.excelVo.util.ExcelGenerator;
import shop.alien.mapper.StoreStaffConfigMapper;
import shop.alien.store.service.StoreStaffConfigService;
import shop.alien.util.ali.AliOSSUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author: fcw
 * @CreateTime: 2025-04-11
 * @Description: 员工管理
 */

@Service
@RequiredArgsConstructor
public class StoreStaffConfigServiceImpl implements StoreStaffConfigService {

    private final StoreStaffConfigMapper storeStaffConfigMapper;

    private final AliOSSUtil aliOSSUtil;

    @Value("${spring.web.resources.excel-path}")
    private String excelPath;
    @Value("${spring.web.resources.excel-clearing-receipt}")
    private String excelClearingReceipt;
    @Value("${spring.web.resources.excel-generate-path}")
    private String excelGeneratePath;
    @Value("${spring.web.resources.url}")
    private String fileUrl;

    @Override
    public IPage<StoreStaffConfig> getStaffConfigList(int page, int size, String status) {
        IPage<StoreStaffConfig> storePage = new Page<>(page, size);
        QueryWrapper<StoreStaffConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(null != status && !status.isEmpty(), "status", status);
        // 排序规则：先按置顶状态降序（置顶的在前），再按置顶时间降序，最后按创建时间降序
        queryWrapper.orderByDesc("top_status", "top_time", "created_time");
        return storeStaffConfigMapper.selectPage(storePage, queryWrapper);
    }

    @Override
    public int addOrUpdateStaffConfig(StoreStaffConfig storeStaffConfig) {
        // 判断是新增还是更新：id为null或0或负数表示新增
        // 注意：新增时不应该传入id，如果传入了非0的id，需要先查询是否存在
        Integer id = storeStaffConfig.getId();
        
        if (id == null || id == 0) {
            // 新增操作：id为null或0
            Date nowDate = new Date(System.currentTimeMillis());
            storeStaffConfig.setCreatedTime(nowDate);
            // 设置删除标记为0（未删除）- 必须设置，否则可能插入失败
            if (storeStaffConfig.getDeleteFlag() == null) {
                storeStaffConfig.setDeleteFlag(0);
            }
            // 如果状态为空，设置默认状态为待审核（0）
            if (StringUtils.isEmpty(storeStaffConfig.getStatus())) {
                storeStaffConfig.setStatus("0");
            }
            // 新增时，确保id为null，让数据库自动生成
            storeStaffConfig.setId(null);
            return storeStaffConfigMapper.insert(storeStaffConfig);
        } else {
            // 更新操作：id不为null且不为0
            // 先查询记录是否存在，如果不存在则转为新增
            StoreStaffConfig existing = storeStaffConfigMapper.selectById(id);
            if (existing == null) {
                // 记录不存在，转为新增操作
                storeStaffConfig.setId(null); // 重置id，让数据库自动生成
                Date nowDate = new Date(System.currentTimeMillis());
                storeStaffConfig.setCreatedTime(nowDate);
                // 设置删除标记为0（未删除）
                if (storeStaffConfig.getDeleteFlag() == null) {
                    storeStaffConfig.setDeleteFlag(0);
                }
                // 如果状态为空，设置默认状态为待审核（0）
                if (StringUtils.isEmpty(storeStaffConfig.getStatus())) {
                    storeStaffConfig.setStatus("0");
                }
                return storeStaffConfigMapper.insert(storeStaffConfig);
            } else {
                // 记录存在，执行更新
                return storeStaffConfigMapper.updateById(storeStaffConfig);
            }
        }
    }

    @Override
    public Integer audit(Integer id, Integer status, String rejectionReason) {
        StoreStaffConfig storeStaffConfig = new StoreStaffConfig();
        storeStaffConfig.setId(id);
        storeStaffConfig.setStatus(String.valueOf(status));
        storeStaffConfig.setRejectionReason(rejectionReason);
        return storeStaffConfigMapper.updateById(storeStaffConfig);
    }

    @Override
    public StoreStaffConfig getStaffConfigDeatail(Integer id) {
        return storeStaffConfigMapper.selectById(id);
    }

    @Override
    public String staffConfigExport(String status) throws IOException {
        QueryWrapper<StoreStaffConfig> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(status), "status", status);
        wrapper.eq("delete_flag", 0);
        wrapper.orderByDesc("created_time");
        List<StoreStaffConfig> storeStaffConfig = storeStaffConfigMapper.selectList(wrapper);
        storeStaffConfig.forEach(item -> {
            if ("0".equals(item.getStatus())) {
                item.setStatus("待审核");
            } else if ("1".equals(item.getStatus())) {
                item.setStatus("审核通过");
            } else {
                item.setStatus("审核拒绝");
            }

        });
        List<StoreStaffConfigExcelVo> storeStaffConfigs = new ArrayList<>();
        int index = 1;
        for (StoreStaffConfig record : storeStaffConfig) {
            StoreStaffConfigExcelVo storeCouponStatusVo = new StoreStaffConfigExcelVo();
            BeanUtils.copyProperties(record, storeCouponStatusVo);
            storeCouponStatusVo.setId(index++); // 设置序号
            storeStaffConfigs.add(storeCouponStatusVo);
        }
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String filePath = ExcelGenerator.generateExcel(excelPath + excelGeneratePath + fileName + ".xlsx", storeStaffConfigs, StoreStaffConfigExcelVo.class);
        return aliOSSUtil.uploadFile(new File(filePath), "excel/" + fileName + ".xlsx");
    }

    @Override
    public Integer deleteStaffConfig(Integer id) {
        // 使用 MyBatis-Plus 的逻辑删除，会自动将 deleteFlag 设置为 1
        // 因为实体类使用了 @TableLogic 注解
        return storeStaffConfigMapper.deleteById(id);
    }

    @Override
    public Integer setTopStatus(Integer id, Integer topStatus) {
        if (id == null || topStatus == null) {
            return 0;
        }
        LambdaUpdateWrapper<StoreStaffConfig> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(StoreStaffConfig::getId, id);
        lambdaUpdateWrapper.set(StoreStaffConfig::getTopStatus, topStatus);
        if (topStatus == 0) {
            lambdaUpdateWrapper.set(StoreStaffConfig::getTopTime, null);
        } else {
            lambdaUpdateWrapper.set(StoreStaffConfig::getTopTime, new Date());
        }
        return storeStaffConfigMapper.update(null, lambdaUpdateWrapper);
    }

    @Override
    public IPage<StoreStaffConfig> queryStaffList(Integer page, Integer size, Integer storeId, String status) {
        IPage<StoreStaffConfig> storePage = new Page<>(page, size);
        QueryWrapper<StoreStaffConfig> queryWrapper = new QueryWrapper<>();
        // 按照店铺ID查询
        if (storeId != null && storeId > 0) {
            queryWrapper.eq("store_id", storeId);
        }
        // 如果状态不为空，则进行精确匹配查询
//        if (StringUtils.isNotEmpty(status)) {
//            queryWrapper.eq("status", status);
//        }
        // 只查询未删除的记录
        queryWrapper.eq("delete_flag", 0);
        queryWrapper.orderByDesc("created_time");
        return storeStaffConfigMapper.selectPage(storePage, queryWrapper);
    }

    @Override
    public StoreStaffConfig queryStaffDetail(Integer id) {
        if (id == null || id <= 0) {
            return null;
        }
        QueryWrapper<StoreStaffConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.eq("delete_flag", 0);
        return storeStaffConfigMapper.selectOne(queryWrapper);


    }
}
