package com.sckw.transport.controller.operate;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.core.exception.CustomPromptException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.enums.SystemTypeEnum;
import com.sckw.core.model.page.PageHelperUtil;
import com.sckw.core.model.page.PageResult;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.HttpResult;
import com.sckw.excel.config.easyexcel.RequestHolder;
import com.sckw.excel.utils.ExcelUtil;
import com.sckw.system.api.RemoteUserService;
import com.sckw.transport.model.dto.WaybillOrderQueryDto;
import com.sckw.transport.model.param.ManagementWaybillOrderQuery;
import com.sckw.transport.model.vo.WaybillOrderExportVo;
import com.sckw.transport.model.vo.WaybillOrderSelectVo;
import com.sckw.transport.model.vo.execlVo.ManagementWaybillOrderExcelVO;
import com.sckw.transport.service.KwtWaybillOrderV1Service;
import com.sckw.transport.service.operateService.KwtManagementWaybillOrderService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author  JC
 * @description 运营管理端-运单controller
 * @date 2023/09/12 09:20:21
 */
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/kwtManagementWaybillOrder")
public class ManagementWaybillOrderController {
    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 6000)
    RemoteUserService remoteUserService;
    @Autowired
    KwtManagementWaybillOrderService managementWaybillOrderService;
    @Autowired
    KwtWaybillOrderV1Service waybillOrderV1Service;


    /**
     * 运营管理端-运单-首页条件查询
     *
     * @param query 查询参数
     * @return  运单响应结果数据
     */
    @RequestMapping(value = "/select", method = RequestMethod.POST)
    public HttpResult selectWaybillOrder(@Valid @RequestBody ManagementWaybillOrderQuery query) {
        try {
            return managementWaybillOrderService.selectWaybillOrder(query);
        } catch (Exception e) {
            log.error("运营管理端-运单-首页条件查询 查询失败:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 运营管理端-运单-首页条件查询
     *
     * @param query 查询参数
     * @return  运单响应结果数据
     */
    @RequestMapping(value = "/selectV1", method = RequestMethod.POST)
    public HttpResult selectWaybillOrder(@Valid @RequestBody WaybillOrderQueryDto query) {
        try {
            //return managementWaybillOrderService.selectWaybillOrder(query);
            //新增客户经理权限过滤
            List<Long> authEntIdList = new ArrayList<>();
            if (SystemTypeEnum.MANAGE.getCode().equals(LoginUserHolder.getSystemType())) {
                if (CollectionUtils.isEmpty(authEntIdList)) {
                    List<Long> ids = remoteUserService.findEnterpriseIdsByUserIdIsMain(LoginUserHolder.getUserId());
                    if (com.sckw.core.utils.CollectionUtils.isEmpty(ids)){
                        return HttpResult.ok(PageHelperUtil.getPageResult(new PageInfo<>(new ArrayList<>())));
                    }
                    authEntIdList.addAll(ids);
                }
            }

            // 设置分页参数
            PageHelper.startPage(query.getPage(), query.getPageSize());
            query.setEntIds(authEntIdList);
            List<WaybillOrderSelectVo> list = waybillOrderV1Service.findListPage(query);
            PageResult result = PageHelperUtil.getPageResult(new PageInfo<>(list));
            return HttpResult.ok(result);
        } catch (Exception e) {
            log.error("运营管理端-运单-首页条件查询 查询失败:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }


    /**
     * 运营管理端-运单-top统计
     *
     * @param query 查询参数
     * @return  运单统计结果
     */
    @RequestMapping(value = "/statistics", method = RequestMethod.POST)
    public HttpResult statisticsWaybillOrder(@Valid @RequestBody ManagementWaybillOrderQuery query) {
        log.error("运营管理端-运单-top统计 查询 :{}", JSONObject.toJSONString(query));
        try {
            return managementWaybillOrderService.statisticsWaybillOrder(query);
        } catch (Exception e) {
            log.error("运营管理端-运单-top统计 失败 :{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 运营管理端-运单-top统计
     *
     * @param query 查询参数
     * @return  运单统计结果
     */
    @RequestMapping(value = "/statisticsV1", method = RequestMethod.POST)
    public HttpResult statisticsWaybillOrder(@Valid @RequestBody WaybillOrderQueryDto query) {
        log.error("运营管理端-运单-top统计 查询 :{}", JSONObject.toJSONString(query));
        try {
            return HttpResult.ok(waybillOrderV1Service.statistics(query));
        } catch (Exception e) {
            log.error("运营管理端-运单-top统计 失败 :{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }


    /***
     * 运营管理端-运单-导出
     * @param query 查询参数
     */
    @RequestMapping(value = "/export", method = RequestMethod.POST)
    public void exportWaybillOrder(@Validated @RequestBody ManagementWaybillOrderQuery query) {
        log.error("运营管理端-运单-导出 query :{}", JSONObject.toJSONString(query));
        HttpServletResponse response = RequestHolder.getResponse();
        List<ManagementWaybillOrderExcelVO> list = managementWaybillOrderService.exportWaybillOrder(query);
        if (CollectionUtils.isEmpty(list)){
            throw new CustomPromptException(HttpStatus.SUCCESS_CODE,"暂无数据，请确认");
        }
        ExcelUtil.downData(response, ManagementWaybillOrderExcelVO.class, list);
    }

    /***
     * 运营管理端-运单-导出
     * @param query 查询参数
     */
    @RequestMapping(value = "/exportV1", method = RequestMethod.POST)
    public void exportWaybillOrder(@Validated @RequestBody WaybillOrderQueryDto query, HttpServletResponse response) {
        log.error("运营管理端-运单-导出 query :{}", JSONObject.toJSONString(query));
        /*查询数据*/
        List<WaybillOrderSelectVo> list = waybillOrderV1Service.findListPage(query);
        if (CollectionUtils.isEmpty(list)) {
            throw new CustomPromptException(HttpStatus.SUCCESS_CODE, "暂无数据，请确认！");
        }
        //数据处理
        List<WaybillOrderExportVo> orders = new ArrayList<>();
        for (WaybillOrderSelectVo select:list) {
            WaybillOrderExportVo exportVo = new WaybillOrderExportVo();
            exportVo.setLoadName(String.join(Global.COMMA, select.getLoadName()));
            exportVo.setLoadAddress(String.join(Global.COMMA, select.getLoadAddress()));
            exportVo.setUnloadName(String.join(Global.COMMA, select.getUnloadName()));
            exportVo.setUnloadAddress(String.join(Global.COMMA, select.getUnloadAddress()));
            orders.add(exportVo);
        }
        ExcelUtil.downData(response, WaybillOrderExportVo.class, orders);
    }


    /**
     * 运营端-运单-获取订单详情
     *
     * @param id 订单id
     * @return  订单数据
     */
    @RequestMapping(value = "/getOrderDetail", method = RequestMethod.GET)
    public HttpResult getOrderDetail(@RequestParam("id") Long id) {
        try {
            return managementWaybillOrderService.getOrderDetail(id);
        } catch (Exception e) {
            log.error("运营端-运单-获取订单详情失败:error :单据id:{}, errorMessage:{}", id, e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 运营端-运单-获取订单详情
     *
     * @param id 订单id
     * @return  订单数据
     */
    @RequestMapping(value = "/getOrderDetailV1", method = RequestMethod.GET)
    public HttpResult getOrderDetailV1(@RequestParam("id") Long id) {
        try {
            return waybillOrderV1Service.waybillDetail(id);
        } catch (Exception e) {
            log.error("运营端-运单-获取订单详情失败:error :单据id:{}, errorMessage:{}", id, e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

}
