package com.ebo.workOrder.serviceBtnEnhance;

import com.ebo.entity.WorkOrderEntity;
import com.ebo.framework.common.exception.ServerException;
import com.ebo.mapper.WorkOrderMapper;
import com.ebo.module.fast.common.BtnServerEnhanceJavaInter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;

@Service
@Slf4j
public class TakeOrdersBtnEnhance implements BtnServerEnhanceJavaInter {

    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Override
    public void executeBefore(String tableName, String buttonCode, Map data) throws ServerException {

    }

    @Override
    public void executeAfter(String tableName, String buttonCode, Map data) throws ServerException, MalformedURLException {
        log.info("-----接单服务业务增强-----");
        String id = data.get("id").toString();
        WorkOrderEntity workOrderEntity = workOrderMapper.selectById(id);
        if (workOrderEntity == null) {
            throw new ServerException("该工单已失效，请重新刷新页面");
        }
        if (workOrderEntity.getStatus().equals("2")){
            workOrderEntity.setStatus("3");
            // 接单时间
            workOrderEntity.setAcceptTime(new Date());
            // 预计工时
            workOrderEntity.setEstimatedWorkHours((Integer) data.get("estimatedWorkHours"));
            // 预计关单时间
            String dateString = (String) data.get("estimatedCloseTime");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime localDateTime = LocalDateTime.parse(dateString, formatter);
            Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            workOrderEntity.setEstimatedCloseTime(date);
            log.info("值为:{}",workOrderEntity.getStatus());
        }else {
            throw new ServerException("系统繁忙，请稍后重试");
        }
        workOrderMapper.updateById(workOrderEntity);
    }
}
