package com.huimv.manage.eartag.service.impl;

import com.huimv.manage.eartag.dao.entity.EtEarmarkEntity;
import com.huimv.manage.eartag.dao.entity.SysBusiConfigParamEntity;
import com.huimv.manage.eartag.dao.repo.SysBusiConfigParamRepo;
import com.huimv.manage.eartag.service.IBusinessConfigService;
import com.huimv.manage.util.Const;
import com.huimv.manage.util.Result;
import com.huimv.manage.util.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Project : huimv.shiwan
 * @Package : com.huimv.biosafety.uface.controller
 * @Description : TODO
 * @Version : 1.0
 * @Author : ZhuoNing
 * @Create : 2020-12-25
 **/
@Service
@Slf4j
public class BusinessConfigService implements IBusinessConfigService {
    @Autowired
    private SysBusiConfigParamRepo configParamRepo;

    /**
     * @Method : listConfigParam
     * @Description :
     * @Params : [paramType, pageSize, pageNo]
     * @Return : com.huimv.manage.util.Result
     * @Author : ZhuoNing
     * @Date : 2021/11/10
     * @Time : 21:18
     */
    @Override
    public Result listConfigParam(String paramType, Integer pageSize, Integer pageNo) {
        //
        Specification<SysBusiConfigParamEntity> sf = (Specification<SysBusiConfigParamEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            if (null != paramType) {
                predList.add(criteriaBuilder.equal(root.get("paramType").as(String.class), paramType));
            }
            //
            Predicate[] pred = new Predicate[predList.size()];
            Predicate and = criteriaBuilder.and(predList.toArray(pred));
            criteriaQuery.where(and);
            //
            List<Order> orders = new ArrayList<>();
            orders.add(criteriaBuilder.desc(root.get("id")));
            return criteriaQuery.orderBy(orders).getRestriction();
        };
        // 分页
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        return new Result(ResultCode.SUCCESS, configParamRepo.findAll(sf, pageable));
    }

    /**
     * @Method : addConfigParam
     * @Description :
     * @Params : [paramName, paramId, paramValue, paramType, remark]
     * @Return : com.huimv.manage.util.Result
     * @Author : ZhuoNing
     * @Date : 2021/11/10
     * @Time : 21:18
     */
    @Override
    public Result addConfigParam(String paramName, String paramId, String paramValue, String paramType, String remark) {
        // 判断是否重名
        if (_isExistParamId(paramId)) {
            return new Result(Const.CODE_PARAM_EXIST, Const.INFO_PARAM_EXIST, false);
        } else {
            SysBusiConfigParamEntity configParamEntity = new SysBusiConfigParamEntity();
            configParamEntity.setParamName(paramName);
            configParamEntity.setParamId(paramId);
            configParamEntity.setParamValue(paramValue);
            configParamEntity.setParamType(paramType);
            configParamEntity.setRemark(remark);
            SysBusiConfigParamEntity addResult = configParamRepo.saveAndFlush(configParamEntity);
            log.info("添加结果=" + addResult);
            return new Result(Const.CODE_OK, Const.SAVE_OK, true);
        }
    }

    // 判断是否存在重复数据
    private boolean _isExistParamId(String paramId) {
        //
        SysBusiConfigParamEntity configParamEntity = new SysBusiConfigParamEntity();
        configParamEntity.setParamId(paramId);
        //
        Example<SysBusiConfigParamEntity> example = Example.of(configParamEntity);
        //
        return configParamRepo.exists(example);
    }

    /**
     * @Method : editConfigParam
     * @Description :
     * @Params : [id, paramName, paramId, paramValue, paramType, remark]
     * @Return : com.huimv.manage.util.Result
     * @Author : ZhuoNing
     * @Date : 2021/11/10
     * @Time : 21:18
     */
    @Override
    public Result editConfigParam(Integer id, String paramName, String paramId, String paramValue, String paramType, String remark) {
        // 判断是否重名
        if (_isExistParamIdAndId(paramId, id)) {
            return new Result(Const.CODE_PARAM_EXIST, Const.INFO_PARAM_EXIST, false);
        } else {
            SysBusiConfigParamEntity configParamEntity = new SysBusiConfigParamEntity();
            configParamEntity.setId(id);
            configParamEntity.setParamName(paramName);
            configParamEntity.setParamId(paramId);
            configParamEntity.setParamValue(paramValue);
            configParamEntity.setParamType(paramType);
            configParamEntity.setRemark(remark);
            SysBusiConfigParamEntity addResult = configParamRepo.saveAndFlush(configParamEntity);
            log.info("编辑结果=" + addResult);
            return new Result(Const.CODE_OK,Const.INFO_EDIT_OK,true);
        }
    }

    // 判断参数id是否重名
    private boolean _isExistParamIdAndId(String paramId, Integer id) {
        //
        List<Object[]> configParamList = configParamRepo.getRepeatTotal(paramId, id);
        Object[] configParamObj = configParamList.get(0);
        BigInteger total = (BigInteger) configParamObj[0];
        if (total.intValue() == 0) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * @Method : removeConfigParam
     * @Description :
     * @Params : [ids]
     * @Return : com.huimv.manage.util.Result
     * @Author : ZhuoNing
     * @Date : 2021/11/10
     * @Time : 21:29
     */
    @Override
    public Result removeConfigParam(String ids) {
        Specification<SysBusiConfigParamEntity> specific = (Specification<SysBusiConfigParamEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            if (null != ids && !ids.trim().equalsIgnoreCase("null")) {
                String[] idsArray = ids.split(",");
                Integer[] idArrInt = new Integer[idsArray.length];
                for (int a = 0; a < idsArray.length; a++) {
                    idArrInt[a] = Integer.parseInt(idsArray[a]);
                }
                predList.add(root.get("id").as(Integer.class).in(idArrInt));
            }
            //
            Predicate[] pred = new Predicate[predList.size()];
            Predicate and = criteriaBuilder.and(predList.toArray(pred));
            criteriaQuery.where(and);
            //
            List<Order> orders = new ArrayList<>();
            orders.add(criteriaBuilder.asc(root.get("id")));
            return criteriaQuery.orderBy(orders).getRestriction();
        };
        //
        List<SysBusiConfigParamEntity> dataList = configParamRepo.findAll(specific);
        configParamRepo.deleteAll(dataList);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * @Method : getConfigParam
     * @Description :
     * @Params : [paramId]
     * @Return : com.huimv.manage.util.Result
     * @Author : ZhuoNing
     * @Date : 2021/11/10
     * @Time : 21:31
     */
    @Override
    public Result getConfigParam(String paramId) {
        Specification<SysBusiConfigParamEntity> spec = (Specification<SysBusiConfigParamEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            if (null != paramId) {
                predList.add(criteriaBuilder.equal(root.get("paramId").as(Integer.class), paramId));
            }
            //
            Predicate[] pred = new Predicate[predList.size()];
            Predicate and = criteriaBuilder.and(predList.toArray(pred));
            criteriaQuery.where(and);
            //
            List<Order> orders = new ArrayList<>();
            orders.add(criteriaBuilder.desc(root.get("id")));
            return criteriaQuery.orderBy(orders).getRestriction();
        };
        //
        return new Result(ResultCode.SUCCESS, configParamRepo.findAll(spec));
    }


}
