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

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.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.service.RegistrationWorkLogService;
import com.jeeplus.human.practice.register.service.RegistrationService;
import com.jeeplus.human.practice.reimburseRegister.domain.ReimburseRegister;
import com.jeeplus.human.practice.reimburseRegister.domain.ReimburseRegisterDetail;
import com.jeeplus.human.practice.reimburseRegister.mapper.ReimburseRegisterDetailMapper;
import com.jeeplus.human.practice.reimburseRegister.mapper.ReimburseRegisterMapper;
import com.jeeplus.sys.feign.IPostApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.PostDTO;
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.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author 王强
 * @version 1.0
 * @date 2023-09-19 13:42
 */
@Service
@Transactional
public class ReimburseRegisterService extends ServiceImpl<ReimburseRegisterMapper, ReimburseRegister> {

    @Resource
    private ReimburseRegisterMapper registerMapper;

    @Resource
    private IFlowableApi flowTaskService;

    @Resource
    private RegistrationService registrationService;

    @Resource
    private ReimburseRegisterDetailMapper detailMapper;

    @Resource
    private RegistrationWorkLogService workLogService;

    public ReimburseRegister saveReimburseRegister(ReimburseRegister registration) throws Exception {
        if (StringUtils.isNotEmpty(registration.getId())){

            ReimburseRegister report = registerMapper.getById(registration.getId());
            if (report != null){
                registration.setCreateById(report.getCreateById());
                registration.setMobilePhone(report.getMobilePhone());
                registration.setCreateName(report.getCreateName());
                return update(registration);
            }
        }
        return add(registration);
    }

    /**
     * 实习报销登记信息
     * @param page
     * @param projectReportData
     * @return
     * @throws Exception
     */
    public IPage<ReimburseRegister> findList(Page<ReimburseRegister> page, ReimburseRegister projectReportData) throws Exception{
        QueryWrapper<ReimburseRegister> queryWrapper = QueryWrapperGenerator.buildQueryCondition (projectReportData,ReimburseRegister.class);
        queryWrapper.eq("a.del_flag","0");
        if (StringUtils.isNotBlank(projectReportData.getType())){
            queryWrapper.eq("a.type",projectReportData.getType());
        }
        if (StringUtils.isNotBlank(projectReportData.getReimbuserName())){
            queryWrapper.like("a.reimbuser_name",projectReportData.getReimbuserName());
        }
        if (StringUtils.isNotBlank(projectReportData.getCreateById())){
            queryWrapper.eq("a.create_by_id",projectReportData.getCreateById());
        }
        if (StringUtils.isNotBlank(projectReportData.getCreateById())){
            queryWrapper.eq("a.create_by_id",projectReportData.getCreateById());
        }

        if (projectReportData.getCreateDates() != null && projectReportData.getCreateDates().length > 0) {
            queryWrapper.between("a.create_time", projectReportData.getCreateDates()[0], projectReportData.getCreateDates()[1]);
        }
        if (projectReportData.getAmounts() != null && projectReportData.getAmounts().length > 0) {
            queryWrapper.between("a.all_reimbursement_amount", projectReportData.getAmounts()[0], projectReportData.getAmounts()[1]);
        }

        IPage<ReimburseRegister> list = registerMapper.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;

    }

    /**
     * 实习报销登记信息
     * @param page
     * @param projectReportData
     * @return
     * @throws Exception
     */
    public IPage<ReimburseRegister> findList2(Page<ReimburseRegister> page, ReimburseRegister projectReportData) throws Exception{
        // 获取当前登录人信息
        UserDTO userDto = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        PostDTO postInfo = SpringUtil.getBean(IPostApi.class).getPostDTOByName("考勤统计人");
        List<UserDTO> userDTOS = SpringUtil.getBean(IUserApi.class).findListFlowAbleByPostId(postInfo.getId());
        for (int i=0; i<userDTOS.size();i++){
            if (userDTOS.get(i).getId().equals(userDto.getId())){
                QueryWrapper<ReimburseRegister> queryWrapper = QueryWrapperGenerator.buildQueryCondition (projectReportData,ReimburseRegister.class);
                queryWrapper.eq("a.del_flag","0");
                projectReportData.setType("5");
                if (StringUtils.isNotBlank(projectReportData.getType())){
                    queryWrapper.eq("a.type",projectReportData.getType());
                }
                if (StringUtils.isNotBlank(projectReportData.getReimbuserName())){
                    queryWrapper.like("a.reimbuser_name",projectReportData.getReimbuserName());
                }
                if (StringUtils.isNotBlank(projectReportData.getCreateById())){
                    queryWrapper.eq("a.create_by_id",projectReportData.getCreateById());
                }
                if (StringUtils.isNotBlank(projectReportData.getCreateById())){
                    queryWrapper.eq("a.create_by_id",projectReportData.getCreateById());
                }

                if (projectReportData.getCreateDates() != null && projectReportData.getCreateDates().length > 0) {
                    queryWrapper.between("a.create_time", projectReportData.getCreateDates()[0], projectReportData.getCreateDates()[1]);
                }
                if (projectReportData.getAmounts() != null && projectReportData.getAmounts().length > 0) {
                    queryWrapper.between("a.all_reimbursement_amount", projectReportData.getAmounts()[0], projectReportData.getAmounts()[1]);
                }

                IPage<ReimburseRegister> list = registerMapper.findList2(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;
            }
        }

        return null;
        //根据  考勤统计人  岗位查询出有该岗位的员工信息

    }

    public ReimburseRegister findById(String id) {
        // 查询基础信息表
        ReimburseRegister info = registerMapper.getById(id);
        List<ReimburseRegisterDetail> childList = detailMapper.getChildList(id);
        if (CollectionUtils.isNotEmpty(childList)){
            info.setDetailList(childList);
        }

        return info;
    }

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

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

        //实习日志明细数据修改操作 先根据日志id删除对应信息，再重新保存
        detailMapper.deleteDetailInfo(report.getId());
        if (CollectionUtils.isNotEmpty(report.getDetailList())){
            List<ReimburseRegisterDetail> amountInfos = report.getDetailList();
            for (ReimburseRegisterDetail 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.setRegisterId(report.getId());
                if (StringUtils.isNotBlank(amountInfo.getWorkLogId())){
                    amountInfo.setWorkLogId(amountInfo.getWorkLogId());
                }
                amountInfo.setReimbursementAmount(amountInfo.getReimbursementAmount());
                detailMapper.insert(amountInfo);
            }
        }
        if (StringUtils.isNotEmpty(reportData.getProcInsId())) {
            String currentTask = flowTaskService.getCurrentTaskName(reportData.getProcInsId());
            if(StringUtils.isNotBlank(currentTask)) {
                if ("部门主任审核".equals(currentTask)) {
                    report.setType("5");
                    //根据创建人去修改实习生实习状态
                    if (StringUtils.isNotBlank(report.getCompletePractice()) && report.getCompletePractice().equals("1")){
                        //设置实习结束日期
                        //查询实习工作日志的最后一天  根据创建人去查，
                        String endTime = workLogService.getLastWorkDay(report.getCreateById());
                        //修改实习状态前先查询是否
                        registrationService.updatePracticeStatus(report.getCreateById(),endTime);

                        //系统账号冻结
                        // 获取当前日期
                        LocalDate currentDate = LocalDate.now();

                        // 获取年、月、日
                        int year = currentDate.getYear();
                        int month = currentDate.getMonthValue();
                        int day = currentDate.getDayOfMonth();
                        String time = year + "年" + month + "月" + day + "日";

                        //发送短信
                        /*String randomCode = "你好" + report.getCreateName() + "！恭喜你完成在我司的实习，希望你今后工作生活顺利。系统将在" + time + "晚上12点冻结账号，请尽快" +
                                "处理好手头的工作！";*/
                        Map<String, Object> stringObjectMap = SpringUtil.getBean(IUserApi.class).sendInternshipFinishRandomCodes(report.getMobilePhone(), report.getCreateName(), time);
                        Integer statusCode = (Integer) stringObjectMap.get("statusCode");
                        if (200 == statusCode) {
                            System.out.println("短信发送成功!");
                        } else if (10001 == statusCode) {
                            String message = (String) stringObjectMap.get("message");
                            System.out.println(message);
                        }else if(10002 == statusCode){
                            System.out.println("账户短信量余额不足，请联系管理员进行充值!");
                        }else if(10003 == statusCode){
                            System.out.println("手机号获取验证码次数已达每日上限!");
                        } else {
                            System.out.println("短信发送失败，错误代码：101，请联系管理员!");
                        }
                    }
                }
            }
        }


        registerMapper.updateById(report);

        return report;
    }

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

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

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

        String id = SnowFlake.getId();
        report.setId(id);
        if (CollectionUtils.isNotEmpty(report.getDetailList())){
            List<ReimburseRegisterDetail> amountInfos = reportData.getDetailList();
            for (ReimburseRegisterDetail 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.setRegisterId(report.getId());
                if (StringUtils.isNotBlank(amountInfo.getWorkLogId())){
                    amountInfo.setWorkLogId(amountInfo.getWorkLogId());
                }
                amountInfo.setReimbursementAmount(amountInfo.getReimbursementAmount());
                detailMapper.insert(amountInfo);
            }
        }
        registerMapper.insert(report);
        return report;
    }

    public void updateStatusById(ReimburseRegister dto) {
        registerMapper.updateStatusById(dto.getId(), dto.getType());
    }

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