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

import cn.hutool.core.collection.CollUtil;
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.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.smartfactory.api.factoryInfo.FactoryInfoApi;
import cn.iocoder.yudao.module.smartfactory.api.factoryInfo.dto.FactoryInfoDTO;
import cn.iocoder.yudao.module.system.controller.admin.customersettlement.vo.*;
import cn.iocoder.yudao.module.system.dal.dataobject.customersettlement.CustomerSettlementDO;
import cn.iocoder.yudao.module.system.dal.dataobject.customersettlement.SettlementItemDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.customersettlement.CustomerSettlementService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
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.security.access.prepost.PreAuthorize;
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.Set;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Tag(name = "管理后台 - 客户结算信息")
@RestController
@RequestMapping("/system/customer-settlement")
@Validated
public class CustomerSettlementController {

    @Resource
    private CustomerSettlementService customerSettlementService;

    @Resource
    private AdminUserService userService;

    @Resource
    private FactoryInfoApi factoryInfoApi;

    @PostMapping("/create")
    @Operation(summary = "创建客户结算信息")
    @PreAuthorize("@ss.hasPermission('system:customer-settlement:create')")
    public CommonResult<Long> createCustomerSettlement(@Valid @RequestBody CustomerSettlementSaveReqVO createReqVO) {
        return success(customerSettlementService.createCustomerSettlement(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新客户结算信息")
    @PreAuthorize("@ss.hasPermission('system:customer-settlement:update')")
    public CommonResult<Boolean> updateCustomerSettlement(@Valid @RequestBody CustomerSettlementSaveReqVO updateReqVO) {
        customerSettlementService.updateCustomerSettlement(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-confirm")
    @Operation(summary = "修改结算状态")
    @PreAuthorize("@ss.hasPermission('system:customer-settlement:update')")
    public CommonResult<Boolean> updateConfirm(@RequestParam("id") Long id,
                                               @RequestParam("status") Integer status) {
        customerSettlementService.updateConfirm(id, status);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除客户结算信息")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('system:customer-settlement:delete')")
    public CommonResult<Boolean> deleteCustomerSettlement(@RequestParam("id") Long id) {
        customerSettlementService.deleteCustomerSettlement(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得客户结算信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:customer-settlement:query')")
    public CommonResult<CustomerSettlementRespVO> getCustomerSettlement(@RequestParam("id") Long id) {
        CustomerSettlementDO customerSettlement = customerSettlementService.getCustomerSettlement(id);
        // 获取结算明细
        List<SettlementItemDO> itemDOS = customerSettlementService.getSettlementItemListBySettlementId(CollUtil.newArrayList(id), null);
        return success(BeanUtils.toBean(customerSettlement, CustomerSettlementRespVO.class)
                .setSettlementItems(BeanUtils.toBean(itemDOS, SettlementItemVO.class)));
    }

    @GetMapping("/page")
    @Operation(summary = "获得客户结算信息分页")
    @PreAuthorize("@ss.hasPermission('system:customer-settlement:query')")
    public CommonResult<PageResult<CustomerSettlementRespVO>> getCustomerSettlementPage(@Valid CustomerSettlementPageReqVO pageReqVO) {
        PageResult<CustomerSettlementDO> pageResult = customerSettlementService.getCustomerSettlementPage(pageReqVO);
        PageResult<CustomerSettlementRespVO> respVO = BeanUtils.toBean(pageResult, CustomerSettlementRespVO.class);
        if (CollUtil.isNotEmpty(respVO.getList())) {

            // 查询结算明细数据
            List<Long> ids = convertList(respVO.getList(), CustomerSettlementRespVO::getId);
            List<SettlementItemDO> itemDOS = customerSettlementService.getSettlementItemListBySettlementId(ids, pageReqVO.getBusinessType());
            // 获取结算明细 map
            Map<Long, List<SettlementItemDO>> itemMap = itemDOS.stream()
                    .collect(Collectors.groupingBy(SettlementItemDO::getSettlementId));

            // 获取所有创建者信息
            Set<Long> creatorIds = respVO.getList().stream()
                    .filter(Objects::nonNull)
                    .map(CustomerSettlementRespVO::getCreator)
                    .map(Long::valueOf)
                    .collect(Collectors.toSet());
            Map<String, AdminUserDO> userMap = userService.getUserList(creatorIds).stream()
                    .collect(Collectors.toMap(user ->
                                    String.valueOf(user.getId()), // 将 Long 类型的 id 转换为 String 类型
                                    v -> v));

            // 获取工厂信息
            Set<Long> factoryIds = convertSet(respVO.getList(), CustomerSettlementRespVO::getCustomerId);
            Map<Long, FactoryInfoDTO> factoryMap = factoryInfoApi.getFactoryMap(factoryIds);

            respVO.getList().forEach(item -> {
                if (itemMap.containsKey(item.getId())) {
                    // 设置明细数据
                    item.setSettlementItems(BeanUtils.toBean(itemMap.get(item.getId()), SettlementItemVO.class));
                }
                // 设置工厂名称
                item.setCustomerName(factoryMap.get(item.getCustomerId()).getShortName());
                // 设置创建人名称
                item.setCreatorName(userMap.get(item.getCreator()) == null ? "" : userMap.get(item.getCreator()).getNickname());
            });
        }

        return success(respVO);
    }

    @GetMapping("/total")
    @Operation(summary = "获得结算统计信息")
    @PreAuthorize("@ss.hasPermission('system:customer-settlement:query')")
    public CommonResult<StatisticsVO> getCustomerSettlementTotal(@Valid CustomerSettlementPageReqVO pageReqVO) {

        return success(customerSettlementService.getCustomerSettlementTotal(pageReqVO));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出客户结算信息 Excel")
    @PreAuthorize("@ss.hasPermission('system:customer-settlement:export')")
    @OperateLog(type = EXPORT)
    public void exportCustomerSettlementExcel(@Valid CustomerSettlementPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<CustomerSettlementDO> list = customerSettlementService.getCustomerSettlementPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "客户结算信息.xls", "数据", CustomerSettlementRespVO.class,
                        BeanUtils.toBean(list, CustomerSettlementRespVO.class));
    }
}