package com.cpop.system.business.controller.backstage;

import com.alibaba.excel.EasyExcel;
import com.cpop.core.base.entity.R;
import com.cpop.system.business.bo.StoreRunOffBo;
import com.cpop.system.business.bo.StoreSignRenewPageBo;
import com.cpop.system.business.bo.StoreSignRenewXmlBo;
import com.cpop.system.business.dto.StoreRenewDto;
import com.cpop.system.business.service.StoreSignService;
import com.cpop.system.business.vo.StoreSignRenewPageVo;
import com.mybatisflex.core.paginate.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 校区-签约表 控制层。
 *
 * @author DB
 * @since 2023-12-13
 */
@RestController
@Tag(name = "校区签约续费接口")
@RequestMapping("/backstage/storeSignRenew")
public class BackstageStoreSignController {

    @Autowired
    private StoreSignService storeSignService;

    /**
     * 获取校区签约续费分页
     * @author DB
     * @since 2024/3/7
     * @return R<Page<StorePageVo>>
     */
    @GetMapping("/getStoreSignRenewPage")
    @Operation(summary = "获取校区签约续费分页")
    public R<Page<StoreSignRenewPageVo>> getStoreSignRenewPage(StoreSignRenewPageBo bo) {
        Page<StoreSignRenewPageVo> page = storeSignService.getStoreSignRenewPage(bo);
        return R.ok(page);
    }

    /**
     * 机构/店铺流失
     * @author DB
     * @since 2023/12/14
     * @param bo 请求参数
     * @return R<Void>
     */
    @PostMapping("/runOff")
    @Operation(summary = "机构流失")
    public R<Void> runOff(@RequestBody @Validated StoreRunOffBo bo) {
        storeSignService.runOff(bo);
        return R.ok();
    }

    /**
     * 获取签约续费导出数据
     * @author DB
     * @since 2023/12/14
     * @param response 响应
     * @param bo 请求参数
     */
    @PostMapping("/getSignRenewXml")
    @Operation(summary = "获取签约续费导出数据")
    public void getRenewXml(HttpServletResponse response, @RequestBody @Validated StoreSignRenewXmlBo bo) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyExcel没有关系
        String fileName = URLEncoder.encode("已续费数据", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), StoreRenewDto.class).sheet("记录").doWrite(storeSignService.getSignRenewXml(bo));
    }

}
