/**
 * Copyright (c) 2018-2099, Chill Zhuang 庄骞 (bladejava@qq.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xiaoniu.subsystem.business.controller;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.xiaoniu.common.core.result.R;
import com.xiaoniu.common.core.utils.BeanUtil;
import com.xiaoniu.common.core.utils.poi.ExcelUtil;
import com.xiaoniu.common.core.vo.LabelAndValueNameVO;
import com.xiaoniu.common.log.annotation.Log;
import com.xiaoniu.common.log.enums.BusinessType;
import com.xiaoniu.subsystem.business.domain.Budget;
import com.xiaoniu.subsystem.business.domain.Expense;
import com.xiaoniu.subsystem.business.domain.dto.BudgetPageDTO;
import com.xiaoniu.subsystem.business.domain.dto.BudgetSaveDTO;
import com.xiaoniu.subsystem.business.domain.dto.BudgetUpdateDTO;
import com.xiaoniu.subsystem.business.domain.vo.BudgetPageVO;
import com.xiaoniu.subsystem.business.domain.vo.BudgetVO;
import com.xiaoniu.subsystem.business.domain.vo.CheckBedroomPageVO;
import com.xiaoniu.subsystem.business.service.IAnnualPlanAmountService;
import com.xiaoniu.subsystem.business.service.IBudgetService;
import com.xiaoniu.subsystem.business.service.IExpenseService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static com.xiaoniu.common.security.utils.SecurityUtils.getUnitId;
import static com.xiaoniu.common.security.utils.SecurityUtils.getUserId;

/**
 * 预算管理表 控制器
 *
 * @author sst
 * @since 2024-11-26
 */
@RestController
@AllArgsConstructor
@RequestMapping("/budget")
@Tag(name = "预算管理表", description = "预算管理表接口")
public class BudgetController {

    private IBudgetService budgetService;
    private IAnnualPlanAmountService amountService;
    private IExpenseService expenseService;

    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @Operation(summary = "详情", description = "传入flightId")
    public R<BudgetVO> detail(@Parameter(description = "班次id", required = true) @RequestParam Long flightId) {
        Budget detail = budgetService.getOne(new LambdaQueryWrapper<Budget>()
                .eq(Budget::getFlightId,flightId)
        );
        return R.data(BeanUtil.copy(detail, BudgetVO.class));
    }

    // /**
    //  * 分页 预算管理表
    //  */
    // @GetMapping("/page")
    // @ApiOperationSupport(order = 2)
    // @Operation(summary = "分页", description = "传入budget")
    // public R<BudgetPageVO> page(@Validated BudgetPageDTO dto) {
    //     BudgetPageVO pageVO = new BudgetPageVO();
    //     IPage<Budget> pages = budgetService.page(new Page<>(dto.getPageNum(), dto.getPageSize()),
    //             new LambdaQueryWrapper<Budget>()
    //                     .orderByDesc(Budget::getCreateTime)
    //                     .eq(null != dto.getFlightId(), Budget::getFlightId, dto.getFlightId())
    //                     .like(StringUtils.isNotBlank(dto.getFlightName()), Budget::getFlightName, dto.getFlightName())
    //                     .like(StringUtils.isNotBlank(dto.getFlightCode()), Budget::getFlightCode, dto.getFlightCode())
    //                     .like(StringUtils.isNotBlank(dto.getBudgetAccount()), Budget::getBudgetAccount, dto.getBudgetAccount())
    //                     .eq(StringUtils.isNotBlank(dto.getTrainingDays()), Budget::getTrainingDays, dto.getTrainingDays())
    //                     .like(StringUtils.isNotBlank(dto.getTissueUnitAddress()), Budget::getTissueUnitAddress, dto.getTissueUnitAddress()));
    //     return R.data(pageVO.setVoList(statistics(pages.getRecords()))
    //             .setVoiPage(BeanUtil.copy(pages, BudgetVO.class)));
    // }
    /**
     * 分页 预算管理表
     */
    @GetMapping("/page")
    @ApiOperationSupport(order = 2)
    @Operation(summary = "分页", description = "传入budget")
    public R<IPage<BudgetVO>> page(@Validated BudgetPageDTO dto) {
        IPage<Budget> pages = budgetService.page(new Page<>(dto.getPageNum(), dto.getPageSize()),
                new LambdaQueryWrapper<Budget>()
                        .orderByDesc(Budget::getCreateTime)
                        .eq(null != dto.getFlightId(), Budget::getFlightId, dto.getFlightId())
                        .like(StringUtils.isNotBlank(dto.getFlightName()), Budget::getFlightName, dto.getFlightName())
                        .like(StringUtils.isNotBlank(dto.getFlightCode()), Budget::getFlightCode, dto.getFlightCode())
                        .like(StringUtils.isNotBlank(dto.getBudgetAccount()), Budget::getBudgetAccount, dto.getBudgetAccount())
                        .eq(StringUtils.isNotBlank(dto.getTrainingDays()), Budget::getTrainingDays, dto.getTrainingDays())
                        .like(StringUtils.isNotBlank(dto.getTissueUnitAddress()), Budget::getTissueUnitAddress, dto.getTissueUnitAddress()));
        return R.data(BeanUtil.copy(pages, BudgetVO.class));
    }

    /**
     * 导出
     */
    @GetMapping("/export")
    @ApiOperationSupport(order = 3)
    @Log(title = "预算导出", businessType = BusinessType.EXPORT)
    @Operation(summary = "导出", description = "传入ids")
    public void export(HttpServletResponse response, @Validated BudgetPageDTO dto) {
        List<Budget> list = new ArrayList<>();
        if (StringUtils.isNotBlank(dto.getIds())) {
            list.addAll(budgetService.list(new LambdaQueryWrapper<Budget>()
                    .orderByDesc(Budget::getCreateTime)
                    .in(StringUtils.isNotBlank(dto.getIds()), Budget::getBudgetId,
                            Arrays.stream(dto.getIds().split(",")).toList())));
        } else {
            list.addAll(budgetService.list(new LambdaQueryWrapper<Budget>()
                    .orderByDesc(Budget::getCreateTime)
                    .eq(null != dto.getFlightId(),
                            Budget::getFlightId, dto.getFlightId())
                    .like(StringUtils.isNotBlank(dto.getFlightName()),
                            Budget::getFlightName, dto.getFlightName())
                    .like(StringUtils.isNotBlank(dto.getFlightCode()),
                            Budget::getFlightCode, dto.getFlightCode())
                    .like(StringUtils.isNotBlank(dto.getBudgetAccount()),
                            Budget::getBudgetAccount, dto.getBudgetAccount())
                    .eq(StringUtils.isNotBlank(dto.getTrainingDays()),
                            Budget::getTrainingDays, dto.getTrainingDays())
                    .like(StringUtils.isNotBlank(dto.getTissueUnitAddress()),
                            Budget::getTissueUnitAddress, dto.getTissueUnitAddress())));
        }
        ExcelUtil<Budget> excelUtil = new ExcelUtil<>(Budget.class);
        excelUtil.exportExcel(response, list, "预算数据");
    }

    /**
     * 新增 预算管理表
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @Operation(summary = "新增", description = "传入budget")
    public R save(@Valid @RequestBody BudgetSaveDTO dto) {
        Budget budget = budgetService.getOne(new LambdaQueryWrapper<Budget>()
                .eq(Budget::getFlightId,dto.getFlightId())
        );
        if (budget != null){
            budgetService.removeById(budget.getBudgetId());
        }
        return R.status(budgetService.save(BeanUtil.copy(dto, Budget.class)
/*                .setAmountPayable(String.valueOf(Integer.parseInt(dto.getBudgetedAmount())
                        - Integer.parseInt(dto.getAdvanceAmount())))*/
                .setCreateDept(getUnitId())
                .setYear(String.valueOf(LocalDate.now().getYear()))
                .setCreateUser(getUserId()).setCreateTime(new Date())));
    }

    /**
     * 修改 预算管理表
     */
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @Operation(summary = "修改", description = "传入budget")
    public R update(@Valid @RequestBody BudgetUpdateDTO dto) {
        return R.status(budgetService.updateById(BeanUtil.copy(dto, Budget.class)
                /*.setAmountPayable(String.valueOf(Integer.parseInt(dto.getBudgetedAmount())
                        - Integer.parseInt(dto.getAdvanceAmount())))*/
                .setUpdateUser(getUserId()).setUpdateTime(new Date())));
    }

    /**
     * 删除 预算管理表
     */
    @PostMapping("/remove")
    @ApiOperationSupport(order = 7)
    @Operation(summary = "删除", description = "传入ids")
    public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String budgetIds) {
        return R.status(budgetService.removeByIds(Arrays.stream(budgetIds.split(",")).toList()));
    }

    @PostMapping("/import")
    @ApiOperationSupport(order = 8)
    @Log(title = "预算导入", businessType = BusinessType.IMPORT)
    @Operation(summary = "导入")
    public R importData(MultipartFile file,
                        @Parameter(description = "是否支持更新", required = true)
                        @RequestParam boolean updateSupport) throws Exception {
        ExcelUtil<Budget> util = new ExcelUtil<>(Budget.class);
        List<Budget> list = util.importExcel(file.getInputStream());
        return R.success(budgetService.importData(list, updateSupport, getUserId()));
    }

    @GetMapping("/importTemplate")
    @ApiOperationSupport(order = 9)
    @Operation(summary = "导入模版下载")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<Budget> util = new ExcelUtil<>(Budget.class);
        util.importTemplateExcel(response, "预算导入模版");
    }

    private List<LabelAndValueNameVO> statistics(List<Budget> list) {
        List<LabelAndValueNameVO> voList = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            voList.add(new LabelAndValueNameVO().setName("年度计划金额").setValue("0"));
            voList.add(new LabelAndValueNameVO().setName("已结算金额").setValue("0"));
            voList.add(new LabelAndValueNameVO().setName("剩余可支配金额").setValue("0"));
            voList.add(new LabelAndValueNameVO().setName("未培训班级数量").setValue("0"));
            voList.add(new LabelAndValueNameVO().setName("培训中班级数量").setValue("0"));
            voList.add(new LabelAndValueNameVO().setName("已培训班级数量").setValue("0"));
            return voList;
        }
        BigDecimal reduce = list.stream().map(l ->
                        BigDecimal.valueOf(Double.parseDouble(StringUtils.isEmpty(l.getBudgetedAmount()) ?
                                "0" : l.getBudgetedAmount())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        voList.add(new LabelAndValueNameVO().setName("年度计划金额").setValue(String.valueOf(reduce)));
        List<Expense> expenseList = expenseService.list(new LambdaQueryWrapper<Expense>()
                .in(Expense::getFlightId, list.stream().map(Budget::getFlightId).toList()));
        BigDecimal reduce1 = expenseList.stream().map(l ->
                        BigDecimal.valueOf(Double.parseDouble(StringUtils.isEmpty(l.getSettlementAmount()) ?
                                "0" : l.getSettlementAmount())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        voList.add(new LabelAndValueNameVO().setName("已结算金额").setValue(String.valueOf(reduce1)));
        voList.add(new LabelAndValueNameVO().setName("剩余可支配金额")
                .setValue(String.valueOf(reduce.subtract(reduce1))));
        voList.add(new LabelAndValueNameVO().setName("未培训班级数量")
                .setValue(String.valueOf(list.stream().filter(l ->
                        new Date().compareTo(l.getTrainingTime()) < 0).count())));
        voList.add(new LabelAndValueNameVO().setName("培训中班级数量")
                .setValue(String.valueOf(list.stream().filter(l ->
                        l.getTrainingTime().compareTo(new Date()) < 0
                                && l.getEndTime().compareTo(new Date()) > 0).count())));
        voList.add(new LabelAndValueNameVO().setName("已培训班级数量")
                .setValue(String.valueOf(list.stream().filter(l ->
                        l.getEndTime().compareTo(new Date()) < 0).count())));
        return voList;
    }

}
