package com.hzs.member.self.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.member.self.CuSelfServiceLog;
import com.hzs.common.domain.member.self.CuSelfServiceLogExt;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.account.service.*;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.handlebusiness.vo.BusinessMemberVO;
import com.hzs.member.self.mapper.CuSelfServiceLogMapper;
import com.hzs.member.self.service.ICuSelfServiceLogService;
import com.hzs.member.self.vo.DomicileChangeVO;
import com.hzs.member.self.vo.MyOrderItemsVO;
import com.hzs.member.self.vo.SelfModifyAddressVO;
import com.hzs.sale.order.ISaOrderServiceApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 自助服务日志表 服务实现类
 */
@Service
public class CuSelfServiceLogServiceImpl extends ServiceImpl<CuSelfServiceLogMapper, CuSelfServiceLog> implements ICuSelfServiceLogService {

    @DubboReference
    ISaOrderServiceApi iSaOrderServiceApi;

    @Autowired
    private ICuMemberAuthenticationService iCuMemberAuthenticationService;
    @Autowired
    private ICuMemberBusinessLicenseService iCuMemberBusinessLicenseService;
    @Autowired
    private ICuMemberService iCuMemberService;
    @Autowired
    private ICuMemberBankService iCuMemberBankService;

    @Override
    public List<SelfModifyAddressVO> querySelfModifyAddressList(SelfModifyAddressVO selfModifyAddressVO) {
        return baseMapper.querySelfModifyAddressList(selfModifyAddressVO);
    }

    @Override
    public List<SelfModifyAddressVO> querySelfModifyAddressManageList(SelfModifyAddressVO selfModifyAddressVO) {
        return baseMapper.querySelfModifyAddressManageList(selfModifyAddressVO);
    }

    @Override
    public Integer selectByMaxApproveNumber(CuSelfServiceLog cuSelfServiceLog) {
        return baseMapper.selectByMaxApproveNumber(cuSelfServiceLog);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean saveChangeDomicile(DomicileChangeVO domicileChangeVO) {
        Long pkMember = domicileChangeVO.getPkMember();

        //更新业务
        iCuMemberService.updateMemberNameAndPhone(pkMember, domicileChangeVO.getChangeMemberName(), domicileChangeVO.getChangePhone(), pkMember);
        //注销实名认证、营业执照
        changeBusinessByChangeName(pkMember, pkMember);
        //重置银行卡
        BusinessMemberVO businessMemberVO = BusinessMemberVO.builder().pkMember(pkMember).build();
        iCuMemberBankService.batchUpdateBankBypkMembers(Collections.singletonList(businessMemberVO), pkMember);
        //修改会员的变更次数
        List<Long> pkMembers = Collections.singletonList(businessMemberVO.getPkMember());
        iCuMemberService.updateMemberEditNumber(pkMembers, pkMember);

        //变更前值
        DomicileChangeVO oldValue = DomicileChangeVO.builder().memberName(domicileChangeVO.getMemberName())
                .phone(domicileChangeVO.getPhone()).idFront(domicileChangeVO.getIdFront()).idBack(domicileChangeVO.getIdBack()).build();
        //变更后的值
        DomicileChangeVO newValue = DomicileChangeVO.builder().changeMemberName(domicileChangeVO.getChangeMemberName())
                .changePhone(domicileChangeVO.getChangePhone()).changeIdFront(domicileChangeVO.getChangeIdFront()).changeIdBack(domicileChangeVO.getChangeIdBack()).build();
        String businessNo = CommonUtil.createSerialNumber(EOrderPrefix.SELF_SERVICE.getValue());
        CuSelfServiceLog oldServiceLog = CuSelfServiceLog.builder()
                .pkMember(pkMember)
                .editType(EApprovalBusiness.DOMICILE_CHANGE.getValue())
                .oldValue(JSONUtil.toJsonStr(oldValue))
                .newValue(JSONUtil.toJsonStr(newValue))
                .businessNo(businessNo)
                .selfRemark(domicileChangeVO.getRemark())
                .description(domicileChangeVO.getDescription())
                .approveStatus(EApproveRechargeStatus.AGREE.getValue())
                .pkAccount(domicileChangeVO.getPkAccount())
                .approveNumber(MagicNumberConstants.CHANGE_NUM)
                .singleAmount(domicileChangeVO.getAmount())
                .editTypePay(ETradeType.getValueByApprovalValue(EApprovalBusiness.DOMICILE_CHANGE.getValue()))
                .build();
        oldServiceLog.setPkCreator(pkMember);
        oldServiceLog.setPkCountry(CountryConstants.CHINA_COUNTRY);
        return this.save(oldServiceLog);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean putin(SelfModifyAddressVO selfModifyAddressVO) {
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SELF_SERVICE.getValue());
        Date date = new Date();
        Long userID = SecurityUtils.getUserId();
        SelfModifyAddressVO oldsma = new SelfModifyAddressVO();
        oldsma.setRecAddress(selfModifyAddressVO.getRecAddress());
        oldsma.setRecName(selfModifyAddressVO.getRecName());
        oldsma.setRecPhone(selfModifyAddressVO.getRecPhone());
        oldsma.setRecProvince(selfModifyAddressVO.getRecProvince());
        oldsma.setRecCity(selfModifyAddressVO.getRecCity());
        oldsma.setPostage(selfModifyAddressVO.getPostage());
        if (StringUtils.isNotNull(selfModifyAddressVO.getRecCounty())) {
            oldsma.setRecCounty(selfModifyAddressVO.getRecCounty());
        }
        SelfModifyAddressVO newsma = new SelfModifyAddressVO();
        newsma.setNewRecAddress(selfModifyAddressVO.getNewRecAddress());
        newsma.setNewRecName(selfModifyAddressVO.getNewRecName());
        newsma.setNewRecPhone(selfModifyAddressVO.getNewRecPhone());
        newsma.setNewRecProvince(selfModifyAddressVO.getNewRecProvince());
        newsma.setNewRecCity(selfModifyAddressVO.getNewRecCity());
        newsma.setNewPostage(selfModifyAddressVO.getNewPostage());
        if (StringUtils.isNotNull(selfModifyAddressVO.getNewRecCounty())) {
            newsma.setNewRecCounty(selfModifyAddressVO.getNewRecCounty());
        }
        //新增修改订单地址日志记录
        CuSelfServiceLog css = new CuSelfServiceLog();
        css.setPkCountry(selfModifyAddressVO.getPkCountry());
        css.setEditType(selfModifyAddressVO.getEditType());
        css.setApproveStatus(EApproveRechargeStatus.AGREE.getValue());
        css.setBusinessNo(code);
        css.setPkMember(selfModifyAddressVO.getPkMember());
        css.setOldValue(JSONObject.toJSONString(oldsma));
        css.setNewValue(JSONObject.toJSONString(newsma));
        css.setApproveNumber(selfModifyAddressVO.getApproveNumber());
        css.setEditType(EApprovalBusiness.SELF_MODIFY_ADDRESS.getValue());
        css.setEditTypePay(EApprovalBusiness.SELF_MODIFY_ADDRESS.getValue());
        css.setSingleAmount(selfModifyAddressVO.getSingleAmount());
        css.setOrderCode(selfModifyAddressVO.getOrderCode());
        css.setCreationTime(date);
        css.setPkCreator(userID);
        css.setSelfRemark(selfModifyAddressVO.getSelfRemark());
        baseMapper.insert(css);
        //修改订单相关信息
        SaOrder so = new SaOrder();
        so.setPkId(selfModifyAddressVO.getPkId());
        so.setPostage(selfModifyAddressVO.getNewPostage());
        so.setRecName(selfModifyAddressVO.getNewRecName());
        so.setRecPhone(selfModifyAddressVO.getNewRecPhone());
        so.setRecProvince(selfModifyAddressVO.getNewRecProvince());
        so.setRecCity(selfModifyAddressVO.getNewRecCity());
        so.setRecCounty(selfModifyAddressVO.getNewRecCounty());
        so.setRecAddress(selfModifyAddressVO.getNewRecAddress());
        if (null != selfModifyAddressVO.getPkStorehouse()) {
            so.setPkStorehouse(selfModifyAddressVO.getPkStorehouse());
        }
        //修改订单的收货地址
        iSaOrderServiceApi.updateOrder(so);
        return true;
    }


    @Override
    public Object[] selectSelfServiceByPkMember(DomicileChangeVO domicileChangeVO) {
        DomicileChangeVO domicileChange;
        List<DomicileChangeVO> domicileChangeVOList = new ArrayList<>();
        List<CuSelfServiceLogExt> cuSelfServiceLogs = baseMapper.selectSelfServiceByPkMember(domicileChangeVO);
        if (CollUtil.isNotEmpty(cuSelfServiceLogs)) {
            for (CuSelfServiceLogExt selfServiceLog : cuSelfServiceLogs) {
                domicileChange = chargeDomicileChangeVO(selfServiceLog);
                domicileChangeVOList.add(domicileChange);
            }
        }
        return new Object[]{cuSelfServiceLogs, domicileChangeVOList};
    }

    @Override
    public Integer showIndexDomicile(Integer pkCountry, Long pkMember) {
        LambdaQueryWrapper<CuSelfServiceLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuSelfServiceLog::getPkMember, pkMember);
        queryWrapper.eq(CuSelfServiceLog::getPkCountry, pkCountry);
        queryWrapper.eq(CuSelfServiceLog::getEditType, EApprovalBusiness.DOMICILE_CHANGE.getValue());
        queryWrapper.eq(CuSelfServiceLog::getApproveStatus, EApproveRechargeStatus.AGREE.getValue());
        Integer count = baseMapper.selectCount(queryWrapper);
        return count > 0 ? EYesNo.NO.getIntValue() : EYesNo.YES.getIntValue();
    }

    @Override
    public DomicileChangeVO selectDomicileChangeDetail(Long pkId) {
        CuSelfServiceLogExt cuSelfServiceLogExt = baseMapper.selectDomicileChangeDetail(pkId);
        return chargeDomicileChangeVO(cuSelfServiceLogExt);
    }

    @Override
    public DomicileChangeVO selectDomicileChangeByPkMember(Long pkMember, Integer editType, Integer pkCountry) {
        CuSelfServiceLogExt cuSelfServiceLogExt = baseMapper.selectDomicileChangeByPkMember(editType, pkMember, pkCountry);
        return chargeDomicileChangeVO(cuSelfServiceLogExt);
    }

    /**
     * 转化户籍VO
     *
     * @param selfServiceLog 自助信息
     * @return DomicileChangeVO
     */
    private DomicileChangeVO chargeDomicileChangeVO(CuSelfServiceLogExt selfServiceLog) {
        DomicileChangeVO oldValue = JSONUtil.toBean(selfServiceLog.getOldValue(), DomicileChangeVO.class);
        DomicileChangeVO newValue = JSONUtil.toBean(selfServiceLog.getNewValue(), DomicileChangeVO.class);
        return DomicileChangeVO.builder()
                .memberCode(selfServiceLog.getMemberCode()).pkId(selfServiceLog.getPkId()).businessNo(selfServiceLog.getBusinessNo())
                .memberName(oldValue.getMemberName()).phone(oldValue.getPhone()).idFront(oldValue.getIdFront()).pkMember(selfServiceLog.getPkMember())
                .idBack(oldValue.getIdBack()).changeMemberName(newValue.getChangeMemberName()).description(selfServiceLog.getDescription())
                .changePhone(newValue.getChangePhone()).changeIdBack(newValue.getChangeIdBack()).pkAccount(selfServiceLog.getPkAccount())
                .changeIdFront(newValue.getChangeIdFront()).amount(selfServiceLog.getSingleAmount())
                .creationTime(selfServiceLog.getCreationTime()).approveStatus(selfServiceLog.getApproveStatus())
                .rejectMsg(selfServiceLog.getRejectMsg())
                .approveTime(selfServiceLog.getApproveTime())
                .remark(selfServiceLog.getSelfRemark()).build();
    }

    /**
     * 更新姓名删除相关实名操作
     *
     * @param pkMember   会员ID
     * @param pkModified 更新人信息
     * @return Boolean
     */
    private void changeBusinessByChangeName(Long pkMember, Long pkModified) {
        List<Long> pkMembers = Collections.singletonList(pkMember);
        //更新实名认证
        Boolean auth = iCuMemberAuthenticationService.deleteByPkMembers(pkMembers, pkModified);
        //更新会员是否实名
        if (auth) {
            iCuMemberService.updateMemberStatusByPkIds(pkMembers, pkModified, EAuthType.REAL_NAME.getValue());
        }
        //更新营业执照
        Boolean license = iCuMemberBusinessLicenseService.updateMemberLicenseByPkMembers(pkMembers, pkModified);
        //更新会员是否营业执照
        if (license) {
            iCuMemberService.updateMemberStatusByPkIds(pkMembers, pkModified, EAuthType.BUS_LICENSE.getValue());
        }
    }

    @Override
    public List<MyOrderItemsVO> queryListByOrderId(List<Long> orderIdList) {
        return baseMapper.queryListByOrderId(orderIdList);
    }

    @Override
    public Integer showHiddenAddress(Long pkMember, Integer pkCountry) {
        Integer count = baseMapper.showHiddenAddressList(pkMember, pkCountry);
        if (count > 0) {
            return EYesNo.YES.getIntValue();
        } else {
            return EYesNo.NO.getIntValue();
        }
    }

}
