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.config.base.FileName;
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.file.entity.FileRet;
import com.tykj.dev.device.file.service.FilesUtil;
import com.tykj.dev.device.task.service.TaskService;
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.aspectj.util.FileUtil;
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.HashMap;
import java.util.List;
import java.util.Map;
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;

    @Autowired
    TaskService taskService;

    @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);
    }

    @Override
    public Map<String, List<FileRet>> getFileList(Integer taskId) {
        Map<String,List<FileRet>> map = new HashMap<>();
        Integer billId = taskService.get(taskId).getBillId();
        AllotBill allotBill = getOne(billId);
        //收件方签收单集合
        map.put(FileName.SIGN.name, FilesUtil.stringFileToList(allotBill.getReceiveFiles()));
        //申请文号文件集合
        map.put(FileName.APPLY.name,FilesUtil.stringFileToList(allotBill.getApplyFiles()));
        //批复文号文件集合
        map.put(FileName.REPLY.name,FilesUtil.stringFileToList(allotBill.getReplyFiles()));
        //发件方回执单集合
        map.put(FileName.RECEIPT.name,FilesUtil.stringFileToList(allotBill.getSendFiles()));
        return map;
    }

    /**
     * @param allotBillSelectVo 查询vo
     * 查询统一筛选器
     */
    private Specification<AllotBill> getSelectSpecification(AllotBillSelectVo allotBillSelectVo) {
        PredicateBuilder<AllotBill> predicateBuilder = Specifications.and();
        //或预言器，判断当前单位是不是发件或收件单位
        PredicateBuilder<AllotBill> predicateBuilder1 = Specifications.or();
        predicateBuilder1.eq("sendUnitId", userUtils.getCurrentUnitId());
        predicateBuilder1.eq("receiveUnitId", userUtils.getCurrentUnitId());
        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();
    }
}
