package com.jeeplus.human.depart.handover.service;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.human.depart.handover.domain.Handover;
import com.jeeplus.human.depart.handover.domain.HandoverRecovery;
import com.jeeplus.human.depart.handover.mapper.HandoverMapper;
import com.jeeplus.human.depart.handover.mapper.HandoverRecoveryMapper;
import com.jeeplus.human.enrollment.enrollmentRegistration.mapper.EnrollmentRegistrationMapper;
import com.jeeplus.human.signature.entity.Action;
import com.jeeplus.human.signature.entity.Location;
import com.jeeplus.human.signature.entity.SignatorieInfo;
import com.jeeplus.human.signature.entity.SignatureContract;
import com.jeeplus.human.signature.utils.Global;
import com.jeeplus.human.signature.utils.SignaturePostUtil;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IPostApi;
import com.jeeplus.sys.feign.IRoleApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.PostDTO;
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.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 王强
 * @version 1.0
 * @date 2023-11-15 8:54
 */
@Service
@Transactional
public class HandoverRecoveryService extends ServiceImpl<HandoverRecoveryMapper, HandoverRecovery> {

    private static final String HTTPTOP = Global.getConfig("signature_http_top");

    /**
     * 离职盖章流程id
     */
    private static String DIMISSIONID  = Global.getConfig("dimission_id");

    /**
     * 会计公司印章
     */
    private static String COMPANYROUNDSEALFINANCEID  = Global.getConfig("company_round_seal_finance_id");

    @Resource
    private HandoverRecoveryMapper recoveryMapper;

    @Resource
    private HandoverMapper handoverMapper;

    @Resource
    private EnrollmentRegistrationMapper registrationMapper;

    public void deleteByRegistrationId(String id){
        QueryWrapper<HandoverRecovery> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("handover_id",id);
        recoveryMapper.delete(queryWrapper);
    }

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

    public void updateStatusById(HandoverRecovery dto) {
        recoveryMapper.updateStatusById(dto.getId(), dto.getType());

    }

    public HandoverRecovery saveHandoverRecovery(HandoverRecovery accounts) throws Exception {
        if (StringUtils.isNotEmpty(accounts.getId())){

            HandoverRecovery report = recoveryMapper.getById(accounts.getId());
            if (report != null){
                accounts.setCreateById(report.getCreateById());
                return update(accounts);
            }
        }
        return add(accounts);
    }

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

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

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

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

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

        if (report.getType().equals("5")){
            //根据用户id将在职状态改为离职
            Handover handover = handoverMapper.getById(report.getHandoverId());
            //获取当前登录人信息
            UserDTO createUserDTO = SpringUtil.getBean ( IUserApi.class ).getById(handover.getCreateById());

            List<WorkAttachmentInfo> attachmentInfoList = SpringUtil.getBean ( IWorkAttachmentApi.class ).selectListByAttachmentId(handover.getId());

            registrationMapper.updateByUserId(handover.getCreateById());
            //发送通知给岗位【考勤统计人】
            PostDTO postInfo = SpringUtil.getBean(IPostApi.class).getPostDTOByName("考勤统计人");
            String userId = getAssignee(postInfo.getId());

            String uuid = UUID.randomUUID().toString();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String day = format.format(new Date());
            String userName = SpringUtil.getBean(IUserApi.class).getById(userId).getName();
            Map<String ,String > map = new HashMap<>();

            map.put("taskId",uuid);
            map.put("title","员工:" + handover.getName() +"已离职");
            map.put("defId",report.getId());
            map.put("taskName","员工:" + handover.getName() +"已离职");
            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<String ,String > map2 = new HashMap<>();

            if("1".equals(handover.getSignatureFlag())){
                map2.put("title","离职交接审批完成，请点击下载离职证明");
                map2.put("taskName","离职交接审批完成，请点击下载离职证明");
            }else{
                map2.put("title","离职交接审批完成，请点击下载离职证明，并到办公室进行盖章");
                map2.put("taskName","离职交接审批完成，请点击下载离职证明，并到办公室进行盖章");
                map2.put("dimissionProveUrl","离职交接审批完成，请点击下载离职证明");
            }

            if(attachmentInfoList.size()>0){
                map2.put("dimissionProveUrl",attachmentInfoList.get(0).getUrl());
            }else{
                map2.put("dimissionProveUrl","");
            }
            map2.put("taskId",uuid);
            map2.put("fileName",createUserDTO.getName() + "离职证明");
            map2.put("defId",report.getHandoverId());
            map2.put("createUser",userDTO.getLoginName());
            map2.put("createTime",day);
            map2.put("noticeName",userName);
            map2.put("noticeId",handover.getCreateById());
            map2.put("createById",userDTO.getId());
            SpringUtil.getBean(IFlowableApi.class).add(map2);

            //离职证明电子章处理
            //对离职证明进行盖章操作
            Map<String, Object> signatureContractIdMap = createSignatureContractId(handover.getWordFilePath());
            boolean success = (boolean) signatureContractIdMap.get("success");
            if(success){
                handover.setSignatureContractId(signatureContractIdMap.get("contractId").toString());
                handoverMapper.updateById(handover);
            }else{
                System.out.println(signatureContractIdMap);
            }
        }

        return report;
    }
    /**
     * 生成并保存签章contractId 信息
     * @param filePath 临时文件路径（需盖章文件）
     * @return
     */
    public Map<String,Object> createSignatureContractId(String filePath){
        Map<String,Object> map = new HashMap<String,Object>();

        //获取文件生成的documentId
        List<String> documentList = Lists.newArrayList();

        try{
            //将下载下来的文件转换为file文件
            File srcFile = new File(filePath);
            //截取文件后缀名
            String substring = srcFile.getName().substring(srcFile.getName().lastIndexOf(".")+1, srcFile.getName().length());
            if(!"doc".equals(substring.toLowerCase()) && !"docx".equals(substring.toLowerCase()) && !"pdf".equals(substring.toLowerCase())){
                map.put("success",false);
                map.put("message","请上传doc、docx或者pdf的文件进行签章操作");
                return map;
            }
            //获取真签单的documentId
            HashMap hashMap = new SignaturePostUtil().getDocument(srcFile);
            String code = hashMap.get("code").toString();
            String documentId = "";
            if("0".equals(code)){
                String result = hashMap.get("result").toString();
                HashMap documentIdMap = JSON.parseObject(result, HashMap.class);
                documentId =  documentIdMap.get("documentId").toString();
                if("".equals(documentId)){
                    map.put("success",false);
                    map.put("message","离职证明文件创建失败");
                    return map;
                }
            }else{
                String message = hashMap.get("message").toString();
                map.put("success",false);
                map.put("message",message);
                return map;
            }

            documentList.add(documentId);

        }catch (Exception e){

        }finally {
            if(StringUtils.isNotBlank(filePath)){
                //根据路径创建文件对象
                File file = new File(filePath);
                //路径是个文件且不为空时删除文件
                if(file.isFile()&&file.exists()){
                    file.delete();
                }
            }
        }

        //根据项目id 和 documentId生成合同id
        HashMap contractIdHashMap = this.getSignatureContractIdByPageSign(documentList);
        String contractIdCode = contractIdHashMap.get("code").toString();
        String contractId = "";
        if("0".equals(contractIdCode)){
            contractId = contractIdHashMap.get("contractId").toString();
            map.put("contractId",contractId);
            if("".equals(contractId)){
                map.put("success",false);
                map.put("message","签章文件创建失败");
                return map;
            }

        }else{
            map.put("success",false);
            map.put("message",contractIdHashMap.get("message").toString());
            return map;
        }

        map.put("success",true);
        map.put("message","生成签章contractId成功");
        return map;
    }

    /**
     * 根据项目报告id 和 documentId生成合同id(页面签署生成)
     * 个人签字章功能
     * @param documentList
     * @return
     */
    public HashMap getSignatureContractIdByPageSign( List<String> documentList){
        HashMap hashMap = new HashMap();
        Set<String> serialIdSet = new HashSet<>();
        //创建签署方信息
        List<Action> actions = Lists.newArrayList();
        Action companyAction = new Action();
        companyAction.setType("CORPORATE");
        companyAction.setName("公司印章");
        companyAction.setSerialNo("1");
        //添加盖章位置
        List<Location> locations = Lists.newArrayList();
        Location location = new Location();
        location.setDocumentId(documentList.get(0));
        location.setSealId(COMPANYROUNDSEALFINANCEID);
        location.setRectType("SEAL_CORPORATE");
        location.setKeyword("单位盖章");
        location.setKeywordIndex(1);
        locations.add(location);

        List<String> serialIdList = new ArrayList<String>(serialIdSet);
        companyAction.setSealIds("[" + String.join(",", serialIdList) + "]");
        //判定该action是否采用自动签署
        companyAction.setAutoSign("true");
        companyAction.setLocations(locations);
        actions.add(companyAction);
        //创建签署方信息表
        List<SignatorieInfo> signatories = Lists.newArrayList();
        SignatorieInfo signatorieInfo1 = new SignatorieInfo();
        signatorieInfo1.setSerialNo("1");
        signatorieInfo1.setTenantName("江苏兴光项目管理有限公司");
        signatorieInfo1.setTenantType("COMPANY");
        signatorieInfo1.setActions(actions);
        signatories.add(signatorieInfo1);
        SignatureContract signatureContract = new SignatureContract();
        signatureContract.setDocuments(documentList);
        //离职证明用印流程id
        signatureContract.setCategoryId(DIMISSIONID);
        signatureContract.setSend(true);
        signatureContract.setSignatories(signatories);
        signatureContract.setSn("");
        signatureContract.setSubject("" + "离职证明");//添加项目名称
        net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(signatureContract);
        System.out.println(json.toString());
        long s5=System.currentTimeMillis();
        System.out.println(json.toString());
        String contractIdMapStr = SignaturePostUtil.sendPostApplicationJson(HTTPTOP + "/contract/createbycategory", json.toString());
        long s6=System.currentTimeMillis();
        System.out.println("获取合同id获取时间：" + (s6 - s5));
        hashMap = JSON.parseObject(contractIdMapStr, HashMap.class);

        return hashMap;
    }



    public String getAssignee(String roleId){
        List<UserDTO> userDTOS = SpringUtil.getBean(IUserApi.class).findListFlowAbleByPostId(roleId);
        StringJoiner idJoiner = new StringJoiner(",");
        for (UserDTO user : userDTOS) {
            idJoiner.add(String.valueOf(user.getId()));
        }

        return idJoiner.toString();
    }
}
