package com.jsowell.web.controller.pile;

import com.jsowell.common.annotation.Log;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.domain.vo.AuthorizedDeptVO;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.common.util.SecurityUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.pile.domain.OrderBasicInfo;
import com.jsowell.pile.domain.PileMerchantInfo;
import com.jsowell.pile.dto.ApplyRefundDTO;
import com.jsowell.pile.dto.ManualSettlementDTO;
import com.jsowell.pile.dto.QueryMerchantOrderDTO;
import com.jsowell.pile.dto.QueryOrderDTO;
import com.jsowell.pile.service.IOrderBasicInfoService;
import com.jsowell.pile.service.IPileMerchantInfoService;
import com.jsowell.pile.service.IPileStationInfoService;
import com.jsowell.pile.vo.web.OrderListVO;
import com.jsowell.service.OrderService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 订单Controller
 *
 * @author jsowell
 * @date 2022-09-30
 */
@RestController
@RequestMapping("/order")
public class OrderBasicInfoController extends BaseController {
	@Autowired
	private IOrderBasicInfoService orderBasicInfoService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private IPileMerchantInfoService pileMerchantInfoService;

	@Autowired
	private IPileStationInfoService pileStationInfoService;

	/**
	 * 查询订单列表
	 * 订单列表页，带数据权限校验
	 */
	@PreAuthorize("@ss.hasPermi('order:order:list')")
	@GetMapping("/order/list")
	public TableDataInfo list(QueryOrderDTO dto) {
		// 权限过滤
		AuthorizedDeptVO authorizedMap = SecurityUtils.getAuthorizedMap();
		if (authorizedMap == null) {
			// 为空表示没有权限，返回空数组
			return new TableDataInfo();
		}
		String deptId = authorizedMap.getDeptId();
		// 根据部门id查询merchantId
		PileMerchantInfo pileMerchantInfo = pileMerchantInfoService.queryInfoByDeptId(deptId);
		if (pileMerchantInfo != null) {
			dto.setMerchantId(String.valueOf(pileMerchantInfo.getId()));
		}
		startPage();
		List<OrderListVO> list = orderBasicInfoService.selectOrderBasicInfoListWithAuth(dto);
		return getDataTable(list);
	}

	/**
	 * 根据参数查询用电度数和消费金额
	 */
	@PreAuthorize("@ss.hasPermi('order:order:list')")
	@GetMapping("/order/totalData")
	public AjaxResult getOrderTotalData(QueryOrderDTO dto) {
		// 权限过滤
		AuthorizedDeptVO authorizedMap = SecurityUtils.getAuthorizedMap();
		if (authorizedMap == null) {
			// 为空表示没有权限，返回空数组
			return new AjaxResult();
		}
		String deptId = authorizedMap.getDeptId();
		if (CollectionUtils.isNotEmpty(authorizedMap.getStationDeptIds())) {
			// 为站点管理员
			List<String> stationIds = pileStationInfoService.getIdsByDeptId(deptId);
			dto.setStationIdList(stationIds);
		}else {
			// 平台管理员或运营商管理员
			// 根据部门id查询merchantId
			PileMerchantInfo pileMerchantInfo = pileMerchantInfoService.queryInfoByDeptId(deptId);
			if (pileMerchantInfo != null) {
				dto.setMerchantId(String.valueOf(pileMerchantInfo.getId()));
			}
		}
		return AjaxResult.success(orderBasicInfoService.getOrderTotalDataV2(dto));
	}

	/**
	 * 导出订单列表
	 */
	@PreAuthorize("@ss.hasPermi('order:order:export')")
	@Log(title = "订单", businessType = BusinessType.EXPORT)
	@PostMapping("/order/export")
	public void export(HttpServletResponse response, QueryOrderDTO orderBasicInfo) {
		// 权限过滤
		AuthorizedDeptVO authorizedMap = SecurityUtils.getAuthorizedMap();
		if (authorizedMap == null) {
			// 为空表示没有权限，返回空数组
			return;
		}
		String deptId = authorizedMap.getDeptId();
		// 根据部门id查询merchantId
		PileMerchantInfo pileMerchantInfo = pileMerchantInfoService.queryInfoByDeptId(deptId);
		if (pileMerchantInfo != null) {
			orderBasicInfo.setMerchantId(String.valueOf(pileMerchantInfo.getId()));
		}
		List<OrderListVO> list = orderBasicInfoService.selectOrderBasicInfoListWithAuth(orderBasicInfo);
		ExcelUtil<OrderListVO> util = new ExcelUtil<OrderListVO>(OrderListVO.class);
		util.exportExcel(response, list, "订单数据");
	}

	/**
	 * 获取订单详细信息 后管订单详情页
	 * http://localhost:8080/order/orderDetail/88000000000001012211161342359448
	 */
	@PreAuthorize("@ss.hasPermi('order:order:query')")
	@GetMapping(value = "/orderDetail/{orderCode}")
	public AjaxResult getInfo(@PathVariable("orderCode") String orderCode) {
		return AjaxResult.success(orderService.queryOrderDetailInfo(orderCode));
	}

	/**
	 * 修改订单 后管调用
	 */
	@PreAuthorize("@ss.hasPermi('order:order:edit')")
	@Log(title = "订单", businessType = BusinessType.UPDATE)
	@PutMapping("/order")
	public AjaxResult edit(@RequestBody OrderBasicInfo orderBasicInfo) {
		return toAjax(orderBasicInfoService.updateOrderBasicInfo(orderBasicInfo));
	}

	/**
	 * 删除订单
	 */
	@PreAuthorize("@ss.hasPermi('order:order:remove')")
	@Log(title = "订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/order/{ids}")
	public AjaxResult remove(@PathVariable Long[] ids) {
		return toAjax(orderBasicInfoService.deleteOrderBasicInfoByIds(ids));
	}


	/**
	 * 人工结算订单
	 * http://localhost:8080/order/manualSettlementOrder
	 */
	@PostMapping("/manualSettlementOrder")
	public AjaxResult manualSettlementOrder(@RequestBody ManualSettlementDTO dto) {
		return toAjax(orderService.manualSettlementOrder(dto));
	}


	/**
	 * 获取运营商订单列表
	 * @param dto
	 * @return
	 */
	@PreAuthorize("@ss.hasPermi('order:order:list')")
	@PostMapping("/getMerchantOrderList")
	public TableDataInfo getMerchantOrderList(@RequestBody QueryMerchantOrderDTO dto) {
		return getDataTable(orderBasicInfoService.getMerchantOrderInfoList(dto));
	}

	/**
	 * 重试订单退款接口
	 * http://localhost:8080/order/retryRefundOrder
	 */
	@PostMapping("/retryRefundOrder")
	public RestApiResponse<?> retryRefundOrder(@RequestBody ApplyRefundDTO dto) {
		RestApiResponse<?> response;
		try {
			orderBasicInfoService.retryRefundOrder(dto.getOrderCode());
			response = new RestApiResponse<>();
		} catch (BusinessException e) {
			logger.error("重试订单退款接口 error,", e);
			response = new RestApiResponse<>(e.getCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("重试订单退款接口 error,", e);
			response = new RestApiResponse<>(e);
		}
		return response;
	}
}
