package com.kingdee.eas.custom.integrationWeb.apimgt.handler;

import com.kingdee.eas.custom.integration.apimgt.OpenPlatformAuthBillApiEntryCollection;
import com.kingdee.eas.custom.integration.apimgt.OpenPlatformAuthBillInfo;
import com.kingdee.eas.custom.integration.base.util.ApiKeyGenerator;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.shr.base.syssetting.BaseItemStateEnum;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.base.syssetting.web.handler.EditHandler;
import com.kingdee.util.DateTimeUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;

/**
 * @Description 开发平台授权单
 * @Date 2026/7/3 18:16
 * @Created by HeYuan
 */
public class OpenPlatformAuthBillEditHandler extends EditHandler {

    @Override
    protected void beforeSave(
            HttpServletRequest request,
            HttpServletResponse response,
            CoreBaseInfo model
    ) throws SHRWebException {
        super.beforeSave(request, response, model);
        //处理保存后,状态写入的枚举的别名错误
        OpenPlatformAuthBillInfo info = (OpenPlatformAuthBillInfo) model;
        BaseItemStateEnum state = info.getState();
        if (state != null) {
            info.put("State", state.getValue());
        }
    }


    @Override
    protected void afterCreateNewModel(
            HttpServletRequest request,
            HttpServletResponse response,
            CoreBaseInfo coreBaseInfo
    ) throws SHRWebException {
        try {
            OpenPlatformAuthBillInfo info = (OpenPlatformAuthBillInfo) coreBaseInfo;
            // 设置状态为启用
            info.setState(BaseItemStateEnum.ENABLE);
            //自动生成密钥
            info.setAppSecret(ApiKeyGenerator.generateAppSecret());

            info.setExpireDate(DateTimeUtils.parseDate("2199-12-31", "yyyy-MM-dd"));
        } catch (ParseException e) {
            throw new ShrWebBizException(e);
        }
    }

    @Override
    protected void verifyModel(
            HttpServletRequest request,
            HttpServletResponse response,
            CoreBaseInfo model
    ) throws SHRWebException {
        OpenPlatformAuthBillInfo info = (OpenPlatformAuthBillInfo) model;
        OpenPlatformAuthBillApiEntryCollection apiEntry = info.getApiEntry();
        if (apiEntry == null || apiEntry.isEmpty()) {
            throw new ShrWebBizException("API接口不能为空");
        }
    }
}
