package com.xunmei.core.resumption.service.impl;

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

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.xunmei.common.core.constant.SecurityConstants;
import com.xunmei.common.core.domain.R;
import com.xunmei.common.core.utils.DateUtils;
import com.xunmei.common.core.utils.Ymd;
import com.xunmei.core.resumption.domain.AppPlan;
import com.xunmei.core.resumption.domain.SysResumption;
import com.xunmei.core.resumption.domain.Todo;
import com.xunmei.core.resumption.domain.TodoRole;
import com.xunmei.core.resumption.mapper.SysResumptionMapper;
import com.xunmei.core.resumption.service.ISysResumptionService;
import com.xunmei.core.resumption.vo.AppRulePointTaskVo;
import com.xunmei.core.resumption.vo.WorkChangeResumptionVo;
import com.xunmei.common.core.utils.ResumptionStatus;
import com.xunmei.common.core.utils.ResumptionType;
import com.xunmei.system.api.RemoteOrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xunmei.common.core.web.page.TableDataInfo;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author xunmei
 * @date 2023-08-22
 */
@Service
public class SysResumptionServiceImpl extends ServiceImpl<SysResumptionMapper, SysResumption> implements ISysResumptionService {
    @Autowired
    private SysResumptionMapper sysResumptionMapper;
    @Autowired
    private RemoteOrgService orgService;

    @Override
    public TableDataInfo selectPage(SysResumption sysResumption) {


        //未删除
//        sysResumption.setDeleted(0L);
        Page<SysResumption> page;
        //分页
        if (sysResumption.getPageNum() != null && sysResumption.getPageSize() != null) {
            page = new Page<>(sysResumption.getPageNum(), sysResumption.getPageSize());
        } else {
            page = new Page<>();
        }
        //查询条件
        QueryWrapper<SysResumption> query = new QueryWrapper<>(sysResumption);
        //下穿
        if (sysResumption.getCheckSub()) {
            List<Long> ids = orgService.selectCheckSubOrgIdList(sysResumption.getOrgId(),SecurityConstants.INNER);
//            if(checkSubOrgIdList.getCode()!=200){
////                return checkSubOrgIdList.getMsg();
//            }
          //  List<Long> ids = checkSubOrgIdList.getData();
            //清空前端传递的org_id
            sysResumption.setOrgId(null);
            //添加in条件
            query.in("org_id", ids);
        }
        //时间范围查询
        if (sysResumption.getParams().get("beginTime") != null && sysResumption.getParams().get("endTime") != null) {
            query.between("create_time", sysResumption.getParams().get("beginTime"), sysResumption.getParams().get("endTime"));
        }
        //获取数据
        page = sysResumptionMapper.selectPage(page, query);
        //抓换为TableDataInfo适配前端
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setMsg("操作成功");
        tableDataInfo.setCode(200);
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setRows(page.getRecords());
        return tableDataInfo;


    }


    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public SysResumption selectSysResumptionById(String id) {
        return sysResumptionMapper.selectById(id);
    }
    @Override
    public void deleteResumption(List<String> ids,Integer year, Integer quarter){
        sysResumptionMapper.deleteResumption(ids,year,quarter);
    }
    @Override
    @Transactional(readOnly= false, rollbackFor = {Exception.class, RuntimeException.class},propagation = Propagation.REQUIRES_NEW)
    public void saveResumption(List<SysResumption> listResumption, List<AppPlan> appPlanList,List<Map<String,Long>> planIdAndOrgs){
        //筛选出listResumption每个对象的 planId和orgId 同时在planIdAndOrgs中的数据
        List<SysResumption> resumptionList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(planIdAndOrgs)&&CollectionUtils.isNotEmpty(listResumption)){
            for (SysResumption re : listResumption) {
                for (Map<String, Long> map : planIdAndOrgs) {
                    if (!(re.getPlanId().equals(map.get("planId")) && re.getOrgId().equals(map.get("orgId")))) {
                        resumptionList.add(re);
                    }
                }
            }
        }else{
            resumptionList = listResumption;
        }
        //this.save(resumptionList);
        this.saveBatch(resumptionList);
        for (SysResumption resumption : resumptionList) {
            AppPlan appPlan = appPlanList.stream().filter(r -> r.getId().equals(resumption.getPlanId())).collect(Collectors.toList()).get(0);
            this.daiban(resumption, resumption.getRoleId(), appPlan, resumption.getOrgId(), Math.toIntExact(resumption.getType()));
        }
    }
    /**
     * 查询【请填写功能名称】列表
     *
     * @param sysResumption 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<SysResumption> selectSysResumptionList(SysResumption sysResumption) {
        return sysResumptionMapper.selectList(new QueryWrapper<>(sysResumption));
    }
    @Override
    public List<WorkChangeResumptionVo> findResumptionList(List<Long> orgIds,Date date,Integer type,Integer status, Integer year,Integer quarter) {
        return sysResumptionMapper.findResumptionList(orgIds,date,type,status,year,quarter);
    }

    @Override
    @Transactional(readOnly= false, rollbackFor = {Exception.class, RuntimeException.class},propagation = Propagation.REQUIRES_NEW)
    public void newbuild(Long orgId, ResumptionType type, final Date dateTime, final Boolean isWork, AppPlan appPlan, List<Object> nfcList, List<AppRulePointTaskVo> pointList, List<Long> roleIds, DateTime planstartTime, DateTime planendTime) {
        Ymd ymd = Ymd.of(dateTime);
        //id使用uuid
        // final Resumption resumption = this.findOrCreate(id,()-> Resumption.newof(orgId,type,ymd,appPlan.getId(), id));
        // 原来的id根据规则参数，可以根据规则产生和数据库里已存在的id，
        // 现在使用uuid，数据库中肯定不存在，故不需要拿id去数据库查询，直接创建新的对象
        List<SysResumption> resumptions = new ArrayList<>();
        Date time = new Date();
        for (Long roleId : roleIds) {
            //结束时间 23:59:59变00:00:00的问题(周，月，季，半年，年)
            if (type.ordinal() != 0 && type.ordinal() != 6) {
                planendTime = DateUtil.endOfDay(planendTime).offset(DateField.MILLISECOND, -999);
            }
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            SysResumption resumption =new SysResumption();
            //resumption.changeWork(isWork);
            resumption.setStatus((long) ResumptionStatus.WAIT.ordinal());
            resumption.setYmd(ymd);
            resumption.setYmdDate(ymd.getDate());
            resumption.setYmdDay(Long.valueOf(ymd.getDay()));
            resumption.setYmdMonth(Long.valueOf(ymd.getMonth()));
            resumption.setYmdWeek(Long.valueOf(ymd.getWeek()));
            resumption.setYmdYear(Long.valueOf(ymd.getYear()));
            resumption.setYmdHour(Long.valueOf(ymd.getHour()));
            resumption.setYmdQuarter(Long.valueOf(ymd.getQuarter()));
            resumption.setYmdHalfyear(Long.valueOf(ymd.getHalfyear()));
            resumption.setPlanId(appPlan.getId());
            resumption.setOrgId(orgId);
            resumption.setId(id);
            resumption.setType((long) type.ordinal());
            resumption.setRoleId(roleId);
            resumption.setPlanStartTime(planstartTime);
            resumption.setPlanEndTime(planendTime);
            resumption.setCreateTime(time);
            resumptions.add(resumption);
        }
        //resumptions = this.save(resumptions);
//        for (SysResumption s :
//                resumptions) {
//            sysResumptionMapper.insert(s);
//        }
        this.saveBatch(resumptions);
        //resumption = this.save(resumption);
        //插入履职数据
//        for (SysResumption resumption : resumptions) {
//            //生成代办
//            daiban(resumption, resumption.getRoleId(), appPlan, orgId, type.ordinal());
//        }

    }
    public void daiban(SysResumption resumption, Long roleId, AppPlan appPlan, Long orgId, int type) {
        Todo todo = new Todo();
        Long appId = 0L; //this.appService.findByNameForApp(IApp.SAFECHECK).getId();
        todo.setId(resumption.getId());
        todo.setOrgId(orgId);

        String name = appPlan.getPlanName();
        if (type == 6) {
            todo.setTitle("每小时履职");
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            name = appPlan.getPlanName() + sdf.format(resumption.getPlanStartTime()) + "-" + sdf.format(resumption.getPlanEndTime());
//            appId = this.appService.findByNameForApp(IApp.MRLZ).getId();
        }
        if (type == 0) {
            todo.setTitle("每日履职");
            //SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
            int planexec = appPlan.getPlanExec();
            String strplanexec = "";
            switch (planexec) {
                case 0:
                    strplanexec = "(全天)";
                    break;
                case 1:
                    strplanexec = "(营业前)";
                    break;
                case 2:
                    strplanexec = "(营业期间)";
                    break;
                case 3:
                    strplanexec = "(营业终了)";
                    break;
            }
            name = appPlan.getPlanName() + strplanexec;//sdf.format(resumption.getPlanStartTime())+"-"+
//            appId = this.appService.findByNameForApp(IApp.MRLZ).getId();
        }
        if (type == 1) {
            todo.setTitle("每周履职");
            name = resumption.getYmd().getYear() + "年第" + resumption.getYmd().getWeek() + "周-" + appPlan.getPlanName();
//            appId = this.appService.findByNameForApp(IApp.MYLZ).getId();
        }
        if (type == 2) {
            todo.setTitle("每月履职");
            name = resumption.getYmd().getYear() + "年第" + resumption.getYmd().getMonth() + "月-" + appPlan.getPlanName();
//            appId = this.appService.findByNameForApp(IApp.MYLZ).getId();
        }
        if (type == 3) {
            todo.setTitle("季度履职");
            name = resumption.getYmd().getYear() + "年第" + resumption.getYmd().getQuarter() + "季度-" + appPlan.getPlanName();
//            appId = this.appService.findByNameForApp(IApp.MNLZ).getId();
        }
        if (type == 4) {
            todo.setTitle("半年履职");
            String strhalfyear = "";
            switch (resumption.getYmd().getHalfyear()) {
                case 1:
                    strhalfyear = "上半年";
                    break;
                case 2:
                    strhalfyear = "下半年";
                    break;
            }
            name = resumption.getYmd().getYear() + "年" + strhalfyear + "-" + appPlan.getPlanName();
//            appId = this.appService.findByNameForApp(IApp.MNLZ).getId();
        }
        if (type == 5) {
            todo.setTitle("年度履职");
            name = resumption.getYmd().getYear() + "年-" + appPlan.getPlanName();
//            appId = this.appService.findByNameForApp(IApp.MNLZ).getId();
        }

        todo.setContent(String.format("%s-等待履职", name));
        todo.setDate(resumption.getPlanStartTime());
        //Date endDate=DateUtils.addMilliseconds( DateUtil.endOfDay(resumption.getPlanEndTime()),-1);
        todo.setEndDate(DateUtil.endOfDay(resumption.getPlanEndTime()));
        todo.setOverDate(DateUtil.endOfDay(resumption.getPlanEndTime()));
        todo.setAppId(appId);
        todo.setRoles(new ArrayList<>());
        TodoRole todoRole = new TodoRole();
        todoRole.setTodoId(todo.getId());
        todoRole.setRoleId(roleId);
        todo.getRoles().add(todoRole);
//        iTodoService.saveTodoAndRoles(todo);
    }
    /**
     * 新增【请填写功能名称】
     *
     * @param sysResumption 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertSysResumption(SysResumption sysResumption) {
        sysResumption.setCreateTime(DateUtils.getNowDate());
        return sysResumptionMapper.insert(sysResumption);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param sysResumption 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateSysResumption(SysResumption sysResumption) {
        sysResumption.setUpdateTime(DateUtils.getNowDate());
        return sysResumptionMapper.updateById(sysResumption);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteSysResumptionByIds(String[] ids) {
        return sysResumptionMapper.deleteBatchIds(Arrays.asList((ids)));
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteSysResumptionById(String id) {
        return sysResumptionMapper.deleteById(id);
    }
}
