package com.liquidnet.client.admin.zhengzai.merchant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.client.admin.zhengzai.merchant.service.IMerchantAuthorizationPermissionsAdminService;
import com.liquidnet.client.admin.zhengzai.merchant.service.IMerchantAuthorizationRecordsAdminService;
import com.liquidnet.client.admin.zhengzai.merchant.utils.MerchantMongoUtil;
import com.liquidnet.client.admin.zhengzai.merchant.utils.MerchantRedisUtil;
import com.liquidnet.common.exception.LiquidnetServiceException;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.merchant.constant.MerchantPermissionConst;
import com.liquidnet.service.merchant.dto.vo.MerchantFieldCheckersVo;
import com.liquidnet.service.merchant.dto.vo.MerchantFieldsVo;
import com.liquidnet.service.merchant.dto.vo.MerchantSponsorsVo;
import com.liquidnet.service.merchant.entity.MerchantAuthorizationPermissions;
import com.liquidnet.service.merchant.entity.MerchantAuthorizationRecords;
import com.liquidnet.service.merchant.mapper.MerchantAuthorizationRecordsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class MerchantAuthorizationRecordsAdminServiceImpl extends ServiceImpl<MerchantAuthorizationRecordsMapper, MerchantAuthorizationRecords> implements IMerchantAuthorizationRecordsAdminService {

    @Autowired
    MerchantRedisUtil merchantRedisUtil;

    @Autowired
    MerchantMongoUtil merchantMongoUtil;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    IMerchantAuthorizationPermissionsAdminService authorizationPermissionsAdminService;

    @Override
    public void authorizationInit(String performanceId, String cuid, String fieldId, String sponsorId) {
        // 创建者


        // 场地方
        MerchantFieldsVo fieldsVo = merchantRedisUtil.getFieldsVoByFieldId(fieldId);
        // 主办方
        MerchantSponsorsVo sponsorsVo = merchantRedisUtil.getSponsorsVoBySponsorId(sponsorId);

    }

    private void performanceCreator(String performanceId, String cuid,  String uid) {
        // 查询已有权限
        LambdaQueryWrapper<MerchantAuthorizationRecords> authorizationRecordsLambdaQueryWrapper = Wrappers.lambdaQuery(MerchantAuthorizationRecords.class);
        authorizationRecordsLambdaQueryWrapper.eq(MerchantAuthorizationRecords::getPerformanceId, performanceId);
        authorizationRecordsLambdaQueryWrapper.eq(MerchantAuthorizationRecords::getUidRole, "creator");
        authorizationRecordsLambdaQueryWrapper.eq(MerchantAuthorizationRecords::getDeletedAt, null);
        MerchantAuthorizationRecords authorizationRecords = getOne(authorizationRecordsLambdaQueryWrapper);

        if (null != authorizationRecords) {

        }


    }

    // 授权场地方
    private boolean performanceFielder(String performanceId, String cuid,  String fieldId) {
        LocalDateTime now = LocalDateTime.now();

        // 查询已有权限
        LambdaQueryWrapper<MerchantAuthorizationRecords> authorizationRecordsLambdaQueryWrapper = Wrappers.lambdaQuery(MerchantAuthorizationRecords.class);
        authorizationRecordsLambdaQueryWrapper.eq(MerchantAuthorizationRecords::getPerformanceId, performanceId);
        authorizationRecordsLambdaQueryWrapper.eq(MerchantAuthorizationRecords::getUidRole, "fielder");
        authorizationRecordsLambdaQueryWrapper.eq(MerchantAuthorizationRecords::getDeletedAt, null);
        MerchantAuthorizationRecords authorizationRecords = getOne(authorizationRecordsLambdaQueryWrapper);

        // 查询场地方
        MerchantFieldsVo fieldsVo = merchantRedisUtil.getFieldsVoByFieldId(fieldId);

        // 是否已存在权限
        if (null != authorizationRecords) {
            // 已存在权限

            if (authorizationRecords.getUid().equals(fieldsVo.getUid())) {
                // 前后 场地方一致 不处理
                return true;
            }

            // 前后 场地方不一致 删除旧权限 及 我的授权
            authorizationRecords.setUpdatedAt(now);
            authorizationRecords.setDeletedAt(now);

            LambdaUpdateWrapper<MerchantAuthorizationRecords> authorizationRecordsLambdaUpdateWrapper = Wrappers.lambdaUpdate(MerchantAuthorizationRecords.class);
            authorizationRecordsLambdaUpdateWrapper
                    .eq(MerchantAuthorizationRecords::getPerformanceId, performanceId)
                    .eq(MerchantAuthorizationRecords::getDeletedAt, null);
            authorizationRecordsLambdaUpdateWrapper.and(wrapper -> wrapper
                    .eq(MerchantAuthorizationRecords::getAuthorizationRecordId, authorizationRecords.getAuthorizationRecordId())
                    .or(wrapper1 -> wrapper1
                            .eq(MerchantAuthorizationRecords::getCuid, authorizationRecords.getUid())
                            .eq(MerchantAuthorizationRecords::getCuidRole, "fielder"))
            );
            authorizationRecordsLambdaUpdateWrapper.set(MerchantAuthorizationRecords::getUpdatedAt, authorizationRecords.getUpdatedAt());
            authorizationRecordsLambdaUpdateWrapper.set(MerchantAuthorizationRecords::getDeletedAt, authorizationRecords.getDeletedAt());
            boolean success = update(authorizationRecordsLambdaUpdateWrapper);
            if (!success) {
                // todo error
                throw new LiquidnetServiceException();
            }
        }

        // 是否添加权限
        if (1 == fieldsVo.getClaimStatus()) {
            ArrayList<MerchantAuthorizationRecords> authorizationRecordsArrayList = new ArrayList<>();
            ArrayList<MerchantAuthorizationPermissions> authorizationPermissionsArrayList = new ArrayList<>();

            // 授权记录
            // todo 用户信息
            MerchantAuthorizationRecords fielderAuthorizationRecords = new MerchantAuthorizationRecords();
            fielderAuthorizationRecords.setAuthorizationRecordId(IDGenerator.nextSnowId());
            fielderAuthorizationRecords.setPerformanceId(performanceId);
            fielderAuthorizationRecords.setUidRole("fielder");
            fielderAuthorizationRecords.setUid(fieldsVo.getUid());
            fielderAuthorizationRecords.setMobile("");
            fielderAuthorizationRecords.setName("");
            fielderAuthorizationRecords.setCuid(cuid);
            fielderAuthorizationRecords.setCuidRole("creator");
            fielderAuthorizationRecords.setCreatedAt(now);
            authorizationRecordsArrayList.add(fielderAuthorizationRecords);
            // 授权权限
            String[] fielderPermissionIds = {
                    MerchantPermissionConst.PerformancePermission.READ.getId(),
                    MerchantPermissionConst.PerformancePermission.CHECK.getId(),
                    MerchantPermissionConst.PerformancePermission.ACCREDIT.getId()
            };
            for (String permissionId : fielderPermissionIds) {
                MerchantAuthorizationPermissions fielderAuthorizationPermissions = new MerchantAuthorizationPermissions();
                fielderAuthorizationPermissions.setAuthorizationPermissionId(IDGenerator.nextSnowId());
                fielderAuthorizationPermissions.setAuthorizationRecordId(fielderAuthorizationRecords.getAuthorizationRecordId());
                fielderAuthorizationPermissions.setPermissionId(permissionId);
                fielderAuthorizationPermissions.setStartTime(now);
                fielderAuthorizationPermissions.setEndTime(now.plusYears(99));
                fielderAuthorizationPermissions.setCreatedAt(now);
                authorizationPermissionsArrayList.add(fielderAuthorizationPermissions);
            }

            // 查询默认验票员
            List<MerchantFieldCheckersVo> fieldCheckersVos = merchantRedisUtil.getFieldCheckersVosByFieldId(fieldId);
            if (!CollectionUtil.isEmpty(fieldCheckersVos)) {
                // 授权权限
                String[] checkerPermissionIds = {
                        MerchantPermissionConst.PerformancePermission.CHECK.getId()
                };

                for (MerchantFieldCheckersVo fieldCheckersVo: fieldCheckersVos) {
                    // 授权记录
                    MerchantAuthorizationRecords checkerAuthorizationRecords = new MerchantAuthorizationRecords();
                    checkerAuthorizationRecords.setAuthorizationRecordId(IDGenerator.nextSnowId());
                    checkerAuthorizationRecords.setPerformanceId(performanceId);
                    checkerAuthorizationRecords.setUidRole("checker");
                    checkerAuthorizationRecords.setUid(fieldCheckersVo.getUid());
                    checkerAuthorizationRecords.setMobile(fieldCheckersVo.getMobile());
                    checkerAuthorizationRecords.setName(fieldCheckersVo.getName());
                    checkerAuthorizationRecords.setCuid(fieldsVo.getUid());
                    checkerAuthorizationRecords.setCuidRole("fielder");
                    checkerAuthorizationRecords.setCreatedAt(now);
                    authorizationRecordsArrayList.add(checkerAuthorizationRecords);

                    // 授权权限
                    for (String permissionId : checkerPermissionIds) {
                        MerchantAuthorizationPermissions checkerAuthorizationPermissions = new MerchantAuthorizationPermissions();
                        checkerAuthorizationPermissions.setAuthorizationPermissionId(IDGenerator.nextSnowId());
                        checkerAuthorizationPermissions.setAuthorizationRecordId(checkerAuthorizationRecords.getAuthorizationRecordId());
                        checkerAuthorizationPermissions.setPermissionId(permissionId);
                        checkerAuthorizationPermissions.setStartTime(now);
                        checkerAuthorizationPermissions.setEndTime(now.plusYears(99));
                        checkerAuthorizationPermissions.setCreatedAt(now);
                        authorizationPermissionsArrayList.add(checkerAuthorizationPermissions);
                    }
                }

                saveBatch(authorizationRecordsArrayList);
                authorizationPermissionsAdminService.saveBatch(authorizationPermissionsArrayList);
            }
        }

        return true;
    }

    // 授权主办方
    private void performanceSponsor(String performanceId, String cuid, String sponsorId) {
        LocalDateTime now = LocalDateTime.now();

        // 查询已有权限
        LambdaQueryWrapper<MerchantAuthorizationRecords> authorizationRecordsLambdaQueryWrapper = Wrappers.lambdaQuery(MerchantAuthorizationRecords.class);
        authorizationRecordsLambdaQueryWrapper.eq(MerchantAuthorizationRecords::getPerformanceId, performanceId);
        authorizationRecordsLambdaQueryWrapper.eq(MerchantAuthorizationRecords::getUidRole, "sponsor");
        authorizationRecordsLambdaQueryWrapper.eq(MerchantAuthorizationRecords::getDeletedAt, null);
        MerchantAuthorizationRecords authorizationRecords = getOne(authorizationRecordsLambdaQueryWrapper);

        // 查询主办方
        MerchantSponsorsVo sponsorsVo = merchantRedisUtil.getSponsorsVoBySponsorId(sponsorId);


    }
}
