package com.ruoyi.system.service.task.impl;

import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.system.domain.grid.GridRegion;
import com.ruoyi.system.domain.grid.GridRegionExample;
import com.ruoyi.system.domain.grid.GridRegionUser;
import com.ruoyi.system.domain.task.*;
import com.ruoyi.system.domain.task.utils.WorkMSGUtils;
import com.ruoyi.system.domain.task.vo.BsGridRegionUser;
import com.ruoyi.system.mapper.task.TkCommonTaskMapper;
import com.ruoyi.system.mapper.task.ext.TkCommonTaskExtMapper;
import com.ruoyi.system.mapper.task.ext.TkRoundSubtaskExtMapper;
import com.ruoyi.system.service.grid.GridRegionService;
import com.ruoyi.system.service.task.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.NumberFormat;
import java.util.*;

/**
 * @Date 2019/3/18 8:39
 * @Author GuoWei
 * @Description: 手动写的service，主要为了事务
 * @Version 1.0
 */
@Service("DiyService")
@Transactional
public class DiyServiceImpl implements DiyService {
    @Autowired
    TkCommonTaskMapper tkCommonTaskMapper;
    @Autowired
    TkCommonTaskExtMapper tkCommonTaskExtMapper;
    @Autowired
    GridRegionService bsWgxxbService;
    @Autowired
    TkRoundPlanService tkRoundPlanService;
    @Autowired
    TkRoundTaskService tkRoundTaskService;
    @Autowired
    TkRoundTaskService taskService;
    @Autowired
    TkRoundSubtaskExtMapper tkRoundSubtaskExtMapper;
    @Autowired
    private TkRoundSubtaskService subtaskService;
    @Autowired
    TkRoundMatterService tkRoundMatterService;
    @Autowired
    TkRoundSubtaskService tkRoundSubtaskService;

    @Value("${app.sms.enable}")
    private boolean smsEnable;
    @Autowired
    private WorkMSGUtils workMSGUtils;

    @Override
    public int insert(TkRoundPlan tkRoundPlan, String[] chooseObjIds, String[] chooseUserIds, List<GridRegionUser> chooseUserJson, List<BsGridRegionUser> chooseObjJson, String origin, String standby3) {

        StringBuffer objNames = new StringBuffer();
        for (BsGridRegionUser bsWgdxb : chooseObjJson) {
            objNames.append(bsWgdxb.getName());
            objNames.append(",");
        }
        objNames.deleteCharAt(objNames.length() - 1);
        tkRoundPlan.setObjNames(objNames.toString());
        int result = tkRoundPlanService.insert(tkRoundPlan);
        if (result == 0) {
            throw new RuntimeException();
        }

        //——————————————————————————————————————————生成任务——————————————————————————————————————————

        // 生成子任务
        // 间隔 eg：1 就是每隔一个月 = 加1后的每两个月(默认是1)
        Integer interval = StringUtils.isBlank(tkRoundPlan.getPeriodInterval()) ? 1 : Integer.parseInt(tkRoundPlan.getPeriodInterval()) + 1;
        // 0:从不重复,1:月巡查,2:周巡查,3:日巡查
        if (tkRoundPlan.getPeriodType().equals("1")) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(tkRoundPlan.getEndDate());
            int endMonth = calendar.get(Calendar.MONTH);
            calendar.setTime(tkRoundPlan.getStartDate());
            int startMonth = calendar.get(Calendar.MONTH);
            int day2 = calendar.get(Calendar.DATE);

            // 重复时间段内每个月
            for (int i = 0; i <= endMonth - startMonth; i++) {
                // 获取每月要重复的日期
                String[] days = tkRoundPlan.getPeriodHz().split(",");
                for (String day : days) {
                    // 时间重置
                    calendar.setTime(tkRoundPlan.getStartDate());
                    calendar.add(Calendar.MONTH, i * interval);

                    calendar.add(Calendar.DATE, (Integer.parseInt(day) - day2));
                    if (calendar.getTimeInMillis() >= tkRoundPlan.getStartDate().getTime()
                            && calendar.getTimeInMillis() <= tkRoundPlan.getEndDate().getTime()) {
                        // 算结束时间
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(calendar.getTime());
                        cal.add(Calendar.MONTH, +1);
                        cal.add(Calendar.DATE, -1);
                        Date endTime = cal.getTime();
                        // 创建任务
                        createTask(tkRoundPlan, calendar.getTime(), endTime.getTime() > tkRoundPlan.getEndDate().getTime() ? tkRoundPlan.getEndDate() : endTime, chooseObjJson, origin,standby3);
                    }
                }
            }
        } else if (tkRoundPlan.getPeriodType().equals("2")) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(tkRoundPlan.getEndDate());
            int endWeek = calendar.get(Calendar.WEEK_OF_YEAR);
            calendar.setTime(tkRoundPlan.getStartDate());
            int startWeek = calendar.get(Calendar.WEEK_OF_YEAR);
            int day2 = calendar.get(Calendar.DAY_OF_WEEK) - 1;

            // 重复时间段内每个星期
            for (int i = 0; i <= endWeek - startWeek; i++) {
                // 获取每周重复的日子
                String[] days = tkRoundPlan.getPeriodHz().split(",");

                for (String day : days) {
                    // 时间重置
                    calendar.setTime(tkRoundPlan.getStartDate());
                    calendar.add(Calendar.DATE, i * 7 * interval);

                    calendar.add(Calendar.DATE, (Integer.parseInt(day) - day2));

                    if (tkRoundPlan.getStartDate().getTime() <= calendar.getTimeInMillis()
                            && calendar.getTimeInMillis() <= tkRoundPlan.getEndDate().getTime()) {
                        // 算结束时间
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(calendar.getTime());
                        cal.add(Calendar.DATE, +6);
                        Date endTime = cal.getTime();
                        // 创建任务
                        createTask(tkRoundPlan, calendar.getTime(), endTime.getTime() > tkRoundPlan.getEndDate().getTime() ? tkRoundPlan.getEndDate() : endTime, chooseObjJson, origin, standby3);
                    }
                }
            }
        } else if (tkRoundPlan.getPeriodType().equals("3")) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(tkRoundPlan.getStartDate());

            // 一直加循环的天数 直到结束的时间
            while (calendar.getTimeInMillis() <= tkRoundPlan.getEndDate().getTime()) {
                // 创建任务
                createTask(tkRoundPlan, calendar.getTime(), calendar.getTime(), chooseObjJson, origin, standby3);
                calendar.add(Calendar.DATE, interval);
            }
        } else {
            // 创建任务
            createTask(tkRoundPlan, tkRoundPlan.getStartDate(), tkRoundPlan.getEndDate(), chooseObjJson, origin, standby3);
        }

        //——————————————————————————————————————————生成任务——————————————————————————————————————————
        return result;
    }

    @Override
    public Map<String, String> getTkScore(Map<String, Object> map) {
        return tkCommonTaskExtMapper.getTkScore(map);
    }

    @Override
    public List<GridRegion> getThird() {
        GridRegionExample example = new GridRegionExample();
        GridRegionExample.Criteria criteria = example.createCriteria();
        criteria.andLevelEqualTo("3");
        criteria.andWgTypeEqualTo("1");
        criteria.andIsValidEqualTo("1");
        example.setOrderByClause(" wg_name ");
        List<GridRegion> bsWgxxbs = bsWgxxbService.selectByExample(example);
        return bsWgxxbs;
    }

    @Override
    @Transactional
    public int deletePlanById(String id) {
        int result = tkRoundPlanService.deleteByStringPrimaryKey(id);

        TkRoundTaskExample example = new TkRoundTaskExample();
        TkRoundTaskExample.Criteria criteria = example.createCriteria();
        criteria.andRoundPlanIdEqualTo(id);
        int result1 = tkRoundTaskService.deleteByExample(example);

        if (result != 1 || result1 != 1) {
            throw new RuntimeException("删除失败");
        }
        return 1;
    }

    @Override
    public int onOff(TkRoundPlan tkRoundPlan) {
        // 改状态
        TkRoundTask tkRoundTask = new TkRoundTask();

        TkRoundTaskExample tkRoundTaskExample = new TkRoundTaskExample();
        TkRoundTaskExample.Criteria criteria = tkRoundTaskExample.createCriteria();
        if (tkRoundPlan.getStatus().equals("1")) {
            // 关
            tkRoundPlan.setStatus("0");
            tkRoundTask.setIsShow("0");
            // 任务状态为未开始的
            criteria.andStatusEqualTo("0");
            // 计划下的任务
            criteria.andRoundPlanIdEqualTo(tkRoundPlan.getId());
        } else {
            // 开
            tkRoundPlan.setStatus("1");
            tkRoundTask.setIsShow("1");
            // 任务目前是隐藏的
            criteria.andIsShowEqualTo("0");
            // 对应计划
            criteria.andRoundPlanIdEqualTo(tkRoundPlan.getId());
        }


        taskService.updateByExampleSelective(tkRoundTask, tkRoundTaskExample);

        int result = tkRoundPlanService.updateByPrimaryKeySelective(tkRoundPlan);
        return result;
    }

    @Override
    public int countByDxlx(String dxlx) {
        return tkRoundSubtaskExtMapper.countByDxlx(dxlx);
    }

    @Override
    public List<TkRoundSubtask> selectByParam(String objId, String startTime, String endTime, String origin, String status, Integer pageNum, Integer pageSize) {
        return tkRoundSubtaskExtMapper.selectByParam(objId, startTime, endTime, origin, status, pageNum, pageSize);
    }

    @Override
    public Map<String, Object> getSubTaskNumByDXLX() {

        List<TkRoundSubtask> list = tkRoundSubtaskExtMapper.getSubTaskNumByDXLX();
        Map<String, Object> result = new HashMap<>();
        for (TkRoundSubtask tkRoundSubtask : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("total", tkRoundSubtask.getTotal());
            map.put("unusual", tkRoundSubtask.getUnusual());
            result.put(tkRoundSubtask.getDxlx(), map);
        }

        return result;
    }

    @Override
    public String getMatterId(String subTaskId) {
        TkRoundSubtask tkRoundSubtask = tkRoundSubtaskService.selectByPrimaryKey(subTaskId);
        TkRoundTask tkRoundTask = tkRoundTaskService.selectByPrimaryKey(tkRoundSubtask.getTaskId());
        TkRoundPlan tkRoundPlan = tkRoundPlanService.selectByPrimaryKey(tkRoundTask.getRoundPlanId());
        return tkRoundPlan.getMatterId();
    }

    @Override
    public int saveSubtask(TkRoundSubtask tkRoundSubtask) {
        int result = 0;
        result = tkRoundSubtaskService.updateByPrimaryKeySelective(tkRoundSubtask);
        if (result == 0) {
            return result;
        }

        // 计算完成百分比
        tkRoundSubtask = tkRoundSubtaskService.selectByPrimaryKey(tkRoundSubtask.getId());
        TkRoundSubtaskExample example = new TkRoundSubtaskExample();
        TkRoundSubtaskExample.Criteria criteria = example.createCriteria();
        criteria.andTaskIdEqualTo(tkRoundSubtask.getTaskId());
        int total = tkRoundSubtaskService.countByExample(example);
        criteria.andStatusNotEqualTo("0");
        int ready = tkRoundSubtaskService.countByExample(example);

        TkRoundTask tkRoundTask = new TkRoundTask();
        tkRoundTask.setId(tkRoundSubtask.getTaskId());
        // 创建一个数值格式化对象
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(0);
        String percent = numberFormat.format((float) ready / (float) total * 100);
        System.out.println("百分比为:" + percent + "%");
        tkRoundTask.setPercent(Integer.parseInt(percent));

        // 更新任务状态（0未开始，1进行中，2已完成）
        if (StringUtils.isNotBlank(percent)) {
            if ("100".equals(percent)) {
                tkRoundTask.setStatus("2");
            } else if ("0".equals(percent)) {
                tkRoundTask.setStatus("0");
            } else {
                tkRoundTask.setStatus("1");
            }
        } else {
            tkRoundTask.setStatus("0");
        }

        result = tkRoundTaskService.updateByPrimaryKeySelective(tkRoundTask);
        return result;
    }

    /**
     * @Date 2019/3/4 16:17
     * @Author Guow
     * @Description: 创建巡查任务
     */
    private String createTask(TkRoundPlan tkRoundPlan, Date date, Date endTime, List<BsGridRegionUser> chooseObjJson, String origin, String standby3) {

        TkRoundTask tkRoundTask = new TkRoundTask();
        tkRoundTask.setId(UUID.randomUUID().toString());
        tkRoundTask.setRoundPlanId(tkRoundPlan.getId());
        if ("4".equals(tkRoundPlan.getPeriodType())) {
            tkRoundTask.setName(tkRoundPlan.getName());
        } else {
            tkRoundTask.setName(DateUtil.getFormatDate(date, "yyyyMMdd") + tkRoundPlan.getName());
        }
        tkRoundTask.setUserIds(tkRoundPlan.getUserIds());
        tkRoundTask.setUserNames(tkRoundPlan.getUserNames());
        tkRoundTask.setOrigin(origin);
        tkRoundTask.setTime(date);
        tkRoundTask.setEndTime(endTime);
        // 默认开关（显示）开
        tkRoundTask.setIsShow("1");
        // 默认状态 未开始
        tkRoundTask.setStatus("0");
        // 默认完成度0%
        tkRoundTask.setPercent(0);
        int result = taskService.insert(tkRoundTask);

        if (smsEnable) {
            //创建待办任务
            if (!"4".equals(tkRoundPlan.getPeriodType())) {
                if (StringUtils.isNotBlank(tkRoundTask.getUserIds())) {
                    String[] userIds = tkRoundTask.getUserIds().split(",");
                    List<String> beassignedUserIds = Arrays.asList(userIds);
                    workMSGUtils.createRoundWork(tkRoundTask, tkRoundPlan.getCreateBy(), beassignedUserIds, tkRoundPlan.getName());
                }

                if (result == 0) {
                    throw new RuntimeException();
                }
            }
        }

        // 方案三：对象listo
        List<BsGridRegionUser> bsWgdxbList = chooseObjJson;
        for (BsGridRegionUser o : bsWgdxbList) {
            String id = o.getId();
            String name = o.getName();
            String gridId = o.getWgId();
            // 对象类型:企业（qy）、资产（zc）、城乡（cx）、商户（sh）、其他（qt）、专属（zs）
            String dxlx = o.getDxlx();
            // 企业类型:1安监、 2环保、 3其他
            String qylx = o.getQylx();
            createSubtask(tkRoundTask, tkRoundPlan, id, name, gridId, dxlx, qylx);
        }

        return "1";
    }

    /**
     * @Date 2019/3/4 16:17
     * @Author Guow
     * @Description: 创建巡查任务
     */
    private String createSubtask(TkRoundTask tkRoundTask, TkRoundPlan tkRoundPlan, String objId, String ObjectName, String gridId, String dxlx, String qylx) {

        TkRoundSubtask tkRoundSubtask = new TkRoundSubtask();
        tkRoundSubtask.setId(UUID.randomUUID().toString());
        tkRoundSubtask.setTaskId(tkRoundTask.getId());
        tkRoundSubtask.setTime(tkRoundTask.getTime());
        tkRoundSubtask.setCreateBy(tkRoundPlan.getCreateBy());
        tkRoundSubtask.setObjId(objId);
        tkRoundSubtask.setDxlx(dxlx);
        tkRoundSubtask.setQylx(qylx);
        tkRoundSubtask.setObjName(ObjectName);
        tkRoundSubtask.setCreateTime(new Date());
        tkRoundSubtask.setGridId(gridId);
        // 巡查结果 0：未巡查；1：正常；2：异常；
        tkRoundSubtask.setStatus("0");
        tkRoundSubtask.setResult("0");
        int result = subtaskService.insert(tkRoundSubtask);
        if (result == 0) {
            throw new RuntimeException();
        } else {
            return "1";
        }
    }
}
