package cn.iocoder.yudao.module.expense.controller.admin.expensetype;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.employee.api.EmployeeApi;
import cn.iocoder.yudao.module.employee.api.dto.EmployeeRespDTO;
import cn.iocoder.yudao.module.expense.controller.admin.expensetype.vo.ExpenseTypePageReqVO;
import cn.iocoder.yudao.module.expense.controller.admin.expensetype.vo.ExpenseTypeRespVO;
import cn.iocoder.yudao.module.expense.controller.admin.expensetype.vo.ExpenseTypeSaveReqVO;
import cn.iocoder.yudao.module.expense.dal.dataobject.expenseitem.ExpenseItemDO;
import cn.iocoder.yudao.module.expense.dal.dataobject.expensetype.ExpenseTypeDO;
import cn.iocoder.yudao.module.expense.service.expensetype.ExpenseTypeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 报销类型信息")
@RestController
@RequestMapping("/finance/expense/type")
@Validated
public class ExpenseTypeController {

    @Resource
    private ExpenseTypeService typeService;

    @Resource
    private EmployeeApi employeeApi;

    @PostMapping("/create")
    @Operation(summary = "创建报销类型信息")
    // @PreAuthorize("@ss.hasPermission('expense:type:create')")
    public CommonResult<Long> createType(@Valid @RequestBody ExpenseTypeSaveReqVO createReqVO) {
        return success(typeService.createType(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新报销类型信息")
    // @PreAuthorize("@ss.hasPermission('expense:type:update')")
    public CommonResult<Boolean> updateType(@Valid @RequestBody ExpenseTypeSaveReqVO updateReqVO) {
        typeService.updateType(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除报销类型信息")
    @Parameter(name = "id", description = "编号", required = true)
    // @PreAuthorize("@ss.hasPermission('expense:type:delete')")
    public CommonResult<Boolean> deleteType(@RequestParam("id") Long id) {
        typeService.deleteType(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得报销类型信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    // @PreAuthorize("@ss.hasPermission('expense:type:query')")
    public CommonResult<ExpenseTypeRespVO> getType(@RequestParam("id") Long id) {
        ExpenseTypeDO type = typeService.getType(id);
        return success(BeanUtils.toBean(type, ExpenseTypeRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得报销类型信息分页")
    // @PreAuthorize("@ss.hasPermission('expense:type:query')")
    public CommonResult<PageResult<ExpenseTypeRespVO>> getTypePage(@Valid ExpenseTypePageReqVO pageReqVO) {
        PageResult<ExpenseTypeDO> pageResult = typeService.getTypePage(pageReqVO);
        PageResult<ExpenseTypeRespVO> voPageResult = BeanUtils.toBean(pageResult, ExpenseTypeRespVO.class);
        List<ExpenseTypeRespVO> list = voPageResult.getList();
        if (CollectionUtil.isNotEmpty(list)) {
            List<Long> employeeIdList = list.stream().map(ExpenseTypeRespVO::getCreator).collect(Collectors.toList());
            List<EmployeeRespDTO> employeeRespDTOList = employeeApi.getEmployeeListByIds(employeeIdList);
            Map<Long, EmployeeRespDTO> longEmployeeRespDTOMap = CollectionUtils.convertMap(employeeRespDTOList, EmployeeRespDTO::getId);
            for (ExpenseTypeRespVO expenseTypeRespVO : list) {
                EmployeeRespDTO employeeRespDTO = longEmployeeRespDTOMap.get(expenseTypeRespVO.getCreator());
                if (Objects.nonNull(employeeRespDTO)) {
                    expenseTypeRespVO.setCreateEmployeeName(employeeRespDTO.getName());
                }
            }
        }
        return success(voPageResult);
    }

    @GetMapping("/list")
    @Operation(summary = "获得报销类型信息列表")
    // @PreAuthorize("@ss.hasPermission('expense:type:query')")
    public CommonResult<List<ExpenseTypeRespVO>> getTypeList() {
        List<ExpenseTypeDO> expenseTypeDOList = typeService.getTypeList();
        return success(BeanUtils.toBean(expenseTypeDOList, ExpenseTypeRespVO.class), "获取报销类型列表成功");
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出报销类型信息 Excel")
    // @PreAuthorize("@ss.hasPermission('expense:type:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportTypeExcel(@Valid ExpenseTypePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ExpenseTypeDO> list = typeService.getTypePage(pageReqVO).getList();
        List<ExpenseTypeRespVO> expenseTypeRespVOList = BeanUtils.toBean(list, ExpenseTypeRespVO.class);
        if (CollUtil.isNotEmpty(expenseTypeRespVOList)) {
            List<Long> employeeIdList = expenseTypeRespVOList.stream().map(ExpenseTypeRespVO::getCreator).collect(Collectors.toList());
            List<EmployeeRespDTO> employeeRespDTOList = employeeApi.getEmployeeListByIds(employeeIdList);
            Map<Long, EmployeeRespDTO> longEmployeeRespDTOMap = CollectionUtils.convertMap(employeeRespDTOList, EmployeeRespDTO::getId);
            for (ExpenseTypeRespVO expenseTypeRespVO : expenseTypeRespVOList) {
                EmployeeRespDTO employeeRespDTO = longEmployeeRespDTOMap.get(expenseTypeRespVO.getCreator());
                if (Objects.nonNull(employeeRespDTO)) {
                    expenseTypeRespVO.setCreateEmployeeName(employeeRespDTO.getName());
                }
            }
        }
        // 导出 Excel
        ExcelUtils.write(response, "报销类型信息.xls", "数据", ExpenseTypeRespVO.class,
                        expenseTypeRespVOList);
    }

    // ==================== 子表（报销费用项目信息） ====================

    @GetMapping("/item/list-by-expense-type-id")
    @Operation(summary = "获得报销费用项目信息列表")
    @Parameter(name = "expenseTypeId", description = "报销类型主键id")
    // @PreAuthorize("@ss.hasPermission('expense:type:query')")
    public CommonResult<List<ExpenseItemDO>> getItemListByExpenseTypeId(@RequestParam("expenseTypeId") Long expenseTypeId) {
        return success(typeService.getItemListByExpenseTypeId(expenseTypeId));
    }

}