package com.hzs.member.self.controller.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.common.core.constant.msg.CommonMsgConstants;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.EApprovalBusiness;
import com.hzs.common.core.enums.EApproveRechargeStatus;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
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.member.self.CuSelfServiceLog;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.sale.ext.SaOrderItemsExt;
import com.hzs.common.domain.system.base.BdStorehouse;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.self.service.ICuSelfServiceLogService;
import com.hzs.member.self.vo.*;
import com.hzs.sale.order.ISaOrderItemsServiceApi;
import com.hzs.sale.order.ISaOrderServiceApi;
import com.hzs.sale.order.dto.OrderItemsParamDTO;
import com.hzs.sale.order.dto.WaresOrderDTO;
import com.hzs.system.base.IAreaServiceApi;
import com.hzs.system.base.ICurrencyServiceApi;
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.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 自助服务-修改收货地址
 **/
@Slf4j
@RequestMapping("/api/self-modify-address")
@RestController
public class ApiSelfModifyAddressController extends BaseController {

    @Autowired
    private ICuSelfServiceLogService serviceLogService;

    @DubboReference
    IAreaServiceApi iAreaServiceApi;
    @DubboReference
    ISaOrderServiceApi iSaOrderServiceApi;
    @DubboReference
    ISaOrderItemsServiceApi iSaOrderItemsServiceApi;
    @DubboReference
    ICurrencyServiceApi iCurrencyServiceApi;


    /**
     * 自助服务-查询已申请修改收货地址
     **/
    @GetMapping("/list")
    public TableDataInfo list(SelfModifyAddressVO selfModifyAddressVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        Long pkMember = SecurityUtils.getUserId();
        selfModifyAddressVO.setPkMember(pkMember);
        selfModifyAddressVO.setPkCountry(pkCountry);
        selfModifyAddressVO.setEditType(EApprovalBusiness.SELF_MODIFY_ADDRESS.getValue());
        startPage();
        List<SelfModifyAddressVO> slList = serviceLogService.querySelfModifyAddressList(selfModifyAddressVO);
        if (CollectionUtil.isNotEmpty(slList)) {
            // 调用system服务，获取地址
            Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(pkCountry).getData();
            // 获取订单ID列表
            List<Long> orderIdList = slList.parallelStream().map(SelfModifyAddressVO::getPkOrder).collect(Collectors.toList());
            // 查询到的订单对应的订单明细列表
            List<MyOrderItemsVO> orderItemsList = serviceLogService.queryListByOrderId(orderIdList);
            if (CollectionUtil.isNotEmpty(orderItemsList)) {
                for (SelfModifyAddressVO sa : slList) {
                    List<MyOrderItemsVO> itemList = new ArrayList<>();
                    for (MyOrderItemsVO mo : orderItemsList) {
                        if (sa.getPkOrder().equals(mo.getPkOrder())) {
                            itemList.add(mo);
                        }
                    }
                    sa.setItemList(itemList);
                    SelfModifyAddressVO sad = JSONObject.parseObject(sa.getNewValue(), SelfModifyAddressVO.class);
                    sa.setRecProvinceVal(areaMap.get(sad.getNewRecProvince()));
                    sa.setRecCityVal(areaMap.get(sad.getNewRecCity()));
                    if (StringUtils.isNotNull(sad.getNewRecCounty())) {
                        sa.setRecCountyVal(areaMap.get(sad.getNewRecCounty()));
                    }
                    sa.setNewRecName(sad.getRecName());
                    sa.setNewRecPhone(sad.getRecPhone());
                    sa.setNewRecAddress(sad.getRecAddress());
                    sa.setSelfRemark(sad.getSelfRemark());
                }
            }
        }

        TableDataInfo tableDataInfo = getDataTable(slList);
        tableDataInfo.setRows(slList);
        return tableDataInfo;
    }


    /**
     * 自助服务-申请修改收货地址-发起签呈申请
     **/
    @PostMapping("/putin")
    public AjaxResult putin(@RequestBody SelfModifyAddressVO selVO) throws Exception {
        //校验是否重复提交记录
        QueryWrapper<CuSelfServiceLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("ORDER_CODE", "APPROVE_STATUS")
                .eq("ORDER_CODE", selVO.getOrderCode())
                .eq("EDIT_TYPE", EApprovalBusiness.SELF_MODIFY_ADDRESS.getValue())
                .and(i -> i.eq("APPROVE_STATUS", EApproveRechargeStatus.WAIT.getValue())
                        .or()
                        .eq("APPROVE_STATUS", EApproveRechargeStatus.SUBMIT.getValue()));
        List<CuSelfServiceLog> serviceLogList = serviceLogService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(serviceLogList)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
        }

        if (StringUtils.isAnyEmpty(selVO.getRecName(),
                selVO.getRecPhone(),
                selVO.getRecAddress(),
                selVO.getOrderCode(),
                selVO.getNewRecName(),
                selVO.getNewRecPhone(),
                selVO.getNewRecAddress())
                || ObjectUtil.emptyCount(
                selVO.getPostage(),
                selVO.getRecProvince(),
                selVO.getRecCity(),
                selVO.getNewRecProvince(),
                selVO.getNewRecCity(),
                selVO.getPayTime()
        ) > 0) {
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        Date date = new Date();
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String formattedDateTime1 = f.format(date);
        String formattedDateTime2 = f.format(selVO.getPayTime());
        String mo1 = DateUtils.getMonth(formattedDateTime1);
        String mo2 = DateUtils.getMonth(formattedDateTime2);
        if (!mo1.equals(mo2)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ORDER_TIMEOUT));
        }

        //查询邮费
        Integer pkCountry = SecurityUtils.getPkCountry();
        R<List<SaOrderExt>> orderList = iSaOrderServiceApi.selfAddressOrderList(selVO.getOrderCode(), EApprovalBusiness.SELF_MODIFY_ADDRESS.getValue(), SecurityUtils.getUserId(), pkCountry);
        if (orderList.getData() != null) {
            List<OrderItemsParam> orderItemsParams = new ArrayList<>();
            List<OrderItemsParamDTO> orderItemsParamsDto = new ArrayList<>();
            // 获取订单ID列表
            List<Long> orderIdList = new ArrayList<>();
            for (SaOrderExt saOrderExt : orderList.getData()) {
                orderIdList.add(saOrderExt.getPkId());
            }
            // 查询订单商品明细列表
            R<List<WaresOrderDTO>> waresAllList = iSaOrderItemsServiceApi.waresListByOrderId(orderIdList);
            // 查询订单产品明细列表
            R<List<SaOrderItemsExt>> productAllList = iSaOrderItemsServiceApi.queryListByOrderId(orderIdList, null);
            orderList.getData().forEach(itm -> {
                if (CollectionUtil.isNotEmpty(waresAllList.getData())) {
                    for (WaresOrderDTO wo : waresAllList.getData()) {
                        if (wo.getPkOrder().intValue() == itm.getPkId().intValue()) {
                            OrderItemsParam oip = BeanUtil.copyProperties(wo, OrderItemsParam.class);
                            if (CollectionUtil.isNotEmpty(productAllList.getData())) {
                                List<WaresItemsParam> waresItemsParamList = new ArrayList<>();
                                for (SaOrderItemsExt saOrderItems : productAllList.getData()) {
                                    WaresItemsParam wip = BeanUtil.copyProperties(saOrderItems, WaresItemsParam.class);
                                    if (wo.getPkOrder().intValue() == saOrderItems.getPkOrder().intValue() &&
                                            wo.getPkWares().intValue() == saOrderItems.getPkWares().intValue()) {
                                        waresItemsParamList.add(wip);
                                    }
                                    if (itm.getPkId().intValue() == saOrderItems.getPkOrder().intValue()) {
                                        itm.setOrderStatus(saOrderItems.getOrderStatus());
                                    }
                                }
                                oip.setWaresItemsParamList(waresItemsParamList);
                                orderItemsParams.add(oip);
                            }
                        }
                    }
                }
            });
            orderItemsParams.forEach(item -> orderItemsParamsDto.add(BeanUtil.copyProperties(item, OrderItemsParamDTO.class)));
        }
        Long pkMember = SecurityUtils.getUserId();
        selVO.setPkMember(pkMember);
        selVO.setPkCountry(pkCountry);

        // 根据收货省获取仓库
        BdStorehouse storehouse = iCurrencyServiceApi.queryBdStorehouseByProvince(selVO.getNewRecProvince()).getData();
        // 根据收货地址更新仓库
        if (null != storehouse) {
            selVO.setPkStorehouse(storehouse.getPkId());
        }

        CuSelfServiceLog cuSelfServiceLog = new CuSelfServiceLog();
        cuSelfServiceLog.setPkCountry(pkCountry);
        cuSelfServiceLog.setApproveStatus(EApproveRechargeStatus.AGREE.getValue());
        cuSelfServiceLog.setEditType(EApprovalBusiness.SELF_MODIFY_ADDRESS.getValue());
        cuSelfServiceLog.setPkMember(selVO.getPkMember());
        //当前最大次数
        Integer approveNumber = serviceLogService.selectByMaxApproveNumber(cuSelfServiceLog);
        selVO.setApproveNumber(approveNumber + 1);

        return AjaxResult.success(serviceLogService.putin(selVO));
    }


}
