package com.yem.or.op;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yem.or.utils.HttpUtils;
import com.yem.or.utils.OrderApiUtils;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.serialization.DataEntitySerializer;
import kd.bos.dataentity.serialization.DataEntitySerializerOption;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.exception.KDBizException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.url.UrlService;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhouc
 * @date 2024/3/22 21:32
 * @className clientdemandAuditEdit
 * @description 客户需求单审核更新下单平台状态接口
 */
public class clientdemandAuditEdit extends AbstractOperationServicePlugIn {
    Log log = LogFactory.getLog(AbstractOperationServicePlugIn.class);

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> keys = e.getFieldKeys();
        keys.add("yem_orderplatid");
        keys.add("yem_synchronization");
        keys.add("yem_billtype");
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntity : dataEntities) {
            dataEntity = BusinessDataServiceHelper.loadSingle(dataEntity.getPkValue(), dataEntity.getDynamicObjectType().getName());
            try {
                String billno = dataEntity.getString("billno");
                DynamicObject yem_billtype = dataEntity.getDynamicObject("yem_billtype");
                if (yem_billtype != null) {
                    String number = yem_billtype.getString("number");
                    if (number.equals("yem_im_clientdema_pj")) {
                        //将单据对象转换为JSON
                        String url = OrderApiUtils.ENDPOINTS + "/admin-api/em/partsorderlist/confirm";
                        Map<String, String> headers = new HashMap<>();
                        addMissInfo(dataEntity);
                        RequestContext requestContext = RequestContext.get();
                        DynamicObjectCollection yem_im_detailedinfor = dataEntity.getDynamicObjectCollection("yem_im_detailedinfor");
                        for (int i = 0; i < yem_im_detailedinfor.size(); i++) {
                            DynamicObject dynamicObject = yem_im_detailedinfor.get(i);
                            String yem_picture = dynamicObject.getString("yem_picture");
                            String imageFullUrl = UrlService.getImageFullUrl(yem_picture);
                            imageFullUrl = imageFullUrl + "?access_token=" + requestContext.getGlobalSessionId();
                            if (imageFullUrl.length() > 0) {
                                Map updatefile = updatefile(imageFullUrl, yem_picture);
                                if (updatefile.size() > 0) {
                                    String status = updatefile.get("status").toString();
                                    if (status.equals("success")) {
                                        String url1 = updatefile.get("url").toString();
                                        dynamicObject.set("yem_ordurl", url1);
                                    } else {
                                        String msg = updatefile.get("msg").toString();
                                        throw new KDBizException("同步下单平台图片错误：" + msg);
                                    }
                                }
                            }
                        }
                        JSONArray getfile = getfile(dataEntity);
                        dataEntity.set("yem_platformurl", getfile.toString());
                        String param = SerializationUtils.toJsonString(dataEntity);
                        log.debug("调用下单平台Json为：" + param);
                        Map<String, String> tokenmap = OrderApiUtils.getToken();
                        if (tokenmap.size() > 0) {
                            String status = tokenmap.get("status");
                            if (status.equals("success")) {
                                String token = tokenmap.get("token");
                                headers.put("Authorization", "Bearer " + token);
                            }
                            String res = HttpUtils.doPostWithHeader(url, param, headers);
                            JSONObject jsonObject = JSONObject.parseObject(res);
                            int code = jsonObject.getIntValue("code");
                            if (code > 0) {
                                String msg = jsonObject.getString("msg");
                                e.setCancel(true);
                                throw new KDBizException("同步下单平台状态异常，异常信息为：" + msg);
                            }
                        }
                    }
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    private void addMissInfo(DynamicObject dataEntity) {
        DynamicObjectCollection detailedinfor = dataEntity.getDynamicObjectCollection("yem_im_detailedinfor");

        for (DynamicObject dynamicObject : detailedinfor) {
            DynamicObject materiel = dynamicObject.getDynamicObject("yem_materiel");
            if (materiel != null) {
                DynamicObject fullObject = BusinessDataServiceHelper.loadSingle(materiel.getPkValue(), "bd_material");
                if (fullObject != null) {
                    dynamicObject.set("yem_materiel", fullObject);
                }
            }
        }
    }


    /**
     * 单据对象
     *
     * @param cacheObject
     * @return
     */
    public String saveSrcBill(DynamicObject cacheObject) {
        DataEntitySerializerOption option = new DataEntitySerializerOption();
        option.setIncludeDataEntityState(false);
        option.setIncludeComplexProperty(true);
        option.setIncludeCollectionProperty(true);
        option.setIncludeType(false);
        String json = DataEntitySerializer.serializerToString(cacheObject, option);
        return json;

    }

    /**
     * 获取分录附件地址
     *
     * @param mapurl
     * @param name
     * @return
     */
    public Map updatefile(String mapurl, String name) {
        Map map = new HashMap<>();
        try {
            String url = OrderApiUtils.ENDPOINTS + "/admin-api/infra/file/upload";
            Map<String, String> token = OrderApiUtils.getToken();
            if (token.size() > 0) {
                if (token.get("status").equals("success")) {
                    Map bomap = new HashMap<>();
                    bomap.put("Authorization", "Bearer " + token.get("token"));
//                    mapurl="http://10.64.112.152:8022/ierp/attachment/downloadImage/735aa977636a4129a15e22b9d37c9945.jpg?access_token=1878420900609526784_oHD1aXLitYVLRgX2sJjpHWMAIZPknIzu2xql0Si1grEBcEPc6dUBqwRvj2e7S11Pe2DqQvIP2Re5wVxB5crOXHwPn34a6Pw2RfAE";
                    MultipartFile multipartFile = HttpUtils.urlToMultipartFile(mapurl, name);
                    if (multipartFile != null) {
                        String result = HttpUtils.doPostFormData(url, "file", multipartFile, new HashMap<>(), bomap);
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        int code = jsonObject.getIntValue("code");
                        if (code == 0) {
                            map.put("url", jsonObject.getString("data"));
                            map.put("msg", "");
                            map.put("status", "success");
                        } else {
                            map.put("status", "success");
                            map.put("url", jsonObject.getString("data"));
                            map.put("msg", jsonObject.getString("msg"));
                        }
                    }
                } else {
                    map.put("status", "err");
                    map.put("msg", "获取TOken异常");
                }
            }
        } catch (IOException e) {
            map.put("status", "err");
            map.put("msg", e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status", "err");
            map.put("msg", "上传附件失败");
        }
        return map;
    }

    /**
     * 获取附件信息
     *
     * @param
     * @return
     */
    public JSONArray getfile(DynamicObject dataEntity) {
        JSONArray jsonArray = new JSONArray();
        try {
            String url = OrderApiUtils.ENDPOINTS + "/admin-api/infra/file/upload";
            List<Map<String, Object>> atts = AttachmentServiceHelper.getAttachments("yem_im_clientdemand", dataEntity.getPkValue().toString(), "attachmentpanel");
            if (atts.size() > 0) {
                for (int i = 0; i < atts.size(); i++) {
                    JSONObject object = new JSONObject();
                    Map<String, Object> map = atts.get(i);
                    Map<String, String> token = OrderApiUtils.getToken();
                    if (token.size() > 0) {
                        if (token.get("status").equals("success")) {
                            Map bomap = new HashMap<>();
                            bomap.put("Authorization", "Bearer " + token.get("token"));
                            MultipartFile multipartFile = HttpUtils.urlToMultipartFile(map.get("url").toString(), map.get("name").toString());
                            if (multipartFile != null) {
                                String result = HttpUtils.doPostFormData(url, "file", multipartFile, new HashMap<>(), bomap);
                                JSONObject jsonObject = JSONObject.parseObject(result);
                                int code = jsonObject.getIntValue("code");
                                if (code == 0) {
                                    object.put("url", jsonObject.getString("data"));
                                    object.put("name", map.get("name").toString());
                                    jsonArray.add(object);
                                } else {
                                    object.put("url", jsonObject.getString("data"));
                                    object.put("name", map.get("name").toString());
                                    jsonArray.add(object);
                                }
                            }
                        } else {
                            object.put("url", "");
                            object.put("erpurl", map.get("url").toString());
                            object.put("msg", "文件上传调用Token失败！");
                            jsonArray.add(object);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.getMessage();
        }
        return jsonArray;
    }
}
