package com.cool.store.service.impl;

import com.cool.store.constants.CommonConstants;
import com.cool.store.constants.RedisConstant;
import com.cool.store.dao.PosAndOrderInfoDAO;
import com.cool.store.dao.ShopAccountDAO;
import com.cool.store.dao.ShopInfoDAO;
import com.cool.store.dao.ShopStageInfoDAO;
import com.cool.store.dao.fees.WalletPayInfoDAO;
import com.cool.store.dao.order.PreAllocationRecordDAO;
import com.cool.store.dto.BatchStatusRefreshDTO;
import com.cool.store.dto.StatusRefreshDTO;
import com.cool.store.entity.ShopAccountDO;
import com.cool.store.entity.ShopInfoDO;
import com.cool.store.entity.fees.WalletPayInfoDO;
import com.cool.store.entity.order.PreAllocationRecordDO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.OpenStatusEnum;
import com.cool.store.enums.PosAndOrderEnum;
import com.cool.store.enums.ShopAccountEnum;
import com.cool.store.enums.fees.WalletFeeItemEnum;
import com.cool.store.enums.point.ShopSubStageStatusEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.request.PostAndOrderRequest;
import com.cool.store.request.xgj.FranchiseFeeCallBackRequest;
import com.cool.store.request.xgj.ReceiptCallBackRequest;
import com.cool.store.response.bigdata.ApiResponse;
import com.cool.store.service.FranchiseFeeService;
import com.cool.store.service.LinePayService;
import com.cool.store.service.OpenApiService;
import com.cool.store.service.PosAndOrderInfoService;
import com.cool.store.utils.RedisUtilPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import static com.cool.store.enums.point.ShopSubStageStatusEnum.*;

/**
 * @Author suzhuhong
 * @Date 2025/4/7 16:54
 * @Version 1.0
 */

@Slf4j
@Service
public class OpenApiServiceImpl implements OpenApiService {

    @Resource
    ShopAccountDAO accountDAO;
    @Resource
    ShopInfoDAO shopInfoDAO;
    @Resource
    ShopStageInfoDAO shopStageInfoDAO;
    @Resource
    PosAndOrderInfoService posAndOrderInfoService;
    @Resource
    PosAndOrderInfoDAO posAndOrderInfoDAO;
    @Resource
    LinePayService linePayService;
    @Resource
    FranchiseFeeService franchiseFeeService;
    @Resource
    WalletPayInfoDAO walletPayInfoDAO;
    @Autowired
    private PreAllocationRecordDAO preAllocationRecordDAO;
    @Resource
    RedisUtilPool redisUtilPool;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean statusRefresh(StatusRefreshDTO statusRefreshDTO) {
        //如果是云流水
        String code = statusRefreshDTO.getShopCode();
        String ylsCode = "";
        if (ShopAccountEnum.YLS.getSystemName().equals(statusRefreshDTO.getSystemSource())){
            ylsCode = code;
            code = StringUtils.substringAfter(ylsCode, "_");
        }

        //查询门店编码
        ShopInfoDO shopInfoDO = shopInfoDAO.selectByStoreCode(code);
        if (Objects.isNull(shopInfoDO)){
            throw  new ServiceException(ErrorCodeEnum.SHOP_NOT_EXIST);
        }
        Integer openStatus = statusRefreshDTO.getOpenStatus()?OpenStatusEnum.OPENSTATUSENUM_5.getCode():OpenStatusEnum.OPENSTATUSENUM_6.getCode();
        accountDAO.updateStatusByShopIdAndSystemName(shopInfoDO.getId(), Arrays.asList(statusRefreshDTO.getSystemSource()), openStatus,null,ylsCode);

        //订货系统开通完成
        if (ShopAccountEnum.YLS.getSystemName().equals(statusRefreshDTO.getSystemSource())){
            ShopAccountDO shopAccountDO = accountDAO.selectByShopIdAndSystemName(shopInfoDO.getId(), ShopAccountEnum.YLS.getSystemName());
            if (Objects.isNull(shopAccountDO)){
                throw new ServiceException(ErrorCodeEnum.SYSTEM_DATA_ERROR);
            }
            PostAndOrderRequest postAndOrderRequest = new PostAndOrderRequest();
            postAndOrderRequest.setShopId(shopInfoDO.getId());
            postAndOrderRequest.setType(PosAndOrderEnum.ORDER.getCode());
            postAndOrderRequest.setRemark("已为您开通订货系统账号和密码，密码已加密，初始密码为身份证后6位，可通过加盟小程序修改密码！");
            postAndOrderRequest.setAccount(shopAccountDO.getAccount());
            postAndOrderRequest.setPassword(shopAccountDO.getPassword());
            posAndOrderInfoService.submitOrUpdate(postAndOrderRequest,null);
        }

        return Boolean.TRUE;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResponse<Boolean> changeReceiptStatus(ReceiptCallBackRequest request) {
        if (Objects.nonNull(request.getPayWay()) && CommonConstants.INDEX_TWO.equals(request.getPayWay())) {
            walletPayInfoDAO.updateClaimStatusByPayNo(request.getReceiptId(), request.getClaimStatus());
            PreAllocationRecordDO preAllocationRecordDO = preAllocationRecordDAO.queryPageByPayNo(request.getReceiptId());
            //认领完成 且是可乐机认领 完成状态
            if (request.getClaimStatus() == 1 && preAllocationRecordDO!=null&&WalletFeeItemEnum.DEVICE_EARNEST_MONEY.getExpenseType().equals(preAllocationRecordDO.getExpenseType())){
                String key = MessageFormat.format(RedisConstant.XGJ_CALLBACK_SHOP, preAllocationRecordDO.getShopId());
                if (StringUtils.isNotEmpty(redisUtilPool.getString(key))){
                    shopStageInfoDAO.batchUpdateShopStageStatus(preAllocationRecordDO.getShopId(),Arrays.asList(SHOP_SUB_STAGE_STATUS_284_7,SHOP_SUB_STAGE_STATUS_80));
                }
            }
            return ApiResponse.success(Boolean.TRUE);
        } else {
            return linePayService.ReceiptCallBack(request);
        }
    }

    @Override
    public ApiResponse<Boolean> changePaymentStatus(FranchiseFeeCallBackRequest request) {
        return franchiseFeeService.changePaymentStatus(request);
    }
}
