package cn.hanghui.outapi.platform.tenant.service.impl;

import cn.hanghui.outapi.platform.common.entity.rest.RestResult;
import cn.hanghui.outapi.platform.common.utils.AppUtils;
import cn.hanghui.outapi.platform.common.utils.Preconditions;
import cn.hanghui.outapi.platform.tenant.entity.dto.auth.OpenInterfaceAuthDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.auth.OpenInterfaceAuthPageDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.auth.OpenInterfaceAuthVo;
import cn.hanghui.outapi.platform.tenant.entity.enums.InterfaceTypeEnum;
import cn.hanghui.outapi.platform.tenant.entity.po.OpenInterfaceAuth;
import cn.hanghui.outapi.platform.tenant.entity.po.Purchaser;
import cn.hanghui.outapi.platform.tenant.mapper.OpenInterfaceAuthMapper;
import cn.hanghui.outapi.platform.tenant.mapper.PurchaserMapper;
import cn.hanghui.outapi.platform.tenant.service.OpenInterfaceAuthService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author shisl
 * @package cn.hanghui.outapi.platform.tenant.service.impl
 * @class OpenInterfaceAuthServiceImpl
 * @date 2024/1/17 下午1:26
 * @description
 */
@Service
@Slf4j
public class OpenInterfaceAuthServiceImpl implements OpenInterfaceAuthService {

    @Resource
    private OpenInterfaceAuthMapper openInterfaceAuthMapper;

    @Resource
    private PurchaserMapper purchaserMapper;


    @Override
    public RestResult<Boolean> add(OpenInterfaceAuthDto dto) {
        //校验购买方是否存在
        OpenInterfaceAuth purchaserAuth = openInterfaceAuthMapper.selectOne(Wrappers.lambdaQuery(OpenInterfaceAuth.class).eq(OpenInterfaceAuth::getPurchaserId, dto.getPurchaserId()).eq(OpenInterfaceAuth::getInterfaceType, dto.getInterfaceType()));
        Purchaser purchaser = purchaserMapper.selectById(dto.getPurchaserId());
        if (Preconditions.isBlank(purchaser)) {
            return RestResult.error("购买方数据不存在或已删除");
        }

        OpenInterfaceAuth auth = null;
        if (Preconditions.isNotBlank(dto.getId())) {
            auth = openInterfaceAuthMapper.selectById(dto.getId());
            if (Preconditions.isBlank(auth)) {
                return RestResult.error("数据不存在或已删除");
            }
            if (Preconditions.isNotBlank(purchaserAuth) && purchaserAuth.getId().longValue() != dto.getId().longValue()) {
                return RestResult.error("接口已授权，勿重复授权");
            }
        } else {
            //校验购买方是否存在
            if (Preconditions.isNotBlank(purchaserAuth)) {
                return RestResult.error("接口已授权，勿重复授权");
            }
            auth = new OpenInterfaceAuth();
            completeAddAuth(auth, purchaser);
        }
        auth.setPurchaserId(dto.getPurchaserId());
        auth.setResultInfoSwitch(dto.getResultInfoSwitch());
        auth.setInterfaceType(dto.getInterfaceType());
        auth.setLimitFrequency(dto.getLimitFrequency());
        auth.setLimitFrequencyTime(dto.getLimitFrequencyTime());
        auth.setLimitTimes(dto.getLimitTimes());
        auth.setDescription(purchaser.getCompanyName());
        auth.setUpdateTime(new Date());
        auth.setExtendParams(dto.getExtendParams());
        if (Preconditions.isNotBlank(dto.getId())) {
            openInterfaceAuthMapper.updateById(auth);
        } else {
            openInterfaceAuthMapper.insert(auth);
        }
        return RestResult.ok(Boolean.TRUE);
    }

    private void completeAddAuth(OpenInterfaceAuth auth, Purchaser purchaser) {
        auth.setCreateTime(new Date());
        auth.setIsDeleted(Boolean.FALSE);
        auth.setStatus(Boolean.TRUE);
        auth.setHadReqTimes(0);
        //TODO。。。创建授权参数
        String appKey = AppUtils.getAppKey();
        String appSecret = AppUtils.getAppSecret(appKey);
        String privateKey = AppUtils.getPrivateKey();
        String appId = DigestUtil.md5Hex(purchaser.getCompanyName() + appKey);
        auth.setAppId(appId);
        auth.setAppKey(appKey);
        auth.setAppSecret(appSecret);
        auth.setPrivateKey(privateKey);
    }

    @Override
    public RestResult<Boolean> del(Long id) {
        OpenInterfaceAuth auth = openInterfaceAuthMapper.selectById(id);
        if (Preconditions.isBlank(auth)) {
            return RestResult.error("数据不存在或已删除");
        }
        openInterfaceAuthMapper.deleteById(auth);
        return RestResult.ok(Boolean.TRUE);
    }

    @Override
    public RestResult<Boolean> updateStatus(Long id, Boolean status) {
        OpenInterfaceAuth auth = openInterfaceAuthMapper.selectById(id);
        if (Preconditions.isBlank(auth)) {
            return RestResult.error("数据不存在或已删除");
        }
        auth.setStatus(status);
        openInterfaceAuthMapper.updateById(auth);
        return RestResult.ok(Boolean.TRUE);
    }

    @Override
    public RestResult<IPage<OpenInterfaceAuthVo>> page(OpenInterfaceAuthPageDto dto) {

        Page<OpenInterfaceAuth> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        LambdaQueryWrapper<OpenInterfaceAuth> wrapper = new LambdaQueryWrapper<>();
        if (Preconditions.isNotBlank(dto.getPurchaserId())) {
            wrapper.eq(OpenInterfaceAuth::getPurchaserId, dto.getPurchaserId());
        }
        wrapper.orderByDesc(OpenInterfaceAuth::getId);
        IPage<OpenInterfaceAuth> iPage = openInterfaceAuthMapper.selectPage(page, wrapper);
        IPage<OpenInterfaceAuthVo> convert = iPage.convert(t -> {
            OpenInterfaceAuthVo item = BeanUtil.copyProperties(t, OpenInterfaceAuthVo.class);
            item.setInterfaceTypeDesc(InterfaceTypeEnum.findByCode(t.getInterfaceType()).getDesc());
            return item;
        });
        complete(convert);
        return RestResult.ok(convert);
    }

    private void complete(IPage<OpenInterfaceAuthVo> convert) {
        List<OpenInterfaceAuthVo> records = convert.getRecords();
        if (Preconditions.isNotBlank(records)) {
            List<Long> purchaserIds = records.stream().map(OpenInterfaceAuthVo::getPurchaserId).collect(Collectors.toList());
            List<Purchaser> purchasers = purchaserMapper.selectList(Wrappers.lambdaQuery(Purchaser.class).in(Purchaser::getId, purchaserIds));
            Map<Long, Purchaser> purchaserMap = purchasers.stream().collect(Collectors.toMap(Purchaser::getId, a -> a, (k1, k2) -> k1));
            records.stream().forEach(item -> {
                Purchaser purchaser = purchaserMap.get(item.getPurchaserId());
                item.setPurchaserName(Preconditions.isNotBlank(purchaser) ? purchaser.getCompanyName() : null);
            });
        }
        convert.setRecords(records);
    }


}
