package org.jeecg.modules.itdmGongDan.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.itdmDevice.mapper.ItdmDeviceMapper;
import org.jeecg.modules.itdmDevice.service.IItdmDeviceService;
import org.jeecg.modules.itdmFirstPage.entity.ItdmTask;
import org.jeecg.modules.itdmFirstPage.mapper.ItdmTaskMapper;
import org.jeecg.modules.itdmFirstPage.service.IItdmTaskService;
import org.jeecg.modules.itdmGongDan.dto.ItdmJHYAddOrUpdateDTO;
import org.jeecg.modules.itdmGongDan.dto.ItdmXMJLAddOrUpdateDTO;
import org.jeecg.modules.itdmGongDan.entity.ItdmGongdanDetail;
import org.jeecg.modules.itdmGongDan.entity.ItdmGongdanMaster;
import org.jeecg.modules.itdmGongDan.entity.ItdmTestPlan;
import org.jeecg.modules.itdmGongDan.mapper.ItdmGongdanDetailMapper;
import org.jeecg.modules.itdmGongDan.mapper.ItdmGongdanMasterMapper;
import org.jeecg.modules.itdmGongDan.mapper.ItdmJCXMSHJHMapper;
import org.jeecg.modules.itdmGongDan.mapper.ItdmTestPlanMapper;
import org.jeecg.modules.itdmGongDan.service.IItdmJCXMSHJHService;
import org.jeecg.modules.itdmGongDan.vo.ItdmJCXMAndSYJHVO;
import org.jeecg.modules.itdmGongDan.vo.ItdmJHYQueryListVO;
import org.jeecg.modules.itdmGongDan.vo.ItdmXMJLQueryListVO;
import org.jeecg.modules.itdmGongDan.vo.ShijiDate;
import org.jeecg.modules.qita.GlobalVariables;
import org.jeecg.modules.weituo.mapper.ItdmWeituoInfoMapper;
import org.jeecg.modules.weituo.mapper.ItdmWeituoYangpinMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 计划排期——试验计划（计划员）；工单制定（项目经理）
 */
@Service
public class ItdmJCXMSHJHServiceImpl implements IItdmJCXMSHJHService {

    @Autowired
    @SuppressWarnings("all")
    private ItdmJCXMSHJHMapper itdmJCXMSHJHMapper;
    @Autowired
    @SuppressWarnings("all")
    private ItdmDeviceMapper itdmDeviceMapper;
    @Autowired
    @SuppressWarnings("all")
    private ItdmWeituoInfoMapper itdmWeituoInfoMapper;
    @Autowired
    @SuppressWarnings("all")
    private ItdmWeituoYangpinMapper itdmWeituoYangpinMapper;
    @Autowired
    @SuppressWarnings("all")
    private ItdmTestPlanMapper itdmTestPlanMapper;
    @Autowired
    @SuppressWarnings("all")
    private ItdmGongdanMasterMapper itdmGongdanMasterMapper;
    @Autowired
    @SuppressWarnings("all")
    private ItdmGongdanDetailMapper itdmGongdanDetailMapper;
    @Autowired
    @SuppressWarnings("all")
    private ItdmTaskMapper taskMapper;
    @Autowired
    @SuppressWarnings("all")
    private IItdmTaskService taskService;
    @Autowired
    @SuppressWarnings("all")
    private IItdmDeviceService deviceService;

    /**
     *   删除2级工单master+对应的工单detail
     */
    public String deleteByGongdanMasterId(String id){
        ItdmGongdanMaster master = itdmGongdanMasterMapper.selectById(id);
        if(master.getShijiStartDate()==null) {//此时可以删除
            itdmGongdanMasterMapper.deleteById(id);

            //然后删原来的工单detail
            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("wo_id",id);
            itdmGongdanDetailMapper.deleteByMap(columnMap);

            if(master.getWorker()!=null){
                Map<String, Object> map = new HashMap<>();
                map.put("jihua_shiyan_id",master.getJihuaShiyanId());
                List<ItdmGongdanMaster> masterList = itdmGongdanMasterMapper.selectByMap(map);
                int num =0;
                for (ItdmGongdanMaster m: masterList){
                    if (m.getWorker().equals(master.getWorker())) num++;
                }
//                if(num==0){ //没有该操作员的任务了，删掉对应委托id和对应操作员的task
//                    ItdmTestPlan plan = itdmTestPlanMapper.selectById(master.getJihuaShiyanId());
//                    Map<String, Object> taskMap = new HashMap<>();
//                    taskMap.put("task_role","操作员");
//                    taskMap.put("task_user",master.getWorker());
//                    taskMap.put("weituo_id",plan.getWeituoId());
//                    taskMapper.deleteByMap(taskMap);
//                }
            }

            return "删除成功!";
        }else  return "不可删除！";
    }


    /**
     * 项目经理新增或修改试工单master
     */
    public String XMJLAddOrUpdate(ItdmXMJLAddOrUpdateDTO dto){
        String msg = "操作成功！";

        String[] arr = dto.getChuanganqiArray();
        String chuanganqi = "";
        for (int i = 0; i < arr.length; i++) {
            if(i==0) chuanganqi = arr[i];
            else chuanganqi = chuanganqi + ","+ arr[i];
        }
        dto.setChuanganqi(chuanganqi);

        if(dto.getParent()!=null){ //二级，先根据id查询工单master，判断有无该对象存在，无的话为新增，有的话修改(项目经理不可修改一级)
            ItdmGongdanMaster gongdanMaster = itdmGongdanMasterMapper.selectById(dto.getId());

            if(gongdanMaster==null){//是新增的数据
                ItdmGongdanMaster itdmGongdanMaster = ItdmXMJLAddOrUpdateDTO.toItdmGongdanMaster(dto);
                itdmGongdanMasterMapper.insert(itdmGongdanMaster);//新增一条工单master
                System.out.println("======================================项目经理新增master" + itdmGongdanMaster.getId());

                //修改工单master对应的试验计划，将状态改为已确认
                ItdmTestPlan itdmTestPlan = itdmTestPlanMapper.selectById(dto.getParent());
                itdmTestPlan.setStatus(1);
                itdmTestPlanMapper.updateById(itdmTestPlan);

                Date startDate = dto.getJihuaStartDate();
                int lastDay = dto.getLastTime();
                for (int i=1;i<=lastDay;i++){
                    Date workDate = new Date(startDate.getTime() + (i-1)*1000*3600*24);
                    ItdmGongdanDetail detail = new ItdmGongdanDetail();
                    detail.setWoId(itdmGongdanMaster.getId());
                    detail.setWorkDate(workDate);
                    detail.setStartTime("00:00");
                    detail.setEndTime("23:59");
                    detail.setChuanganqi(dto.getChuanganqi());
                    detail.setJihuaDeviceId(itdmGongdanMaster.getShebeiId());
                    itdmGongdanDetailMapper.insert(detail);//新增对应日期的工单detail
                }

                //修改项目经理拆解工单task状态为1进行中——需要先判断
                Map<String, Object> testPlanMap = new HashMap<>();
                testPlanMap.put("weituo_id",dto.getWeituoId());
                testPlanMap.put("pm",dto.getPm());
                testPlanMap.put("status",0); //未确认
                List<ItdmTestPlan> testPlanList = itdmTestPlanMapper.selectByMap(testPlanMap);
                if(testPlanList == null || testPlanList.isEmpty() || testPlanList.get(0)==null){ //都已确认
                    Map<String, Object> columnMap = new HashMap<>();
                    columnMap.put("task_role",GlobalVariables.xmjl);//"项目经理"
                    columnMap.put("weituo_id",dto.getWeituoId());
                    columnMap.put("task_user",dto.getPm());
                    List<ItdmTask> taskList = taskMapper.selectByMap(columnMap);
                    if(taskList != null && !taskList.isEmpty() && taskList.get(0)!=null) {
                        ItdmTask itdmTask1 = taskList.get(0);
                        itdmTask1.setTaskStatus(1);
                        taskMapper.updateById(itdmTask1);
                    }
                }
            }else {//非空，是用于修改的数据——先判断能否修改
                if(dto.getShijiStartDate()==null){//此时可以修改

                    //先修改工单master
                    ItdmGongdanMaster itdmGongdanMaster = ItdmXMJLAddOrUpdateDTO.toItdmGongdanMaster(dto);
                    itdmGongdanMaster.setId(dto.getId());
                    itdmGongdanMasterMapper.updateById(itdmGongdanMaster);
                    System.out.println("======================================项目经理修改master" + dto.getId());

                    //修改工单master对应的试验计划，将状态改为已确认
                    ItdmTestPlan itdmTestPlan = itdmTestPlanMapper.selectById(dto.getParent());
                    itdmTestPlan.setStatus(1);
                    itdmTestPlanMapper.updateById(itdmTestPlan);

                    //然后删原来的工单detail
                    ItdmGongdanDetail itdmGongdanDetail = new ItdmGongdanDetail();
                    itdmGongdanDetail.setWoId(dto.getId());
                    QueryWrapper<ItdmGongdanDetail> wrapper = new QueryWrapper<>(itdmGongdanDetail);
                    itdmGongdanDetailMapper.delete(wrapper);

                    //再拆成工单detail，再插入新的工单detail
                    Date startDate = dto.getJihuaStartDate();
                    int lastDay = dto.getLastTime();
                    for (int i=1;i<=lastDay;i++){
                        Date workDate = new Date(startDate.getTime() + (i-1)*1000*3600*24);
                        ItdmGongdanDetail detail = new ItdmGongdanDetail();
                        detail.setWoId(dto.getId());
                        detail.setWorkDate(workDate);
                        detail.setStartTime("00:00");
                        detail.setEndTime("23:59");
                        detail.setChuanganqi(dto.getChuanganqi());
                        detail.setJihuaDeviceId(itdmGongdanMaster.getShebeiId());
                        itdmGongdanDetailMapper.insert(detail);//新增对应日期的工单detail
                    }

                    //修改项目经理拆解工单task状态为1进行中——需要先判断
                    Map<String, Object> testPlanMap = new HashMap<>();
                    testPlanMap.put("weituo_id",dto.getWeituoId());
                    testPlanMap.put("pm",dto.getPm());
                    testPlanMap.put("status",0);//未确认状态
                    List<ItdmTestPlan> testPlanList = itdmTestPlanMapper.selectByMap(testPlanMap);
                    if(testPlanList == null || testPlanList.isEmpty() || testPlanList.get(0)==null){ //都已确认
                        Map<String, Object> map = new HashMap<>();
                        map.put("task_role",GlobalVariables.xmjl);//"项目经理"
                        map.put("weituo_id",dto.getWeituoId());
                        map.put("task_user",dto.getPm());
                        List<ItdmTask> tList = taskMapper.selectByMap(map);
                        if(tList != null && !tList.isEmpty() && tList.get(0)!=null){
                            ItdmTask itdmTask1 = tList.get(0);
                            itdmTask1.setTaskStatus(1);
                            taskMapper.updateById(itdmTask1);
                        }
                    }
                }else msg="不可修改！";
            }
        }
        return msg;
    }

    /**
     * 项目经理查询列表——一级列表
     */
    public List<ItdmXMJLQueryListVO> getXMJLFirstList(String weituoNo){
        String weituoId = itdmWeituoInfoMapper.selectByWeituoNo(weituoNo);
        List<ItdmXMJLQueryListVO> list1 = itdmJCXMSHJHMapper.getXMJLFirstList(weituoId);
        List<ItdmXMJLQueryListVO> list2 = list1.stream().map(i -> {
            String deviceName = "";
            if(i.getShebeiId()!=null && !i.getShebeiId().equals("")){
                deviceName = deviceService.queryNameByIdList(i.getShebeiId());
            }
            return ItdmXMJLQueryListVO.toItdmXMJLQueryListVO1(i,weituoNo,deviceName);
        }).collect(Collectors.toList());
        return list2;
    }

    /**
     * 项目经理查询列表——二级列表
     */
    public List<ItdmXMJLQueryListVO> getXMJLSecondList(String weituoNo){
        String weituoId = itdmWeituoInfoMapper.selectByWeituoNo(weituoNo);
        List<ItdmXMJLQueryListVO> list1 = itdmJCXMSHJHMapper.getXMJLSecondList(weituoId);
        List<ItdmXMJLQueryListVO> list2 = list1.stream().map(i->
                ItdmXMJLQueryListVO.toItdmXMJLQueryListVO2(i,weituoNo)).collect(Collectors.toList());
        return list2;
    }

    /**
     * 计划员新增或修改试验计划——231130——改设备为多选
     */
    public String JHYAddAndUpdate(@RequestBody ItdmJHYAddOrUpdateDTO dto){
        String msg = "提交成功！";

        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String realName = loginUser.getRealname(); // 登录人姓名

        ItdmTestPlan itdmTestPlan = ItdmJHYAddOrUpdateDTO.toItdmTestPlan(dto);
        if(dto.getTestPlanId()==null){ //新增试验计划
            itdmTestPlan.setStatus(0);//试验计划初始状态为未确认0
            itdmTestPlanMapper.insert(itdmTestPlan);
            dto.setTestPlanId(itdmTestPlan.getId());
            //同时新增一条一样的工单master
            ItdmGongdanMaster master = ItdmJHYAddOrUpdateDTO.toItdmGongdanMaster(dto);
            itdmGongdanMasterMapper.insert(master);
            System.out.println("======================================计划员新增试验计划新增master" + master.getId());
            //再拆成工单detail，再插入新的工单detail
            Date startDate = dto.getJihuaStartDate();
            int lastDay = dto.getLastTime();
            for (int i=1;i<=lastDay;i++){
                Date workDate = new Date(startDate.getTime() + (i-1)*1000*3600*24);
                ItdmGongdanDetail detail = new ItdmGongdanDetail();
                detail.setWoId(master.getId());
                detail.setWorkDate(workDate);
                detail.setStartTime("00:00");
                detail.setEndTime("23:59");
                detail.setChuanganqi(dto.getChuanganqi());
                detail.setJihuaDeviceId(master.getShebeiId());
                itdmGongdanDetailMapper.insert(detail);
            }
            //新增该pm的项目经理拆解工单的task
            ItdmTask itdmTask = new ItdmTask();
            itdmTask.setTaskRole(GlobalVariables.xmjl);//"项目经理"
            itdmTask.setTaskUser(dto.getPm());
            itdmTask.setWeituoId(dto.getWeituoId());
            itdmTask.setTaskContent("拆解工单");
            itdmTask.setTaskStatus(0);//待办
            taskService.insertTaskAfterJudge(itdmTask);


            //修改计划员计划排期task状态为1进行中
            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("task_role",GlobalVariables.jhy);//"计划员"
            columnMap.put("weituo_id",dto.getWeituoId());
            columnMap.put("task_user",realName);
            List<ItdmTask> taskList = taskMapper.selectByMap(columnMap);
            if(!taskList.isEmpty()) {
                ItdmTask itdmTask1 = taskList.get(0);
                itdmTask1.setTaskStatus(1);
                taskMapper.updateById(itdmTask1);
            }

            //删除该委托其他计划员计划排期task
            Map<String, Object> deleteMap = new HashMap<>();
            deleteMap.put("task_role", GlobalVariables.jhy);//”计划员“
            columnMap.put("weituo_id", dto.getWeituoId());
            deleteMap.put("task_status",0);
            taskService.removeByMap(deleteMap);

        }else if(dto.getStatus() == 0){//状态为“未确定”，可以修改试验计划

            QueryWrapper<ItdmTestPlan> planWrapper = new QueryWrapper<>();
            planWrapper.eq("id",dto.getTestPlanId());
            ItdmTestPlan plan = itdmTestPlanMapper.selectOne(planWrapper);//原计划试验对象

            itdmTestPlan.setId(dto.getTestPlanId());
            itdmTestPlanMapper.updateById(itdmTestPlan);//修改试验计划

            //先判断有没有改项目经理
            String pmplan = plan.getPm(); //原来的
            String pmVO = dto.getPm(); // 此次的
            if(pmplan==null){ //原来的为空，此次不为空
                //查原来该委托id，项目经理，新pm的task
                ItdmTask nItdmTask = new ItdmTask();
                nItdmTask.setTaskUser(pmVO);
                nItdmTask.setWeituoId(dto.getWeituoId());
                nItdmTask.setTaskRole(GlobalVariables.xmjl);//"项目经理"
                nItdmTask.setTaskContent("拆解工单");
                nItdmTask.setTaskStatus(0);
                taskService.insertTaskAfterJudge(nItdmTask);
            }else if(pmplan!=null && !pmplan.equals(pmVO)){  //改了：
                QueryWrapper<ItdmTestPlan> planWrapper1 = new QueryWrapper<>();
                planWrapper1.eq("weituo_id",dto.getWeituoId());
                planWrapper1.eq("pm",pmplan); //原来的
                List<ItdmTestPlan> testPlanList = itdmTestPlanMapper.selectList(planWrapper1);
                if(testPlanList.isEmpty()){
                    //该委托id、原pm对应试验计划列表若为空删除原pm、项目经理、委托id对应的task
                    QueryWrapper<ItdmTask> taskWrapper = new QueryWrapper<>();
                    taskWrapper.eq("weituo_id",dto.getWeituoId());
                    taskWrapper.eq("task_role",GlobalVariables.xmjl);//"项目经理"
                    taskWrapper.eq("task_user",plan.getPm());
                    taskMapper.delete(taskWrapper);
                }

                //查原来该委托id，项目经理，新pm的task
                ItdmTask nItdmTask = new ItdmTask();
                nItdmTask.setTaskUser(dto.getPm());
                nItdmTask.setWeituoId(dto.getWeituoId());
                nItdmTask.setTaskRole(GlobalVariables.xmjl);//"项目经理"
                nItdmTask.setTaskContent("拆解工单");
                nItdmTask.setTaskStatus(0);
                taskService.insertTaskAfterJudge(nItdmTask);
            }

            //查原来的工单master
            Map<String, Object> masterMap = new HashMap<>();
            masterMap.put("jihua_shiyan_id",itdmTestPlan.getId());
            List<ItdmGongdanMaster> masterList = itdmGongdanMasterMapper.selectByMap(masterMap);
            //删原来的工单master
            itdmGongdanMasterMapper.deleteByMap(masterMap);
            //删掉原来的工单detail
            if(masterList != null && !masterList.isEmpty() && masterList.get(0)!=null){
                for (ItdmGongdanMaster m: masterList){
                    Map<String, Object> detailMap = new HashMap<>();
                    detailMap.put("wo_id",m.getId());
                    itdmGongdanDetailMapper.deleteByMap(detailMap);
                }
            }

            //新增一条一样的工单master
            ItdmGongdanMaster master = ItdmJHYAddOrUpdateDTO.toItdmGongdanMaster(dto);
            itdmGongdanMasterMapper.insert(master);
            System.out.println("======================================计划员修改试验计划新增master" + master.getId());
            //再拆成工单detail，再插入新的工单detail
            Date startDate = dto.getJihuaStartDate();
            int lastDay = dto.getLastTime();
            for (int i=1;i<=lastDay;i++){
                Date workDate = new Date(startDate.getTime() + (i-1)*1000*3600*24);
                ItdmGongdanDetail detail = new ItdmGongdanDetail();
                detail.setWoId(master.getId());
                detail.setWorkDate(workDate);
                detail.setStartTime("00:00");
                detail.setEndTime("23:59");
                detail.setChuanganqi(dto.getChuanganqi());
                detail.setJihuaDeviceId(master.getShebeiId());
                itdmGongdanDetailMapper.insert(detail);
            }
        }else if(dto.getStatus() != 0){
            if(msg.equals("提交成功！")) msg="检测项目"+ dto.getTestItems();
            else msg=msg+ "和"+ dto.getTestItems();
        }
        if(msg.equals("提交成功！")) return msg;
        else return msg+"状态已确定或完成，无法修改！";
    }

    /**
     * 计划员查询列表
     */
    public List<ItdmJHYQueryListVO> getAll3(String weituoNo){
        if(weituoNo!=null){
            String weituoId = itdmWeituoInfoMapper.selectByWeituoNo(weituoNo);
            List<ItdmJHYQueryListVO> list = itdmJCXMSHJHMapper.getAll3(weituoId);
            List<ItdmJHYQueryListVO> list1 = list.stream().map(i -> {
                String testPlanId = i.getTestPlanId();
                ShijiDate shijiDate = itdmGongdanMasterMapper.getShijiDateByTestPlanId(testPlanId);

                String jhpqStatus = "0"; //0未完成1已完成
                List<ItdmGongdanMaster> shijiEndList = itdmGongdanMasterMapper.getShijiEndDateListByTestPlanId(testPlanId);
                if(shijiEndList==null || shijiEndList.isEmpty()) jhpqStatus="1"; //已完成

                String deviceName = "";
                if(i.getShebeiId()!=null && !i.getShebeiId().equals("")){
                    deviceName = deviceService.queryNameByIdList(i.getShebeiId());
                }

                return ItdmJHYQueryListVO.toItdmJHYQueryListVO3(i,weituoNo,shijiDate,jhpqStatus,deviceName);
            }).collect(Collectors.toList());
            return list1;
        }else {
            List<ItdmJHYQueryListVO> list = itdmJCXMSHJHMapper.getAllWithoutWeituoId();
            List<ItdmJHYQueryListVO> list1 = list.stream().map(i -> {
                String weituoNo1 = itdmWeituoInfoMapper.selectById(i.getWeituoId()).getWeituoNo();
                String testPlanId = i.getTestPlanId();
                ShijiDate shijiDate = itdmGongdanMasterMapper.getShijiDateByTestPlanId(testPlanId);

                String jhpqStatus = "0"; //0未完成1已完成
                List<ItdmGongdanMaster> shijiEndList = itdmGongdanMasterMapper.getShijiEndDateListByTestPlanId(testPlanId);
                if(shijiEndList==null || shijiEndList.isEmpty()) jhpqStatus="1"; //已完成

                String deviceName = "";
                if(i.getShebeiId()!=null && !i.getShebeiId().equals("")){
                    deviceName = deviceService.queryNameByIdList(i.getShebeiId());
                }

                return ItdmJHYQueryListVO.toItdmJHYQueryListVO3(i,weituoNo1,shijiDate,jhpqStatus,deviceName);
            }).collect(Collectors.toList());
            return list1;
        }

    }

    /**
     * 项目经理查询列表——一级列表——通过登录用户查询
     */
    public List<ItdmXMJLQueryListVO> getXMJLFirstListByUserName(String weituoNo,String realName){
        String weituoId = itdmWeituoInfoMapper.selectByWeituoNo(weituoNo);
        List<ItdmXMJLQueryListVO> list1 = itdmJCXMSHJHMapper.getXMJLFirstListByUserName(weituoId,realName);
        List<ItdmXMJLQueryListVO> list2 = list1.stream().map(i->{
                    String deviceName = "";
                    if(i.getShebeiId()!=null && !i.getShebeiId().equals("")){
                        deviceName = deviceService.queryNameByIdList(i.getShebeiId());
                    }
                    return ItdmXMJLQueryListVO.toItdmXMJLQueryListVO1(i,weituoNo,deviceName);
        }).collect(Collectors.toList());
        return list2;
    }
    /**
     * 项目经理查询列表——二级列表——通过登录用户查询
     */
    public List<ItdmXMJLQueryListVO> getXMJLSecondListByUserName(String weituoNo,String realName){
        String weituoId = itdmWeituoInfoMapper.selectByWeituoNo(weituoNo);
        List<ItdmXMJLQueryListVO> list1 = itdmJCXMSHJHMapper.getXMJLSecondListByUserName(weituoId,realName);
        List<ItdmXMJLQueryListVO> list2 = list1.stream().map(i->
                ItdmXMJLQueryListVO.toItdmXMJLQueryListVO2(i,weituoNo)).collect(Collectors.toList());
        return list2;
    }

}
