package com.yc.ship.module.otc.service.storeaudit;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.ship.framework.common.enums.CommonStatusEnum;
import com.yc.ship.framework.common.lang.Asserts;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.framework.tenant.core.aop.TenantIgnore;
import com.yc.ship.framework.tenant.core.context.TenantContextHolder;
import com.yc.ship.module.ota.api.OtaDistributorApi;
import com.yc.ship.module.ota.api.dto.DistributorRespDTO;
import com.yc.ship.module.otc.controller.admin.storeaudit.vo.StoreAuditPageReqVO;
import com.yc.ship.module.otc.controller.admin.storeaudit.vo.StoreAuditRespVO;
import com.yc.ship.module.otc.controller.admin.storeaudit.vo.StoreAuditSaveReqVO;
import com.yc.ship.module.otc.dal.dataobject.store.StoreDO;
import com.yc.ship.module.otc.dal.dataobject.storeaudit.StoreAuditDO;
import com.yc.ship.module.otc.dal.dataobject.storecard.StoreCardDO;
import com.yc.ship.module.otc.dal.mysql.storeaudit.StoreAuditMapper;
import com.yc.ship.module.otc.enums.TradeModeEnum;
import com.yc.ship.module.otc.enums.UseStatusEnum;
import com.yc.ship.module.otc.service.store.StoreService;
import com.yc.ship.module.otc.service.storecard.StoreCardService;
import com.yc.ship.module.system.api.user.AdminUserApi;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;

import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yc.ship.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static com.yc.ship.module.otc.enums.ErrorCodeConstants.*;

/**
 * 旅行社门店授信提额/授信充值/余额充值 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class StoreAuditServiceImpl implements StoreAuditService {

    @Resource
    private AdminUserApi userApi;

    @Resource
    private StoreAuditMapper storeAuditMapper;

    @Resource
    private StoreService storeService;

    @Resource
    private StoreCardService storeCardService;

    @Resource
    private OtaDistributorApi otaDistributorApi;

    @Override
    public Long createStoreAudit(StoreAuditSaveReqVO createReqVO) {

        long loginUserId = getLoginUserId();
        DistributorRespDTO distributor = otaDistributorApi.getDistributorByLoginUserId(loginUserId);
        if(distributor == null) {
            throw exception(NOT_ASSOCIATED_DISTRIBUTOR);
        }
        String userName = userApi.getUser(loginUserId).getNickname();
        createReqVO.setDistributorId(distributor.getId());
        // 插入
        StoreAuditDO storeAudit = BeanUtils.toBean(createReqVO, StoreAuditDO.class);
        StoreDO store = storeService.getStore(storeAudit.getStoreId());
        StoreCardDO storeCardDO = storeCardService.getStoreCardByStoreId(store.getId());
        storeAudit.setPlatTenantId(distributor.getTenantId());

        if(ObjectUtil.equal(storeAudit.getOperateType(),1)){
            Asserts.isTrue(ObjectUtil.notEqual(storeCardDO.getBalanceType(), CommonStatusEnum.ENABLE.getStatus()),"当前门店禁止使用预付款");
        }else if(ObjectUtil.equal(storeAudit.getOperateType(),3)){
            Asserts.isTrue(ObjectUtil.notEqual(storeCardDO.getCreditType(), CommonStatusEnum.ENABLE.getStatus()),"当前门店禁止使用授信");
        }
        LocalDateTime now = LocalDateTime.now();
        storeAudit.setId(IdWorker.getId(storeAudit));
        storeAudit.setStatus(0);
//        storeAudit.setOperateType(3);
        storeAudit.setApplyTime(now);

        storeAudit.setApplyUser(loginUserId);
        storeAudit.setApplyUserName(userName);
        storeAuditMapper.insert(storeAudit);
        // 返回
        return storeAudit.getId();
    }

    @Override
    public Long updateStoreAudit(StoreAuditSaveReqVO updateReqVO) {
        long loginUserId = getLoginUserId();
        Long tenantId = TenantContextHolder.getTenantId();
        String userName = userApi.getUser(loginUserId).getNickname();
        // 校验存在
//        validateStoreAuditExists(updateReqVO.getId());
        StoreAuditDO storeAudit = storeAuditMapper.selectById(updateReqVO.getId());

        StoreAuditDO updateObj = BeanUtils.toBean(updateReqVO, StoreAuditDO.class);
        LocalDateTime now = LocalDateTime.now();
        updateObj.setAuditUser(loginUserId);
        updateObj.setAuditUserName(userName);
        updateObj.setAuditTime(now);

        if(updateReqVO.getStatus() == 1){
            StoreDO store = storeService.getStore(storeAudit.getStoreId());
            StoreCardDO storeCardDO = storeCardService.getStoreCardByStoreId(store.getId());
            if(ObjectUtil.equal(storeAudit.getOperateType(),1)){
                if(ObjectUtil.notEqual(storeCardDO.getBalanceType(), UseStatusEnum.ENABLE.getStatus())) {
                    throw exception(STORE_DISABLED_BALANCE);
                }
            }else if(ObjectUtil.equal(storeAudit.getOperateType(),3)){
                if(ObjectUtil.notEqual(storeCardDO.getCreditType(), UseStatusEnum.ENABLE.getStatus())) {
                    throw exception(STORE_DISABLED_CREDIT);
                }
            }
            //审核通过处理
            // 1.余额，2.授信充正，3.授信提额
            int operateType = updateReqVO.getOperateType();
            int type = operateType == 1 ? 1 : operateType == 2 ? 2 : 99;
            TradeModeEnum tradeModeEnum = TradeModeEnum.valueOf(operateType, type, updateReqVO.getOperateMode());
            //现在没有授信充值了 2025-12-23，授信还款只能根据账单
            Long logId;
            if(tradeModeEnum == TradeModeEnum.BALANCE_ADMIN_RECHARGE_1 || tradeModeEnum == TradeModeEnum.BALANCE_ADMIN_RECHARGE_2
                    || tradeModeEnum == TradeModeEnum.QUOTA_1 || tradeModeEnum == TradeModeEnum.QUOTA_2){
                int rechargeDistributeType = storeAudit.getRechargeDistributeType() ==null?0: storeAudit.getRechargeDistributeType();
                if(rechargeDistributeType == 1){

                    logId = storeService.updateStoreCardWithPlat(storeCardDO,storeAudit,tradeModeEnum, loginUserId);
                }else{
                    //只能平台账号才能充值
                    Asserts.isTrue(ObjectUtil.equals(tenantId,storeAudit.getPlatTenantId()),"只能平台用户才能进行充值");
                    //直接门店充值
                    logId = storeService.updateStoreCard(storeAudit.getStoreId(), tradeModeEnum, storeAudit.getAmount(), loginUserId, storeAudit.getId(), null, null);
                }
            }else {
                logId = storeService.updateStoreCard(storeAudit.getStoreId(), tradeModeEnum, storeAudit.getAmount(), loginUserId, null, null, null);
            }
            updateObj.setRechargeLogId(logId);
        }

        // 更新
        storeAuditMapper.updateById(updateObj);
        return updateObj.getRechargeLogId();
    }

    @Override
    @TenantIgnore
    public void deleteStoreAudit(Long id) {
        // 校验存在
        validateStoreAuditExists(id);
        // 删除
        storeAuditMapper.deleteById(id);
    }

    private void validateStoreAuditExists(Long id) {
        if (storeAuditMapper.selectById(id) == null) {
            throw exception(STORE_AUDIT_NOT_EXISTS);
        }
    }

    @Override
    @TenantIgnore
    public StoreAuditDO getStoreAudit(Long id) {
        return storeAuditMapper.selectById(id);
    }

    @Override
    public PageResult<StoreAuditDO> getStoreAuditPage(StoreAuditPageReqVO pageReqVO) {
        return storeAuditMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<StoreAuditRespVO> getPlatStoreAuditPage(StoreAuditPageReqVO pageReqVO) {
        Asserts.isTrue(pageReqVO.getPlatTenantId()!=null,"平台租户ID不能为空");
        IPage<StoreAuditRespVO> page = new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        IPage<StoreAuditRespVO> result =  storeAuditMapper.selectStoreAuditByPage(page,pageReqVO);
        return new PageResult<>(result.getRecords(), result.getTotal());
    }

}
