package com.rongwei.bscommon.sys.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwei.bscommon.sys.dao.EquMaintenancePredictivePlanDao;
import com.rongwei.bscommon.sys.feign.RwAdminFeign;
import com.rongwei.bscommon.sys.service.EquMaintenancePredictivePlanService;
import com.rongwei.bscommon.sys.service.EquMaintenanceTaskService;
import com.rongwei.bsentity.domain.EquMaintenancePredictivePlanDo;
import com.rongwei.bsentity.domain.EquMaintenancePredictivePlanVo;
import com.rongwei.bsentity.domain.EquMaintenanceTaskDo;
import com.rongwei.bsentity.enums.PlantEnum;
import com.rongwei.bsentity.enums.TaskStatusEnum;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.utils.SecurityUtil;
import com.rongwei.rwcommonentity.commonservers.vo.SysSerialVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.*;
import java.util.*;

import static com.rongwei.safecommon.utils.SaveConstans.SysUser.DEVICESUBSYSTEMID;
import static com.rongwei.safecommon.utils.SaveConstans.SysUser.DEVICESUBSYSTEMNAME;

@Service
public class EquMaintenancePredictivePlanServiceImpl extends ServiceImpl<EquMaintenancePredictivePlanDao, EquMaintenancePredictivePlanDo> implements EquMaintenancePredictivePlanService {

    private final static Logger log = LoggerFactory.getLogger(EquMaintenancePredictivePlanServiceImpl.class);

    @Autowired
    EquMaintenancePredictivePlanService equMaintenancePredictivePlanService;

    @Autowired
    EquMaintenancePredictivePlanDao equMaintenancePredictivePlanDao;

    @Autowired
    EquMaintenanceTaskService equMaintenanceTaskService;

    @Autowired
    private RwAdminFeign rwAdminFeign;


    @Override
    public R generateMaintenanceTask(List<String> ids) {
        List<EquMaintenanceTaskDo> maintenanceTaskDoList =new ArrayList<>();
        EquMaintenanceTaskDo equMaintenanceTaskDo = null;

        //1.根据选中的id 查询预测保养信息记录
        List<EquMaintenancePredictivePlanVo> predictivePlanVos= equMaintenancePredictivePlanDao.queryDateByids(ids);

        for (EquMaintenancePredictivePlanVo predictivePlanVo:predictivePlanVos){
            equMaintenanceTaskDo =new EquMaintenanceTaskDo();

            BeanUtils.copyProperties(predictivePlanVo, equMaintenanceTaskDo);

            //【预测下次保养日期】 >=  当前日期，则取【预测下次保养日期】的年份，否则取  当前日期年份
           if(predictivePlanVo.getNextmaintenancedate().getTime()>= System.currentTimeMillis()){
               equMaintenanceTaskDo.setPlanyear(predictivePlanVo.getNextmaintenancedate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().getYear());
               equMaintenanceTaskDo.setMonth(predictivePlanVo.getNextmaintenancedate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().getMonthValue()+"");
           }else {
               equMaintenanceTaskDo.setPlanyear(LocalDate.now().getYear());
               equMaintenanceTaskDo.setMonth(LocalDate.now().getMonthValue()+"");
           };
           //是否要停机
            equMaintenanceTaskDo.setIshalt(predictivePlanVo.getIshalt());
            //计划开始时间 计划结束时间
            if (SetTimeToHourAM(predictivePlanVo.getNextmaintenancedate(),8).getTime()< System.currentTimeMillis()){
                equMaintenanceTaskDo.setTaskstart(SetTimeToHourAM(new Date(),8));
                equMaintenanceTaskDo.setTaskend(SetTimeToHourAM(new Date(),12));
            }else {
                equMaintenanceTaskDo.setTaskstart(SetTimeToHourAM(predictivePlanVo.getNextmaintenancedate(),8));
                equMaintenanceTaskDo.setTaskend(SetTimeToHourAM(predictivePlanVo.getNextmaintenancedate(),12));
            };
            equMaintenanceTaskDo.setCreateuserid(DEVICESUBSYSTEMID);
            equMaintenanceTaskDo.setCreateusername(DEVICESUBSYSTEMNAME);
            equMaintenanceTaskDo.setCreatedate(new Date());
            equMaintenanceTaskDo.setModifyuserid(DEVICESUBSYSTEMID);
            equMaintenanceTaskDo.setModifyusername(DEVICESUBSYSTEMNAME);
            equMaintenanceTaskDo.setModifydate(new Date());
            equMaintenanceTaskDo.setTaskstate(TaskStatusEnum.EXPORT_DISTRIBUTION.code);
            equMaintenanceTaskDo.setId(SecurityUtil.getUUID());
            equMaintenanceTaskDo.setPredictivemaintenanceplanid(predictivePlanVo.getId());
            //设置流水号
            setTaskId(equMaintenanceTaskDo);
            maintenanceTaskDoList.add(equMaintenanceTaskDo);

        }
        if (maintenanceTaskDoList.size()>0){
            equMaintenanceTaskService.insertBatch(maintenanceTaskDoList);
        }

        return R.ok();
    }

    private void setTaskId(EquMaintenanceTaskDo equMaintenanceTaskDo) {
        SysSerialVo sysSerialVo = new SysSerialVo();
        String plantSimp = PlantEnum.addrOf(equMaintenanceTaskDo.getTenantid());
        String plantype = equMaintenanceTaskDo.getPlantype();
        sysSerialVo.setModulecode("equ_maintenance_task_aq_code_" + plantSimp);
        sysSerialVo.setResetrule("date:yyyy");
        sysSerialVo.setRuleTemplateStr(plantSimp +"-"+plantype+"-@{date:yyyyMM}-@{serialNumber:#00000}");
        sysSerialVo.setIfautomaticreset("y");
            R serialNumberCode = rwAdminFeign.getSerialNumberCode(sysSerialVo);
            if ("200".equals(serialNumberCode.getCode())) {
                Object data = serialNumberCode.getData();
                equMaintenanceTaskDo.setTaskid(JSONObject.parseObject(JSONObject.toJSONString(data), Map.class).get("code").toString());
            }

    }



    /**
     * 设置时间时分秒 设值小时整点
     *
     * @param originalDate
     * @param hour
     * @return
     */
    public Date SetTimeToHourAM(Date originalDate, int hour){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(originalDate);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }
}
