package com.hys.app.service.erp.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hys.app.converter.erp.CompanyConverter;
import com.hys.app.framework.context.user.AdminUserContext;
import com.hys.app.mapper.erp.CompanyMapper;
import com.hys.app.model.erp.entity.*;
import com.hys.app.service.erp.CompanyManager;
import com.hys.app.framework.exception.ServiceException;
import com.hys.app.service.erp.CompanyPackageManager;
import com.hys.app.util.ValidateUtil;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * 平台管理员业务类
 *
 * @author zh
 * @version v7.0
 * @since v7.0.0
 * 2018-06-20 20:38:26
 */
@Service
@AllArgsConstructor
public class CompanyManagerImpl extends ServiceImpl<CompanyMapper, Company> implements CompanyManager {

    private RedisTemplate redisTemplate;
    private CompanyPackageManager companyPackageManager;

    @Override
    public Long createCompany(CompanyDO companyDO) {
        //todo 需要调起支付在支付的回调里面更改公司的使用状态
        Company convert = CompanyConverter.INSTANCE.convert(companyDO);
        checkParam(convert);
        convert.setEndUseTime(LocalDateTime.now().plusDays(15));
        save(convert);
        return convert.getId();
    }

    @Override
    public Long updateCompany(CompanyUpdateDO companyUpdateDO, Long id) {
        Company company = ValidateUtil.getOne(baseMapper, Company::getId, id, "企业");
        CompanyConverter.INSTANCE.convert(company, companyUpdateDO);
        updateById(company);
        return id;
    }

    @Override
    public Long renewCompany(CompanyRenewDO companyUpdateDO, Long id) {
        redisTemplate.opsForHash().put("company", id, companyUpdateDO);
        //todo  如果没到期就续费并更改了套餐和人数需要计算出来差价，在付款了之后再回调里面更改状态和到期时间
        return null;
    }

    @Override
    public CompanyVO getOneCompany(Long id) {
        return CompanyConverter.INSTANCE.convert(ValidateUtil.getOne(baseMapper, Company::getId, id, "企业"));
    }

    @Override
    public IPage<CompanyVO> getPage(CompanyQuery query) {
        Page<Company> page = page(new Page<>(query.getPageNo(), query.getPageSize()),
                new LambdaQueryWrapper<Company>().like(StrUtil.isNotBlank(query.getName()), Company::getName, query.getName())
                        .like(StrUtil.isNotBlank(query.getIndustry()), Company::getIndustry, query.getIndustry())
                        .like(StrUtil.isNotBlank(query.getUserName()), Company::getUserName, query.getUserName())
                        .ge(ObjectUtil.isNotNull(query. getHasUse()), Company::getEndUseTime, LocalDateTime.now())
                        .eq(!AdminUserContext.hasFound(),Company::getId,AdminUserContext.getCompanyId()));
        Page<CompanyVO> convert = CompanyConverter.INSTANCE.convert(page);
        for (CompanyVO vo : convert.getRecords()) {
            //todo 人员做好了之后统计人数
            vo.setCurrentUserNum(1);
        }
        return convert;
    }

    @Override
    public BigDecimal renewCompanyDifference(Long id) {
        Company company =getById(AdminUserContext.getCompanyId());
        CompanyPackage changePackage = companyPackageManager.getById(id);
        CompanyPackage usePackage = companyPackageManager.getById(company.getCompanyPackageId());
        BigDecimal subtract = changePackage.getMoney().divide(BigDecimal.valueOf(changePackage.getDay()))
                .subtract(usePackage.getMoney().divide(BigDecimal.valueOf(usePackage.getDay())));
        if (subtract.compareTo(BigDecimal.ZERO)<0){
            return BigDecimal.ZERO;
        }
        long betweenDay = DateUtil.betweenDay(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()),
                Date.from(company.getEndUseTime().atZone(ZoneId.systemDefault()).toInstant()),
                true);
        return subtract.multiply(BigDecimal.valueOf(betweenDay));
    }



    private void checkParam(Company convert) {
        if (Pattern.matches(".*[\\u4e00-\\u9fa5\\p{P}].*", convert.getCreditCode())){
            throw new ServiceException("统一社会信用代码不能包含中文和特殊符号");
        }
        if (ValidateUtil.checkRepeat(baseMapper, Company::getCreditCode, convert.getCreditCode(), Company::getId, convert.getId())) {
            throw new ServiceException("统一社会代码已存在");
        }
        if (ValidateUtil.checkRepeat(baseMapper, Company::getName, convert.getName(), Company::getId, convert.getId())) {
            throw new ServiceException("公司名称重复");
        }
    }
}
