package shop.alien.store.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.LifeAppealManage;
import shop.alien.entity.store.LifeNotice;
import shop.alien.entity.store.StoreComment;
import shop.alien.entity.store.StoreCommentAppeal;
import shop.alien.entity.store.dto.LifeAppealManageDto;
import shop.alien.entity.store.excelVo.LifeAppealManageExcelVo;
import shop.alien.entity.store.excelVo.StoreInfoExcelVo;
import shop.alien.entity.store.excelVo.util.ExcelGenerator;
import shop.alien.entity.result.R;
import shop.alien.entity.store.vo.LifeAppealManageVo;
import shop.alien.mapper.LifeAppealManageMapper;
import shop.alien.mapper.LifeNoticeMapper;
import shop.alien.mapper.StoreCommentAppealMapper;
import shop.alien.mapper.StoreCommentMapper;
import shop.alien.util.type.LifeNoticeUtil;
import shop.alien.util.ali.AliOSSUtil;

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

/**
 * 申诉管理
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LifeAppealManageService {

    private final LifeAppealManageMapper lifeAppealManageMapper;

    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeNoticeUtil lifeNoticeUtil;

    private final StoreCommentAppealMapper storeCommentAppealMapper;

    private final StoreCommentMapper storeCommentMapper;

    private final AliOSSUtil aliOSSUtil;

    @Value("${spring.web.resources.excel-path}")
    private String excelPath;

    @Value("${spring.web.resources.excel-generate-path}")
    private String excelGeneratePath;

    public IPage<LifeAppealManageVo> getStores(int page, int size, String storeName, String storeContact, String storePhone, String appealType) {
        IPage<LifeAppealManageVo> storePage = new Page<>(page, size);
        return lifeAppealManageMapper.getAppealManagement(storePage, storeName, storeContact, storePhone, appealType);
    }

    public int addOrUpdateStore(LifeAppealManage store) {
        if (StringUtils.isEmpty(store.getId())) {
            Date nowDate = new Date(System.currentTimeMillis());
            store.setAppealTime(nowDate);
            return lifeAppealManageMapper.insert(store);
        } else {
            return lifeAppealManageMapper.updateById(store);
        }
    }

    public int setStoreState(LifeAppealManageDto lifeAppealManageDto) {
        StoreCommentAppeal storeCommentAppeal = storeCommentAppealMapper.selectById(lifeAppealManageDto.getId());
        storeCommentAppeal.setAppealStatus(Integer.parseInt(lifeAppealManageDto.getAppealType()));

        //如果通过，删除评论
        if ("1".equals(lifeAppealManageDto.getAppealType())) {
            LambdaQueryWrapper<StoreComment> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StoreComment::getId, storeCommentAppeal.getCommentId());
            storeCommentMapper.delete(queryWrapper);
        }
        LifeNotice notice = new LifeNotice();
        if (lifeAppealManageDto.getAppealType().equals("1")) {
            notice.setContext("系统同意了您的申请");
        } else {
            notice.setContext("系统驳回了您的申请");
        }
        notice.setCreatedTime(new Date());
        notice.setNoticeType(1);
        lifeNoticeUtil.fillUserTypeAndRefId(notice);
        lifeNoticeMapper.insert(notice);
        return storeCommentAppealMapper.updateById(storeCommentAppeal);
    }

    public int setIsRead(String id) {
        LambdaUpdateWrapper<LifeAppealManage> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(LifeAppealManage::getId, id)
                .set(LifeAppealManage::getIsRead, "1");
        return lifeAppealManageMapper.update(null, updateWrapper);
    }

    public List<LifeAppealManage> getAppealByStoreId(String storeId) {
        LambdaUpdateWrapper<LifeAppealManage> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(LifeAppealManage::getStoreId, storeId)
                .orderByDesc(LifeAppealManage::getAppealTime);
        return lifeAppealManageMapper.selectList(wrapper);
    }

    /**
     * 商家端-申诉历史
     *
     * @param pageNum    页数
     * @param pageSize   页容
     * @param storeId    门店id
     * @param appealType 审批状态:1:已同意,2:已驳回,3:待处理
     * @return IPage<LifeAppealManage>
     */
    public IPage<LifeAppealManageVo> getAppealHistory(Integer pageNum, Integer pageSize, Integer storeId, Integer appealType) {
        IPage<LifeAppealManageVo> appealHistoryPage = new Page<>(pageNum, pageSize);
        QueryWrapper<LifeAppealManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(storeId != null, "a.store_id", storeId)
                .eq(appealType != null, "a.appeal_type", appealType)
                .eq("a.delete_flag", 0)
                .eq("b.delete_flag", 0)
                .orderByDesc("a.appeal_time");
        return lifeAppealManageMapper.getAppealHistory(appealHistoryPage, queryWrapper);
    }

    public String appealsExport(String appealType, String storeName, String storePhone) throws IOException {
        QueryWrapper<LifeAppealManage> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(appealType), "appeal_status", appealType);
        wrapper.like(StringUtils.isNotEmpty(storeName), "store_name", storeName);
        wrapper.like(StringUtils.isNotEmpty(storePhone), "store_phone", storePhone);
        wrapper.eq("delete_flag", 0);
        wrapper.orderByDesc("created_time");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/M/d HH:mm:ss");
        List<LifeAppealManageVo> storeStaffConfig = lifeAppealManageMapper.getAppealManagement(storeName, storePhone, appealType, null);
        storeStaffConfig.forEach(item -> {
            if ("0".equals(item.getAppealType())) {
                item.setAppealType("待审批");
            } else if ("1".equals(item.getAppealType())) {
                item.setAppealType("已同意");
            } else {
                item.setAppealType("已驳回");
            }
        });
        List<LifeAppealManageExcelVo> storeStaffConfigs = new ArrayList<>();
        int index = 1;
        for (LifeAppealManage record : storeStaffConfig) {
            LifeAppealManageExcelVo storeCouponStatusVo = new LifeAppealManageExcelVo();
            BeanUtils.copyProperties(record, storeCouponStatusVo);
            storeCouponStatusVo.setId(index++); // 设置序号
            storeCouponStatusVo.setAppealTime(sdf.format(record.getAppealTime()));
            storeStaffConfigs.add(storeCouponStatusVo);
        }
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String filePath = ExcelGenerator.generateExcel(excelPath + excelGeneratePath + fileName + ".xlsx", storeStaffConfigs, LifeAppealManageExcelVo.class);
        String url = aliOSSUtil.uploadFile(new File(filePath), "excel/" + fileName + ".xlsx");
        return url;
    }

    /**
     * 平台端：根据申诉主键查询详情（与「获取申诉列表」同一数据源 store_comment_appeal）。
     *
     * @param id 评论申诉表主键 {@code store_comment_appeal.id}
     * @return 成功返回详情；id 为空或记录不存在返回失败信息
     */
    public R<LifeAppealManageVo> getAppealDetailById(Integer id) {
        if (id == null) {
            log.warn("LifeAppealManageService.getAppealDetailById: 申诉ID为空");
            return R.fail("申诉ID不能为空");
        }
        LifeAppealManageVo appealDetail = lifeAppealManageMapper.getAppealDetailById(id);
        if (appealDetail == null) {
            log.info("LifeAppealManageService.getAppealDetailById: 未找到记录, id={}", id);
            return R.fail("申诉记录不存在");
        }
        log.info("LifeAppealManageService.getAppealDetailById: 查询成功, id={}, storeId={}", id, appealDetail.getStoreId());
        return R.data(appealDetail);
    }
}
