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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.ormapping.CanNotDeleteException;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.eas.custom.esign.*;
import com.kingdee.eas.custom.esign.bizEnum.SyncStatusEnum;
import com.kingdee.eas.custom.esign.tsign.hz.comm.EsignHttpResponse;
import com.kingdee.eas.custom.esign.tsign.hz.exception.EsignException;
import com.kingdee.eas.custom.esign.util.EsignHttpUtil;
import com.kingdee.shr.base.syssetting.BaseItemStateEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import javax.ejb.*;

import com.kingdee.bos.*;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.eas.common.EASBizException;

import java.lang.String;
import java.sql.Connection;
import java.sql.Time;
import java.util.HashMap;
import java.util.Map;

/**
 * 电子签文件模板
 */
public class ESignTemplateFileEntryControllerBean extends AbstractESignTemplateFileEntryControllerBean {
    private static Logger logger = Logger.getLogger(ESignTemplateFileEntryControllerBean.class);

    /**
     * 同步成功
     *
     * @param ctx
     * @param entryId
     * @param syncResult
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    protected void _syncSuccess(Context ctx, String entryId, String syncResult) throws BOSException, EASBizException {
        super._syncSuccess(ctx, entryId, syncResult);
        if (StringUtils.isBlank(entryId)) {
            throw new EASBizException(EASBizException.CHECKBLANK, new Object[]{"单据id不能为空!"});
        }
        if (StringUtils.isBlank(syncResult)) {
            syncResult = "同步成功";
        }
        ESignTemplateFileEntryInfo eSignTemplateFileEntryInfo = getESignTemplateFileEntryInfo(ctx, new ObjectUuidPK(entryId));
        eSignTemplateFileEntryInfo.setSyncStatus(SyncStatusEnum.SYNCED);
        eSignTemplateFileEntryInfo.setSyncResult(syncResult);
        eSignTemplateFileEntryInfo.setSyncTime(new Time(System.currentTimeMillis()));
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("syncStatus");
        sic.add("syncResult");
        sic.add("syncTime");
        updatePartial(ctx, eSignTemplateFileEntryInfo, sic);
    }

    /**
     * 同步失败
     *
     * @param ctx
     * @param entryId
     * @param syncResult
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    protected void _syncFail(Context ctx, String entryId, String syncResult) throws BOSException, EASBizException {
        super._syncFail(ctx, entryId, syncResult);
        if (StringUtils.isBlank(entryId)) {
            throw new EASBizException(EASBizException.CHECKBLANK, new Object[]{"单据id不能为空!"});
        }
        if (StringUtils.isBlank(syncResult)) {
            syncResult = "同步失败";
        }
        ESignTemplateFileEntryInfo eSignTemplateFileEntryInfo = getESignTemplateFileEntryInfo(ctx, new ObjectUuidPK(entryId));
        eSignTemplateFileEntryInfo.setSyncStatus(SyncStatusEnum.SYNC_FAILED);
        eSignTemplateFileEntryInfo.setSyncResult(syncResult);
        eSignTemplateFileEntryInfo.setSyncTime(new Time(System.currentTimeMillis()));
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("syncStatus");
        sic.add("syncResult");
        sic.add("syncTime");
        updatePartial(ctx, eSignTemplateFileEntryInfo, sic);
    }

    /**
     * 同步模板字段
     *
     * @param ctx
     * @param entryId
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    protected void _syncTemplateFields(Context ctx, String entryId)
            throws BOSException, EASBizException {
        super._syncTemplateFields(ctx, entryId);
        if (StringUtils.isBlank(entryId)) {
            throw new EASBizException(EASBizException.CHECKBLANK, new Object[]{"单据id不能为空!"});
        }
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("*");
        sic.add("fields.*");
        ESignTemplateFileEntryInfo eSignTemplateFileEntryInfo = getESignTemplateFileEntryInfo(ctx, new ObjectUuidPK(entryId), sic);
        String eSignTemplateId = eSignTemplateFileEntryInfo.getESignTemplateId();
        if (StringUtils.isBlank(eSignTemplateId)) {
            throw new BOSException("e 签宝模板 id为空!");
        }
        //1.调用接口获取模板字段
        EsignHttpResponse response = null;
        try {
            response = EsignHttpUtil.getDocTemplatesDetailById(eSignTemplateId);
        } catch (EsignException e) {
            e.printStackTrace();
            throw new BOSException("调用e签宝接口报错: " + e.getMessage());
        }
        String body = response.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (0 != jsonObject.getInteger("code")) {
            throw new BOSException(jsonObject.getString("message"));
        }
        JSONObject data = jsonObject.getJSONObject("data");
        //附件下载地址
        String fileDownloadUrl = data.getString("fileDownloadUrl");
        JSONArray components = data.getJSONArray("components");
        //2.比较现有模板字段,如果新增字段则添加,删除字段就更新为失效
        ESignTemplateFileEntryFieldCollection fields = eSignTemplateFileEntryInfo.getFields();
        Map<String, ESignTemplateFileEntryFieldInfo> fieldMap = new HashMap<String, ESignTemplateFileEntryFieldInfo>();
        for (int i = 0; i < fields.size(); i++) {
            ESignTemplateFileEntryFieldInfo fieldInfo = fields.get(i);
            fieldMap.put(fieldInfo.getTemplateFieldId(), fieldInfo);
        }
        for (int i = 0; i < components.size(); i++) {
            JSONObject component = components.getJSONObject(i);
            //组件id
            String componentId = component.getString("componentId");
            //组件编码(可以为空)
            String componentKey = component.getString("componentKey");
            //组件名称
            String componentName = component.getString("componentName");
            //是否必填
            boolean isRrequired = component.getBoolean("required");
            //组件排序,从1开始
            int componentOrder = component.getInteger("componentOrder");
            ESignTemplateFileEntryFieldInfo fieldInfo = fieldMap.get(componentId);
            if (fieldInfo != null) {
                fieldMap.remove(componentId);
            } else {
                fieldInfo = new ESignTemplateFileEntryFieldInfo();
                fieldInfo.setTemplateFieldId(componentId);
                fields.add(fieldInfo);
            }
            //修改字段名称
            fieldInfo.setTemplateFieldName(componentName);
            //修改字段排序
            fieldInfo.setSeq(componentOrder);
            //修改是否必填
            fieldInfo.setRequired(isRrequired);
            //组件编码
            fieldInfo.setTemplateFieldKey(componentKey);
        }
        if (!fieldMap.isEmpty()) {
            //已经失效的字段
            for (String componentId : fieldMap.keySet()) {
                fieldMap.get(componentId).setInvalid(true);
            }
        }
        //更新
        update(ctx, new ObjectUuidPK(entryId), eSignTemplateFileEntryInfo);
        //3.同步模板附件
        //syncTemplateAttachments(ctx, billId);

    }


    /**
     * 检查电子签名模板文件是否可以删除
     *
     * @param ctx 上下文对象
     * @param pk  对象主键
     * @param cn  数据库连接
     * @throws CanNotDeleteException 当数据处于启用状态或发生业务异常时抛出
     */
    @Override
    protected void _canDelete(Context ctx, IObjectPK pk, Connection cn) throws CanNotDeleteException {
        super._canDelete(ctx, pk, cn);
        try {
            // 获取电子签名模板文件信息并检查状态
            ESignTemplateFileEntryInfo info = getESignTemplateFileEntryInfo(ctx, pk);
            BaseItemStateEnum state = info.getState();
            if (BaseItemStateEnum.ENABLE.equals(state)) {
                throw new CanNotDeleteException("启用的数据，不允许删除！");
            }
        } catch (BOSException e) {
            logger.error(e.getMessage(), e);
            throw new CanNotDeleteException(e);
        } catch (EASBizException e) {
            logger.error(e.getMessage(), e);
            throw new CanNotDeleteException(e);
        }
    }

}