package com.yem.wm.bd.user.from;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yem.wm.utils.YunzhijiaUtils;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhouc
 * @date 2024/4/26 17:04
 * @className UserFromEdit
 * @description
 */
public class UserFromEdit extends AbstractBillPlugIn {

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String operateKey = e.getOperateKey();
        DynamicObject bill = this.getModel().getDataEntity(true);
        if (operateKey.equals("getopenid")) {
            String useropenid = bill.getString("useropenid");
            String phone = bill.getString("phone");
            if (phone.length() == 0) {
                this.getView().showErrorNotification("当前用户未维护手机号，禁止获取openid！");
                return;
            }
            if (useropenid.length() > 0) {

            } else {
                Map<String, String> OpenId = getOpenId(phone);
                if (OpenId.size() > 0) {
                    bill.set("eid", "54991");
                    bill.set("tid", "54991");
                    bill.set("useropenid", OpenId.get("openId"));
                    bill.set("fuid", OpenId.get("uid"));
                    SaveServiceHelper.update(bill);
                    this.getView().invokeOperation("refresh");
//                    this.getView().showSuccessNotification("获取成功！！");
                }
            }
        }
    }

    public static Map<String, String> getOpenId(String phonNum) {
        Map<String, String> map = new HashMap<>();
        try {
            String req = "{\"type\":0,\"array\":[\"" + phonNum + "\"]}";
            String retstr = YunzhijiaUtils.doPost(YunzhijiaUtils.yzjurl + "/cmmpapi/cmmp/person.do?tokenId=D4EB05B9FE9C41D0868D33EC92AAEDB4", req);
            JSONObject retJson = JSONObject.parseObject(retstr);
            JSONArray datas = retJson.getJSONArray("data");
            for (int i = 0; i < datas.size(); i++) {
                JSONObject data = datas.getJSONObject(i);
                map.put("openId", data.getString("openId"));
                map.put("uid", data.getString("uid"));
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        }
        return map;
    }
}
