package com.hzs.ground.order.controller.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.msg.ScmMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.poi.ExcelUtil;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.ground.order.ext.SaOrderSettleExt;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.ground.order.param.OrderItemsParam;
import com.hzs.ground.order.param.OrderQueryParam;
import com.hzs.ground.order.service.ISaOrderSettleService;
import com.hzs.ground.order.service.ISupplierOrderService;
import com.hzs.ground.order.vo.SaOrderSettleVo;
import com.hzs.system.base.ISystemConfigServiceApi;
import com.hzs.system.base.dto.BdCubasdocDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 订单控制类
 *
 * @author: sui q
 * @time: 2022/8/27 16:20
 * @description:
 * @classname: OrderController
 * @package_name: com.hzs.sale.order.controller
 */
@RestController
@RequestMapping("/manage/order")
@Slf4j
public class SupplierOrderController extends BaseController {

    @DubboReference
    private ISystemConfigServiceApi systemConfigServiceApi;

    @Autowired
    private ISupplierOrderService supplierOrderService;

    @Autowired
    private ISaOrderSettleService saOrderSettleService;

    /**
     * 查询列表
     *
     * @return cubasdocParam 入参
     */
    @PostMapping("/list")
    public TableDataInfo listSupplierOrder(@RequestBody OrderQueryParam orderQueryParam) {
        // 根据登录人获取供应商，根据登录账号查找绑定的供应商，查询供应商表
        R<BdCubasdocDTO> bdCubasdocDate = systemConfigServiceApi.queryBdCubasdocByUser(SecurityUtils.getUserId());
        if (!bdCubasdocDate.isSuccess() || bdCubasdocDate.getData() == null) {
            return getDataTable(Collections.emptyList());
        }
        orderQueryParam.setPkSupplier(bdCubasdocDate.getData().getPkSupplier());
        // 根据供应商查询可以查询到的订单
        startPage();
        orderQueryParam.setPkCountry(SecurityUtils.getPkCountry());
        List<SaOrderExt> orderList = supplierOrderService.querySaOrderByCondition(orderQueryParam);
        for (SaOrderExt saOrderExt : orderList) {
            for (EOrderStatus value : EOrderStatus.values()) {
                if (value.getValue() == saOrderExt.getOrderStatus()) {
                    saOrderExt.setOrderStatusVal(value.getLabel());
                    break;
                }
            }
        }
        return getDataTable(orderList);
    }

    @PostMapping("/send")
    public AjaxResult sendGood(@RequestBody List<OrderItemsParam> orderItemsParamList) {
        // 验证是否有该产品的权限，验证订单是否已经发货
        R<BdCubasdocDTO> bdCubasdocDate = systemConfigServiceApi.queryBdCubasdocByUser(SecurityUtils.getUserId());
        if (!bdCubasdocDate.isSuccess() || bdCubasdocDate.getData() == null) {
            return AjaxResult.error("该账号没有绑定供应商");
        }
        for (OrderItemsParam orderItemsParam : orderItemsParamList) {
            if (orderItemsParam.getLogisticsCode() == null || orderItemsParam.getLogisticsCompany() == null) {
                return AjaxResult.error("请输入物流单号，物流公司");
            }
        }
        OrderQueryParam orderQueryParam = new OrderQueryParam();
        orderQueryParam.setPkSupplier(bdCubasdocDate.getData().getPkSupplier());
        orderQueryParam.setOrderItemsParamList(orderItemsParamList);
        orderQueryParam.setPkCountry(SecurityUtils.getPkCountry());
        orderQueryParam.setPkCreator(SecurityUtils.getUserId());
        List<SaOrderExt> orderList = supplierOrderService.querySaOrderByCondition(orderQueryParam);
        if (orderList == null) {
            return AjaxResult.error("存在不属于该用户的产品，不能发货");
        }
        int size = 0;
        for (SaOrderExt saOrderExt : orderList) {
            size += saOrderExt.getOrderItemsExtList().size();
        }
        if (size < orderItemsParamList.size()) {
            return AjaxResult.error("存在不属于该用户的产品，不能发货");
        }
        supplierOrderService.sendGood(orderQueryParam, orderItemsParamList, orderList);
        return AjaxResult.success();
    }

    /**
     * 查询列表
     *
     * @return cubasdocParam 入参
     */
    @PostMapping("/list-settle")
    @Log(module = EOperationModule.SUPPLIER_SETTLE_ORDER, business = EOperationBusiness.SUPPLIER_SETTLE_ORDER, method = EOperationMethod.SELECT)
    public TableDataInfo listSettleOrder(@RequestBody OrderQueryParam orderQueryParam) {
        // 根据登录人获取供应商，根据登录账号查找绑定的供应商，查询供应商表
        R<BdCubasdocDTO> bdCubasdocDate = systemConfigServiceApi.queryBdCubasdocByUser(SecurityUtils.getUserId());
        if (bdCubasdocDate != null && bdCubasdocDate.getData() != null) {
            orderQueryParam.setPkSupplier(bdCubasdocDate.getData().getPkSupplier());
        }
        // 根据供应商查询可以查询到的订单
        startPage();
        orderQueryParam.setPkCountry(SecurityUtils.getPkCountry());
        List<SaOrderSettleExt> orderSettleExtList = saOrderSettleService.querySaOrderSettle(orderQueryParam);
        return getDataTable(orderSettleExtList);
    }

    /**
     * 分页查询会员某个时间段内的奖金汇总
     */
    @PostMapping("/export-list")
    @Log(module = EOperationModule.SUPPLIER_SETTLE_ORDER, business = EOperationBusiness.SUPPLIER_SETTLE_ORDER, method = EOperationMethod.EXPORT)
    public void exportSettleOrder(HttpServletResponse response, OrderQueryParam orderQueryParam){
        // 根据登录人获取供应商，根据登录账号查找绑定的供应商，查询供应商表
        R<BdCubasdocDTO> bdCubasdocDate = systemConfigServiceApi.queryBdCubasdocByUser(SecurityUtils.getUserId());
        if (bdCubasdocDate != null && bdCubasdocDate.getData() != null) {
            orderQueryParam.setPkSupplier(bdCubasdocDate.getData().getPkSupplier());
        }
        // 根据供应商查询可以查询到的订单
        orderQueryParam.setPkCountry(SecurityUtils.getPkCountry());
        List<SaOrderSettleExt> orderSettleExtList = saOrderSettleService.querySaOrderSettle(orderQueryParam);
        List<SaOrderSettleVo>  saOrderSettleVoList = packageScmExportVo(orderSettleExtList);
        ExcelUtil<SaOrderSettleVo> util = new ExcelUtil<>(SaOrderSettleVo.class);
        util.exportExcel(response, saOrderSettleVoList, "订单结算导出");
    }

    private List<SaOrderSettleVo> packageScmExportVo(List<SaOrderSettleExt> orderSettleExtList) {
        List<SaOrderSettleVo> saOrderSettleVoList = new ArrayList<>();
        for (SaOrderSettleExt saOrderSettleExt : orderSettleExtList) {
            SaOrderSettleVo saOrderSettleVo = BeanUtil.copyProperties(saOrderSettleExt, SaOrderSettleVo.class);
            if(EDealerYesNo.YES.getValue() == saOrderSettleExt.getSettleStatus()){
                saOrderSettleVo.setSettleStatusVal(EDealerYesNo.YES.getLabel());
            }else{
                saOrderSettleVo.setSettleStatusVal(EDealerYesNo.NO.getLabel());
            }
            saOrderSettleVoList.add(saOrderSettleVo);
        }
        return saOrderSettleVoList;
    }

    /**
     * 结算订单
     *
     * @return cubasdocParam 入参
     */
    @PostMapping("/settle-order")
    @Log(module = EOperationModule.SUPPLIER_SETTLE_ORDER, business = EOperationBusiness.SUPPLIER_SETTLE_ORDER, method = EOperationMethod.SETTLE)
    public AjaxResult settleOrder(@RequestBody OrderQueryParam orderQueryParam) {
        orderQueryParam.setPkCountry(SecurityUtils.getPkCountry());
        List<SaOrderSettleExt> orderSettleExtList = saOrderSettleService.querySaOrderSettle(orderQueryParam);
        if (CollectionUtil.isEmpty(orderSettleExtList)) {
            return AjaxResult.error(ScmMsgConstants.SETTLE_ORDER_NOT_EXISTS);
        }
        // 分为线上线下2部分
        for (SaOrderSettleExt saOrderSettleExt : orderSettleExtList) {
            // 验证状态
            if (EYesNo.YES.getIntValue() == saOrderSettleExt.getSettleStatus()) {
                return AjaxResult.error(ScmMsgConstants.SETTLE_ORDER_HAS_SETTLE);
            }
        }
        saOrderSettleService.updateSaOrderSettle(orderSettleExtList);
        return AjaxResult.success();
    }

//    /**
//     * 撤销订单并入库（走签呈），签呈页面点击确定按钮
//     *
//     * @param scmApproveParam 参数
//     */
//    @PostMapping("/submit")
//    @Log(module = EOperationModule.SUPPLIER_SETTLE_ORDER, business = EOperationBusiness.SUPPLIER_SETTLE_ORDER, method = EOperationMethod.UPDATE)
//    public AjaxResult submitSettleOrder(@RequestBody ScmApproveParam scmApproveParam) {
//        scmApproveParam.setPkCountry(SecurityUtils.getPkCountry());
//        if(scmApproveParam.getPkId() == null){
//            return AjaxResult.error(TransactionUtils.getContent(ScmMsgConstants.IC_GENERAL_IN_NOT_EXIST));
//        }
//        IcGeneralInHExt generalInhExt = generalInhService.queryGeneralInById(scmApproveParam.getPkId(), EScmOrderStatus.SAVE.getValue());
//        if (generalInhExt == null) {
//            return AjaxResult.error(TransactionUtils.getContent(ScmMsgConstants.IC_GENERAL_IN_NOT_EXIST));
//        }
//        // 验证该订单是否存在签呈，存在待审核的签呈不能再次发起
//        List<ScmOrderApproveLog> scmOrderApproveLogs = scmOrderApproveLogService.queryScmOrderApproveLogByCondition(scmApproveParam.getPkId(), EApprovalBusiness.IC_GENERAL_IN_APPROVE.getValue(), null);
//        if(CollectionUtil.isNotEmpty(scmOrderApproveLogs)){
//            return AjaxResult.error(TransactionUtils.getContent(ScmMsgConstants.PURCHASE_EXISTS_AGENT));
//        }
//        generalInhService.auditGeneralInByApproveParamSubmit(scmApproveParam, userTokenService.getLoginUser());
//        return AjaxResult.success();
//    }

}
