package com.yc.ship.module.marketing.controller.admin.policy;

import com.yc.ship.framework.common.util.collection.CollectionUtils;
import com.yc.ship.framework.common.util.collection.MapUtils;
import com.yc.ship.module.marketing.dal.dataobject.policydetail.PolicyDetailDO;
import com.yc.ship.module.marketing.service.policydetail.PolicyDetailService;
import com.yc.ship.module.product.controller.admin.distributorDiscount.vo.DistributorDiscountCountryRespVO;
import com.yc.ship.module.resource.dal.dataobject.ship.ResourceShipDO;
import com.yc.ship.module.resource.service.ship.ResourceShipService;
import com.yc.ship.module.system.api.area.AreaApi;
import com.yc.ship.module.system.api.area.dto.AreaCountryDTO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import com.yc.ship.framework.common.pojo.PageParam;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.pojo.CommonResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import static com.yc.ship.framework.common.pojo.CommonResult.success;

import com.yc.ship.framework.excel.core.util.ExcelUtils;

import com.yc.ship.framework.apilog.core.annotation.ApiAccessLog;
import static com.yc.ship.framework.apilog.core.enums.OperateTypeEnum.*;

import com.yc.ship.module.marketing.controller.admin.policy.vo.*;
import com.yc.ship.module.marketing.dal.dataobject.policy.PolicyDO;
import com.yc.ship.module.marketing.service.policy.PolicyService;

@Tag(name = "管理后台 - 营销政策")
@RestController
@RequestMapping("/marketing/policy")
@Validated
public class PolicyController {

    @Resource
    private PolicyService policyService;

    @Resource
    private PolicyDetailService policyDetailService;

    @Resource
    private ResourceShipService resourceShipService;

    @Resource
    private AreaApi areaApi;

    @PostMapping("/create")
    @Operation(summary = "创建营销政策")
    @PreAuthorize("@ss.hasPermission('marketing:policy:create')")
    public CommonResult<Long> createPolicy(@Valid @RequestBody PolicySaveReqVO createReqVO) {
        return success(policyService.createPolicy(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新营销政策")
    @PreAuthorize("@ss.hasPermission('marketing:policy:update')")
    public CommonResult<Boolean> updatePolicy(@Valid @RequestBody PolicySaveReqVO updateReqVO) {
        policyService.updatePolicy(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除营销政策")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('marketing:policy:delete')")
    public CommonResult<Boolean> deletePolicy(@RequestParam("id") Long id) {
        policyService.deletePolicy(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得营销政策")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('marketing:policy:query')")
    public CommonResult<PolicyRespVO> getPolicy(@RequestParam("id") Long id) {
        PolicyDO policy = policyService.getPolicy(id);
        PolicyRespVO policyRespVO = BeanUtils.toBean(policy, PolicyRespVO.class);
        List<PolicyDetailDO> policyDetails = policyDetailService.getByPolicyId(id);
        Set<Long> voyageIds = CollectionUtils.convertSet(policyDetails, PolicyDetailDO::getVoyageId);
        policyRespVO.setVoyageIds(new ArrayList<>(voyageIds));
        return success(policyRespVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得营销政策分页")
    @PreAuthorize("@ss.hasPermission('marketing:policy:query')")
    public CommonResult<PageResult<PolicyRespVO>> getPolicyPage(@Valid PolicyPageReqVO pageReqVO) {
        PageResult<PolicyDO> pageResult = policyService.getPolicyPage(pageReqVO);
        PageResult<PolicyRespVO> result = BeanUtils.toBean(pageResult, PolicyRespVO.class);
        List<PolicyRespVO> list = result.getList();
        List<Long> shipIds = CollectionUtils.convertList(list, PolicyRespVO::getShipId);
        List<ResourceShipDO> shipList = resourceShipService.getList(shipIds);
        Map<Long, ResourceShipDO> shipDOMap = CollectionUtils.convertMap(shipList, ResourceShipDO::getId);
        list.stream().forEach(policyRespVO -> {
            MapUtils.findAndThen(shipDOMap, policyRespVO.getShipId(), resourceShipDO -> {
                policyRespVO.setShipName(resourceShipDO.getName());
            });
        });
        return success(result);
    }

    // 获取可以使用的营销政策
    @PostMapping("/get-usable-policy")
    @Operation(summary = "获取可以使用的营销政策")
    public CommonResult<List<PolicyRespVO>> getUsablePolicy(@Validated @RequestBody PolicyUsableReqVO reqVO) {
        List<PolicyRespVO> list = policyService.getUsablePolicy(reqVO);
        return success(list);
    }

    // 获取可以使用的营销政策
    @GetMapping("/get-usable-policy-new")
    @Operation(summary = "获取可以使用的营销政策")
    public CommonResult<List<PolicyRespVO>> getUsablePolicyNew(Long voyageId) {
        List<PolicyRespVO> list = policyService.getUsablePolicyByVoyageId(voyageId);
//        List<PolicyRespVO> result = BeanUtils.toBean(list, PolicyRespVO.class);
//        result.stream().forEach(policyRespVO -> {
//            List<Long> areaIds = policyRespVO.getAreaIds();
//            List<AreaCountryDTO> areaCountryDTOS = areaApi.getAreaCountryListByAreaIds(areaIds);
//            List<Integer> countryIds = CollectionUtils.convertList(areaCountryDTOS, AreaCountryDTO::getCountryId);
//            policyRespVO.setCountryIds(countryIds);
//        });
//        List<Long> policyIds = CollectionUtils.convertList(list, PolicyDO::getId);
//        List<PolicyDetailDO> policyDetails = policyDetailService.getByPolicyIds(policyIds);
//        Map<Long, List<PolicyDetailDO>> longListMap = CollectionUtils.convertMultiMap(policyDetails, PolicyDetailDO::getPolicyId);
//        result.stream().forEach(policyRespVO -> {
//            List<PolicyDetailDO> policyDetailDOList = longListMap.get(policyRespVO.getId());
//            List<Long> voyageIds = CollectionUtils.convertList(policyDetailDOList, PolicyDetailDO::getVoyageId);
//            policyRespVO.setVoyageIds(voyageIds);
//            List<Long> roomModelIds = CollectionUtils.convertList(policyDetailDOList, PolicyDetailDO::getRoomModelIds).stream().flatMap(List::stream).collect(Collectors.toList());
//            policyRespVO.setRoomModelIds(roomModelIds);
//        });
        return success(list);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出营销政策 Excel")
    @PreAuthorize("@ss.hasPermission('marketing:policy:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportPolicyExcel(@Valid PolicyPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<PolicyDO> list = policyService.getPolicyPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "营销政策.xls", "数据", PolicyRespVO.class,
                        BeanUtils.toBean(list, PolicyRespVO.class));
    }

}