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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
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.base.CuMember;
import com.hzs.common.domain.member.self.CuSelfServiceLog;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.account.dto.BusinessCommissionDTO;
import com.hzs.member.account.dto.MemberAmountDTO;
import com.hzs.member.account.dto.MemberBalanceDTO;
import com.hzs.member.account.service.ICuMemberBaseService;
import com.hzs.member.account.service.ICuMemberTradeService;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.self.service.ICuSelfServiceLogService;
import com.hzs.member.self.vo.SelfModifyAddressVO;
import com.hzs.system.base.IAreaServiceApi;
import com.hzs.system.config.IServiceChargeServiceApi;
import com.hzs.system.config.dto.ServiceChargeDTO;
import com.hzs.system.sys.dto.LoginUser;
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.math.BigDecimal;
import java.util.*;

/**
 * @description: 自助服务-修改收货地址
 * @author: zhang jing
 * @date: 2023/4/17 11:57
 * @param:
 * @return:
 **/
@Slf4j
@RequestMapping("/manage/self-modify-address")
@RestController
public class SelfModifyAddressController extends BaseController {

    @Autowired
    private ICuSelfServiceLogService serviceLogService;
    @Autowired
    private ICuMemberTradeService cuMemberTradeService;
    @Autowired
    private ICuMemberBaseService cuMemberBaseService;
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private ICuMemberService cuMemberService;

    @DubboReference
    IAreaServiceApi iAreaServiceApi;
    @DubboReference
    IServiceChargeServiceApi serviceChargeServiceApi;


    /**
     * @description: 自助服务-查询已申请修改收货地址
     * @author: zhang jing
     * @date: 2023/4/17 14:40
     * @param: [cuSelfServiceLogVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.MODIFY_ADDRESS, business = EOperationBusiness.MODIFY_ADDRESS, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(SelfModifyAddressVO selfModifyAddressVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        selfModifyAddressVO.setPkCountry(pkCountry);
        selfModifyAddressVO.setEditType(EApprovalBusiness.SELF_MODIFY_ADDRESS.getValue());
        startPage();
        List<SelfModifyAddressVO> slList = serviceLogService.querySelfModifyAddressManageList(selfModifyAddressVO);
        if (CollectionUtil.isNotEmpty(slList)) {
            // 调用system服务，获取地址
            Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(pkCountry).getData();
            // 查询到的订单对应的订单明细列表
            if (CollectionUtil.isNotEmpty(slList)) {
                for (SelfModifyAddressVO sa : slList) {
                    SelfModifyAddressVO csso = JSONObject.parseObject(sa.getNewValue(), SelfModifyAddressVO.class);
                    sa.setNewRecName(csso.getNewRecName());
                    sa.setNewRecPhone(csso.getNewRecPhone());
                    sa.setNewRecProvince(csso.getNewRecProvince());
                    sa.setNewRecCity(csso.getNewRecCity());
                    sa.setNewRecCounty(csso.getNewRecCounty());
                    sa.setNewRecAddress(csso.getNewRecAddress());
                    sa.setRecProvinceVal(areaMap.get(sa.getRecProvince()));
                    sa.setRecCityVal(areaMap.get(sa.getRecCity()));
                    if (StringUtils.isNotNull(sa.getRecCounty())) {
                        sa.setRecCountyVal(areaMap.get(sa.getRecCounty()));
                    }
                    sa.setNewRecProvinceVal(areaMap.get(sa.getNewRecProvince()));
                    sa.setNewRecCityVal(areaMap.get(sa.getNewRecCity()));
                    if (StringUtils.isNotNull(sa.getNewRecCounty())) {
                        sa.setNewRecCountyVal(areaMap.get(sa.getNewRecCounty()));
                    }
                }
            }
        }

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

    /**
     * @description: 同意前查询
     * @author: zhang jing
     * @date: 2023/6/29 10:50
     * @param: [selVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @PostMapping("/queryPass")
    @Log(module = EOperationModule.MODIFY_ADDRESS, business = EOperationBusiness.MODIFY_ADDRESS, method = EOperationMethod.SELECT)
    public AjaxResult queryPass(@RequestBody SelfModifyAddressVO selVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (CollectionUtil.isEmpty(selVO.getBusinessNoList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        if (null == selVO.getApproveOperation()) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.APPROVE_OPERATION_NOT_NULL));
        }
        List<SelfModifyAddressVO> selList = new ArrayList<>();
        // 调用system服务，获取地址
        Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(pkCountry).getData();
        for (String businessNo : selVO.getBusinessNoList()) {
            if (StringUtils.isEmpty(businessNo)) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.WORK_NO_NOT_NULL));
            }
            QueryWrapper<CuSelfServiceLog> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("BUSINESS_NO", businessNo);
            CuSelfServiceLog serviceLog = serviceLogService.getOne(queryWrapper);
            QueryWrapper<CuSelfServiceLog> check = new QueryWrapper<>();
            check.eq("ORDER_CODE", serviceLog.getOrderCode());
            check.eq("EDIT_TYPE", EApprovalBusiness.SELF_MODIFY_ADDRESS.getValue());
            check.eq("APPROVE_STATUS", EApproveRechargeStatus.WAIT.getValue());
            List<CuSelfServiceLog> serviceLogList = serviceLogService.list(check);
            if (CollectionUtil.isNotEmpty(serviceLogList)) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
            }
            SelfModifyAddressVO nselVO = JSONObject.parseObject(serviceLog.getNewValue(), SelfModifyAddressVO.class);
            nselVO.setPkMember(serviceLog.getPkMember());
            nselVO.setBusinessNo(businessNo);
            CuMember member = cuMemberService.getMember(serviceLog.getPkMember());
            nselVO.setMemberCode(member.getMemberCode());
            nselVO.setMemberName(member.getMemberName());
            nselVO.setOrderCode(serviceLog.getOrderCode());
            SelfModifyAddressVO oselVO = JSONObject.parseObject(serviceLog.getOldValue(), SelfModifyAddressVO.class);
            nselVO.setRecName(oselVO.getRecName());
            nselVO.setRecPhone(oselVO.getRecPhone());
            nselVO.setRecProvinceVal(areaMap.get(oselVO.getRecProvince()));
            nselVO.setNewRecProvinceVal(areaMap.get(nselVO.getNewRecProvince()));
            nselVO.setRecCityVal(areaMap.get(oselVO.getRecCity()));
            nselVO.setNewRecCityVal(areaMap.get(nselVO.getNewRecCity()));
            if (null != oselVO.getRecCounty()) {
                nselVO.setRecCountyVal(areaMap.get(oselVO.getRecCounty()));
            }
            if (null != nselVO.getNewRecCounty()) {
                nselVO.setNewRecCountyVal(areaMap.get(nselVO.getNewRecCounty()));
            }
            nselVO.setRecAddress(oselVO.getRecAddress());
            selList.add(nselVO);
        }
        return AjaxResult.success(selList);
    }

    /**
     * @description: 自助服务-申请修改收货地址-管理员初审
     * @author: zhang jing
     * @date: 2023/4/17 14:48
     * @param: [cuSelfServiceLogVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @PostMapping("/pass")
    @Log(module = EOperationModule.MODIFY_ADDRESS, business = EOperationBusiness.MODIFY_ADDRESS, method = EOperationMethod.AGREE)
    public AjaxResult pass(@RequestBody SelfModifyAddressVO selVO) {
        if (CollectionUtil.isEmpty(selVO.getBusinessNoList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        if (CollectionUtil.isEmpty(selVO.getUserIdList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EXAMINE_AND_APPROVE_NOT_NULL));
        }
        selVO.setApproveOperation(EApproveOperation.AGREE.getValue());
        Date date = new Date();
        Integer pkCountry = SecurityUtils.getPkCountry();

        selVO.setPkCountry(pkCountry);
        selVO.setModifiedTime(date);
        selVO.setPkModified(SecurityUtils.getUserId());
        List<SelfModifyAddressVO> selList = new ArrayList<>();
        if (selVO.getApproveOperation() == EApproveOperation.AGREE.getValue()) {
            for (String businessNo : selVO.getBusinessNoList()) {
                QueryWrapper<CuSelfServiceLog> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("BUSINESS_NO", businessNo);
                CuSelfServiceLog serviceLog = serviceLogService.getOne(queryWrapper);
                selVO.setPkId(serviceLog.getPkId());
                selVO.setPkMember(serviceLog.getPkMember());
                selVO.setBusinessNo(businessNo);
                SelfModifyAddressVO nselVO = JSONObject.parseObject(serviceLog.getNewValue(), SelfModifyAddressVO.class);
                SelfModifyAddressVO oselVO = JSONObject.parseObject(serviceLog.getOldValue(), SelfModifyAddressVO.class);
                BigDecimal differ = nselVO.getNewPostage().subtract(oselVO.getPostage());
                List<SelfModifyAddressVO> errorList = new ArrayList<>();
//                Map<Integer, ApprovalInfoDTO> approvalInfoMap =
//                        iApprovalServiceApi.queryApprovalInfo(Collections.singletonList(EApprovalBusiness.SELF_MODIFY_ADDRESS.getValue()), pkCountry).getData();
//                // 根据审批业务类型判断是否配置审批流程
//                ApprovalInfoDTO approvalInfo = approvalInfoMap.get(EApprovalBusiness.SELF_MODIFY_ADDRESS.getValue());
//                if (null == approvalInfo || CollectionUtil.isEmpty(approvalInfo.getItemList())) {
//                    // 审批 或者 审批流程 没有配置，则不允许进行申请
//                    log.error("{} 提交自助服务修改收货地址申请失败，未配置审批流程", EApprovalBusiness.SELF_MODIFY_ADDRESS.getLabel());
//                    return AjaxResult.error(ConfigMsgConstants.SELF_MODIFY_ADDRESS_PETITION_NOT_NULL);
//                }
                // 当前登录用户
                LoginUser loginUser = userTokenService.getLoginUser();
                selVO.setLoginUser(loginUser);
                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);
                //查询扣费金额，账户信息
                ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                serviceChargeDTO.setType(EApprovalBusiness.SELF_MODIFY_ADDRESS.getValue());
                serviceChargeDTO.setPkCountry(pkCountry);
                serviceChargeDTO.setQuantity(approveNumber + 1);
                R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
                BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                memberAmountDTO.setPkMember(selVO.getPkMember());
                if (differ.compareTo(new BigDecimal(0)) > 0) {
                    memberAmountDTO.setTradeAmount(serviceChargeDTOR.getData().getCost().add(differ));
                } else {
                    memberAmountDTO.setTradeAmount(serviceChargeDTOR.getData().getCost());
                }
                selVO.setSingleAmount(serviceChargeDTOR.getData().getCost());
                selVO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                selVO.setPkAccountKey(cuMemberBaseService.translateAccountValue(serviceChargeDTOR.getData().getPkAccount()));
                memberAmountDTOList.add(memberAmountDTO);
                selVO.setMemberAmountDTOList(memberAmountDTOList);
                businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                businessCommissionDTO.setPkCountry(pkCountry);
                if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                    //接口查询金额是否足够
                    List<MemberBalanceDTO> memberBalanceList = cuMemberTradeService.selectBalanceNotEnoughMember(businessCommissionDTO);
                    if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                        memberBalanceList.forEach(item -> {
                            SelfModifyAddressVO error = BeanUtil.copyProperties(item, SelfModifyAddressVO.class);
                            error.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT));
                            errorList.add(error);
                        });
                    }
                }
                selList.add(selVO);
            }
        }
        return AjaxResult.success(serviceLogService.firstInstance(selList));
    }

    /**
     * @description: 修改地址-驳回
     * @author: zhang jing
     * @date: 2023/6/7 14:40
     * @param: [selVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @PostMapping("/reject")
    @Log(module = EOperationModule.MODIFY_ADDRESS, business = EOperationBusiness.MODIFY_ADDRESS, method = EOperationMethod.REJECT)
    public AjaxResult reject(@RequestBody SelfModifyAddressVO selVO) {
        if (CollectionUtil.isEmpty(selVO.getBusinessNoList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        if (StringUtils.isEmpty(selVO.getRejectMsg())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.REJECT_MSG_NOT_NULL));
        }
        selVO.setApproveOperation(EApproveOperation.REJECT.getValue());
        List<SelfModifyAddressVO> selList = new ArrayList<>();
        Date date = new Date();
        Integer pkCountry = SecurityUtils.getPkCountry();
        selVO.setPkCountry(pkCountry);
        selVO.setModifiedTime(date);
        selVO.setPkModified(SecurityUtils.getUserId());
        for (String businessNo : selVO.getBusinessNoList()) {
            QueryWrapper<CuSelfServiceLog> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("BUSINESS_NO", businessNo);
            CuSelfServiceLog serviceLog = serviceLogService.getOne(queryWrapper);
            selVO.setPkId(serviceLog.getPkId());
            selList.add(selVO);
        }
        return AjaxResult.success(serviceLogService.firstInstance(selList));
    }

}
