package com.example.removetolocal.service.impl;

import com.example.removetolocal.newdevice.dao.DeviceLibraryDao;
import com.example.removetolocal.newdevice.dao.PackingLibraryDao;
import com.example.removetolocal.newdevice.domin.DeviceLibrary;
import com.example.removetolocal.newdevice.domin.PackingLibrary;
import com.example.removetolocal.newrepel.dao.DeviceRepelDao;
import com.example.removetolocal.newrepel.dao.DeviceRepelDetailDao;
import com.example.removetolocal.newrepel.dao.RepelDeviceUnitDao;
import com.example.removetolocal.newrepel.dao.RepelTaskStatisticalDao;
import com.example.removetolocal.newrepel.entity.DeviceRepel;
import com.example.removetolocal.newrepel.entity.DeviceRepelDetail;
import com.example.removetolocal.newrepel.entity.RepelTaskStatistical;
import com.example.removetolocal.newstorage.bto.TaskBto;
import com.example.removetolocal.newstorage.dao.TaskDao;
import com.example.removetolocal.newstorage.dao.TaskLogDao;
import com.example.removetolocal.newstorage.entity.Task;
import com.example.removetolocal.newstorage.entity.TaskLog;
import com.example.removetolocal.newuser.domin.Units;
import com.example.removetolocal.newuser.domin.User;
import com.example.removetolocal.oldentity.DevTasklog;
import com.example.removetolocal.oldentity.DevTaskmain;
import com.example.removetolocal.oldentity.dao.DevTasklogDao;
import com.example.removetolocal.oldentity.dao.DevTaskmainDao;
import com.example.removetolocal.oldentity.dao.DevTaskoperaterDao;
import com.example.removetolocal.oldrepel.dao.DevScrapDao;
import com.example.removetolocal.oldrepel.dao.DevScrapDetailDao;
import com.example.removetolocal.oldrepel.dao.DevScrapnoticeDao;
import com.example.removetolocal.oldrepel.dao.DevScrapnoticeUnitDao;
import com.example.removetolocal.oldrepel.entity.DevScrap;
import com.example.removetolocal.oldrepel.entity.DevScrapnoticeUnit;
import com.example.removetolocal.oldrepel.entity.vo.ModelCount;
import com.example.removetolocal.service.RepelService;
import com.example.removetolocal.service.UserService;
import com.example.removetolocal.utils.JacksonUtil;
import com.example.removetolocal.utils.StringUtils;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author zjm
 * @Description 清退
 * @Date 2021/2/27 下午3:58
 * @Version 1.0
 */
@Service
@Slf4j
public class RepelServiceImpl implements RepelService {
    //新数据库的表结构 Dao
    @Autowired
    DeviceRepelDao deviceRepelDao;

    @Autowired
    DeviceRepelDetailDao deviceRepelDetailDao;

    @Autowired
    RepelDeviceUnitDao repelDeviceUnitDao;

    @Autowired
    RepelTaskStatisticalDao repelTaskStatisticalDao;

    //原数据表结构  dao
    @Autowired
    DevScrapDao devScrapDao;

    @Autowired
    DevScrapDetailDao devScrapDetailDao;

    @Autowired
    DevScrapnoticeDao devScrapnoticeDao;

    @Autowired
    DevScrapnoticeUnitDao devScrapnoticeUnitDao;


    //task
    @Autowired
    DevTaskmainDao devTaskmainDao;
    @Autowired
    DevTaskoperaterDao devTaskoperaterDao;
    @Autowired
    TaskDao taskDao;
    @Autowired
    DevTasklogDao devTasklogDao;
    @Autowired
    TaskLogDao taskLogDao;

    @Autowired
    DeviceLibraryDao deviceLibraryDao;

    @Autowired
    PackingLibraryDao packingLibraryDao;

    @Autowired
    UserService userService;

    @Override
    public void repelDataConversion() {

        devScrapnoticeDao.findAll().stream().filter(devScrapnotice -> devScrapnotice.getStatus()==3).forEach(
                devScrapnotice -> {
                DeviceRepel deviceRepel1= devScrapnotice.toDeviceRepel();
                deviceRepel1.setUnitName(userService.getUnitNameByOldId(devScrapnotice.getApplyUnit()));
                List<Integer> integers = StringUtils.stringToList(devScrapnotice.getCatalogIds());
                List<PackingLibrary> packingLibraries= packingLibraryDao.findAllByOldIdIn(integers);
                deviceRepel1.setFielding(StringUtils.ListToString(packingLibraries.stream().map(PackingLibrary::getId).collect(Collectors.toList())));
                DeviceRepel deviceRepel=deviceRepelDao.save(deviceRepel1);
                Task taskBto1= toTask27(devScrapnotice.getId(),deviceRepel.getId());
                Map<String,Integer> map=new HashMap<>();
                packingLibraries.forEach(
                        packingLibrary -> {
                            map.put(packingLibrary.getModel(),0);
                        }
                );
                List<DevScrapnoticeUnit> devScrapnoticeUnitList= devScrapnoticeUnitDao.findAllByNoticeId(devScrapnotice.getId());
                List<RepelTaskStatistical> list=new ArrayList<>();
                devScrapnoticeUnitList.stream().filter(devScrapnoticeUnit -> devScrapnoticeUnit.getStatus()==4).forEach(
                        devScrapnoticeUnit -> {
                            List<DevScrap> devScraps= devScrapDao.findAllByNoticeIdAndStatus(devScrapnoticeUnit.getId(),4);
                            if (devScraps.size()==0){
                                return;
                            }
                            DevScrap devScrap = devScraps.get(0);
                           //发起单位
                            if (devScrap.getApplyUnit()== null){
                                log.info("{},ApplyUnit数据为空",devScrap.getId());
                                return;
                            }
                            if (devScrap.getHandleUnit()== null){
                                log.info("{},HandleUnit数据为空",devScrap.getId());
                                return;
                            }
                            if (devScrap.getApplyUser()== null){
                                log.info("{},ApplyUser数据为空",devScrap.getId());
                                return;
                            }
                            if (devScrap.getHandleUser()== null){
                                log.info("{},HandleUser数据为空",devScrap.getId());
                                return;
                            }

                           Units unit1=userService.getUnitByOldId(devScrap.getApplyUnit());
                           //收件单位
                           Units unit2=userService.getUnitByOldId(devScrap.getHandleUnit());
                           //发起人
                           User user1=userService.getUserByOldId(devScrap.getApplyUser());
                           //接受人
                           User user2=userService.getUserByOldId(devScrap.getHandleUser());
                           //发起确认人
                           User userConfirm1=userService.getUserByOldId(devScrap.getApplyConfirmUser());
                            //接受确认人
                           User userConfirm2=userService.getUserByOldId(devScrap.getHandleConfirmUser());

                            DeviceRepelDetail deviceRepelDetail=devScrap.toDeviceRepelDetail();
                            List<Integer> idList=new ArrayList<>();
                            if (devScrapnoticeUnit.getDevIds()!=null&&devScrapnoticeUnit.getDevIds().equals("")){
                               List<DeviceLibrary> deviceLibraries= deviceLibraryDao.findAllByOldIdIn(StringUtils.stringToList(","+devScrapnoticeUnit.getDevIds()));
                               deviceLibraries.forEach(
                                       deviceLibrary -> {
                                           if (map.containsKey(deviceLibrary.getModel())){
                                               map.put(deviceLibrary.getModel(),map.get(deviceLibrary.getModel()+1));
                                           }else {
                                               log.info("没找到对应的类型:{}",deviceLibrary.getId());
                                           }
                                           idList.add(deviceLibrary.getId());
                                       }
                               );
                            }
                            List<ModelCount> modelCounts=new ArrayList<>();
                           for (String key:map.keySet()){
                                modelCounts.add(new ModelCount(key,map.get(key)));
                           }
                           deviceRepelDetail.setSubmitDescription(devScrapnoticeUnit.getOpinion());
                           deviceRepelDetail.setDeviceIds(StringUtils.ListToString(idList));
                           deviceRepelDetail.setRepelId(deviceRepel.getId());
                           deviceRepelDetail.setSendUnit(unit1.getName());
                           deviceRepelDetail.setSendUnitId(unit1.getUnitId());
                           deviceRepelDetail.setReceiveUnit(unit2.getName());
                           deviceRepelDetail.setReceiveUnitId(unit2.getUnitId());
                           deviceRepelDetail.setSendUserAId(user1.getUserId());
                           deviceRepelDetail.setSendUserAName(user1.getName());
                           deviceRepelDetail.setSendUserBId(userConfirm1.getUserId());
                           deviceRepelDetail.setSendUserBName(userConfirm1.getName());

                            deviceRepelDetail.setReceiveUserAId(user2.getUserId());
                            deviceRepelDetail.setReceiveUserAName(user2.getName());
                            deviceRepelDetail.setReceiveUserBName(userConfirm2.getName());
                            deviceRepelDetail.setReceiveUserBId(userConfirm2.getUserId());
                            deviceRepelDetail= deviceRepelDetailDao.save(deviceRepelDetail);
                            Task taskBto= toTask26(devScrap.getId(),deviceRepelDetail.getId());
                            list.add(new RepelTaskStatistical(deviceRepel.getId(), taskBto1.getId(), taskBto.getId(), 1, unit1.getName(), JacksonUtil.toJSon(modelCounts), ""));
                        }
                );
                    repelTaskStatisticalDao.saveAll(list);
                }

        );

    }

    private Task toTask26(Integer id1,Integer id2){
        //task转换
        DevTaskmain devTaskmain = devTaskmainDao.findByTypeAndResourceId(26,id1);
        if (devTaskmain.getIsComplete()==1||devTaskmain.getIsSeal()==1) {
            TaskBto taskBto = devTaskmain.parseToTaskBto();
            taskBto.setBillId(id2);
            taskBto.setOldId(devTaskmain.getId());
            Task task = taskDao.save(taskBto.toDo());
            //添加业务日志
            List<DevTasklog> devTasklogs = devTasklogDao.findAllByTaskId(devTaskmain.getId());
            devTasklogs.forEach(devTasklog -> {
                TaskLog taskLog = new TaskLog();
                taskLog.setCreateTime(devTasklog.getOperateTime());
                taskLog.setCreateUserId(userService.getUserByOldId(devTasklog.getOperater()).getUserId());
                taskLog.setUpdateTime(taskLog.getCreateTime());
                taskLog.setUpdateUserId(taskLog.getCreateUserId());
                taskLog.setFileDetail("Ǵ");
                taskLog.setRemark(devTasklog.getNote());
                taskLog.setTaskId(task.getId());
                taskLog.setOldId(devTasklog.getId());
                taskLogDao.save(taskLog);
            });
            return task;
        }
        return new Task();
    }

    private Task toTask27(Integer id1,Integer id2){
        //task转换
        DevTaskmain devTaskmain = devTaskmainDao.findByTypeAndResourceId(25,id1);
        if (devTaskmain.getIsComplete()==1||devTaskmain.getIsSeal()==1) {
            TaskBto taskBto = devTaskmain.parseToTaskBto();
            taskBto.setBillId(id2);
            taskBto.setOldId(devTaskmain.getId());
            Task task = taskDao.save(taskBto.toDo());
            //添加业务日志
            List<DevTasklog> devTasklogs = devTasklogDao.findAllByTaskId(devTaskmain.getId());
            devTasklogs.forEach(devTasklog -> {
                TaskLog taskLog = new TaskLog();
                taskLog.setCreateTime(devTasklog.getOperateTime());
                taskLog.setCreateUserId(userService.getUserByOldId(devTasklog.getOperater()).getUserId());
                taskLog.setUpdateTime(taskLog.getCreateTime());
                taskLog.setUpdateUserId(taskLog.getCreateUserId());
                taskLog.setFileDetail("Ǵ");
                taskLog.setRemark(devTasklog.getNote());
                taskLog.setTaskId(task.getId());
                taskLog.setOldId(devTasklog.getId());
                taskLogDao.save(taskLog);
            });
            return task;
        }
        return new Task();
    }

}
