package com.tykj.dev.device.repair.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.repair.repository.RepairBackBillDao;
import com.tykj.dev.device.repair.service.RepairBackBillService;
import com.tykj.dev.device.repair.subject.domin.RepairBackBill;
import com.tykj.dev.device.repair.subject.vo.RepairBillSelectVo;
import com.tykj.dev.device.user.util.UserUtils;
import com.tykj.dev.misc.exception.ApiException;
import com.tykj.dev.misc.utils.JacksonUtil;
import com.tykj.dev.misc.utils.ResultUtil;
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 zjm
 * @version 1.0.0
 * @ClassName DeviceRepairBackBillServiceImpl.java
 * @Description TODO
 * @createTime 2020年08月25日 10:36:00
 */
@Service
public class RepairBackBillServiceImpl implements RepairBackBillService {
    @Autowired
    RepairBackBillDao deviceRepairBackBillDao;

    @Autowired
    BlockChainUtil blockChainUtil;

    @Autowired
    UserUtils userUtils;

    @Override
    public RepairBackBill save(RepairBackBill deviceRepairBackBillEntity) {
        RepairBackBill repairBackBill = deviceRepairBackBillDao.save(deviceRepairBackBillEntity);
        CompletableFuture.runAsync(()->{
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            RepairBackBill repairBackBill1 = getOne(repairBackBill.getId());
            BcHash bcText = blockChainUtil.sendHash(1000, JacksonUtil.toJSon(repairBackBill1));
            String recordId = bcText.getData().getRecordID();
            repairBackBill1.setRecordId(recordId);
            deviceRepairBackBillDao.save(repairBackBill1);
        });
        return repairBackBill;
    }

    @Override
    public boolean delete(Integer id) {
        return false;
    }

    @Override
    public List<RepairBackBill> findAll() {
        return deviceRepairBackBillDao.findAll();
    }

    @Override
    public RepairBackBill update(RepairBackBill deviceRepairBackBillEntity) {
        RepairBackBill repairBackBill = deviceRepairBackBillDao.save(deviceRepairBackBillEntity);
        CompletableFuture.runAsync(()->blockChainUtil.appendHash(JacksonUtil.toJSon(repairBackBill),repairBackBill.getRecordId()), TaskBeanConfig.getThreadPoolTaskScheduler());
        return repairBackBill;
    }

    @Override
    public RepairBackBill getOne(Integer id) {
        Optional<RepairBackBill> repairBackBill = deviceRepairBackBillDao.findById(id);
        if (repairBackBill.isPresent()) {
            return repairBackBill.get();
        } else {
            throw new ApiException(ResultUtil.failed("所查询的Id不存在"));
        }
    }

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

    @Override
    public Page<RepairBackBill> getPage(RepairBillSelectVo deviceRepairBillSelectVo, Pageable pageable) {
        return deviceRepairBackBillDao.findAll(getSelectSpecification(deviceRepairBillSelectVo), pageable);
    }

    private Specification<RepairBackBill> getSelectSpecification(RepairBillSelectVo deviceRepairBillSelectVo) {
        PredicateBuilder<RepairBackBill> predicateBuilder = Specifications.and();
        PredicateBuilder<RepairBackBill> predicateBuilder1 = Specifications.or();
        predicateBuilder1.eq("sendUnit", userUtils.getCurrentUserUnitName());
        predicateBuilder1.eq("receiveUnit", userUtils.getCurrentUserUnitName());
        predicateBuilder.predicate(predicateBuilder1.build());
        if (deviceRepairBillSelectVo != null) {
            if (deviceRepairBillSelectVo.getReceiveUnit() != null) {
                predicateBuilder.eq("receiveUnit", deviceRepairBillSelectVo.getReceiveUnit());
            }
            if (deviceRepairBillSelectVo.getSendUnit() != null) {
                predicateBuilder.eq("sendUnit", deviceRepairBillSelectVo.getSendUnit());
            }
            if (deviceRepairBillSelectVo.getContent() != null) {
                Class<RepairBackBill> deviceRepairBillEntityClass = RepairBackBill.class;
                Field[] declaredFields = deviceRepairBillEntityClass.getDeclaredFields();
                PredicateBuilder<RepairBackBill> p = Specifications.or();
                for (Field field : declaredFields) {
                    if (field.getType().equals(String.class) && field.getAnnotation(Transient.class) == null) {
                        p.like(field.getName(), "%" + deviceRepairBillSelectVo.getContent() + "%");
                    }
                }
                predicateBuilder.predicate(p.build());
            }
            if (deviceRepairBillSelectVo.getStartTime() != null) {
                predicateBuilder.gt("createTime", deviceRepairBillSelectVo.getStartTime());
            }
            if (deviceRepairBillSelectVo.getEndTime() != null) {
                predicateBuilder.lt("createTime", deviceRepairBillSelectVo.getEndTime());
            }
        }
//        predicateBuilder.eq("repairStatus", 5);
        return predicateBuilder.build();
    }
}
