package com.tykj.dev.device.allot.service.impl;

import com.github.wenhao.jpa.PredicateBuilder;
import com.github.wenhao.jpa.Specifications;
import com.tykj.dev.blockcha.subject.entity.BcHash;
import com.tykj.dev.blockcha.subject.service.BlockChainUtil;
import com.tykj.dev.config.TaskBeanConfig;
import com.tykj.dev.device.allot.repository.AllotBillDao;
import com.tykj.dev.device.allot.service.AllotBillService;
import com.tykj.dev.device.allot.subject.domin.AllotBill;
import com.tykj.dev.device.allot.subject.vo.AllotBillSelectVo;
import com.tykj.dev.device.user.subject.service.UserPublicService;
import com.tykj.dev.device.user.util.UserUtils;
import com.tykj.dev.misc.utils.JacksonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.persistence.Transient;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

/**
 * @author dengdiyi
 */
@Service
public class AllotBillServiceImpl implements AllotBillService {

    @Autowired
    private AllotBillDao allotBillDao;

    @Autowired
    private UserPublicService userPublicService;

    @Autowired
    private BlockChainUtil blockChainUtil;

    @Autowired
    private UserUtils userUtils;

    @Override
    public AllotBill addEntity(AllotBill allotBillEntity) {
        AllotBill allotBill = allotBillDao.save(allotBillEntity);
        //异步上链
        CompletableFuture.runAsync(() ->{
            //延迟2s防止同时写入
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //获取最新数据
            AllotBill allotBill1 = getOne(allotBill.getId());
            //上链获得recordId并存入表中
            BcHash bcText = blockChainUtil.sendHash(1000, JacksonUtil.toJSon(allotBill1));
            String recordId = bcText.getData().getRecordID();
            allotBill1.setRecordId(recordId);
            allotBillDao.save(allotBill1);
        }, TaskBeanConfig.getThreadPoolTaskScheduler());
        return allotBill;
    }

    /**
     * @param allotBills 异步上链
     */
    @Override
    @Async("taskScheduler")
    public void sendHash(List<AllotBill> allotBills) {
        allotBills.forEach(allotBill -> {
            BcHash bcText = blockChainUtil.sendHash(1000, JacksonUtil.toJSon(allotBill));
            String recordId = bcText.getData().getRecordID();
            allotBill.setRecordId(recordId);
            update(allotBill);
        });
    }

    @Override
    public AllotBill update(AllotBill allotBillEntity) {
        //save
        AllotBill allotBill = allotBillDao.save(allotBillEntity);
        //根据recordId追加上链
        CompletableFuture.runAsync(() -> blockChainUtil.appendHash(JacksonUtil.toJSon(allotBill), allotBill.getRecordId()),TaskBeanConfig.getThreadPoolTaskScheduler());
        return allotBill;
    }

    @Override
    public Page<AllotBill> getPage(AllotBillSelectVo allotBillSelectVo, Pageable pageable) {
        Page<AllotBill> page = allotBillDao.findAll(getSelectSpecification(allotBillSelectVo), pageable);
        //id转换为人名
        for (AllotBill a : page.getContent()) {
            if (a.getSendUseraId()!=null) {
                a.setSenderUserA(userPublicService.getOne(a.getSendUseraId()).getName());
            }
            if (a.getSendUserbId()!=null) {
                a.setSenderUserB(userPublicService.getOne(a.getSendUserbId()).getName());
            }
            if (a.getReceiveUseraId()!=null) {
                a.setReceiveUserA(userPublicService.getOne(a.getReceiveUseraId()).getName());
            }
            if (a.getReceiveUserbId()!=null) {
                a.setReceiveUserB(userPublicService.getOne(a.getReceiveUserbId()).getName());
            }
        }
        return page;
    }

    @Override
    public List<AllotBill> getList(AllotBillSelectVo allotBillSelectVo) {
        return allotBillDao.findAll(getSelectSpecification(allotBillSelectVo));
    }

    @Override
    public AllotBill getOne(Integer id) {
        Optional<AllotBill> resultEntity = allotBillDao.findById(id);
        return resultEntity.orElse(null);
    }

    @Override
    public void delete(Integer id) {
        allotBillDao.deleteById(id);
    }

    /**
     * @param allotBillSelectVo 查询vo
     * 查询统一筛选器
     */
    private Specification<AllotBill> getSelectSpecification(AllotBillSelectVo allotBillSelectVo) {
        PredicateBuilder<AllotBill> predicateBuilder = Specifications.and();
        //或预言器，判断当前单位是不是发件或收件单位
        PredicateBuilder<AllotBill> predicateBuilder1 = Specifications.or();
        predicateBuilder1.eq("sendUnit", userUtils.getCurrentUserUnitName());
        predicateBuilder1.eq("receiveUnit", userUtils.getCurrentUserUnitName());
        predicateBuilder.predicate(predicateBuilder1.build());
        if (allotBillSelectVo != null) {
            if (allotBillSelectVo.getReplayNumber() != null) {
                predicateBuilder.eq("replayNumber", allotBillSelectVo.getReplayNumber());
            }
            if (allotBillSelectVo.getReceiveUnit() != null) {
                predicateBuilder.eq("receiveUnit", allotBillSelectVo.getReceiveUnit());
            }
            if (allotBillSelectVo.getReceiveUseraId() != null) {
                predicateBuilder.eq("receiveUseraId", allotBillSelectVo.getReceiveUseraId());
            }
            if (allotBillSelectVo.getSendUnit() != null) {
                predicateBuilder.eq("sendUnit", allotBillSelectVo.getSendUnit());
            }
            if (allotBillSelectVo.getSendUseraId() != null) {
                predicateBuilder.eq("sendUseraId", allotBillSelectVo.getSendUseraId());
            }
            if (allotBillSelectVo.getContent() != null) {
                Class<AllotBill> allotBillEntityClass = AllotBill.class;
                Field[] declaredFields = allotBillEntityClass.getDeclaredFields();
                PredicateBuilder<AllotBill> p = Specifications.or();
                for (Field field : declaredFields) {
                    if (field.getType().equals(String.class) && field.getAnnotation(Transient.class) == null) {
                        p.like(field.getName(), "%" + allotBillSelectVo.getContent() + "%");
                    }
                }
                predicateBuilder.predicate(p.build());
            }
            if (allotBillSelectVo.getStartTime() != null) {
                predicateBuilder.gt("sendTime", allotBillSelectVo.getStartTime());
            }
            if (allotBillSelectVo.getEndTime() != null) {
                predicateBuilder.lt("sendTime", allotBillSelectVo.getEndTime());
            }
            predicateBuilder.notIn("allotStatus", 0);
        }
        return predicateBuilder.build();
    }
}
