package com.ym.mec.biz.service.impl;

import com.ym.mec.biz.dal.dao.InspectionItemDao;
import com.ym.mec.biz.dal.entity.InspectionItem;
import com.ym.mec.biz.dal.page.InspectionQueryInfo;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.util.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ym.mec.biz.dal.entity.Inspection;
import com.ym.mec.biz.dal.dao.InspectionDao;
import com.ym.mec.biz.service.InspectionService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class InspectionServiceImpl extends BaseServiceImpl<Long, Inspection> implements InspectionService {

    @Autowired
    private InspectionDao inspectionDao;
    @Autowired
    private InspectionItemDao inspectionItemDao;

    @Override
    public BaseDAO<Long, Inspection> getDAO() {
        return inspectionDao;
    }

    @Override
    public PageInfo<Inspection> getPageList(InspectionQueryInfo queryInfo) {
        if (queryInfo.getMonth() != null) {
            queryInfo.setStartTime(DateUtil.getFirstDayOfMonth(queryInfo.getMonth()));
            queryInfo.setEndTime(DateUtil.getLastTimeWithDay(DateUtil.getLastDayOfMonth(queryInfo.getMonth())));
        }
        PageInfo<Inspection> pageInfo = this.queryPage(queryInfo);
        if (pageInfo.getRows().size() > 0) {
            List<Inspection> rows = pageInfo.getRows();
            List<Long> inspectionIds = rows.stream().map(Inspection::getId).collect(Collectors.toList());
            List<InspectionItem> itemCountAndTimes = inspectionItemDao.getItemCountAndTimes(inspectionIds);
            for (Inspection row : rows) {
                for (InspectionItem itemCountAndTime : itemCountAndTimes) {
                    if (!row.getId().equals(itemCountAndTime.getInspectionId())) continue;
                    row.setItemNum(itemCountAndTime.getPlannedTimes());
                    row.setTimes(itemCountAndTime.getTimes());
                }
            }
        }
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Inspection> add(List<Inspection> inspections, Integer operationUserId) {
        Date nowDate = new Date();
        Date month = DateUtil.getFirstDayOfMonth(nowDate);
        for (Inspection inspection : inspections) {
            if(inspection.getMonth().before(month)){
                throw new BizException("工作周期不能早于当前月份");
            }
            inspection.setOperation(operationUserId);
            inspection.setCreateTime(nowDate);
            inspection.setUpdateTime(nowDate);
            inspectionDao.insert(inspection);
            for (InspectionItem inspectionItem : inspection.getInspectionItems()) {
                inspectionItem.setInspectionId(inspection.getId());
                inspectionItem.setOrganId(inspection.getOrganId());
                inspectionItem.setUserId(inspection.getUserId());
                inspectionItem.setMemo("");
                inspectionItem.setOperation(operationUserId);
                inspectionItem.setCreateTime(nowDate);
                inspectionItem.setUpdateTime(nowDate);
            }
            inspectionItemDao.batchInsert(inspection.getInspectionItems());
        }
        return inspections;
    }

    @Override
    public Inspection getInfo(Long id) {
        return inspectionDao.getInfo(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Inspection updateInspection(Inspection inspection, Integer operationUserId) {
        Date nowDate = new Date();
        Date month = DateUtil.getFirstDayOfMonth(nowDate);
        if(inspection.getMonth().before(month)){
            throw new BizException("工作周期不能早于当前月份");
        }
        if (inspection.getInspectionItems() == null || inspection.getInspectionItems().size() <= 0) {
            throw new BizException("任务事项不能为空");
        }
        Inspection oldInspection = inspectionDao.get(inspection.getId());
        if (oldInspection == null) {
            throw new BizException("巡查任务不存在，请核查");
        }
        oldInspection.setUpdateTime(nowDate);
        inspectionDao.update(oldInspection);

        List<InspectionItem> updateItems = inspection.getInspectionItems().stream().filter(e -> e.getId() != null).collect(Collectors.toList());
        List<InspectionItem> addItems = inspection.getInspectionItems().stream().filter(e -> e.getId() == null).collect(Collectors.toList());

        List<InspectionItem> delItems = new ArrayList<>();
        List<InspectionItem> oldItems = inspectionItemDao.getItemByInspectionId(inspection.getId());
        for (InspectionItem oldItem : oldItems) {
            boolean isUpdate = false;
            for (InspectionItem updateItem : updateItems) {
                if (!oldItem.getId().equals(updateItem.getId())) continue;
                isUpdate = true;
            }
            if (!isUpdate) {
                if (oldItem.getPlannedTimes() > 0) {
                    throw new BizException(oldItem.getItem().getDesc() + "已有日程安排不能删除");
                }
                delItems.add(oldItem);
            }
        }
        //增加新的
        for (InspectionItem addItem : addItems) {
            addItem.setInspectionId(oldInspection.getId());
            addItem.setOrganId(oldInspection.getOrganId());
            addItem.setUserId(oldInspection.getUserId());
            addItem.setMemo("");
            addItem.setOperation(operationUserId);
            addItem.setCreateTime(nowDate);
            addItem.setUpdateTime(nowDate);
        }
        //插入新的
        if (addItems.size() > 0) {
            inspectionItemDao.batchInsert(addItems);
        }
        //删除
        if (delItems.size() > 0) {
            List<Long> itemIds = delItems.stream().map(InspectionItem::getId).collect(Collectors.toList());
            inspectionItemDao.deleteByIds(itemIds);
        }
        //修改现有的
        if (updateItems.size() > 0) {
            for (InspectionItem updateItem : updateItems) {
                updateItem.setUpdateTime(nowDate);
                updateItem.setOperation(operationUserId);
            }
            inspectionItemDao.batchUpdate(updateItems);
        }
        return inspection;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delInspections(Long id) {
        List<InspectionItem> items = inspectionItemDao.getItemByInspectionId(id);
        for (InspectionItem item : items) {
            if (item.getPlannedTimes() > 0) {
                throw new BizException(item.getItem().getDesc() + "已有日程安排不能删除");
            }
        }
        inspectionDao.delete(id);
        inspectionItemDao.deleteByInspectionId(id);
        return true;
    }
}


