package com.kingdee.eas.custom.esign.osf;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.bsf.service.app.IHRMsfService;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.esign.ESignGlobalStatusOverviewCollection;
import com.kingdee.eas.custom.esign.ESignGlobalStatusOverviewFactory;
import com.kingdee.eas.custom.esign.ESignGlobalStatusOverviewInfo;
import com.kingdee.eas.custom.esign.IESignGlobalStatusOverview;
import com.kingdee.eas.custom.esign.bizEnum.EsignStatusEnum;
import com.kingdee.eas.custom.esign.util.SyncSignedFilesUtil;

import java.util.Map;

/**
 * https://open.esign.cn/doc/opendoc/notify3/sblzg8
 * 签署类通知事件
 *
 * 签署方-已读通知:OPERATOR_READ
 *
 * 签署方-签署结果通知:SIGN_MISSON_COMPLETE
 *
 * 流程结束通知:SIGN_FLOW_COMPLETE
 *
 * 签署发起成功通知:SIGN_FLOW_INITIATED
 *
 * 签署人更正个人信息回调通知:OPERATOR_CORRECT_IDENTITY
 *
 * 经办人转交签署任务通知:TRANSMISS_SIGN
 *
 * 用印审批驳回通知:SIGN_SEAL_EXAMINE_REJECTED
 *
 * 合同发起解约通知:SIGN_FILE_RESCISSION_INITIATE
 *
 * 合同解约成功通知:SIGN_FILE_RESCINDED
 *
 * 抄送方-已读通知:COPIER_READ
 *
 * 批量签署结果通知:BATCH_SIGN_FLOW_COMPLETE
 *
 *
 * description: CallBackToOSFService <br>
 * date: 24/11/2025 下午 5:11 <br>
 * author: lhbj <br>
 * version: 1.0 <br>
 */
public class CallBackToOSFService implements IHRMsfService {
    @Override
    public Object process(Context ctx, Map map) throws EASBizException, BOSException {
        String data = (String) map.get("data");
        System.out.println(data);
        JSONObject jsonObject =JSONObject.parseObject(data);
        String action = jsonObject.getString("action");
        if("SIGN_FLOW_COMPLETE".equals(action)){
            return SIGN_FLOW_COMPLETE(ctx,jsonObject);
        }

        return "success";
    }

    /**
     * 签署人打开签署文件
     * {
     *     "action": "OPERATOR_READ",
     *     "timestamp": 1763969581086,
     *     "signFlowId": "f106295489f7421b82c8c78ca1673aed",
     *     "customBizNum": "62453221152523",
     *     "signOrder": 1,
     *     "readTime": "2025-11-24 15:33:01",
     *     "operator": {
     *         "psnId": "8f69856a21584a04b4b7be84ca49ed0c",
     *         "psnAccount": {
     *             "accountMobile": "17620530018"
     *         }
     *     }
     * }
     * @param jsonObject
     * @return
     */
    public Map<String,Object> OPERATOR_READ(Context ctx,JSONObject jsonObject){
        Map<String,Object> map = Maps.newHashMap();
        map.put("state","success");
        return map;
    }

    /**
     * 签署人签名消息任务完成
     *
     * {
     *     "action": "SIGN_MISSON_COMPLETE",
     *     "timestamp": 1763969637171,
     *     "signFlowId": "f106295489f7421b82c8c78ca1673aed",
     *     "customBizNum": "62453221152523",
     *     "signOrder": 1,
     *     "operateTime": 1763969637000,
     *     "signResult": 4,(2 - 签署完成，4 - 拒签)
     *     "resultDescription": "测试回调",
     *     "operator": {
     *         "psnId": "8f69856a21584a04b4b7be84ca49ed0c",
     *         "psnAccount": {
     *             "accountMobile": "17620530018"
     *         }
     *     }
     * }
     * @param jsonObject
     * @return
     */
    public Map<String,Object> SIGN_MISSON_COMPLETE(Context ctx,JSONObject jsonObject){
        Map<String,Object> map = Maps.newHashMap();
        map.put("state","success");

        return map;
    }

    /**
     * 签署人签名流程任务完成
     * {
     *     "action": "SIGN_FLOW_COMPLETE",
     *     "timestamp": 1763969637153,
     *     "signFlowId": "f106295489f7421b82c8c78ca1673aed",
     *     "signFlowTitle": "测试签署",
     *     "signFlowStatus": "7",
     *     "statusDescription": "测试回调",
     *     "signFlowCreateTime": 1763969482000,
     *     "signFlowStartTime": 1763969483000,
     *     "signFlowFinishTime": 1763969637000
     * }
     * signFlowStatus:
     *  2 - 已完成（所有签署方完成签署）
     *  3 - 已撤销（发起方撤销签署任务）
     *  5 - 已过期（签署截止日到期后触发）
     *  7 - 已拒签（签署方拒绝签署）
     *
     * @param jsonObject
     * @return
     */
    public Map<String,Object> SIGN_FLOW_COMPLETE(Context ctx,JSONObject jsonObject) throws BOSException, EASBizException {
        Map<String, Object> map = getStringObjectMap(ctx, jsonObject);
        this.afterComplete(ctx, jsonObject);
        return map;
    }

    public Map<String, Object> getStringObjectMap(Context ctx, JSONObject jsonObject) throws BOSException, EASBizException {
        Map<String,Object> map = Maps.newHashMap();
        map.put("state","success");
        String signFlowStatus = jsonObject.getString("signFlowStatus");
        String signFlowId = jsonObject.getString("signFlowId");
        String statusDescription = jsonObject.getString("statusDescription");
        EntityViewInfo view = new EntityViewInfo();
        FilterInfo filterInfo = new FilterInfo();
        filterInfo.getFilterItems().add(new FilterItemInfo("signFlowId='"+signFlowId+"'"));
        view.setFilter(filterInfo);
        SelectorItemCollection selectorItemCollection = new SelectorItemCollection();
        selectorItemCollection.add(new SelectorItemInfo("*"));
        view.setSelector(selectorItemCollection);
        IESignGlobalStatusOverview globalStatusOverview = ESignGlobalStatusOverviewFactory.getLocalInstance(ctx);
        ESignGlobalStatusOverviewCollection collection = globalStatusOverview.getESignGlobalStatusOverviewCollection(view);
        for( int i=0;i<collection.size();i++){
            try {
                ESignGlobalStatusOverviewInfo info = collection.get(i);
                info.setEsignStatus(EsignStatusEnum.getEnum(Integer.parseInt(signFlowStatus)));
                info.setDescription(statusDescription);
                SyncSignedFilesUtil.syncAttachmentsForEmpPage(ctx, info.getId().toString());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        SelectorItemCollection selectorUpdatePartial = new SelectorItemCollection();
        selectorUpdatePartial.add(new SelectorItemInfo("esignStatus"));
        selectorUpdatePartial.add(new SelectorItemInfo("description"));
        globalStatusOverview.updatePartialBatchData(collection,selectorUpdatePartial);
        return map;
    }


    public void afterComplete(Context ctx, JSONObject jsonObject) {

    }
}
