package thyyxxk.webserver.service.utilities;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.dao.his.utilities.workorder.WorkOrderDao;
import thyyxxk.webserver.dao.his.utilities.workorder.WorkOrderDetailDao;
import thyyxxk.webserver.entity.login.UserInfo;
import thyyxxk.webserver.entity.utilities.workorder.*;
import thyyxxk.webserver.service.hutoolcache.UserCache;
import thyyxxk.webserver.utils.SnowFlakeId;
import thyyxxk.webserver.utils.StringUtil;
import thyyxxk.webserver.utils.TokenUtil;

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

@Service
public class WorkOrderService {
    private final WorkOrderDao dao;
    private final WorkOrderDetailDao detailDao;
    private final UserCache userCache;

    @Autowired
    public WorkOrderService(WorkOrderDao dao, WorkOrderDetailDao detailDao, UserCache userCache) {
        this.dao = dao;
        this.detailDao = detailDao;
        this.userCache = userCache;
    }

    public List<WorkOrder> insertNewOrder(WorkOrder workOrder) {
        String creator = TokenUtil.getInstance().getTokenUserId();
        UserInfo user = userCache.get(creator);
        workOrder.setId(SnowFlakeId.instance().nextId());
        workOrder.setCreator(creator);
        workOrder.setCreatorName(user.getName());
        workOrder.setDept(user.getDeptCode());
        workOrder.setDeptName(user.getDeptName());
        dao.insert(workOrder);
        return getAllOrdersByCreator(creator);
    }

    public List<WorkOrder> getAllOrdersByCreator(String creator) {
        QueryWrapper<WorkOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("creator", creator);
        wrapper.orderByDesc("createtime");
        return dao.selectList(wrapper);
    }

    public List<WorkOrder> getAllOrders(OrderInquiry inquiry) {
        inquiry.setUser(TokenUtil.getInstance().getTokenUserId());
        if (inquiry.getState() != WorkOrderEnum.StateEnum.ALL) {
            inquiry.setStmt(" and state='" + inquiry.getState() + "'");
        }
        List<WorkOrder> list = dao.getPlatOrders(inquiry);
        if (inquiry.getMeTaken() == WorkOrderEnum.MeTakenEnum.YES) {
            list.removeIf(item -> item.getMeTaken() == 0);
        } else {
            list.removeIf(item -> item.getMeTaken() > 0);
        }
        return list;
    }

    public String takeWorkOrder(WorkOrder workOrder) {
        String participant = TokenUtil.getInstance().getTokenUserId();
        WorkOrderDetail detail = new WorkOrderDetail();
        detail.setId(SnowFlakeId.instance().nextId());
        detail.setParentId(workOrder.getId());
        detail.setParticipant(participant);
        detail.setParticipantName(userCache.getEmployeeName(participant));
        detail.setContent(workOrder.getExpContent());
        detailDao.insert(detail);

        workOrder.setState(WorkOrderEnum.StateEnum.TAKEN);
        dao.updateById(workOrder);

        return "接单成功。";
    }

    public List<WorkOrderDetail> getMyTakenOrders(TakenInquiry inquiry) {
        QueryWrapper<WorkOrderDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("participant", TokenUtil.getInstance().getTokenUserId());
        if (StringUtil.notBlank(inquiry.getBegintime())) {
            wrapper.ge("createtime", inquiry.getBegintime());
        }
        if (StringUtil.notBlank(inquiry.getEndtime())) {
            wrapper.le("createtime", inquiry.getEndtime());
        }
        if (inquiry.getProgress() != WorkOrderEnum.ProgressEnum.ALL) {
            wrapper.eq("progress", inquiry.getProgress());
        }
        wrapper.orderByDesc("createtime");
        return detailDao.selectList(wrapper);
    }

    public String updateOrderProgress(WorkOrderDetail detail) {
        WorkOrderEnum.ProgressEnum progress = detail.getProgress();
        if (progress == WorkOrderEnum.ProgressEnum.IN_PROCESS) {
            orderStart(detail);
        } else if (progress == WorkOrderEnum.ProgressEnum.PROCESS_FINISHED) {
            orderFinish(detail);
        }
        detailDao.updateById(detail);
        return "更新成功。";
    }

    private void orderStart(WorkOrderDetail detail) {
        WorkOrder order = new WorkOrder();
        order.setId(detail.getParentId());
        order.setState(WorkOrderEnum.StateEnum.TAKEN);
        order.setBegintime(new Date());
        dao.updateById(order);
    }

    private void orderFinish(WorkOrderDetail detail) {
        detail.setFinishtime(new Date());
        WorkOrder order = new WorkOrder();
        order.setId(detail.getParentId());
        order.setState(WorkOrderEnum.StateEnum.FINISHED);
        order.setEndtime(detail.getFinishtime());
        dao.updateById(order);
    }
}
