package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.excelVo.util.ExcelExporter;
import shop.alien.entity.store.vo.PlatformShopMembershipAdminRowVo;
import shop.alien.mapper.PlatformShopMembershipAdminMapper;
import shop.alien.store.service.PlatformShopMembershipAdminQueryService;

import java.net.URLEncoder;
import java.util.List;

@Service
@RequiredArgsConstructor
public class PlatformShopMembershipAdminQueryServiceImpl implements PlatformShopMembershipAdminQueryService {

    private final PlatformShopMembershipAdminMapper platformShopMembershipAdminMapper;

    @Override
    public IPage<PlatformShopMembershipAdminRowVo> pageStores(
            String keyword,
            Integer membershipUiStatus,
            String expiryStart,
            String expiryEnd,
            int pageNum,
            int pageSize) {
        Page<PlatformShopMembershipAdminRowVo> p = new Page<>(pageNum, pageSize);
        return platformShopMembershipAdminMapper.selectStoreMembershipPage(p, keyword, membershipUiStatus, expiryStart, expiryEnd);
    }

    @Override
    public ResponseEntity<byte[]> exportStores(
            String keyword,
            Integer membershipUiStatus,
            String expiryStart,
            String expiryEnd) {
        try {
            List<PlatformShopMembershipAdminRowVo> list =
                    platformShopMembershipAdminMapper.selectStoreMembershipList(keyword, membershipUiStatus, expiryStart, expiryEnd);
            String[] headers = {"商家名称", "联系人", "联系方式", "开通日期", "到期日期", "状态"};
            byte[] excelData = ExcelExporter.exportToExcel(list, headers, "已购买会员商家列表");
            HttpHeaders responseHeaders = new HttpHeaders();
            responseHeaders.add(
                    "Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode("已购买会员商家列表.xlsx", "UTF-8") + "\";charset=utf-8");
            responseHeaders.set("Charset", "UTF-8");
            return new ResponseEntity<>(excelData, responseHeaders, HttpStatus.OK);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
