package fi.er.webService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.openapi.common.custom.annotation.ApiController;
import kd.bos.openapi.common.custom.annotation.ApiMapping;
import kd.bos.openapi.common.custom.annotation.ApiParam;
import kd.bos.openapi.common.custom.annotation.ApiPostMapping;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import nckd.jimin.jyyy.fi.common.NstcApiReturnModel;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zf
 * 接收九恒星行名行号
 */
@ApiController(value = "bank", desc = "自定义API 行名行号同步")
@ApiMapping(value = "saveBankApi")
public class SaveBankApi implements Serializable {
    protected static final Long DEFAULT_ORG_ID = 100000L;
    private static final Log logger = LogFactory.getLog(SaveAccountApi.class);


    /**
     * @description 行名行号同步接口
     * @param data
     * @return CustomApiResult
     */
    @ApiPostMapping(value = "/save", desc = "同步行名行号")
    public CustomApiResult<JSONObject> saveBank (@ApiParam(value = "九恒星行名行号") JSONArray data) {
        StringBuilder resultString = new StringBuilder();
        List<BankSynReturnModel> returnList = new ArrayList<>();
        Boolean result = true;

        //默认的国家
        DynamicObject defaultgj = BusinessDataServiceHelper.loadSingle("1000001", "bd_country");


        RequestContext rc = RequestContext.get();
        DynamicObject user = BusinessDataServiceHelper.loadSingleFromCache(rc.getCurrUserId(), "bos_user");

        JSONArray dataArray = new JSONArray();

        if(data == null || data.size() == 0){
            return returnResult("500", "E", "接口调用失败，data无实际数据", null);
        }

        JSONObject dataJSON = data.getJSONObject(0);
        if(dataJSON.get("param0") == null){
            return returnResult("500", "E", "接口调用失败，param0无实际数据", null);
        }

        JSONArray paramArray = dataJSON.getJSONArray("param0");
        if(paramArray == null || paramArray.size() == 0){
            return returnResult("500", "E", "接口调用失败，param0无实际数据", null);
        }

        //循环传入的数据
        for (int i = 0; i < paramArray.size(); i++) {
            JSONObject eobject = paramArray.getJSONObject(i);

            try {
                NstcApiReturnModel contractSynReturnModel = syncBank(eobject, defaultgj, user);
                if ("500".equals(contractSynReturnModel.getCode())) {
                    result = false;
                }

                dataArray.add(JSONObject.parseObject(JSON.toJSONString(contractSynReturnModel)));
            } catch (Exception e) {
                logger.error("保存银行账号失败：{}", e.getMessage());

                NstcApiReturnModel returnModel = new NstcApiReturnModel();

                returnModel.setNumber(eobject.get("number")+"");
                returnModel.setName(eobject.get("name")+"");
                returnModel.setCode("500");
                returnModel.setMessage("保存银行账号失败: " + e.getMessage());

                dataArray.add(JSONObject.parseObject(JSON.toJSONString(returnModel)));
            }
        }

        return returnResult("200", "S", "接口调用成功，同步结果请查看responseData参数", dataArray);
    }


    /**
     * @description 保存行名行号
     * @param jsonObject
     */
    private NstcApiReturnModel syncBank(JSONObject jsonObject,DynamicObject defaultgj ,DynamicObject user) {
        NstcApiReturnModel contractSynReturnModel = new NstcApiReturnModel();
        String number = jsonObject.get("number")+"";
        String name = jsonObject.get("name")+"";
        if ("".equals(number)||"".equals(name)) {
            contractSynReturnModel.setCode("500");
            contractSynReturnModel.setMessage("名称和编码不能为空");
            return contractSynReturnModel;
        }

        contractSynReturnModel.setNumber(number);
        contractSynReturnModel.setName(name);

        //查询是否存在，存在则返回。不存在更新
        QFilter qFilter = new QFilter("number","=",number);
        DynamicObject bebankinfo =  BusinessDataServiceHelper.loadSingle("bd_bebank",new QFilter[]{qFilter});
        if(bebankinfo!=null){
            //已存在
            contractSynReturnModel.setCode("500");
            contractSynReturnModel.setMessage("该行号已存在");
            return contractSynReturnModel;
        }

        bebankinfo =BusinessDataServiceHelper.newDynamicObject("bd_bebank");
        bebankinfo.set("number",number);
        bebankinfo.set("name",name);
        bebankinfo.set("country",defaultgj);
        bebankinfo.set("union_number",number);
        bebankinfo.set("provincetxt",jsonObject.get("provinceName")+"");//省份
        bebankinfo.set("citytxt",jsonObject.get("cityName")+"");//城市
        bebankinfo.set("enable",1);
        bebankinfo.set("status","C");


        Date curDate = new Date();
        bebankinfo.set("creator", user);
        bebankinfo.set("createtime", curDate);

        //执行保存
        OperationResult result = SaveServiceHelper.saveOperate("bd_bebank", new DynamicObject[]{bebankinfo}, OperateOption.create());

        StringBuilder err = new StringBuilder();
        if (result.getSuccessPkIds().size() > 0) {
            if (result.isSuccess()) {
                contractSynReturnModel.setCode("200");
                contractSynReturnModel.setMessage("保存成功");
                return contractSynReturnModel;
            } else {
                for (int k = 0; k < result.getAllErrorOrValidateInfo().size(); k++) {
                    String message = result.getAllErrorOrValidateInfo().get(k).getMessage();
                    err.append("/").append(message);
                }
                contractSynReturnModel.setCode("500");
                contractSynReturnModel.setMessage(err.toString());
                return contractSynReturnModel;
            }
        }else{
            contractSynReturnModel.setCode("500");
            contractSynReturnModel.setMessage("保存失败");
            return contractSynReturnModel;
        }
    }

    /**
     * 自定义返回data对象
     * @param code  编码
     * @param message  错误信息
     * @return   CustomApiResult  返回
     */
    public CustomApiResult<JSONObject> returnResult(String code, String status, String message, JSONArray dataArrary){
        JSONObject reslutData = new JSONObject();

        JSONArray responseData = new JSONArray();
        JSONObject dataJSON = new JSONObject();
        dataJSON.put("data", dataArrary);

        responseData.add(dataJSON);

        reslutData.put("code", code);
        reslutData.put("status", status);
        reslutData.put("message", message);
        reslutData.put("responseData", responseData);

        return CustomApiResult.success(reslutData);
    }
}
