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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huimv.manage.eartag.dao.entity.EtApplyEntity;
import com.huimv.manage.eartag.dao.repo.EtApplyRepo;
import com.huimv.manage.eartag.service.IApplyService;
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.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

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

    /**
     * @Method : listApply
     * @Description : 所有任务展示列表
     * @Params : []
     * @Return : com.huimv.manage.util.Result
     * @Author : ZhuoNing
     * @Date : 2021/10/28
     * @Time : 18:20
     */
    @Override
    public Result listApply() {
        //
        return new Result(ResultCode.SUCCESS, applyRepo.listApply());
    }

    @Override
    public Result listApply(Integer applyId, Date startDate, Date endDate, Integer returnState, Integer deliverState, Integer pageSize, Integer pageNo) {
        Specification<EtApplyEntity> sf = (Specification<EtApplyEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            if (null != applyId) {
                predList.add(criteriaBuilder.equal(root.get("applyId").as(Integer.class), applyId));
            }
            if (null != startDate) {
                predList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("startDate").as(Date.class), startDate));
            }
            if (null != endDate) {
                predList.add(criteriaBuilder.lessThanOrEqualTo(root.get("endDate").as(Date.class), endDate));
            }
            if (null != returnState) {
                predList.add(criteriaBuilder.equal(root.get("returnState").as(Integer.class), returnState));
            }
            if (null != deliverState) {
                predList.add(criteriaBuilder.equal(root.get("deliverState").as(Integer.class), deliverState));
            }
            //
            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,applyRepo.listApply(pageable,applyId));
        return new Result(ResultCode.SUCCESS, applyRepo.findAll(sf, pageable));
    }

    /**
     * @Method : saveNewMission
     * @Description : 保存新任务（号）
     * @Params : [applyJa]
     * @Return : com.huimv.manage.util.Result
     * @Author : ZhuoNing
     * @Date : 2021/10/28
     * @Time : 18:20
     */
    @Override
    public Result saveNewMission(JSONArray applyJa) {
        for (int a = 0; a < applyJa.size(); a++) {
            JSONObject applyJo = applyJa.getJSONObject(a);
            EtApplyEntity applyEntity = new EtApplyEntity();
            applyEntity.setMissionProcessor(applyJo.getString("missionProcessor"));
            applyEntity.setOrgId(applyJo.getString("orgId"));
            applyEntity.setOrgName(applyJo.getString("orgName"));
            applyEntity.setOrgAddress(applyJo.getString("orgAddress"));
            applyEntity.setOrgLinkman(applyJo.getString("orgLinkman"));
            applyEntity.setPostCode(applyJo.getString("postCode"));
            applyEntity.setOrgTel(applyJo.getString("orgTel"));
            applyEntity.setApplyId(applyJo.getIntValue("applyId"));
            applyEntity.setAssignedDate(applyJo.getString("assignedDate"));
            applyEntity.setEarmarkAmount(applyJo.getIntValue("earmarkAmount"));
            applyEntity.setRealEarmarkAmount(applyJo.getIntValue("realEarmarkAmount"));
            applyEntity.setConsignmentDate(applyJo.getString("consignmentDate"));
            applyEntity.setApplyRegionName(applyJo.getString("applyRegionName"));
            applyEntity.setAnimalType(applyJo.getString("animalType"));
            applyEntity.setAnimalTypeName(applyJo.getString("animalTypeName"));
            applyEntity.setSetDownState(0);
            applyEntity.setDeliverState(0);
            applyRepo.saveAndFlush(applyEntity);
        }
        return new Result(ResultCode.SUCCESS, Const.SAVE_NEW_MESSION);
    }

    @Override
    public JSONArray filterExistApply(JSONArray downloadApplyJa) {
        JSONArray newApplyJa = new JSONArray();

        for (int a = 0; a < downloadApplyJa.size(); a++) {
            JSONObject downApplyJo = downloadApplyJa.getJSONObject(a);
//            System.out.println("downApplyJo>>"+downApplyJo);
//            System.out.println("applyId>>"+downApplyJo.getIntValue("applyId"));
            EtApplyEntity applyEntity = new EtApplyEntity();
            applyEntity.setApplyId(downApplyJo.getIntValue("applyId"));
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("apply_id", ExampleMatcher.GenericPropertyMatchers.contains());
            Example example = Example.of(applyEntity, matcher);
//            boolean applyExistBln = applyRepo.exists(example);
//            System.out.println("applyExistBln>>"+applyExistBln);
            if (!applyRepo.exists(example)) {
                newApplyJa.add(downApplyJo);
            }
        }
        return newApplyJa;
    }

    /**
     * @Method : setMissionHasDownloadState
     * @Description :
     * @Params : [applyId, state]
     * @Return : com.huimv.manage.util.Result
     * @Author : ZhuoNing
     * @Date : 2021/10/29
     * @Time : 15:36
     */
    @Override
    public Result setMissionHasDownloadState(int applyId, int state) {
        EtApplyEntity applyEntity = new EtApplyEntity();
        applyEntity.setApplyId(applyId);
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("apply_id", ExampleMatcher.GenericPropertyMatchers.contains());
        Example example = Example.of(applyEntity, matcher);
        Optional optional = applyRepo.findOne(example);
        if (optional.isPresent()) {
            EtApplyEntity applyEntity1 = (EtApplyEntity) optional.get();
            applyEntity1.setSetDownState(state);
            applyEntity1.setSetDownDate(new Timestamp(new Date().getTime()));
            applyRepo.saveAndFlush(applyEntity1);
            return new Result(ResultCode.SUCCESS);
        } else {
            return new Result(Const.CODE_NO_RECORD, Const.NO_RECORD, false);
        }
    }
    


}
