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

import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.alipay.sofa.runtime.api.annotation.SofaService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.winsea.svc.base.base.constant.SystemConstant;
import com.winsea.svc.base.base.entity.CommonParameterCompany;
import com.winsea.svc.base.base.service.ICommonParameterCompanyService;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.yh.saas.plugin.news.command.ParameterCompanyCommand;
import com.yh.saas.plugin.news.entity.NewsBasicParameterCompany;
import com.yh.saas.plugin.news.entity.ParameterCompany;
import com.yh.saas.plugin.news.enums.NewsEnums;
import com.yh.saas.plugin.news.enums.NewsExceptionEnums;
import com.yh.saas.plugin.news.exception.NewsException;
import com.yh.saas.plugin.news.mapper.NewsParameterCompanyMapper;
import com.yh.saas.plugin.news.service.INewsBasicParameterCompanyService;
import com.yh.saas.plugin.news.service.INewsParameterCompanyService;
import com.yh.saas.plugin.news.util.thread.ObservableRunnable;
import com.yh.saas.plugin.news.util.thread.ThreadLifeCycleObserver;
import com.yh.saas.plugin.news.vo.ParameterCompanyVo;
import com.yh.saas.common.support.util.IdGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Chenly
 * @since 2019-10-10
 */
@SofaService
public class NewsParameterCompanyServiceImpl extends ServiceImpl<NewsParameterCompanyMapper, ParameterCompany> implements INewsParameterCompanyService {


    @Autowired
    private INewsBasicParameterCompanyService newsBasicParameterCompanyService;

    @SofaReference
    private ICommonParameterCompanyService parameterCompanyService;


    @Override
    public List<ParameterCompanyVo> getParameterCompany(String const_code,String parameterValue) {
        Wrapper<ParameterCompany> wrapper = new EntityWrapper<>();
        wrapper.eq(ParameterCompany.QueryFields.COMP_ID, AuthSecurityUtils.getCurrentUserInfo().getCompId());
        wrapper.eq(ParameterCompany.QueryFields.CONST_CODE, const_code);
        wrapper.eq(ParameterCompany.QueryFields.DELETE_FLAG,"0");
        if (StringUtils.isNotEmpty(parameterValue)){
            wrapper.like(ParameterCompany.QueryFields.PARAMETERVALUE,parameterValue);
        }
        wrapper.orderBy(ParameterCompany.QueryFields.ORDER_NUM, true);
        List<ParameterCompany> parameterCompanyList=this.selectList(wrapper);
        List<ParameterCompanyVo> parameterCompanyVoList=new ArrayList<ParameterCompanyVo>();
        parameterCompanyList.stream().forEach(parameterCompany -> {
            ParameterCompanyVo parameterCompanyVo = new ParameterCompanyVo();
            BeanUtils.copyProperties(parameterCompany, parameterCompanyVo);
            parameterCompanyVoList.add(parameterCompanyVo);
        });
       return parameterCompanyVoList;
    }



    @Override
    @Transactional
    public void deleteParameterCompanyById(String id) {
        ParameterCompany repair=this.selectById(id);
        if(null == repair){
            throw new NewsException(NewsExceptionEnums.NEWS_0001.getCode());
        }
        this.deleteById(id);
    }

    /**
     * 批量新增或保存 系统常量
     *
     * @param parameterList
     */
    @Override
    public void createOrUpdateList(List<CommonParameterCompany> parameterList) {
        if (CollectionUtils.isEmpty(parameterList)) {
            return;
        }
        String compId = parameterList.get(0).getCompId();
        String constCode = parameterList.get(0).getConstCode();
        if (com.yh.saas.common.support.util.StringUtils.isEmpty(compId)) {
            compId = SystemConstant.SYSTEM_COMP_ID;
        }
        // 删掉本次删除的
        List<ParameterCompany> oldList = this.selectList(new EntityWrapper<ParameterCompany>()
                .eq(ParameterCompany.QueryFields.COMP_ID, compId)
                .eq(ParameterCompany.QueryFields.CONST_CODE, constCode));
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(oldList)) {
            List<String> newIdList = parameterList.stream().map(CommonParameterCompany::getParameterId).collect(Collectors.toList());
            List<String> oldIdList = oldList.stream().map(ParameterCompany::getId).collect(Collectors.toList());
            oldIdList.removeAll(newIdList);
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(oldIdList)) {
                this.deleteBatchIds(oldIdList);
            }
        }

        // 新增或更新
        for (int i = 0; i < parameterList.size(); i++) {
            CommonParameterCompany parameter = parameterList.get(i);
            if (com.yh.saas.common.support.util.StringUtils.isEmpty(parameter.getConstCode())) {
                continue;
            }
            if (com.yh.saas.common.support.util.StringUtils.isEmpty(parameter.getCompId())) {
                parameter.setCompId(compId);
            }
            if(com.yh.saas.common.support.util.StringUtils.isEmpty(parameter.getParameterKey())) {
                Integer maxKey = this.baseMapper.selectMaxkey(compId, constCode);
                parameter.setParameterKey(maxKey == null ? "0" : String.valueOf(maxKey + 1));
            }
            parameter.setOrderNum(i + 1 + "");
            parameterCompanyService.insertOrUpdate(parameter);
        }
    }

    @Override
    public String saveParameterCompany(ParameterCompanyCommand request) {
        //校验是否重名
        if(checkName(request)>0) {
            throw new NewsException(NewsExceptionEnums.NEWS_0003.getCode());
        }
        String uuid="";
        if (StringUtils.isEmpty(request.getId())) {
            uuid=UUID.randomUUID().toString().replaceAll("-","");
            ParameterCompany repairParameterCompany = new ParameterCompany();
            repairParameterCompany.setConstCode(request.getConstCode());
            repairParameterCompany.setParameterValue(request.getParameterValue());
            /*repairParameterCompany.setParameterValueEn(request.getParameterValueEn());*/
            repairParameterCompany.setId(uuid);
            repairParameterCompany.setDescription(request.getDescription());
            repairParameterCompany.setDeleteFlag("0");
            repairParameterCompany.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
            int maxKey = getMaxkey(repairParameterCompany) + 1;
            repairParameterCompany.setParameterKey(String.valueOf(maxKey));
            int orderNum = maxOrderNum(repairParameterCompany);
            repairParameterCompany.setOrderNum(++orderNum);
            repairParameterCompany.setCreateDate(new Date());
            repairParameterCompany.setCreateUserId(AuthSecurityUtils.getCurrentUserInfo().getUserId());
            repairParameterCompany.setUpdateDate(new Date());
            repairParameterCompany.setUpdateUserId(AuthSecurityUtils.getCurrentUserInfo().getUserId());
            repairParameterCompany.setUpdateFlag("0");

            this.insert(repairParameterCompany);
        } else {
            ParameterCompany repairParameterCompany = this.selectById(request.getId());
            repairParameterCompany.setParameterValue(request.getParameterValue());
            repairParameterCompany.setDescription(request.getDescription());
            baseMapper.updateById(repairParameterCompany);
            uuid=request.getId();
        }
       return uuid;
    }


    @Override
    public void changeOrder(String id) {
        if(StringUtils.isBlank(id)){
            throw new NewsException(NewsExceptionEnums.NEWS_0002.getCode());
        }
        String[] ids=id.split(",");
        List<ParameterCompany> list=new ArrayList<ParameterCompany>();
        for (int i=0 ;i<ids.length;i++) {
            ParameterCompany parameterCompany=new ParameterCompany();
            parameterCompany.setId(ids[i]);
            parameterCompany.setOrderNum(i+1);
            list.add(parameterCompany);
        }
        if(CollectionUtils.isNotEmpty(list)) {
            this.updateBatchById(list);
        }

    }

    @Override
    public List<CommonParameterCompany> queryCommonParameterTenant(ParameterCompany parameterCompany) {

        return parameterCompanyService.selectList(new EntityWrapper<CommonParameterCompany>()
                .eq(ParameterCompany.QueryFields.COMP_ID, parameterCompany.getCompId())
                .eq(ParameterCompany.QueryFields.CONST_CODE, parameterCompany.getConstCode())
                .eq(ParameterCompany.QueryFields.DELETE_FLAG, NewsEnums.DELETE_FLAG_0.getCode())
                .orderBy(ParameterCompany.QueryFields.PARAMETERKEY, true)
                .setSqlSelect(
                        "const_code as constCode,parameter_id as id,parameter_id as parameterId,parameter_key as parameterKey, parameter_value as parameterValue, parameter_value_en parameterValueEn"));
    }

    /**
     * 最大序号
     *
     * @param compParameter
     * @return
     */
    private int maxOrderNum(ParameterCompany compParameter) {
        Wrapper<ParameterCompany> entityWrapper = new EntityWrapper<>();
        entityWrapper.setSqlSelect(" IFNULL(Max(order_num),0) as rowCnt ");
        entityWrapper.eq("comp_id", compParameter.getCompId());
        entityWrapper.eq("const_code", compParameter.getConstCode());
        ParameterCompany InfoList = selectOne(entityWrapper);
        if (InfoList == null || InfoList.getRowCnt() == 0) {
            return 0;
        } else {
            return InfoList.getRowCnt();
        }
    }

    private int getMaxkey(ParameterCompany compParameter) {
        Wrapper<ParameterCompany> compEntity = new EntityWrapper<>();
        compEntity.eq("const_code", compParameter.getConstCode());
        compEntity.eq("comp_id", compParameter.getCompId());
        compEntity.setSqlSelect("max(CAST(parameter_key as SIGNED)) as maxId  ");
        ParameterCompany quotesCnt = this.selectOne(compEntity);
        return null == quotesCnt ? 0 : quotesCnt.getMaxId();
    }


    public int checkName(ParameterCompanyCommand compParameter) {
        Wrapper<ParameterCompany> entityWrapper = new EntityWrapper<>();
        entityWrapper.setSqlSelect(" count(1) as rowCnt ");
        entityWrapper.eq("delete_flag", "0");
        entityWrapper.eq("comp_id", AuthSecurityUtils.getCurrentUserInfo().getCompId());
        entityWrapper.eq("const_code", compParameter.getConstCode());
        entityWrapper.eq("parameter_value", compParameter.getParameterValue());
        if(StringUtils.isNotBlank(compParameter.getId())){
            entityWrapper.ne("id", compParameter.getId());
        }
        ParameterCompany InfoList = this.selectOne(entityWrapper);
        if (InfoList == null || InfoList.getRowCnt() == 0) {
            return 0;
        } else {
            return 1;
        }
    }


    /**
     * 新建默认公司变量信息
     *
     * @param compId
     */
    @Override
    public void createBasicParameter(String compId) {

        ThreadLifeCycleObserver observer = new ThreadLifeCycleObserver();
        // 线程异步处理
        new Thread(new ObservableRunnable(observer, () -> {
            // 查所有默认变量
            List<NewsBasicParameterCompany> basicList = newsBasicParameterCompanyService.selectList(new EntityWrapper<>());
            List<ParameterCompany> parameterList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(basicList)) {
                basicList.forEach(basic -> {
                    ParameterCompany parameter = new ParameterCompany();
                    BeanUtils.copyProperties(basic, parameter);
                    parameter.setCompId(compId);
                    parameter.setId(IdGenerator.generateUUID());
                    parameterList.add(parameter);
                });
                this.insertBatch(parameterList);
            }
        })).start();
    }

    
}
