package cn.iocoder.yudao.module.system.controller.admin.yk;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.system.controller.admin.yk.vo.*;
import cn.iocoder.yudao.module.system.dal.dataobject.yk.YkElderlyDeliveryDO;
import cn.iocoder.yudao.module.system.dal.dataobject.yk.YkElderlyExpenseRecordDO;
import cn.iocoder.yudao.module.system.dal.dataobject.home.HomeElderlyInfoDO;
import cn.iocoder.yudao.module.system.dal.dataobject.yk.YkElderlySelfFundedRecord;
import cn.iocoder.yudao.module.system.service.yk.YkElderlyInfoService;
import cn.iocoder.yudao.module.system.service.yk.YkElderlySelfFundedRecordService;
import com.alibaba.excel.EasyExcel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.io.IOException;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 颐康中心长者信息")
@RestController
@RequestMapping("/ykCenter")
@Validated
public class YkElderlyInfoController {

    @Autowired
    private YkElderlyInfoService ykElderlyInfoService;

    @Autowired
    private YkElderlySelfFundedRecordService ykElderlySelfFundedRecordService;

    @PostMapping("/elderly/create")
    @Operation(summary = "创建颐康中心长者信息")
    public CommonResult<Long> createElderlyInfo(@Valid @RequestBody YkElderlyInfoSaveReqVO createReqVO) {
        return success(ykElderlyInfoService.createElderlyInfo(createReqVO));
    }

    @PutMapping("/elderly/update")
    @Operation(summary = "更新颐康中心长者信息")
    public CommonResult<Boolean> updateElderlyInfo(@Valid @RequestBody YkElderlyInfoSaveReqVO updateReqVO) {
        ykElderlyInfoService.updateElderlyInfo(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/elderly/delete")
    @Operation(summary = "删除颐康中心长者信息")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteElderlyInfo(@RequestParam("id") Long id) {
        ykElderlyInfoService.deleteElderlyInfo(id);
        return success(true);
    }

    @DeleteMapping("/elderly/deleteBatch")
    @Operation(summary = "批量删除颐康中心长者信息")
    @TenantIgnore
    public CommonResult<Boolean> batchDeleteElderlyInfo(@RequestBody @NotEmpty(message = "ID列表不能为空") List<Long> ids) {
        ykElderlyInfoService.batchDeleteElderlyInfo(ids);
        return success(true);
    }

    @GetMapping("/elderly/detail")
    @Operation(summary = "获得颐康中心长者信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<YkElderlyInfoRespVO> getElderlyInfo(@RequestParam("id") Long id) {
        HomeElderlyInfoDO elderlyInfo = ykElderlyInfoService.getElderlyInfo(id);
        return success(cn.iocoder.yudao.framework.common.util.object.BeanUtils.toBean(elderlyInfo, YkElderlyInfoRespVO.class));
    }

    @GetMapping("/elderly/list")
    @Operation(summary = "获得颐康中心长者信息分页")
    @TenantIgnore
    public CommonResult<PageResult<YkElderlyInfoRespVO>> getElderlyInfoPage(@Valid YkElderlyInfoPageReqVO pageVO) {
        PageResult<HomeElderlyInfoDO> pageResult = ykElderlyInfoService.getElderlyInfoPage(pageVO);
        return success(cn.iocoder.yudao.framework.common.util.object.BeanUtils.toBean(pageResult, YkElderlyInfoRespVO.class));
    }

    @PostMapping("/elderly/import")
    @Operation(summary = "导入颐康中心长者信息")
    public CommonResult<String> importElderlyInfo(@RequestPart("file") MultipartFile file) throws IOException {
        List<YkElderlyInfoImportVO> dataList = ExcelUtils.read(file, YkElderlyInfoImportVO.class);
        for (YkElderlyInfoImportVO data : dataList) {
            YkElderlyInfoSaveReqVO saveReqVO = BeanUtils.toBean(data, YkElderlyInfoSaveReqVO.class);
            ykElderlyInfoService.createElderlyInfo(saveReqVO);
        }
        return success("导入成功，共导入" + dataList.size() + "条数据");
    }

    @GetMapping("/elderly/downloadExcel")
    @Operation(summary = "下载颐康中心长者导入模板")
    public void downloadFile(HttpServletResponse response) throws IOException {
        String filePath = "files/颐康中心长者导入模板.xlsx";
        ClassPathResource classPathResource = new ClassPathResource(filePath);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=颐康中心长者导入模板");
        IOUtils.copy(classPathResource.getInputStream(), response.getOutputStream());
        response.flushBuffer();
    }

//    @GetMapping("/export-excel")
//    @Operation(summary = "导出颐康中心长者信息 Excel")
//    public void exportElderlyInfoExcel(@Valid YkElderlyInfoExportReqVO exportReqVO,
//              HttpServletResponse response) throws IOException {
//        List<HomeElderlyInfoDO> list = ykElderlyInfoService.getElderlyInfoList(exportReqVO);
//        // 导出 Excel
//        List<YkElderlyInfoRespVO> datas = cn.iocoder.yudao.framework.common.util.object.BeanUtils.toBean(list, YkElderlyInfoRespVO.class);
//        ExcelUtils.write(response, "颐康中心长者信息.xls", "数据", YkElderlyInfoRespVO.class, datas);
//    }

    @GetMapping("/meal/page")
    @Operation(summary = "获取颐康中心长者送餐记录分页列表")
    @TenantIgnore
    public CommonResult<PageResult<YkElderlyMealRespVO>> getElderlyMealPage(@Valid YkElderlyMealPageReqVO pageReqVO) {
        PageResult<YkElderlyMealRespVO> pageResult = ykElderlyInfoService.getElderlyMealPage(pageReqVO);
        return success(pageResult);
    }


    @PutMapping("/meal/batch-confirm")
    @Operation(summary = "批量确认送餐")
    @TenantIgnore
    public CommonResult<Boolean> batchConfirm(@RequestBody YkMealBatchConfirmReqVO reqVO){
        ykElderlyInfoService.batchConfirm(reqVO);
        return success(true);
    }

    @DeleteMapping("/meal/deleteBatch")
    @Operation(summary = "批量删除送餐记录")
    @TenantIgnore
    public CommonResult<Boolean> batchDeleteDeliveryRecord(@RequestBody @NotEmpty(message = "ID列表不能为空") List<Long> ids) {
        ykElderlyInfoService.batchDeleteDeliveryRecord(ids);
        return success(true);
    }


    @GetMapping("/meal/history/list")
    @Operation(summary = "获取送餐历史记录分页列表")
    @TenantIgnore
    public CommonResult<PageResult<YkElderlyDeliveryDO>> getDeliveryHistoryPage(@Valid YkElderlyDeliveryHistoryPageReqVO pageReqVO) {
        PageResult<YkElderlyDeliveryDO> pageResult = ykElderlyInfoService.getDeliveryHistoryPage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/meal/today/list")
    @Operation(summary = "获取今日送餐单列表")
    @TenantIgnore
    public CommonResult<List<YkElderlyDeliveryHistoryRespVO>> getTodayMealList() {
        List<YkElderlyDeliveryHistoryRespVO> todayMealList = ykElderlyInfoService.getTodayMealList();
        return success(todayMealList);
    }


    @PutMapping("/meal/delivery/amount")
    @Operation(summary = "登记送工费")
    @TenantIgnore
    public CommonResult<Boolean> recordDeliveryFee(@Valid @RequestBody YkDeliveryFeeRecordReqVO reqVO) {
        ykElderlyInfoService.recordDeliveryFee(reqVO);
        return success(true);
    }

    @PostMapping("/finance/import")
    @Operation(summary = "导入财务数据")
    public CommonResult<String> importExpenseRecord(@RequestPart("file") MultipartFile file) throws IOException {
//        List<YkElderlyExpenseRecordImportVO> dataList = ExcelUtils.read(file, YkElderlyExpenseRecordImportVO.class);
//        return success(ykElderlyInfoService.importExpenseRecord(dataList));
        // 只读取第一个sheet页的数据
        // 显式只读取第一个sheet页的数据
        List<YkElderlyExpenseRecordImportVO> dataList = EasyExcel.read(file.getInputStream(), YkElderlyExpenseRecordImportVO.class, null)
                .sheet(0) // 指定只读取第一个sheet
                .doReadSync();
        return success(ykElderlyInfoService.importExpenseRecord(dataList));
    }

    @GetMapping("/finance/downloadExcel")
    @Operation(summary = "下载为老财务数据导入模板")
    public void downloadFinanceFile(HttpServletResponse response) throws IOException {
        String filePath = "files/为老财务数据导入模板.xlsx";
        ClassPathResource classPathResource = new ClassPathResource(filePath);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=为老财务数据导入模板");
        IOUtils.copy(classPathResource.getInputStream(), response.getOutputStream());
        response.flushBuffer();
    }

    @PutMapping("/finance/balance/update")
    @Operation(summary = "更新余额")
    @TenantIgnore
    public CommonResult<Boolean> updateBalance(@Valid @RequestBody YkBalanceUpdateReqVO reqVO) {
        ykElderlyInfoService.updateBalance(reqVO);
        return success(true);
    }

    @PutMapping("/finance/delivery/update")
    @Operation(summary = "更新送工费")
    @TenantIgnore
    public CommonResult<Boolean> updateDeliveryFee(@Valid @RequestBody YkBalanceUpdateReqVO reqVO) {
        ykElderlyInfoService.updateDeliveryFee(reqVO);
        return success(true);
    }

    @PutMapping("/finance/confirm")
    @Operation(summary = "确认财务数据")
    @TenantIgnore
    public CommonResult<Boolean> confirmFinanceData(@Valid @RequestBody YkFinanceConfirmReqVO reqVO) {
        ykElderlyInfoService.confirmFinanceData(reqVO);
        return success(true);
    }

    @GetMapping("/finance/change/balance/list")
    @Operation(summary = "获取余额变动记录分页列表")
    @TenantIgnore
    public CommonResult<PageResult<YkElderlyExpenseRecordDO>> getBalanceRecordPage(@Valid YkBalanceRecordPageReqVO pageReqVO) {
        PageResult<YkElderlyExpenseRecordDO> pageResult = ykElderlyInfoService.getBalanceRecordPage(pageReqVO);
        return success(pageResult);
    }

    @DeleteMapping("/finance/change/balance/delete-batch")
    @Operation(summary = "批量删除财务变动记录")
    @TenantIgnore
    public CommonResult<Boolean> batchDeleteExpenseRecord(@RequestBody @NotEmpty(message = "ID列表不能为空") List<Long> ids) {
        ykElderlyInfoService.batchDeleteExpenseRecord(ids);
        return success(true);
    }
    @PutMapping("/meal/update-standard")
    @Operation(summary = "更新餐标")
    @TenantIgnore
    public CommonResult<Boolean> updateStandard(@Valid @RequestBody YkMealUpdateStandardReqVO reqVO) {
        ykElderlyInfoService.updateStandard(reqVO);
        return success(true);
    }

    @PostMapping("/finance/import-recharge")
    @Operation(summary = "助餐配餐服务充值退费财务数据导入")
    public CommonResult<String> importRecharge(@RequestPart("file") MultipartFile file) throws IOException {
        // 只读取第一个sheet页的数据
        // 显式只读取第一个sheet页的数据
        List<YkElderlyExpenseRecordWeChatImportVO> dataList = EasyExcel.read(file.getInputStream(), YkElderlyExpenseRecordWeChatImportVO.class, null)
                .sheet(0) // 指定只读取第一个sheet
                .doReadSync();
        return success(ykElderlyInfoService.importRecharge(dataList));
    }

    @GetMapping("/finance-recharge/downloadExcel")
    @Operation(summary = "下载助餐配餐服务充值退费财务数据导入模板")
    public void downloadFinanceRechargeFile(HttpServletResponse response) throws IOException {
        try {
            String filePath = "files/充值数据导入模板.xlsx";
            ClassPathResource classPathResource = new ClassPathResource(filePath);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=充值数据导入模板");
            IOUtils.copy(classPathResource.getInputStream(), response.getOutputStream());
            response.flushBuffer();
        }catch (Exception e){
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }

    @GetMapping("/self-funded-everyday/list")
    @Operation(summary = "获取每日自费金额登记列表")
    @TenantIgnore
    public CommonResult<PageResult<YkElderlySelfFundedRecord>> getSelfFundedRecordPage(@Valid YkElderlySelfFundedRecordPageReqVO pageReqVO) {
        PageResult<YkElderlySelfFundedRecord> pageResult = ykElderlySelfFundedRecordService.getSelfFundedRecordPage(pageReqVO);
        return success(pageResult);
    }

    @PostMapping("/self-funded-everyday/add")
    @Operation(summary = "新增每日自费金额登记")
    @TenantIgnore
    public CommonResult<Long> createSelfFundedRecord(@Valid @RequestBody YkElderlySelfFundedRecordSaveReqVO createReqVO) {
        return success(ykElderlySelfFundedRecordService.createSelfFundedRecord(createReqVO));
    }

    @PutMapping("/self-funded-everyday/update")
    @Operation(summary = "编辑每日自费金额登记")
    @TenantIgnore
    public CommonResult<Boolean> updateSelfFundedRecord(@Valid @RequestBody YkElderlySelfFundedRecordSaveReqVO updateReqVO) {
        ykElderlySelfFundedRecordService.updateSelfFundedRecord(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/self-funded-everyday/delete")
    @Operation(summary = "删除每日自费金额记录")
    @Parameter(name = "id", description = "编号", required = true)
    @TenantIgnore
    public CommonResult<Boolean> deleteSelfFundedRecord(@RequestParam("id") Long id) {
        ykElderlySelfFundedRecordService.deleteSelfFundedRecord(id);
        return success(true);
    }

    @DeleteMapping("/self-funded-everyday/delete-batch")
    @Operation(summary = "批量删除每日自费金额记录")
    @TenantIgnore
    public CommonResult<Boolean> batchDeleteSelfFundedRecord(@RequestBody @NotEmpty(message = "ID列表不能为空") List<Long> ids) {
        ykElderlySelfFundedRecordService.batchDeleteSelfFundedRecord(ids);
        return success(true);
    }
}