package com.yh.saas.plugin.operation.service.impl;

import com.alipay.sofa.rpc.common.RpcConstants;
import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.alipay.sofa.runtime.api.annotation.SofaReferenceBinding;
import com.alipay.sofa.runtime.api.annotation.SofaService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.winsea.svc.base.base.entity.*;
import com.winsea.svc.base.base.service.*;
import com.winsea.svc.base.base.util.DataResult;
import com.winsea.svc.base.base.util.DateUtils;
import com.winsea.svc.base.base.util.PinYinUtils;
import com.winsea.svc.base.basic.service.IFwCompanyModuleService;
import com.winsea.svc.base.plugin.entity.ServiceFeature;
import com.winsea.svc.base.plugin.entity.TenantPlugin;
import com.winsea.svc.base.plugin.entity.TenantService;
import com.winsea.svc.base.plugin.entity.TenantServiceItem;
import com.winsea.svc.base.plugin.service.IManagerService;
import com.winsea.svc.base.plugin.service.ITenantPluginService;
import com.winsea.svc.base.plugin.service.ITenantServService;
import com.winsea.svc.base.plugin.service.ITenantServiceItemService;
import com.winsea.svc.base.security.entity.User;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.yh.saas.common.support.event.SupportEventBus;
import com.yh.saas.common.support.event.payload.TenantDisabledEvent;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.common.support.util.uniqueness.UniquenessChecker;
import com.yh.saas.plugin.operation.entity.TenantOperateHis;
import com.yh.saas.plugin.operation.enums.TenantStatusEnums;
import com.yh.saas.plugin.operation.exception.OperationErrorCodeEnums;
import com.yh.saas.plugin.operation.exception.OperationException;
import com.yh.saas.plugin.operation.qo.TenantQO;
import com.yh.saas.plugin.operation.service.IOperateHisService;
import com.yh.saas.plugin.operation.service.IOperationTenantService;
import com.yh.saas.plugin.operation.service.IOperatorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 租户服务实现
 *
 * @author SunTianjun
 */
@Slf4j
@SofaService
public class OperationTenantServiceImpl implements IOperationTenantService {

    @Autowired
    private SupportEventBus eventBus;

    @SofaReference
    private ICommonCompanyService companyService;

    @SofaReference
    private IFwCompanyModuleService companyModuleService;

    @SofaReference
    private IManagerService managerService;

    @Autowired
    private IOperatorService operatorService;

    @SofaReference
    private ITenantServService tenantServService;

    @SofaReference
    private ITenantServiceItemService tenantServiceItemService;

//    @SofaReference
//    private IAnnoIssueInfoService annoIssueInfoService;

//    @SofaReference
//    private ICertificateService certificateService;

    @SofaReference
    private ICommonStaffService commonStaffService;

    @SofaReference
    private ICommonDictionaryCategoryService commonDictionaryCategoryService;

//    @SofaReference
//    private INewsParameterCompanyService newsParameterCompanyService;

//    @SofaReference
//    private ICrewBasicParameterService crewBasicParameterService;

    @SofaReference(binding = @SofaReferenceBinding(bindingType = RpcConstants.PROTOCOL_TYPE_BOLT, timeout = 30000))
    private ITenantPluginService tenantPluginService;

    @SofaReference
    private ICommonTenantService tenantService;

    @Autowired
    private IOperateHisService operateHisService;

    @SofaReference
    private IRoleResourceBizService roleResourceBizService;

    @SofaReference
    private ICommonRoleService commonRoleService;

    private static final String INIT_CLOUD_DISK = "10G";

    private static final String VESSEL_FLAG = "V";

    /**
     * @Param: 要加上标示的租户id
     * @Author: lxc
     * @Date: 9:21 2020/12/29 0029
     * @description:
     */
    @Value("${data.tenant_id:}")
    private String inTenantId;

    @Override
    @Transactional
    public String create(CommonTenant tenant) {


        tenantService.CheckTenantUnique(tenant);


        tenant.setTenantId(IdGenerator.generateUUID());
        tenant.setCloudDiskSize(INIT_CLOUD_DISK);
        tenant.setEnabled(1);
        //租户新建直接为使用中用户
        tenant.setStatusFlag(TenantStatusEnums.BEING_USED.getCode());
        tenant.setStatus(TenantStatusEnums.BEING_USED.getValueZh());
        tenant.setStatusEn(TenantStatusEnums.BEING_USED.getValueEn());
//        tenantService.insert(tenant);
//
//        com.winsea.svc.base.base.entity.CommonTenant baseTenant = new com.winsea.svc.base.base.entity.CommonTenant();
//        BeanUtils.copyProperties(tenant, baseTenant);
        tenantService.create(tenant);


        String compId = IdGenerator.generateUUID();
        CommonCompany company = createCompany(tenant, compId);


        CommonManager manager = new CommonManager();
        manager.setManagerId(IdGenerator.generateLongIncrId());
        manager.setCompId(compId);
        manager.setManagerMobilePhone(tenant.getLinkmanPhone());
        manager.setManagerName(tenant.getLinkmanName());
        manager.setTenantId(tenant.getTenantId());
        manager.setPassword("y123456");

        //验证manager
        com.winsea.svc.base.plugin.util.DataResult dataResult = managerService.checkCommonManager(manager);
        if (null != dataResult) {
            throw new UniquenessChecker.UniquenessException(dataResult.getCode(), dataResult.getMessage());
        }

        //验证commonStaff
        CommonStaff commonStaff = new CommonStaff();
        commonStaff.setCompId(compId);
        commonStaff.setStaffAccount(manager.getManagerMobilePhone());
        commonStaff.setStaffMobilePhone(manager.getManagerMobilePhone());
        DataResult dataRoleResult = commonStaffService.checkCommonRole(commonStaff);
        if (null != dataRoleResult) {
            throw new UniquenessChecker.UniquenessException(dataRoleResult.getCode(), dataRoleResult.getMessage());
        }
        //创建账户
        this.managerService.create(manager);

//         复制简单的基础数据
//        certificateService.createBasicCertInfo(manager.getCompId());
//
//        annoIssueInfoService.releaseTenant(tenant.getTenantId());// 插入默认新闻
//
//        newsParameterCompanyService.createBasicParameter(manager.getCompId());
//
//        crewBasicParameterService.initData(manager.getCompId());

        return tenant.getTenantId();
    }


    private CommonCompany createCompany(CommonTenant tenant, String compId) {
        CommonCompany company = new CommonCompany();
        company.setCompId(compId);
        company.setCompName(tenant.getTenantName());
        company.setCompSimpleName(tenant.getCompSimpleNameEn());
        company.setCompSimpleNameEn(PinYinUtils.convertHanzi2Pinyin(tenant.getCompSimpleNameEn(), false).toLowerCase());
        company.setTenantId(tenant.getTenantId());
        company.setCompDomainName(tenant.getCompDomainName());
        company.setCompTypeKey("1");
        company.setCompTypeValue("船东及船管");
        company.setOrganizationMonetaryKey("1");
        company.setOrganizationMonetaryValue("元");
        company.setCompNameEn(tenant.getTenantEnName());
        company.setCompLinkman(tenant.getLinkmanName());
        company.setCompTel(tenant.getLinkmanPhone());
        company.setCreateDate(new Date());
        company.setCreateUserId("sysadmin");
        company.setUpdateDate(new Date());
        company.setUpdateUserId("sysadmin");
        company.setServiceExpiredDate(DateUtils.rollYear(new Date(), 1));
        List<CommonDictionaryCategory> commonDictionaryCategoryList = commonDictionaryCategoryService.findByTypeAndName("COMPANY_LOGO", null);
        if (CollectionUtils.isNotEmpty(commonDictionaryCategoryList)) {
            company.setCompHeadimg(commonDictionaryCategoryList.get(0).getDictionaryCategoryName());
        }
        DataResult dataResult = companyService.checkCommonCompany(company);
        if (null != dataResult) {
            throw new UniquenessChecker.UniquenessException(dataResult.getCode(), dataResult.getMessage());
        }

        this.companyService.create(company);

        return company;
    }

    @Override
    @Transactional
    public void changeInfo(CommonTenant tenant) {
        if (!this.checkoutTenantName(tenant.getTenantName(), tenant.getTenantId(), tenant.getCompSimpleNameEn())) {
            throw new OperationException(OperationErrorCodeEnums.TENANT_NAME_REPEAT);
        }
        //通过租户名称自动化寻址

        CommonCompany company = new CommonCompany();
        company.setCompId(tenant.getCompId());
        company.setCompNameEn(tenant.getTenantEnName());
        company.setCompLinkman(tenant.getLinkmanName());
        company.setCompTel(tenant.getLinkmanPhone());
        company.setCompName(tenant.getTenantName());
        company.setCompSimpleName(tenant.getCompSimpleNameEn());
        company.setCompSimpleNameEn(PinYinUtils.convertHanzi2Pinyin(tenant.getCompSimpleNameEn(), false).toLowerCase());
        company.setCompDomainName(tenant.getCompDomainName());
        company.setCompImo(tenant.getShipNumber());

        DataResult dataResult = companyService.checkCommonCompany(company);
        if (null != dataResult) {
            throw new UniquenessChecker.UniquenessException(dataResult.getCode(), dataResult.getMessage());
        }
        companyService.changeInfo(company);

        tenant.setEnabled(null);
//        tenant.updateById();
//
//        com.winsea.svc.base.base.entity.CommonTenant baseCommonTenant = new com.winsea.svc.base.base.entity.CommonTenant();
//        BeanUtils.copyProperties(tenant, baseCommonTenant);
        tenantService.updateById(tenant);
    }


    @Override
    @Transactional
    public void change(CommonCompany commonCompany) {
        //通过租户名称自动化寻址

        CommonCompany company = companyService.selectById(commonCompany.getCompId());
        company.setCompImo(commonCompany.getCompImo());
        companyService.updateById(company);
    }

    @Override
    @Transactional
    public void changeTrialInfo(CommonTenant tenant) throws ParseException {
//        if (!this.checkoutTenantName(tenant.getTenantName(), tenant.getTenantId(), tenant.getCompSimpleNameEn())) {
//            throw new OperationException(OperationErrorCodeEnums.TENANT_NAME_REPEAT);
//        }
        //通过租户名称自动化寻址
//        RpcInvokeContext.getContext().putRequestBaggage(RpcContextBaseVariableNames.TENANT_NAME, tenant.getTenantName());

        CommonTenant commonTenant = this.getTenantDetail(tenant.getTenantId());
        tenant.setLinkmanPassword(commonTenant.getLinkmanPassword());
        //如果该租户是从待审核状态变为使用中或试用租户,插基础数据
        if (StringUtils.equals("1", commonTenant.getStatusFlag())) {

            if (StringUtils.equals("2", tenant.getStatusFlag())
                    || StringUtils.equals("3", tenant.getStatusFlag())) {
                // 创建企业后台管理员
                CommonManager manager = createManagerInfo(tenant);
//
                // 复制简单的基础数据
//                certificateService.createBasicCertInfo(manager.getCompId());
//
//                annoIssueInfoService.releaseTenant(tenant.getTenantId());// 插入默认新闻
//
//                newsParameterCompanyService.createBasicParameter(manager.getCompId());
//
//                crewBasicParameterService.initData(manager.getCompId());

            }
        }

        if (StringUtils.equals("1", tenant.getStatusFlag())) {
            tenant.setStatusFlag(TenantStatusEnums.TO_BE_REVIEWED.getCode());
            tenant.setStatus(TenantStatusEnums.TO_BE_REVIEWED.getValueZh());
            tenant.setStatusEn(TenantStatusEnums.TO_BE_REVIEWED.getValueEn());
        } else if (StringUtils.equals("2", tenant.getStatusFlag())) {
            tenant.setStatusFlag(TenantStatusEnums.ON_TRIAL.getCode());
            tenant.setStatus(TenantStatusEnums.ON_TRIAL.getValueZh());
            tenant.setStatusEn(TenantStatusEnums.ON_TRIAL.getValueEn());
        } else if (StringUtils.equals("3", tenant.getStatusFlag())) {
            tenant.setStatusFlag(TenantStatusEnums.BEING_USED.getCode());
            tenant.setStatus(TenantStatusEnums.BEING_USED.getValueZh());
            tenant.setStatusEn(TenantStatusEnums.BEING_USED.getValueEn());
        } else if (StringUtils.equals("4", tenant.getStatusFlag())) {
            tenant.setStatusFlag(TenantStatusEnums.OUT_OF_SERVICE.getCode());
            tenant.setStatus(TenantStatusEnums.OUT_OF_SERVICE.getValueZh());
            tenant.setStatusEn(TenantStatusEnums.OUT_OF_SERVICE.getValueEn());
        }

        List<com.yh.saas.plugin.operation.entity.CommonOperator> operators = operatorService.selectList(new EntityWrapper<com.yh.saas.plugin.operation.entity.CommonOperator>()
                .eq(com.yh.saas.plugin.operation.entity.CommonOperator.QueryFields.OPERATOR_ID, tenant.getCustomerServiceStaffId()));
        tenant.setCustomerServiceStaffName(
                CollectionUtils.isEmpty(operators) ? null : operators.get(0).getOperatorName());
        tenant.setCustomerServiceStaffPhone(
                CollectionUtils.isEmpty(operators) ? null : operators.get(0).getOperatorMobilePhone());

        CommonCompany company = new CommonCompany();
        company.setCompId(tenant.getCompId());
        company.setCompNameEn(tenant.getTenantEnName());
        company.setCompLinkman(tenant.getLinkmanName());
        company.setCompTel(tenant.getLinkmanPhone());
        company.setCompName(tenant.getTenantName());
        company.setCompSimpleName(tenant.getCompSimpleNameEn());
        company.setCompSimpleNameEn(PinYinUtils.convertHanzi2Pinyin(tenant.getCompSimpleNameEn(), false).toLowerCase());

        DataResult dataResult = companyService.checkCommonCompany(company);
        if (null != dataResult) {
            throw new UniquenessChecker.UniquenessException(dataResult.getCode(), dataResult.getMessage());
        }
        companyService.changeInfo(company);

        tenant.setEnabled(null);
//        tenant.updateById();
//
//        com.winsea.svc.base.base.entity.CommonTenant baseCommonTenant = new com.winsea.svc.base.base.entity.CommonTenant();
//        BeanUtils.copyProperties(tenant, baseCommonTenant);
        tenantService.updateById(tenant);

        //更新开通服务的到期时间
        List<TenantPlugin> pluginList = tenantPluginService.findTenantPluginDetails(tenant.getTenantId(), null);
        if (CollectionUtils.isNotEmpty(pluginList)) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            for (TenantPlugin plug : pluginList) {
                plug.setPluginExpiredDate(simpleDateFormat.parse(tenant.getContractEndDate()));
            }
            tenantPluginService.updateBatchById(pluginList);
        }

        //如果修改了状态 插入操作历史
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (!StringUtils.equals(commonTenant.getStatusFlag(), tenant.getStatusFlag())) {
            User currentUser = AuthSecurityUtils.getCurrentUserInfo();
            TenantOperateHis operate = new TenantOperateHis();
            operate.setId(IdGenerator.generateLongIncrId());
            operate.setOperateDate(sdf.format(new Date()));
            operate.setTenantId(tenant.getTenantId());
            operate.setOperateUser(currentUser.getLoginName());
            if (StringUtils.equals("4", tenant.getStatusFlag())) {//如果停用 需要加上停用原因
                operate.setOperateContent(tenant.getStatus() + ":" + tenant.getReason());
            } else {
                operate.setOperateContent(tenant.getStatus());
            }
            operateHisService.insert(operate);
        }

        try {
            //试用中增加自动开通管理权限
            if (StringUtils.equals("2", tenant.getStatusFlag())) {
                log.info("开始设置权限方法");
                Set<String> resources = new HashSet<>();
                String tenantId = commonTenant.getTenantId();
                List<TenantPlugin> pluginDetails = tenantPluginService.findTenantPluginDetails(tenantId, null);
                for (TenantPlugin pluginDetail : pluginDetails) {
                    List<TenantService> activatedServices = pluginDetail.getActivatedServices();
                    for (TenantService activatedService : activatedServices) {
                        List<ServiceFeature> features = activatedService.getFeatures();
                        Set<String> resourceIds = features.stream().map(ServiceFeature::getFeatureCode).collect(Collectors.toSet());
                        //过滤掉=船员库：船员库_查看自己；在船船员_查看自己；证书管理：证书管理_查看自己，三个权限
                        resourceIds = resourceIds.stream().filter(s -> !"BasicInfo-userReview".equalsIgnoreCase(s)
                                && !"CrewOnShip-userReview".equalsIgnoreCase(s) && !"CertificateManagement-userReview".equalsIgnoreCase(s)).collect(Collectors.toSet());
                        resources.addAll(resourceIds);
                    }
                }
                log.info("查询到权限");
                Wrapper<CommonRole> wrapepr = new EntityWrapper<>();
                wrapepr.eq(CommonRole.QueryFields.TENANT_ID, tenantId);
                wrapepr.eq(CommonRole.QueryFields.ROLE_NAME, "系统管理员");
                List<CommonRole> roleList = commonRoleService.selectList(wrapepr);
                if (null != roleList && roleList.size() > 0) {
                    CommonRole commonRole = roleList.get(0);
                    log.info("设置权限到" + commonRole.getRoleId() + "用户中");
                    log.info("权限有" + resources);
                    roleResourceBizService.bind(commonRole.getRoleId(), resources);
                }
                log.info("结束设置权限方法");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private CommonManager createManagerInfo(CommonTenant tenant) {

        CommonManager manager = new CommonManager();
        manager.setManagerId(IdGenerator.generateLongIncrId());
        manager.setCompId(tenant.getCompId());
        manager.setManagerMobilePhone(tenant.getLinkmanPhone());
        manager.setManagerName(tenant.getLinkmanName());
        manager.setTenantId(tenant.getTenantId());
        // 创建账户
        manager.setManagerId(IdGenerator.generateUUID());
        manager.setPassword(tenant.getLinkmanPassword());

        com.winsea.svc.base.plugin.util.DataResult dataResult = managerService.checkCommonManager(manager);
        if (null != dataResult) {
            throw new UniquenessChecker.UniquenessException(dataResult.getCode(), dataResult.getMessage());
        }

        managerService.createTrial(manager, tenant);

        // 激活插件，返回插件(code,id)Map
//        Map<String, String> pluginCodeIdMap = tenantServService.activate(tenant.getActivatedServices(), manager.getTenantId(), tenant.getPluginAttributes());

//        // 更新客户端公司使用的模块
//        CommonCompany company = companyService.selectOne(new EntityWrapper<CommonCompany>()
//                .eq(CommonCompany.QueryFields.TENANT_ID, manager.getTenantId()).isNull(CommonCompany.QueryFields.PARENT_COMP_ID));

//        if (companyService != null) {
//            companyModuleService.createCompanyModule(company.getCompId(), pluginCodeIdMap);
//        }
        return manager;
    }

    @Override
    public void enable(String tenantId) {

        CommonTenant tenant = tenantService.selectById(tenantId);

        //通过租户名称自动化寻址
//        TenantRpcInvokeContext.putTenantRpcInvokeContext(tenant.getTenantName());

        toggle(tenantId, 1);
    }

    @Transactional
    @Override
    public void disable(String tenantId) {

        CommonTenant tenant = tenantService.selectById(tenantId);

        //通过租户名称自动化寻址
//        RpcInvokeContext.getContext().putRequestBaggage(RpcContextBaseVariableNames.TENANT_NAME, tenant.getTenantName());

        toggle(tenantId, 0);

        eventBus.postPayload(new TenantDisabledEvent(tenantId));
    }

    @Override
    public Page<CommonTenant> search(String keyword, Page<CommonTenant> pageAndSortInfo) {

//        Wrapper<CommonTenant> wrapper = QueryUtils.generateFuzzySearchWrapper(keyword, CommonTenant.class);
        Wrapper<CommonTenant> wrapper = new EntityWrapper();
        //租户管理页面只显示状态为使用中的租户
        wrapper.eq(CommonTenant.QueryFields.STATUS_FLAG, "3");
        // 模糊搜索
        if (StringUtils.isNotBlank(keyword)) {
            String searchKeyword = keyword.replaceAll(" ", "");
            wrapper.andNew(
                    "replace(" + CommonTenant.QueryFields.TENANT_NAME_EN + ",' ','')like {0} or "
                            + CommonTenant.QueryFields.TENANT_NAME + " like {0} or "
                            + CommonTenant.QueryFields.COMP_SIMPLE_NAME_EN + " like {0} or "
                            + CommonTenant.QueryFields.LINKMAN_PHONE + " like {0} or "
                            + CommonTenant.QueryFields.LINKMAN_NAME + " like {0} ",
                    "%" + searchKeyword + "%");
        }
        Page<CommonTenant> commonTenantPage = tenantService.selectPage(pageAndSortInfo, wrapper);
        List<CommonTenant> records = commonTenantPage.getRecords();
        for (CommonTenant tenant : records) {
            //用于判断是否是体验账号公司，加上备件与还原按钮
            String tenantId = tenant.getTenantId();
            if (inTenantId.equalsIgnoreCase(tenantId)) {
//                tenant.setTestFlag(tenantId);
            }
        }
        return commonTenantPage;
    }

    @Override
    public Page<CommonTenant> getTrialList(TenantQO tenantQO) throws ParseException {

        Wrapper<CommonTenant> wrapper = new EntityWrapper();
        if (!StringUtils.isEmpty(tenantQO.getStatusFlag())) {
            wrapper.eq(CommonTenant.QueryFields.STATUS_FLAG, tenantQO.getStatusFlag());
        }
        // 模糊搜索
        if (StringUtils.isNotBlank(tenantQO.getKeyword())) {
            String searchKeyword = tenantQO.getKeyword().replaceAll(" ", "");
            wrapper.andNew(
                    CommonTenant.QueryFields.TENANT_NAME + " like {0} or "
                            + CommonTenant.QueryFields.LINKMAN_NAME + " like {0} ",
                    "%" + searchKeyword + "%");
        }
        wrapper.orderBy("update_date", false);
        Page<CommonTenant> tenantPage = tenantService.selectPage(tenantQO.getQueryPage(), wrapper);
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(tenantPage.getRecords())) {
            for (CommonTenant tenant : tenantPage.getRecords()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                if (StringUtils.isNotBlank(tenant.getContractEndDate())) {
                    Date endDate = sdf.parse(tenant.getContractEndDate());
                    tenant.setDaysRemaining((int) ((endDate.getTime() - System.currentTimeMillis()) / (24 * 3600 * 1000)));
                }
            }
        }
        return tenantPage;
    }

    /**
     * 启用/激活
     *
     * @param tenantId 租户ID
     * @param enabled  是否启用
     */
    private void toggle(String tenantId, Integer enabled) {
        CommonTenant tenant = new CommonTenant();
        tenant.setTenantId(tenantId);
        tenant.setEnabled(enabled);
        tenantService.updateById(tenant);

        //通过租户名称自动化寻址
        // TenantRpcInvokeContext.putTenantRpcInvokeContext(tenant.getTenantName());

        CommonTenant baseCommonTenant = new CommonTenant();
        BeanUtils.copyProperties(tenant, baseCommonTenant);
        tenantService.updateById(baseCommonTenant);
    }

    @Override
    public Boolean checkoutTenantName(String tenantName, String tenantId, String compSimpleNameEn) {
        int result;
        if (tenantId == null) {
            result = tenantService.selectCount(
                    new EntityWrapper<CommonTenant>().eq(CommonTenant.QueryFields.TENANT_NAME, tenantName));
        } else {
            result = tenantService
                    .selectCount(new EntityWrapper<CommonTenant>().eq(CommonTenant.QueryFields.TENANT_NAME, tenantName)
                            .ne(CommonTenant.QueryFields.TENANT_ID, tenantId));
        }
        if (!StringUtils.isEmpty(compSimpleNameEn) && result <= 0) {
            result = tenantService.selectCount(
                    new EntityWrapper<CommonTenant>().eq(CommonTenant.QueryFields.COMP_SIMPLE_NAME_EN, compSimpleNameEn)
                            .ne(CommonTenant.QueryFields.TENANT_ID, tenantId));
        }
        if (result == 0) {
            return true;
        }
        return false;
    }

    @Override
    public CommonTenant getTenantDetail(String tenantId) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        CommonTenant tenant = tenantService.selectById(tenantId);
//        List<com.yh.saas.plugin.operation.entity.CommonOperator> operators = operatorService.selectList(new EntityWrapper<CommonOperator>()
//                .eq(CommonOperator.QueryFields.OPERATOR_ID, tenant.getCustomerServiceStaffId()));
        com.yh.saas.plugin.operation.entity.CommonOperator opr = operatorService.selectById(tenant.getCustomerServiceStaffId());
        tenant.setCustomerServiceStaffName(
                null == opr ? null : opr.getOperatorName());
        tenant.setCustomerServiceStaffPhone(
                null == opr ? null : opr.getOperatorMobilePhone());
        if (StringUtils.isNotBlank(tenant.getContractEndDate())) {
            Date endDate = sdf.parse(tenant.getContractEndDate());
            tenant.setDaysRemaining((int) ((endDate.getTime() - System.currentTimeMillis()) / (24 * 3600 * 1000)));
        }
        Wrapper<CommonCompany> wrapperComp = new EntityWrapper<>();
        wrapperComp.eq(CommonCompany.QueryFields.TENANT_ID, tenantId);
        wrapperComp.isNull(CommonCompany.QueryFields.PARENT_COMP_ID);
        CommonCompany company = this.companyService.selectOne(wrapperComp);
        if (company != null) {
            tenant.setCompId(company.getCompId());
            tenant.setCompDomainName(company.getCompDomainName());
        }

        return tenant;
    }

    @Override
    public List<TenantService> getTenantService(String tenantId) {
        List<TenantService> tenantServices = tenantServService.findTenantPluginServices(tenantId, TenantService.ServiceStatus.ACTIVATED);
        tenantServices = tenantServices.stream().filter(tenantService -> "1".equals(tenantService.getFormFlag())).collect(Collectors.toList());
        tenantServices.forEach(tenantService -> {
            List<TenantServiceItem> tenantServiceItems = tenantServiceItemService.findServiceCode(tenantId, tenantService.getServiceCode());
            tenantServiceItems = tenantServiceItems.stream().filter(tenantServiceItem -> "1".equals(tenantServiceItem.getFormFlag())).collect(Collectors.toList());
            tenantService.setTenantServiceItems(tenantServiceItems);
        });
        return tenantServices;
    }

    @Override
    public DataResult CheckTenantUnique(CommonTenant tenant) {
        return tenantService.checkTenantUniqueReturnEntity(tenant);
    }

    @Override
    public void updateCommonTenantById(CommonTenant tenant) {
        tenantService.updateById(tenant);
    }

    @Override
    public void saveCommonTenant(CommonTenant tenant) {
        tenantService.insert(tenant);
    }

    private Boolean checkoutCompDomainName(String compId, String compDomainName) {
        List<CommonCompany> companies = companyService.selectList(new EntityWrapper<CommonCompany>()
                .eq(CommonCompany.QueryFields.COMP_DOMAIN_NAME, compDomainName)
                .ne(CommonCompany.QueryFields.COMP_ID, compId));

        return CollectionUtils.isEmpty(companies);
    }

}
