package com.jeeplus.human.enrollment.enrollmentRegistration.service;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.human.enrollment.enrollmentRegistration.domain.EnrollmentKeyCard;
import com.jeeplus.human.enrollment.enrollmentRegistration.domain.EnrollmentRiceCard;
import com.jeeplus.human.enrollment.enrollmentRegistration.domain.EnrollmentWageCard;
import com.jeeplus.human.enrollment.enrollmentRegistration.mapper.EnrollmentKeyCardMapper;
import com.jeeplus.human.enrollment.enrollmentRegistration.utils.SnowFlake;
import com.jeeplus.sys.feign.IUserApi;
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.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author 王强
 * @version 1.0
 * @date 2023-10-17 8:57
 */
@Service
@Transactional
public class EnrollmentKeyCardService extends ServiceImpl<EnrollmentKeyCardMapper, EnrollmentKeyCard> {

    @Resource
    private EnrollmentKeyCardMapper keyCardMapper;

    @Resource
    private EnrollmentRiceCardService riceCardService;

    public void deleteByRegistrationId(String id){
        QueryWrapper<EnrollmentKeyCard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("enrollment_registration_id",id);
        keyCardMapper.delete(queryWrapper);
    }

    public EnrollmentKeyCard findById(String id) throws Exception {
        // 查询基础信息表
        EnrollmentKeyCard info = keyCardMapper.getById(id);
        return info;
    }

    public void updateStatusById(EnrollmentKeyCard dto) {
        keyCardMapper.updateStatusById(dto.getId(), dto.getType());
    }

    public EnrollmentKeyCard saveSecurityCard(EnrollmentKeyCard registration) throws Exception {
        if (StringUtils.isNotEmpty(registration.getId())){

            EnrollmentKeyCard report = keyCardMapper.getById(registration.getId());
            if (report != null){
                registration.setEnrollmentRegistrationId(report.getEnrollmentRegistrationId());
                return update(registration);
            }
        }
        return add(registration);
    }

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

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

        EnrollmentKeyCard report = new EnrollmentKeyCard();
        BeanUtils.copyProperties(reportData, report);
        report.setCreateById(userDTO.getId());
        report.setCreateTime(new Date());
        report.setUpdateTime(new Date());
        report.setUpdateById(userDTO.getId());
        keyCardMapper.insert(report);

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

        EnrollmentKeyCard report = new EnrollmentKeyCard();
        BeanUtils.copyProperties(reportData, report);
        report.setUpdateById(userDTO.getId());
        report.setUpdateTime(new Date());
        keyCardMapper.updateById(report);
        if (report.getType().equals("5")){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String day = format.format(new Date());
            //发送通知到入职登记的人员
            String userId = keyCardMapper.getNoticeUserId(report.getId());
            String userName = SpringUtil.getBean(IUserApi.class).getById(userId).getName();
            String uuid = UUID.randomUUID().toString();
            //发送通知
            Map<String ,String > map = new HashMap<>();
            map.put("taskId",uuid);
            map.put("title","门卡领取提醒");
            map.put("defId",report.getId());
            map.put("taskName","门卡领取提醒");
            map.put("createUser",userDTO.getLoginName());
            map.put("createTime",day);
            map.put("noticeName",userName);
            map.put("noticeId",userId);
            map.put("createById",report.getCreateById());
            SpringUtil.getBean(IFlowableApi.class).add(map);

            Map map2 = SpringUtil.getBean(IFlowableApi.class).getByNameForFen("完善餐补卡号");
            String procDefId = map2.get("id")+"";
            //发起完善餐补卡号流程
            String uid = SnowFlake.getId();
            EnrollmentRiceCard wageCard = new EnrollmentRiceCard();
            wageCard.setId(uid);
            wageCard.setCreateById("1");
            wageCard.setUpdateById("1");
            wageCard.setProcessDefinitionId(procDefId);
            wageCard.setEnrollmentRegistrationId(report.getEnrollmentRegistrationId());
            riceCardService.save(wageCard);

            String procDefKey = map2.get("key")+"";
            String businessTable = "human_resources_enrollment_rice_card";
            String businessId = uid;
            String title = "完善餐补卡号";
            String assignee = userId;
            String recordType = "";
            Map<String,String> newMap = new HashMap();
            newMap.put("procDefId", procDefId);
            newMap.put("procDefKey", procDefKey);
            newMap.put("businessTable", businessTable);
            newMap.put("businessId", businessId);
            newMap.put("title", title);
            newMap.put("assignee", assignee);
            newMap.put("recordType", recordType);
            String procInsId = SpringUtil.getBean(IFlowableApi.class).startForFen(newMap);

            wageCard.setProcInsId(procInsId);
            wageCard.setType("2");
            riceCardService.saveOrUpdate(wageCard);


        }

        return report;
    }
}
