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

import com.alibaba.excel.EasyExcel;
import com.cpop.core.base.R;
import com.cpop.system.business.bo.StoreRenewPageBo;
import com.cpop.system.business.bo.StoreRenewXmlBo;
import com.cpop.system.business.bo.StoreRunOffBo;
import com.cpop.system.business.dto.StoreRenewDto;
import com.cpop.system.business.service.StoreSignService;
import com.cpop.system.business.vo.StoreRenewPageVo;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

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

    @Autowired
    private StoreSignService storeSignService;

    /**
     * 分页查询校区续费
     * @author DB
     * @since 2023/12/14
     * @param bo 请求参数
     * @return Page<StoreSign>
     */
    @GetMapping("/getStoreRenewPage")
    @ApiOperation("分页查询校区续费")
    public R<Page<StoreRenewPageVo>> getStoreRenewPage(@ApiParam("分页信息") @Validated StoreRenewPageBo bo) {
        Page<StoreRenewPageVo> page = storeSignService.getStoreRenewPage(bo);
        return R.ok(page);
    }

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

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

}
