package com.yc.ship.module.trade.controller.admin.orderjzdetail;

import com.yc.ship.framework.apilog.core.annotation.ApiAccessLog;
import com.yc.ship.framework.common.pojo.CommonResult;
import com.yc.ship.framework.common.pojo.PageParam;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.framework.excel.core.util.ExcelUtils;
import com.yc.ship.module.product.dal.dataobject.voyage.VoyageDO;
import com.yc.ship.module.product.service.voyage.VoyageService;
import com.yc.ship.module.resource.dal.dataobject.route.ResourceRouteDO;
import com.yc.ship.module.resource.service.route.ResourceRouteService;
import com.yc.ship.module.system.api.dict.DictDataApi;
import com.yc.ship.module.system.api.dict.dto.DictDataRespDTO;
import com.yc.ship.module.trade.controller.admin.orderjzdetail.vo.OrderJzDetailPageReqVO;
import com.yc.ship.module.trade.controller.admin.orderjzdetail.vo.OrderJzDetailRespVO;
import com.yc.ship.module.trade.controller.admin.orderjzdetail.vo.OrderJzDetailSaveReqVO;
import com.yc.ship.module.trade.dal.dataobject.orderjzdetail.OrderJzDetailDO;
import com.yc.ship.module.trade.service.orderjzdetail.OrderJzDetailService;
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.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

import static com.yc.ship.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static com.yc.ship.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 订单接站人员名单")
@RestController
@RequestMapping("/trade/order-jz-detail")
@Validated
public class OrderJzDetailController {

  @Resource
  private OrderJzDetailService orderJzDetailService;

  @Resource
  private VoyageService voyageService;

  @Resource
  private ResourceRouteService resourceRouteService;

  @Resource
  DictDataApi dictDataApi;

  @PostMapping("/create")
  @Operation(summary = "创建订单接站人员名单")
  @PreAuthorize("@ss.hasPermission('trade:order-jz-detail:create')")
  public CommonResult<Long> createOrderJzDetail(@Valid @RequestBody OrderJzDetailSaveReqVO createReqVO) {
    return success(orderJzDetailService.createOrderJzDetail(createReqVO));
  }

  @PutMapping("/update")
  @Operation(summary = "更新订单接站人员名单")
  @PreAuthorize("@ss.hasPermission('trade:order-jz-detail:update')")
  public CommonResult<Boolean> updateOrderJzDetail(@Valid @RequestBody OrderJzDetailSaveReqVO updateReqVO) {
    orderJzDetailService.updateOrderJzDetail(updateReqVO);
    return success(true);
  }

  @DeleteMapping("/delete")
  @Operation(summary = "删除订单接站人员名单")
  @Parameter(name = "id", description = "编号", required = true)
  public CommonResult<Boolean> deleteOrderJzDetail(@RequestParam("id") Long id) {
    orderJzDetailService.deleteOrderJzDetail(id);
    return success(true);
  }

  @GetMapping("/get")
  @Operation(summary = "获得订单接站人员名单")
  @Parameter(name = "id", description = "编号", required = true, example = "1024")
  @PreAuthorize("@ss.hasPermission('trade:order-jz-detail:query')")
  public CommonResult<OrderJzDetailRespVO> getOrderJzDetail(@RequestParam("id") Long id) {
    OrderJzDetailDO orderJzDetail = orderJzDetailService.getOrderJzDetail(id);
    return success(BeanUtils.toBean(orderJzDetail, OrderJzDetailRespVO.class));
  }

  @GetMapping("/page")
  @Operation(summary = "获得订单接站人员名单分页")
  @PreAuthorize("@ss.hasPermission('trade:order-jz-detail:query')")
  public CommonResult<PageResult<OrderJzDetailRespVO>> getOrderJzDetailPage(@Valid OrderJzDetailPageReqVO pageReqVO) {
    PageResult<OrderJzDetailDO> pageResult = orderJzDetailService.getOrderJzDetailPage(pageReqVO);
    return success(BeanUtils.toBean(pageResult, OrderJzDetailRespVO.class));
  }

  @GetMapping("/export-excel")
  @Operation(summary = "导出订单接站人员名单 Excel")
  @ApiAccessLog(operateType = EXPORT)
//  @PreAuthorize("@ss.hasPermission('trade:order-jz-detail:query')")
  public void exportOrderJzDetailExcel(@Valid OrderJzDetailPageReqVO pageReqVO,
                                       HttpServletResponse response) throws IOException {
    if (StringUtils.isEmpty(pageReqVO.getVoyageId())) {
      throw new RuntimeException("航次编号不能为空");
    }
    VoyageDO voyageDO = voyageService.getVoyage(Long.valueOf(pageReqVO.getVoyageId()));
    if (voyageDO == null) {
      throw new RuntimeException("航次信息不能为空");
    }

    pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
    List<OrderJzDetailDO> list = orderJzDetailService.selectPageByVoyageId(pageReqVO.getVoyageId());

    List<DictDataRespDTO> dictAddressList = null;
    ResourceRouteDO resourceRouteDO = resourceRouteService.getRoute(voyageDO.getRouteId());
    if (resourceRouteDO != null) {
      int dir = resourceRouteDO.getDirection().intValue();
      if (dir == 2) {
        dictAddressList = dictDataApi.getDictDataList("order_jz_x");
      } else {
        dictAddressList = dictDataApi.getDictDataList("order_jz");
      }
    }


    final List<DictDataRespDTO> dictTimeList = dictDataApi.getDictDataList("order_time_jz");
    // 导出 Excel
    List<OrderJzDetailRespVO> exportList = BeanUtils.toBean(list, OrderJzDetailRespVO.class);
    final List<DictDataRespDTO> finalAddressList = dictAddressList;
    exportList.forEach(vo -> {
      vo.setVoyage(voyageDO.getName());

      // 接站地点
      if (finalAddressList != null) {
        List<DictDataRespDTO> addressList = finalAddressList.stream().filter(d -> d.getValue().equals(vo.getAddress())).collect(Collectors.toList());
        if (addressList != null && addressList.size() > 0) {
          vo.setAddress(addressList.get(0).getLabel());
        }
      }

      // 接站时间
      if(dictTimeList!=null) {
        List<DictDataRespDTO> timeList = dictTimeList.stream().filter(d -> d.getValue().equals(vo.getArriveTime())).collect(Collectors.toList());
        if (timeList != null && timeList.size() > 0) {
          vo.setArriveTime(timeList.get(0).getLabel());
        }
      }
    });
    ExcelUtils.write(response, "订单接站人员名单.xls", "数据", OrderJzDetailRespVO.class,
      BeanUtils.toBean(exportList, OrderJzDetailRespVO.class));
  }


  @PostMapping("/sign")
  @PermitAll
  public CommonResult<Long> createOrderJzDetail(@Valid @RequestBody List<OrderJzDetailSaveReqVO> createReqVOList) {
    return success(orderJzDetailService.createOrderJzDetail(createReqVOList));
  }

  @GetMapping("/simple-list")
  @Operation(summary = "获得订单接站人员名单")
  public CommonResult<List<OrderJzDetailRespVO>> getOrderJzDetailList(@Valid OrderJzDetailPageReqVO pageReqVO) {
    List<OrderJzDetailDO> pageResult = orderJzDetailService.getOrderJzDetailList(pageReqVO);
    return success(BeanUtils.toBean(pageResult, OrderJzDetailRespVO.class));
  }




  @GetMapping("/visitor/query")
  @Operation(summary = "获得订单接站人员名单分页")
  @PreAuthorize("@ss.hasPermission('trade:order-jz-detail-sign:query')")
  public CommonResult<PageResult<OrderJzDetailRespVO>> queryOrderJzDetailPage(@Valid OrderJzDetailPageReqVO pageReqVO) {
    PageResult<OrderJzDetailDO> pageResult = orderJzDetailService.getOrderJzDetailPage2(pageReqVO);
    return success(BeanUtils.toBean(pageResult, OrderJzDetailRespVO.class));
  }

  @PostMapping("/visitor/sign")
  @Operation(summary = "游客登记")
  @PreAuthorize("@ss.hasPermission('trade:order-jz-detail-sign:save')")
  public CommonResult<Long> visitorSign(@Valid @RequestBody OrderJzDetailSaveReqVO createReqVO) {
    return success(orderJzDetailService.signOrderJzDetail(createReqVO));
  }


  @DeleteMapping("/visitor/sign/clean")
  @Operation(summary = "游客登记")
  @PreAuthorize("@ss.hasPermission('trade:order-jz-detail-sign:delete')")
  public CommonResult<Long> visitorSignClean(String  id) {
    return success(orderJzDetailService.cleanOrderJzDetail(id));
  }
}