package com.jeeplus.human.practice.logwrite.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeeplus.common.SecurityUtils;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.human.enrollment.enrollmentRegistration.utils.SnowFlake;
import com.jeeplus.human.practice.logwrite.domain.RegistrationWorkLog;
import com.jeeplus.human.practice.logwrite.domain.RegistrationWorkLogDetail;
import com.jeeplus.human.practice.logwrite.mapper.RegistrationWorkLogDetailMapper;
import com.jeeplus.human.practice.logwrite.mapper.RegistrationWorkLogMapper;
import com.jeeplus.human.practice.logwrite.service.dto.RegistrationWorkLogDto;
import com.jeeplus.sys.feign.IRoleApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.OfficeDTO;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author 王强
 * @version 1.0
 * @date 2023-09-15 10:01
 */
@Service
@Transactional
public class RegistrationWorkLogService extends ServiceImpl<RegistrationWorkLogMapper, RegistrationWorkLog> {

    @Resource
    private RegistrationWorkLogMapper mapper;

    @Resource
    private RegistrationWorkLogDetailMapper detailMapper;

    @Resource
    private IFlowableApi flowTaskService;

    /**
     * 实习日志信息
     * @param page
     * @param projectReportData
     * @return
     * @throws Exception
     */
    public IPage<RegistrationWorkLogDto> findList(Page<RegistrationWorkLogDto> page, RegistrationWorkLogDto projectReportData) throws Exception{
        QueryWrapper<RegistrationWorkLogDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition (projectReportData,RegistrationWorkLogDto.class);
        queryWrapper.eq("a.del_flag","0");
        if (StringUtils.isNotBlank(projectReportData.getType())){
            queryWrapper.eq("a.type",projectReportData.getType());
        }
        if (StringUtils.isNotBlank(projectReportData.getWorkName())){
            queryWrapper.like("a.work_name",projectReportData.getWorkName());
        }
        if (ObjectUtil.isNotEmpty(projectReportData.getCreateDates())) {
            queryWrapper.between("start_time", projectReportData.getCreateDates()[0], projectReportData.getCreateDates()[1])
                    .or()
                    .between("end_time", projectReportData.getCreateDates()[0], projectReportData.getCreateDates()[1]);
        }
        if (StringUtils.isNotBlank(projectReportData.getProjectManager())){
            queryWrapper.eq("a.project_manager",projectReportData.getProjectManager());
        }
        IPage<RegistrationWorkLogDto> list = mapper.findList(page, queryWrapper);
        list.getRecords().forEach(item -> {
            // 入库 修改申请
            if (com.jeeplus.utils.StringUtils.isNotBlank(item.getTaskId()) && com.jeeplus.utils.StringUtils.isNotBlank(item.getType())) {
                if ("2".equals(item.getType())) { // “审核中”的数据要获取数据审核人
                    item.setAuditUserIds(flowTaskService.getTaskAuditUsers(item.getTaskId()));  // 获取数据审核人
                }
            }
        });
        return list;

    }

    public RegistrationWorkLog saveRegistrationWorkLog(RegistrationWorkLog registration) throws Exception {
        if (StringUtils.isNotEmpty(registration.getId())){

            RegistrationWorkLog report = mapper.getById(registration.getId());
            if (report != null){
                return update(registration);
            }
        }
        return add(registration);
    }

    public RegistrationWorkLog findById(String id) {
        // 查询基础信息表
        RegistrationWorkLog info = mapper.getById(id);
        List<RegistrationWorkLogDetail> childList = detailMapper.getChildList(id);
        if (CollectionUtils.isNotEmpty(childList)){
            info.setAmountInfos(childList);
        }

        return info;
    }

    public void updateStatusById(RegistrationWorkLogDto dto) {
        mapper.updateStatusById(dto.getId(), dto.getType());
    }

    public String remove(String id) {
        // 删除基础信息表
        mapper.removeById(id);
        //明细对应数据也要同步删除
        detailMapper.deleteDetailInfo(id);
        return "操作成功";
    }

    /**
     * 修改
     */
    @Transactional(rollbackFor = Exception.class)
    public RegistrationWorkLog update(RegistrationWorkLog reportData) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));

        RegistrationWorkLog report = new RegistrationWorkLog();
        BeanUtils.copyProperties(reportData, report);
        report.setUpdateById(userDTO.getId());
        report.setUpdateTime(new Date());

        //实习日志明细数据修改操作 先根据日志id删除对应信息，再重新保存
        detailMapper.deleteDetailInfo(report.getId());
        if (CollectionUtils.isNotEmpty(report.getAmountInfos())){
            List<RegistrationWorkLogDetail> amountInfos = report.getAmountInfos();
            for (RegistrationWorkLogDetail amountInfo : amountInfos) {
                // 生成id
                String amountId = SnowFlake.getId();
                amountInfo.setId(amountId);
                amountInfo.setCreateById(userDTO.getId());
                amountInfo.setCreateTime(new Date());
                amountInfo.setUpdateById(userDTO.getId());
                amountInfo.setUpdateTime(new Date());
                amountInfo.setDelFlag(0);
                // 保存基础表信息主键值
                amountInfo.setWorkLogId(report.getId());
                if (StringUtils.isNotBlank(amountInfo.getLocationId())){
                    amountInfo.setLocation(amountInfo.getLocationId());
                }
                detailMapper.insert(amountInfo);
            }
        }

        mapper.updateById(report);

        return report;
    }

    /**
     * 新增
     */
    @Transactional(rollbackFor = Exception.class)
    public RegistrationWorkLog add(RegistrationWorkLog reportData) throws Exception{

        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));

        RegistrationWorkLog report = new RegistrationWorkLog();
        BeanUtils.copyProperties(reportData, report);

        String id = SnowFlake.getId();
        report.setId(id);
        if (CollectionUtils.isNotEmpty(report.getAmountInfos())){
            List<RegistrationWorkLogDetail> amountInfos = reportData.getAmountInfos();
            for (RegistrationWorkLogDetail amountInfo : amountInfos) {
                // 生成id
                String amountId = SnowFlake.getId();
                amountInfo.setId(amountId);
                amountInfo.setCreateById(userDTO.getId());
                amountInfo.setCreateTime(new Date());
                amountInfo.setUpdateById(userDTO.getId());
                amountInfo.setUpdateTime(new Date());
                amountInfo.setDelFlag(0);
                // 保存基础表信息主键值
                amountInfo.setWorkLogId(report.getId());
                if (StringUtils.isNotBlank(amountInfo.getLocationId())){
                    amountInfo.setLocation(amountInfo.getLocationId());
                }
                detailMapper.insert(amountInfo);
            }
        }
        mapper.insert(report);
        return report;
    }

    /**
     * 根据创建人id去查最后一天的日志
     * @param createById
     * @return
     */
    public String getLastWorkDay(String createById) {
        return mapper.getLastWorkDay(createById);
    }
}
