package com.yh.saas.plugin.yiliangyiyun.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.winsea.svc.base.workflow.entity.Workflow;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.plugin.yiliangyiyun.constant.StatusEnum;
import com.yh.saas.plugin.yiliangyiyun.entity.*;
import com.yh.saas.plugin.yiliangyiyun.exception.YException;
import com.yh.saas.plugin.yiliangyiyun.exception.YExceptionEnum;
import com.yh.saas.plugin.yiliangyiyun.mapper.FuelFillingInfoMapper;
import com.yh.saas.plugin.yiliangyiyun.service.IFillingDetailInfoService;
import com.yh.saas.plugin.yiliangyiyun.service.IFuelFillingInfoService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.plugin.yiliangyiyun.service.INewWorkflowService;
import com.yh.saas.plugin.yiliangyiyun.service.IShortFillingInfoService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 记录加油信息 服务实现类
 * </p>
 *
 * @author Gdc
 * @since 2022-06-24
 */
@Service
public class FuelFillingInfoServiceImpl extends ServiceImpl<FuelFillingInfoMapper, FuelFillingInfo> implements IFuelFillingInfoService {

    @Autowired
    private IFuelFillingInfoService fuelFillingInfoService;
    @Autowired
    private IFillingDetailInfoService fillingDetailInfoService;
    @Autowired
    private IShortFillingInfoService shortFillingInfoService;
    @Autowired
    private INewWorkflowService workflowService;

    /**
     * 添加长途加油信息
     *
     * @param fuelFillingInfo
     * @return
     */
    @Override
    public String addFilling(FuelFillingInfo fuelFillingInfo) {
        String id = "";
        //判断开始/结束轨迹(0开始1结束)
        if ("0".equals(fuelFillingInfo.getTrackFlag())) {
            //新增主键id
            fuelFillingInfo.setId(IdGenerator.generateUUID());
            //行程状态改为已开始
            fuelFillingInfo.setTravelStatus(StatusEnum.TRACK_START.getName());
            fuelFillingInfo.setTravelStatusFlag(StatusEnum.TRACK_START.getFlag());

            //获取当前年月日
            SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");//设置日期格式
            String date = f.format(new Date(System.currentTimeMillis()));
            //查询信息数量包括已删除的集合
            List<FuelFillingInfo> fuelFillingInfoList = this.selectFillingNoList(fuelFillingInfo);//调用Service中的方法
            //生成请假编号
            if (fuelFillingInfoList.size() > 0) {
                //取第一条数据的编号
                String n = fuelFillingInfoList.get(0).getFillingNo();
                //截取编号后4位
                int intNumber = Integer.parseInt(n.substring(13));
                intNumber++;
                String Number = String.valueOf(intNumber);
                for (int i = 0; i < 4; i++) {
                    Number = Number.length() < 4 ? "0" + Number : Number;
                }
                //编号自增
                Number = "JY" + date + Number;
                fuelFillingInfo.setFillingNo(Number);
            } else {
                //如果当天数据为空，生成第一条数据
                String Number = "JY" + date + "0001";
                fuelFillingInfo.setFillingNo(Number);
            }
            if (fuelFillingInfo.getFillingNo().contains("null")) {
                throw new YException(YExceptionEnum.QUALITY_HAVE_ERROR);
            }

            this.insert(fuelFillingInfo);
            id = fuelFillingInfo.getId();
        } else {
            FuelFillingInfo fuelFillingInfo1 = fuelFillingInfoService.selectOne(new EntityWrapper<FuelFillingInfo>()
                    .eq("comp_id", fuelFillingInfo.getCompId())
                    .eq("common_id", fuelFillingInfo.getCommonId())
                    .eq("car_no", fuelFillingInfo.getCarNo()));
            if (fuelFillingInfo1 != null) {
                //行程状态改为已结束
                fuelFillingInfo1.setTravelStatusFlag(StatusEnum.TRACK_END.getFlag());
                fuelFillingInfo1.setTravelStatus(StatusEnum.TRACK_END.getName());
                fuelFillingInfo1.setDestinationProvince(fuelFillingInfo.getDestinationProvince());
                fuelFillingInfo1.setDestinationCity(fuelFillingInfo.getDestinationCity());
                fuelFillingInfo1.setDestinationArea(fuelFillingInfo.getDestinationArea());
                fuelFillingInfo1.setDestinationLongitude(fuelFillingInfo.getDestinationLongitude());
                fuelFillingInfo1.setDestinationLatitude(fuelFillingInfo.getDestinationLatitude());
                this.updateById(fuelFillingInfo1);
                id = fuelFillingInfo1.getId();
            }
        }
        return id;
    }

    /**
     * 长途加油记录查询
     *
     * @param fuelFillingInfo
     * @return
     */
    @Override
    public Page<FuelFillingInfo> selectFilling(FuelFillingInfo fuelFillingInfo) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (fuelFillingInfo.getCurrentPage() - 1)
                * fuelFillingInfo.getPageSize());
        //  公司ID
        pageView.put("compId", fuelFillingInfo.getCompId());
        pageView.put("commonId", fuelFillingInfo.getCommonId());
        pageView.put("searchType", fuelFillingInfo.getSearchType());
        pageView.put("pageSize", fuelFillingInfo.getPageSize());
        pageView.put("currentPage", fuelFillingInfo.getCurrentPage());
        // 查询总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<FuelFillingInfo> dataList = baseMapper.getListByCondition(pageView);
        Page<FuelFillingInfo> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(fuelFillingInfo.getCurrentPage());
        page.setSize(fuelFillingInfo.getPageSize());
        return page;
    }

    /**
     * 查看长途加油信息
     *
     * @param id
     * @return
     */
    @Override
    public FuelFillingInfo getFilling(String id) {
        //根据id查询加油信息
        FuelFillingInfo fuelFillingInfo = this.selectById(id);
        return fuelFillingInfo;
    }

    /**
     * 加油管理列表(PC)
     *
     * @param fuelFillingInfo
     * @return
     */
    @Override
    public Page<FuelFillingInfo> selectFillingPc(FuelFillingInfo fuelFillingInfo) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (fuelFillingInfo.getCurrentPage() - 1)
                * fuelFillingInfo.getPageSize());
        //  公司ID
        pageView.put("compId", fuelFillingInfo.getCompId());
        pageView.put("pageSize", fuelFillingInfo.getPageSize());
        pageView.put("currentPage", fuelFillingInfo.getCurrentPage());
        pageView.put("searchKeyWord", fuelFillingInfo.getSearchKeyWord());
        pageView.put("startDate", fuelFillingInfo.getStartDate());
        pageView.put("endDate", fuelFillingInfo.getEndDate());
        // 查询总数
        Integer dataCount = baseMapper.getCountByConditionPc(pageView);
        List<FuelFillingInfo> dataList = baseMapper.getListByConditionPc(pageView);
        if (!CollectionUtils.isEmpty(dataList)) {
            for (FuelFillingInfo fuelFillingInfo1 : dataList) {
                //加油明细列表
                List<FillingDetailInfo> fillingDetailInfoList = fillingDetailInfoService.selectList(new EntityWrapper<FillingDetailInfo>()
                        .eq("filling_id", fuelFillingInfo1.getId())
                        .eq("delete_flag", "0"));
                if (CollectionUtils.isNotEmpty(fillingDetailInfoList)) {
                    fuelFillingInfo1.setFillingDetailInfoList(fillingDetailInfoList);
                }
                //短途行程列表
                List<ShortFillingInfo> shortFillingInfoList = shortFillingInfoService.selectList(new EntityWrapper<ShortFillingInfo>()
                        .eq("filling_id", fuelFillingInfo1.getId())
                        .eq("delete_flag", "0"));
                if (CollectionUtils.isNotEmpty(shortFillingInfoList)) {
                    fuelFillingInfo1.setShortFillingInfoList(shortFillingInfoList);
                }
            }
        }
        Page<FuelFillingInfo> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(fuelFillingInfo.getCurrentPage());
        page.setSize(fuelFillingInfo.getPageSize());
        return page;
    }

    /**
     * 加油管理-付款
     *
     * @param fuelFillingInfo1
     * @return
     */
    @Override
    public String fillingPayMoney(FuelFillingInfo fuelFillingInfo1) {
        FuelFillingInfo fuelFillingInfo = fuelFillingInfoService.selectById(fuelFillingInfo1.getId());
        if (fuelFillingInfo != null) {
            //状态改为已报销
            fuelFillingInfo.setTravelStatus(StatusEnum.TRACK_REIMBURSEMENT.getName());
            fuelFillingInfo.setTravelStatusFlag(StatusEnum.TRACK_REIMBURSEMENT.getFlag());
            //更新数据
            fuelFillingInfoService.updateById(fuelFillingInfo);
//            boolean isStartWorkflow = StringUtils.isBlank(fuelFillingInfo.getWorkflowId());
//            // 不是退回的单子
//            if (isStartWorkflow) {
//                Workflow workflow = workflowService
//                        .findLatestWorkflowByBusinessCodeByApp(fuelFillingInfo.getCompId(), "FILLINGFUKUAN-APPROVE");
//                // 没配置审核流程，直接结束并处理信息
//                if (workflow == null) {
//                    throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
//                }
//                // 开启审核流
//                else {
//                    // 设置状态 已提交审核
//                    fuelFillingInfo.setWorkflowId(workflow.getId());
//                    fuelFillingInfoService.updateById(fuelFillingInfo);
//                    workflowService.startInstance(workflow.getId(), fuelFillingInfo.getId());
//                }
//            }
//            // 退回的单子 再启用
//            else {
//                fuelFillingInfoService.updateById(fuelFillingInfo);
//                workflowService.activateInstance(fuelFillingInfo.getWorkflowId(), fuelFillingInfo.getId());
//            }
        }
        return "OK";
    }
    /**
     * 查询加油编号
     *
     * @param
     * @return
     */
    @Override
    public List<FuelFillingInfo> selectFillingNoList(FuelFillingInfo fuelFillingInfo) {
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String date = f.format(new Date(System.currentTimeMillis()));
        Map<String, Object> pageView = new HashMap<>(7);
        pageView.put("date", date);
        pageView.put("compId", fuelFillingInfo.getCompId());
        List<FuelFillingInfo> dataList = baseMapper.getListByConditionFilling(pageView);
        return dataList;
    }
}
