package org.linlinjava.jz.db.service.hm;

import com.google.common.collect.Lists;
import org.linlinjava.jz.db.dao.HmEmployTaskSetMapper;
import org.linlinjava.jz.db.dao.HmTaskCategoryMapper;
import org.linlinjava.jz.db.dao.HmTaskItemMapper;
import org.linlinjava.jz.db.domain.*;
import org.linlinjava.jz.db.dto.hm.HmSetTaskItemDTO;
import org.linlinjava.jz.db.dto.hm.HmSetTaskItemDTO.Item;
import org.linlinjava.jz.db.dto.hm.HmSetTaskItemDTO.TaskItem;
import org.linlinjava.jz.db.dto.hm.calendar.CalendarDto;
import org.linlinjava.jz.db.service.ContractSubTemplateService;
import org.linlinjava.jz.db.util.HmResponseUtil;
import org.linlinjava.jz.db.util.hm.CalendarUtil;
import org.linlinjava.jz.db.util.hm.HmButlerTaskLogContans;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fuxubing
 */
@Service
public class HmEmployTaskSetService {
    @Resource
    private HmEmployTaskSetMapper hmEmployTaskSetMapper;
    @Resource
    private HmTaskCategoryMapper hmTaskCategoryMapper;
    @Resource
    private HmTaskItemMapper hmTaskItemMapper;
    @Resource
    private HmEmployRelationService hmEmployRelationService;
    @Resource
    private ContractSubTemplateService contractSubTemplateService;
    @Resource
    private HmButlerTaskChildService hmButlerTaskChildService;

    public Map<String, Object> queryGroupByTaskType(String orderNo) {
        // 每日任务
        List<Map<String, Object>> dayTask = getDiffTypeTask(orderNo, 1);
        // 每周任务
        List<Map<String, Object>> weekTask = getDiffTypeTask(orderNo, 2);
        // 每月任务
        List<Map<String, Object>> monthTask = getDiffTypeTask(orderNo, 3);
        Map<String, Object> map = new HashMap<>(16);
        map.put("dayTask", dayTask);
        map.put("weekTask", weekTask);
        map.put("monthTask", monthTask);
        return map;
    }

    public List<Map<String, Object>> getDiffTypeTask(String orderNo, Integer taskType) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Map<String, Object>> maps = hmEmployTaskSetMapper.queryGroupByTaskType(orderNo, taskType);
        maps.forEach(item -> {
            HmTaskCategory hmTaskCategory = hmTaskCategoryMapper.selectByPrimaryKey((Long) item.get("category_id"));
            String itemId = item.get("item_id").toString();
            String[] split = itemId.split(",");
            StringBuilder itemName = new StringBuilder();
            for (String s : split) {
                HmTaskItem hmTaskItem = hmTaskItemMapper.selectByPrimaryKey(Long.parseLong(s));
                itemName.append(hmTaskItem.getItemName()).append(",");
            }
            Map<String, Object> map = new HashMap<>(16);
            map.put("categoryId", hmTaskCategory.getId());
            map.put("categoryName", hmTaskCategory.getCategoryName());
            map.put("items", itemName.deleteCharAt(itemName.length() - 1));
            map.put("itemIds", itemId);
            mapList.add(map);
        });

        return mapList;
    }

    public List<Map<String, Object>> selectChooseTaskItem(String orderNo, int taskType) {
        List<Map<String, Object>> list = Lists.newArrayList();
        HmTaskCategoryExample example = new HmTaskCategoryExample();
        example.or().andDisabledEqualTo(false);
        List<HmTaskCategory> taskCategories = hmTaskCategoryMapper.selectByExample(example);

        for (HmTaskCategory taskCategory : taskCategories) {
            Map<String, Object> map = new HashMap<>(16);
            List<Map<String, Object>> maps = hmEmployTaskSetMapper.selectByOrderNoAndCategory(orderNo,
                    taskCategory.getId(), taskType);
            map.put("categoryId", taskCategory.getId());
            map.put("categoryName", taskCategory.getCategoryName());
            map.put("TaskItems", maps);

            int ct = 0;
            for (Map<String, Object> m : maps) {
                if (m.get("choose").toString().equals("1")) {
                    ct++;
                }
            }

            map.put("chooseSize", ct);
            list.add(map);
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    public void setTask(String orderNo, HmSetTaskItemDTO hmSetTaskItemDTO) {
        // 如果已设置任务，删除重新设
        deleteByOrderNo(orderNo, hmSetTaskItemDTO.getTaskType());
        // 要刪除同订单下面的 相同的任务子类
        List<TaskItem> taskItems2 = hmSetTaskItemDTO.getTaskItems();
        taskItems2.forEach(e -> {
            List<Item> item = e.getItemIds();
            for (Item i : item) {
            	//选中才执行
            	if(i.getChoose().equals(1)) {
            		HmEmployTaskSetExample example = new HmEmployTaskSetExample();
            		example.or().andOrderNoEqualTo(orderNo)
//                .andTaskTypeEqualTo(hmSetTaskItemDTO.getTaskType())
//                .andCategoryIdEqualTo(e.getCategoryId())
            		.andItemIdEqualTo(i.getItemId());
            		hmEmployTaskSetMapper.deleteByExample(example);
            	}
            }
        });

        List<HmSetTaskItemDTO.TaskItem> taskItems = hmSetTaskItemDTO.getTaskItems();
        for (HmSetTaskItemDTO.TaskItem taskItem : taskItems) {
            for (HmSetTaskItemDTO.Item item : taskItem.getItemIds()) {
                if (item.getChoose() == 1) {
                    HmEmployTaskSet hmEmployTaskSet = new HmEmployTaskSet();
                    hmEmployTaskSet.setOrderNo(orderNo);
                    hmEmployTaskSet.setTaskType(hmSetTaskItemDTO.getTaskType());
                    hmEmployTaskSet.setEmployRelationId(hmEmployRelationService.queryByOrderNo(orderNo).getId());
                    hmEmployTaskSet.setCategoryId(taskItem.getCategoryId());
                    hmEmployTaskSet.setItemId(item.getItemId());
                    hmEmployTaskSet.setCreateTime(LocalDateTime.now());
                    hmEmployTaskSet.setUpdateTime(LocalDateTime.now());

                    hmEmployTaskSetMapper.insertSelective(hmEmployTaskSet);
                }
            }
        }

        // 如果有跟进类taskchildid，要加记录
        if (null != hmSetTaskItemDTO.getChildTaskId()) {
            String operateContent = HmButlerTaskLogContans.TASK_LOG_TASKLISTSET;
            hmButlerTaskChildService.completeChildTask(hmSetTaskItemDTO.getChildTaskId(),
                    hmSetTaskItemDTO.getChildTaskId(), operateContent);
        }

    }

    public int deleteByOrderNo(String orderNo, int taskType) {
        HmEmployTaskSetExample example = new HmEmployTaskSetExample();
        example.or().andOrderNoEqualTo(orderNo).andTaskTypeEqualTo(taskType);
        return hmEmployTaskSetMapper.deleteByExample(example);
    }

    public Object getServantTaskInfo(Long employRelationId) {
        // 日历
        // 是否需要打卡
        // 日，周，月，任务
        HmEmployRelation relation = hmEmployRelationService.queryById(employRelationId);
        if (null == relation) {
            return HmResponseUtil.fail_null();
        }
        ContractSubTemplate contractSubTemplate = contractSubTemplateService.selectByOrderNo(relation.getOrderNo());
        if (null == contractSubTemplate) {
            return HmResponseUtil.fail_null();
        }

        CalendarDto calendarDto = CalendarDto.currentDayMonth(CalendarUtil.getCurrMonth(new Date()));

        if (null != relation.getRestDay()) {
            calendarDto = CalendarDto.setBusinessRestDay(calendarDto, relation.getRestDay().split(","));
        }

        List<Map<String, Object>> day = getDiffTypeTask(relation.getOrderNo(), 1);
        List<Map<String, Object>> week = getDiffTypeTask(relation.getOrderNo(), 2);
        List<Map<String, Object>> month = getDiffTypeTask(relation.getOrderNo(), 3);

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("calendar", calendarDto);
        data.put("isNeedClock", relation.getIsNeedClock());
        data.put("everyDayTask", getStrList(day));
        data.put("everyWeekTask", getStrList(week));
        data.put("everyMonthTask", getStrList(month));

        // this.orderData.serviceInfo.monthRestDays
        
        data.put("monthRestDays", contractSubTemplate.getMonthRestDays());

        return HmResponseUtil.ok(data);
    }

    private String getStrList(List<Map<String, Object>> day) {
        if (null == day || day.size() == 0) {
            return "";
        }
//		Collection<Object> list=new ArrayList<Object>();
        StringBuilder itemName = new StringBuilder();
        if (null != day && day.size() > 0) {
            for (Map<String, Object> r : day) {
                if (r.isEmpty()) {
                    continue;
                }
                itemName.append(r.get("items")).append(",");
            }
        }
        return itemName.deleteCharAt(itemName.length() - 1).toString();
    }

    public List<Map<String, Object>> getTaskByTaskType(Long employRelationId, int taskType) {
        return hmEmployTaskSetMapper.getTaskByTaskType(employRelationId, taskType);
    }

}
