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

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.exception.base.BaseException;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.RandomNumberGenerator;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.member.detail.CuMemberServiceLog;
import com.hzs.common.domain.member.store.CuStore;
import com.hzs.common.domain.member.store.ext.CuStoreExt;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.detail.service.ICuMemberServiceLogService;
import com.hzs.member.store.mapper.CuStoreMapper;
import com.hzs.member.store.param.StoreQueryParam;
import com.hzs.member.store.service.ICuStoreService;
import com.hzs.member.store.vo.CuStoreVO;
import com.hzs.sale.order.ISaOrderServiceApi;
import com.hzs.system.base.ICountryServiceApi;
import com.hzs.system.base.dto.CountryDTO;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.sys.IApprovalServiceApi;
import com.hzs.system.sys.dto.ApprovalBusinessResultDTO;
import com.hzs.system.sys.dto.ApprovalSubmitDTO;
import com.hzs.system.sys.dto.LoginUser;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 店铺设置 服务实现类
 *
 * @author hzs
 * @since 2023-05-04
 */
@Service
public class CuStoreServiceImpl extends ServiceImpl<CuStoreMapper, CuStore> implements ICuStoreService {

    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private ICuMemberServiceLogService memberServiceLogService;
    @DubboReference
    private IApprovalServiceApi approvalServiceApi;

    @DubboReference
    private ICountryServiceApi iCountryServiceApi;
    @DubboReference
    private ISaOrderServiceApi iSaOrderServiceApi;

    /**
     * @description: 查询店铺列表
     * @author: zhang jing
     * @date: 2023/5/4 17:56
     * @param: [storeVO]
     * @return: java.util.List<com.hzs.member.store.vo.CuStoreVO>
     **/
    @Override
    public List<CuStoreVO> queryStoreList(CuStoreVO storeVO) {
        return baseMapper.queryStoreList(storeVO);
    }

    /**
     * @description: 校验店铺订单
     * @author: zhang jing
     * @date: 2023/10/31 17:23
     * @param: [storeVO]
     * @return: java.util.List<com.hzs.member.store.vo.CuStoreVO>
     **/
    @Override
    public CuStoreVO checkOrder(CuStoreVO storeVO) {
        return baseMapper.checkOrder(storeVO);
    }

    /**
     * @description: 查询最新店铺编号
     * @author: zhang jing
     * @date: 2024/1/2 14:07
     * @param: []
     * @return: java.util.List<com.hzs.common.domain.member.store.CuStore>
     **/
    @Override
    public List<CuStore> selectMaxList(Integer pkCountry) {
        return baseMapper.selectMaxList(pkCountry);
    }

    /**
     * @description: 店铺配置发起签呈
     * @author: zhang jing
     * @date: 2024/4/3 11:35
     * @param: [custoreVO]
     * @return: boolean
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean petition(CuStoreVO custoreVO) {
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.HANDLE_BUSINESS.getValue());
        LoginUser loginUser = userTokenService.getLoginUser();
        // 修改审核状态添加日志记录
        CuMemberServiceLog memberLog = new CuMemberServiceLog();
        memberLog.setPkMember(custoreVO.getPkMember());
        memberLog.setPkCreator(custoreVO.getPkCreator());
        memberLog.setCreationTime(custoreVO.getCreationTime());
        memberLog.setPkCountry(custoreVO.getPkCountry());
        memberLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
        memberLog.setBusinessNo(code);
        memberLog.setEditType(EControlType.getStoreBusiness(custoreVO.getControlType()).getValue());
        memberLog.setEditTypePay(EControlType.getStoreBusiness(custoreVO.getControlType()).getValue());
        memberLog.setNewValue(JSONObject.toJSONString(custoreVO));
        memberLog.setProcessType(EProcessType.AVOIDPAY.getValue());
        memberServiceLogService.save(memberLog);
        //生成签呈
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EControlType.getStoreBusiness(custoreVO.getControlType()))
                .businessCode(code)
                .signType(ESignType.getEnumByValue(custoreVO.getSignType()))
                .remark(custoreVO.getRemark())
                .userIdList(custoreVO.getUserIdList())
                .sendIdList(custoreVO.getSendIdList())
                .fileList(custoreVO.getFileList())
                .build();
        R<String> submit = approvalServiceApi.submit(approvalSubmitDTO, loginUser);
        if (!submit.isSuccess()) {
            log.error("====" + submit.getData());
            throw new RuntimeException(TransactionUtils.getContent(ConfigMsgConstants.CU_STORE_PETITION));
        }
        return true;
    }

    /**
     * @description: 店铺配置签呈审核通过驳回
     * @author: zhang jing
     * @date: 2024/4/3 14:48
     * @param: [approvalBusinessResultDTO]
     * @return: boolean
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean cuStoreByBusinessNo(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
//        CuStoreVO cuStoreVO = new CuStoreVO();
        Integer pkCountry = approvalBusinessResultDTO.getLoginUser().getDataCountry();
        QueryWrapper<CuMemberServiceLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("BUSINESS_NO", approvalBusinessResultDTO.getBusinessCode());
        queryWrapper.eq("APPROVE_STATUS", EApproveStatus.ALREADY_SUBMIT.getValue());
        List<CuMemberServiceLog> memberServiceLogList = memberServiceLogService.list(queryWrapper);
        Date date = new Date();
        Long userID = approvalBusinessResultDTO.getLoginUser().getUserId();
        R<CountryDTO> country = iCountryServiceApi.getCountry(pkCountry);
        if (CollectionUtil.isNotEmpty(memberServiceLogList)) {
            for (CuMemberServiceLog cs : memberServiceLogList) {
                //审核通过 修改审核状态,累加修改次数
                cs.setPkModified(userID);
                cs.setModifiedTime(date);
                cs.setApproveStatus(approvalBusinessResultDTO.getEApproveStatus().getValue());
                memberServiceLogService.updateById(cs);
                if (approvalBusinessResultDTO.getEApproveStatus().getValue() == EApproveStatus.FINISH.getValue()) {
                    if (approvalBusinessResultDTO.getEApprovalBusiness().getValue() == EApprovalBusiness.CU_STORE_SAVE.getValue()) {
                        //新增店铺配置
                        List<CuStore> cuStoreCode = selectMaxList(pkCountry);
                        String code = "";
                        //根据当前国家获取编号头
                        if (CollectionUtil.isNotEmpty(cuStoreCode)) {
                            code = RandomNumberGenerator.getNextStoreCode(cuStoreCode.get(0).getStoreCode(), country.getData().getCode().length());
                        } else {
                            code = RandomNumberGenerator.getNextStoreCode(country.getData().getCode() + "0001", country.getData().getCode().length());
                        }
                        CuStore cuStore = JSONObject.parseObject(cs.getNewValue(), CuStore.class);
                        cuStore.setStoreCode(code);
                        cuStore.setPkMember(cs.getPkMember());
                        cuStore.setPkCountry(pkCountry);
                        cuStore.setPkCreator(userID);
                        cuStore.setCreationTime(date);
                        baseMapper.insert(cuStore);
                    }
                    if (approvalBusinessResultDTO.getEApprovalBusiness().getValue() == EApprovalBusiness.CU_STORE_MODIFY.getValue()) {
                        //修改店铺配置
                        CuStore cuStore = JSONObject.parseObject(cs.getNewValue(), CuStore.class);
                        cuStore.setPkMember(cs.getPkMember());
                        cuStore.setPkModified(userID);
                        cuStore.setModifiedTime(date);
                        CuStoreVO custoreVO=JSONObject.parseObject(cs.getNewValue(), CuStoreVO.class);
                        CuStoreVO storeLevel = queryStoreLevelById(custoreVO);
                        if(storeLevel.getLevelValue() == ELevelValue.GOLD_DRILL.getValue()){
                            cuStore.setBindingProvince(null);
                        }else{
                            cuStore.setBindingCountry(null);
                        }
                        baseMapper.updateStore(cuStore);
                    }
                    if (approvalBusinessResultDTO.getEApprovalBusiness().getValue() == EApprovalBusiness.CU_STORE_DELETE.getValue()) {
                        //删除店铺配置
                        CuStore cuStore = JSONObject.parseObject(cs.getNewValue(), CuStore.class);
                        UpdateWrapper<CuStore> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
                        updateWrapper.set("MODIFIED_TIME", date);
                        updateWrapper.set("PK_MODIFIED", userID);
                        updateWrapper.eq("PK_ID", cuStore.getPkId());
                        baseMapper.update(null, updateWrapper);
                    }
                }
            }

        }
        return true;
    }

    @Override
    public List<CuStoreExt> queryAllMemberStore() {
        return baseMapper.queryAllMemberStore();
    }


    /**
     * @description: 添加店铺
     * @author: zhang jing
     * @date: 2023/10/12 11:36
     * @param: [store, currency]
     * @return: boolean
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveStore(CuStore store, R<CurrencyDTO> currency, CuMember member) {
        baseMapper.insert(store);
        if (store.getAchieve() != null && store.getAchieve().compareTo(BigDecimal.ZERO) > 0 &&
                store.getAmount() != null && store.getAmount().compareTo(BigDecimal.ZERO) > 0) {
            // 入库订单列表
            SaOrder so = new SaOrder();
            // 生成订单编号
            String orderCode = CommonUtil.createSerialNumber(EOrderPrefix.ORDER_CODE);
            so.setOrderCode(orderCode);
            so.setPayTime(store.getCreationTime());
            so.setCreationTime(store.getCreationTime());
            so.setOrderStatus(EOrderStatus.PAY.getValue());
            so.setPkCountry(store.getPkCountry());
            so.setOrderType(EOrderType.FICTITIOUS_ORDER.getValue());
            so.setPkRate(currency.getData().getPkId());
            so.setOrderAmount(store.getAmount());
            so.setOrderAchieve(store.getAchieve());
            so.setPkMember(store.getPkMember());
            so.setPkCreator(store.getPkMember());
            so.setPkMemberStore(store.getPkId());
            so.setPayType(EOrderPayType.OFFLINE.getValue());
            so.setTranType(ETransportType.LAND.getValue());
            so.setPkReference(member.getPkParent());
            so.setDeliveryWay(EDelivery.SHOP_PICKED_UP.getValue());
            so.setRecName(member.getMemberName());
            so.setRecPhone(member.getPhone());
            List<SaOrder> saveOrderList = new ArrayList<>();
            saveOrderList.add(so);
            R orderResult = iSaOrderServiceApi.insertUnrealOrderBach(saveOrderList);
            if (!orderResult.isSuccess()) {
                throw new BaseException("店铺配置生成订单异常");
            }

        }
        return true;
    }

    /**
     * @description:
     * @author: zhang jing
     * @date: 2023/10/31 15:33
     * @param: [pkId]
     * @return: boolean
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDelete(String pkId) {
        List<Integer> pkIdList = Arrays.stream(pkId.split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        for (Integer id : pkIdList) {
            UpdateWrapper<CuStore> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("PK_ID", id);
            updateWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
            updateWrapper.set("PK_MODIFIED", SecurityUtils.getUserId());
            updateWrapper.set("MODIFIED_TIME", new Date());
            baseMapper.update(null, updateWrapper);
        }
        return true;
    }

    @Override
    public List<CuStoreExt> queryStoreApiList(StoreQueryParam param) {
        return baseMapper.queryStoreApiList(param);
    }

    /**
     * @description: 查询店铺等级值
     * @author: zhang jing
     * @date: 2024/4/9 11:50
     * @param: [param]
     * @return: java.lang.Integer
     **/
    @Override
    public CuStoreVO queryStoreLevelById(CuStoreVO param) {
        return baseMapper.queryStoreLevelById(param);
    }

    /**
     * @description: 修改店铺信息
     * @author: zhang jing
     * @date: 2024/7/4 14:05
     * @param: [cuStore]
     * @return: int
     **/
    @Override
    public int updateStore(CuStore cuStore) {
        return baseMapper.updateStore(cuStore);
    }


}
