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

import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.winsea.svc.base.base.entity.*;
import com.winsea.svc.base.base.service.ICommonCompanyService;
import com.winsea.svc.base.base.service.ICommonDictionaryCategoryService;
import com.winsea.svc.base.base.service.ICommonStaffService;
import com.winsea.svc.base.base.service.ICommonTenantService;
import com.winsea.svc.base.base.util.DateUtils;
import com.winsea.svc.base.base.util.PinYinUtils;
import com.winsea.svc.base.base.util.SmsClient;
import com.winsea.svc.base.plugin.service.IManagerService;
import com.winsea.svc.base.plugin.util.DataResult;
import com.winsea.svc.base.security.exception.AuthErrorCodeEnums;
import com.winsea.svc.base.security.exception.AuthException;
import com.winsea.svc.base.security.service.IVeriCodeService;
import com.yh.saas.common.support.util.DateUtil;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.common.support.util.uniqueness.UniquenessChecker;
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.service.IOperatorService;
import com.yh.saas.plugin.operation.service.IVisitorRegisterService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 游客注册 服务类
 * </p>
 *
 * @author wangs
 * @since 2020年2月25日11:15:57
 */
@Service
public class VisitorRegisterServiceImpl implements IVisitorRegisterService {


    /**
     * UTF-8编码发送接口地址
     */
    @Value("${sms.gateway.url:}")
    private String url;

    /**
     * 短信操作接口地址(UTF8)
     */
    @Value("${sms.gateway.action-url:}")
    private String actionUrl;

    /**
     * 中国网建帐号用户名
     */
    @Value("${sms.gateway.access-id:}")
    private String accessId;

    /**
     * 中国网建帐号接口秘钥
     */
    @Value("${sms.gateway.access-key:}")
    private String accessKey;

    /**
     * 固定客服id
     */
    @Value("${customer.service.staff.id:}")
    private String staffId;

    private static final String INIT_CLOUD_DISK = "10G";

    private static final String MESSAGE_INFO = "尊敬的“赢海云管船”用户您好，恭喜您注册成功，客户顾问会在第一时间联系您，请保持手机畅通！";

    @SofaReference
    private ICommonDictionaryCategoryService commonDictionaryCategoryService;

    @Autowired
    private IOperatorService operatorService;

    @SofaReference
    private IVeriCodeService veriCodeService;

    @SofaReference
    private ICommonStaffService commonStaffService;

    @SofaReference
    private ICommonCompanyService companyService;

    @SofaReference
    private ICommonTenantService tenantService;

    @SofaReference
    private IManagerService managerService;


    /**
     * 前端免费用户注册
     *
     * @param tenant
     * @return
     */
    @Override
    @Transactional
    public String createNewVisitor(CommonTenant tenant) throws IOException {

//        通过租户名称自动化寻址
        try {
            veriCodeService.check(tenant.getLinkmanPhone(), tenant.getVeriCode());
        } catch (Exception e) {
            throw new AuthException(AuthErrorCodeEnums.VERI_CODE_INCORRECT);
        }

        tenantService.CheckTenantUnique(tenant);

        CommonStaff staff = commonStaffService.selectOne(new EntityWrapper<CommonStaff>()
                .eq(CommonStaff.QueryFields.STAFF_ACCOUNT, tenant.getLinkmanPhone()));
        if (staff != null) {
            throw new OperationException(OperationErrorCodeEnums.TENANT_PHONE_REPEAT);
        }
        tenant.setTenantId(IdGenerator.generateUUID());
        tenant.setLinkmanPassword(tenant.getPassword());
        tenant.setCloudDiskSize(INIT_CLOUD_DISK);
        tenant.setEnabled(1);
        tenant.setServiceType(CommonTenant.SERVICE_TYPE_STATUS.SHIP_COAST_CLIENT);
        tenant.setShipNumber("1");
        //默认插入一个固定的客服
        tenant.setCustomerServiceStaffId(staffId);
        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());
        //默认给60天试用期限
        Date serviceExpiredDate = DateUtils.rollDay(new Date(), 60);
        tenant.setContractStartDate(DateUtil.formatYMD(new Date()));
        tenant.setContractEndDate(DateUtil.formatYMD(serviceExpiredDate));
        //刚注册待审核状态
        tenant.setStatusFlag(TenantStatusEnums.TO_BE_REVIEWED.getCode());
        tenant.setStatus(TenantStatusEnums.TO_BE_REVIEWED.getValueZh());
        tenant.setStatusEn(TenantStatusEnums.TO_BE_REVIEWED.getValueEn());
        //租户的英文名，简称默认为注册时填的公司名
        if (StringUtils.isBlank(tenant.getCompSimpleNameEn())) {
            tenant.setCompSimpleNameEn(tenant.getTenantName());
        }
        if (StringUtils.isBlank(tenant.getTenantEnName())) {
            tenant.setTenantEnName(tenant.getTenantName());
        }
        //租户注册来源
        if (StringUtils.equals("1", tenant.getTenantSource())) {//
            tenant.setTenantSource("WinSea平台");
        } else if (StringUtils.equals("2", tenant.getTenantSource())) {
            tenant.setTenantSource("WinSea官网");
        } else if (StringUtils.equals("3", tenant.getTenantSource())) {
            tenant.setTenantSource("海大航运视界");
        }
//        tenant.insert();

//        CommonTenant baseTenant = new CommonTenant();
//        BeanUtils.copyProperties(tenant, baseTenant);
        tenantService.insert(tenant);


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

        SmsClient sc = new SmsClient(url, actionUrl, accessId, accessKey);
        //给注册用户发送短信
        sc.sendSMS(tenant.getLinkmanPhone(), MESSAGE_INFO);
        //给客服人员发送短信
        SmsClient sc1 = new SmsClient(url, actionUrl, accessId, accessKey);
        String message = "“赢海云管船”有新用户注册，请到及时审核！公司名称：" + tenant.getTenantName() + ",联系人："
                + tenant.getLinkmanName() + ",联系电话：" + tenant.getLinkmanPhone();
        sc1.sendSMS("18601950853", message);
        return tenant.getTenantId();
    }

    private CommonCompany createCompany(CommonTenant tenant, String compId, Date serviceExpiredDate) {
        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.getCompSimpleNameEn());
        company.setCompTypeKey("1");
        company.setCompTypeValue("船东及船管");
        company.setOrganizationMonetaryKey("1");
        company.setOrganizationMonetaryValue("元");
        company.setCompNameEn(tenant.getTenantEnName());
        company.setCompLinkman(tenant.getLinkmanName());
        company.setCompTel(tenant.getLinkmanPhone());
        // 服务到期日期
        company.setServiceExpiredDate(serviceExpiredDate);
        List<CommonDictionaryCategory> commonDictionaryCategoryList = commonDictionaryCategoryService.findByTypeAndName("COMPANY_LOGO", null);
        if (CollectionUtils.isNotEmpty(commonDictionaryCategoryList)) {
            company.setCompHeadimg(commonDictionaryCategoryList.get(0).getDictionaryCategoryName());
        }
        com.winsea.svc.base.base.util.DataResult dataResult = companyService.checkCommonCompany(company);
        if (null != dataResult) {
            throw new UniquenessChecker.UniquenessException(dataResult.getCode(), dataResult.getMessage());
        }

        this.companyService.create(company);
        return company;
    }


    private CommonManager createManagerInfo(CommonTenant tenant, String 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.setManagerId(IdGenerator.generateUUID());
        manager.setPassword(tenant.getPassword());

        DataResult dataResult = managerService.checkCommonManager(manager);
        if (null != dataResult) {
            throw new UniquenessChecker.UniquenessException(dataResult.getCode(), dataResult.getMessage());
        }

        managerService.create(manager);


//        Account account = new Account();
//        account.setLoginName(manager.getManagerName());
//        account.setLoginPassword(tenant.getPassword());
//        account.setUserId(manager.getManagerId());
//        account.setUserMobilePhone(manager.getManagerMobilePhone());
//        account.setAccountType(Account.AccountType.MANAGER);
//        account.setEnabled(1);
//        account.setTenantId(manager.getTenantId());
//        account.setCompId(manager.getCompId());

        //验证manager
//        com.yh.saas.common.plugin.util.DataResult dataResult = managerService.checkCommonManager(manager);
//        if (null != dataResult) {
//            throw new UniquenessChecker.UniquenessException(dataResult.getCode(), dataResult.getMessage());
//        }
//
//        accountService.create(account);
        return manager;
    }
}
