/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.dispatch.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.dispatch.common.FlowConstant;
import com.tofly.dispatch.dto.DispatchOrderDto;
import com.tofly.dispatch.dto.DispatchOrderQuery;
import com.tofly.dispatch.dto.DispatchOrderSendDto;
import com.tofly.dispatch.entity.DispatchLog;
import com.tofly.dispatch.entity.DispatchOrder;
import com.tofly.dispatch.entity.DispatchOrderReply;
import com.tofly.dispatch.entity.Emergency;
import com.tofly.dispatch.service.DispatchOrderReplyService;
import com.tofly.dispatch.service.DispatchOrderService;
import com.tofly.dispatch.service.FileService;
import com.tofly.dispatch.util.UploadFiles;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.tofly.dispatch.mapper.DispatchOrderMapper;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 指令管理
 *
 * @author admin
 * @date Fri Nov 11 00:00:00 CST 2022
 */
@Service("dispatchOrderService")
public class DispatchOrderServiceImpl extends ServiceImpl<DispatchOrderMapper, DispatchOrder> implements DispatchOrderService {
  @Autowired
  private FileService fileService;
  @Autowired
  private DispatchOrderReplyService dispatchOrderReplyService;

    @Value("${dispatch.ftp.order}")
    private String filePath;
    @Override
    public boolean saveOrder(DispatchOrderDto dispatchOrderDto, List<MultipartFile> fileList,boolean isAdd) {
         if(isAdd){
             return InsertOrder(dispatchOrderDto,fileList);
         }else{
             return UpdateOrder(dispatchOrderDto,fileList);
         }


    }

   public  boolean InsertOrder(DispatchOrderDto dispatchOrderDto, List<MultipartFile> fileList){
       DispatchOrder data=new DispatchOrder();

       if (CollUtil.isNotEmpty(fileList)) {
           String fileIds = UploadFiles.saveFiles(fileService, fileList, dispatchOrderDto.getUploadFileids(), dispatchOrderDto.getUploadFileids(),
                   filePath, "TF_DIS_DISPATCH_ORDER_W");
           if (!StringUtils.isEmpty(fileIds)) {
               dispatchOrderDto.setUploadFileids(fileIds);
           }
       }
       BeanUtils.copyProperties(dispatchOrderDto, data);
       data.setSendState("0");
       data.setOrderState("-1");
       return this.save(data);

   }
    public  boolean UpdateOrder(DispatchOrderDto dispatchOrderDto, List<MultipartFile> fileList){
        DispatchOrder data=this.getById(dispatchOrderDto.getId());
        if(data==null){
            throw new RuntimeException("修改参数错误");
        }
        if(data.getSendState().equals("1")){
            throw new RuntimeException("已发送的指令不能修改");
        }
        if(StringUtil.isEmpty(dispatchOrderDto.getRemark()) ||
                dispatchOrderDto.getRemark().equals("null")){
                dispatchOrderDto.setRemark("");
        }

        String fileIds=data.getUploadFileids();
        if(StringUtil.isNotEmpty(dispatchOrderDto.getUploadFileids())){
            fileIds=dispatchOrderDto.getUploadFileids();
            if(fileIds.equals("[]")){
                fileIds="";
            }
        }

            String fileIdsList = UploadFiles.saveFiles(fileService, fileList, data.getUploadFileids(), fileIds,
                    filePath, "TF_DIS_DISPATCH_ORDER_W");

                dispatchOrderDto.setUploadFileids(fileIdsList);

        DispatchOrder order=new DispatchOrder();
        BeanUtils.copyProperties(dispatchOrderDto, order);

        return this.updateById(order);

    }

    @Override
    public boolean sendOrder(DispatchOrderSendDto dispatchOrderSendDto) {
        DispatchOrder data=this.getById(dispatchOrderSendDto.getId());
        if(data==null){
            throw new RuntimeException("发送参数错误");
        }
        if(data.getSendState().equals("1")){
            throw new RuntimeException("该指令已经发送，不能重复发送");
        }

        DispatchOrder order=new DispatchOrder();
        BeanUtils.copyProperties(dispatchOrderSendDto, order);
        order.setOrderState("0"); //未接受
        order.setSendState("1");//已发送
        order.setSendTime(new Date());
        return this.updateById(order);
    }

    @Override
    public boolean acceptOrder(String ids, String orderState,String refuseReason) {
        List<String> list_id = Arrays.asList(ids.split(","));
        List<DispatchOrder> list=this.listByIds(list_id);
        switch (orderState){
            case  "1":
            case "2":
             boolean isExit=list.stream().anyMatch(a->a.getOrderState().equals("3"));
              if(isExit){
                 throw new RuntimeException("有已经完成的指令，不能进行指令接收操作");
                }
             break;
            default:
                break;
        }
  if(orderState.equals("2")){
       if(StringUtil.isEmpty(refuseReason)){
           throw new RuntimeException("指令拒绝接受原因不能为空");
       }

  }else{
      refuseReason="";
  }
        boolean update = this.update(new DispatchOrder(), new UpdateWrapper<DispatchOrder>().lambda()
                .set(DispatchOrder::getOrderState, orderState)
                .set(DispatchOrder::getRefuseReason, refuseReason)
                .in(DispatchOrder::getId, list_id));


        return update;
    }

    @Override
    public Page<DispatchOrder> getPageData(Page page, DispatchOrderQuery query) {
        if (query.getExecutionStartTime() != null && query.getExecutionEndTime() != null) {
            if (query.getExecutionStartTime().getTime() > query.getExecutionEndTime().getTime()) {
                throw new RuntimeException("执行开始时间不能大于结束时间");
            }
        }

        if (query.getSendStartTime() != null && query.getSendEndTime() != null) {
            if (query.getSendStartTime().getTime() > query.getSendEndTime().getTime()) {
                throw new RuntimeException("发送开始时间不能大于结束时间");
            }
        }

        if (query.getStartTime() != null && query.getStartTime() != null) {
            if (query.getStartTime().getTime() > query.getEndTime().getTime()) {
                throw new RuntimeException("开始时间不能大于结束时间");
            }
        }

        return this.baseMapper.getPageData(page, query);
    }

    @Override
    public boolean deleteByIds(String ids) {
        List<String> list = Arrays.asList(ids.split(","));
        Integer count_check=this.count(Wrappers.<DispatchOrder>lambdaQuery()
                .in(DispatchOrder::getId,list)
                       .and(a->a.eq(DispatchOrder::getSendState,1)
                               .or().ne(DispatchOrder::getCreateUser,SecurityUtils.getUserId())));
        if (count_check > 0) {
            throw new RuntimeException("只能删除自己创建的并且没有发送的指令");
        }

      /*  dispatchOrderReplyService.remove(Wrappers.<DispatchOrderReply>lambdaQuery()
                .in(DispatchOrderReply::getOrderId,list));*/
        return this.removeByIds(list);

    }
}
