package yem.wmc.imc.formplugin.dynamic;
import com.alibaba.fastjson.JSONObject;
import kd.bos.fileservice.FileItem;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.form.control.Control;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.util.StringUtils;
import yem.wmc.imc.utils.AllElectricLoginUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Base64;  //原来的
import java.util.Date;
import java.util.EventObject;
import java.util.UUID;

import static yem.wmc.imc.utils.AllElectricLoginUtils.newAllElectricLoginInfo;


/**
 * @author 金亮
 * @date 2024/1/16 15:41
 * @relevantfile 全电同步自主登录界面（yem_imc_allelectriclogin）
 * @description 同步接口-全电同步自主登录
 * @versions 1.0
 */
public class AllElectricLoginDynamic extends AbstractFormPlugin {

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
//        defultAllElectricLoginQR(1);
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addClickListeners("yem_logincheck", "yem_refreshqr", "yem_getverificationcode");//验证登录结果,刷新二维码,获取验证码
    }

    @Override
    public void click(EventObject e) {
        super.click(e);
        Control source = (Control) e.getSource();
        String key = source.getKey();
        if ("yem_logincheck".equals(key)) { //验证登录结果
            String loginType = (String) this.getModel().getValue("yem_buttongroup");//单选按钮组
            if (loginType.equals("A")) { //手机短信效验
                Long phonenumber = (Long) this.getModel().getValue("yem_phonenumber");//获取手机号
                String smsCodes = (String) this.getModel().getValue("yem_smscode");//手机短信验证码
                if (phonenumber == 0) { //未输入手机号
                    this.getView().showErrorNotification("未输入手机号");  // 所有第三方接口都未调用手机号，无效操作
                    return;
                } else if (StringUtils.isEmpty(smsCodes)) { //未输入验证码
                    this.getView().showErrorNotification("请输入验证码");
                    return;
                }
                String phoneSid = (String) this.getModel().getValue("yem_phonesid"); //手机短信验证码sid
                String smsCode = (String) this.getModel().getValue("yem_smscode");//手机短信验证码
                // 调用接口1：同步接口-全电同步自主登录提交短信验证码
                JSONObject phoneJson = AllElectricLoginUtils.allElectricSyncSubmitSms(Long.valueOf(phoneSid), smsCode);
                if (!phoneJson.getString("code").equals("200")) {
                    this.getView().showErrorNotification(phoneJson.getString("message"));
                } else { //code =200 的话
                    JSONObject data = phoneJson.getJSONObject("data");
                    if (data.getInteger("status") == 1) { //登录成功
                        this.getView().showSuccessNotification(data.getString("message"));
                        //往数据库中增加一条数据（登录信息）
                        newAllElectricLoginInfo();

                    } else if (data.getInteger("status") == 2) { //登录失败
                        this.getView().showErrorNotification(data.getString("message"));
                        //往数据库中增加一条数据（登录信息）
                        Boolean b = newAllElectricLoginInfo();
                        System.out.println("b为：" + b);
                    }
                }
            } else if (loginType.equals("B")) {//税务App二维码效验
                //调用接口2：同步接口-全电同步自主登录获取二维码扫码结果
                String yemSid = (String) this.getModel().getValue("yem_qrsid"); //1.获取动态表单存储的sid
                JSONObject qrJson = AllElectricLoginUtils.allElectricSyncGetQrCodeStatus(Long.valueOf(yemSid));
                if (!qrJson.getString("code").equals("200")) {
                    this.getView().showErrorNotification(qrJson.getString("message"));
                } else { //code =200 的话
                    JSONObject data = qrJson.getJSONObject("data");
                    if (data.getInteger("status") == 1) { //登录成功
                        this.getView().showSuccessNotification(data.getString("message"));
                        // 往数据库中增加一条数据（登录信息）
                        newAllElectricLoginInfo();
                    } else if (data.getInteger("status") == 2) { //登录失败
                        this.getView().showErrorNotification(data.getString("message"));
                    }
                }
            }
        } else if ("yem_refreshqr".equals(key)) {//刷新二维码
            //重新调用：同步接口-全电同步自主登录
            defultAllElectricLoginQR(1);

        } else if ("yem_getverificationcode".equals(key)) { //获取短信验证码
            Long phonenumber = (Long) this.getModel().getValue("yem_phonenumber");//获取手机号
            if (phonenumber == 0) { //未输入手机号
                this.getView().showErrorNotification("未输入手机号");  // 所有第三方接口都未调用手机号，无效操作
                return;
            }
            defultAllElectricLoginQR(0);
        }
    }


    /**
     * //同步接口-全电同步自主登录（打开动态表单默认扫码）
     * @param loginType 效验方式(0未短信验证码，1为税务App扫码效验)
     */
    public void defultAllElectricLoginQR(Integer loginType) {
        JSONObject loginSjon = AllElectricLoginUtils.allElectricLogIn(loginType);
        if (!loginSjon.getString("code").equals("200")) {
            this.getView().showErrorNotification(loginSjon.getString("message"));
            return;
        }
        String uuid = UUID.randomUUID().toString();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        String format = sdf.format(date);
        String filePath = format + uuid + ".png";
        if (!loginSjon.containsKey("data")) {
            return;
        }
        JSONObject data = loginSjon.getJSONObject("data");
        String sidStr = data.getString("sid");
        if (loginType == 1) {//税务App扫码
            this.getModel().setValue("yem_qrsid", sidStr); //将值赋值给动态表单上
        } else if (loginType == 0) { //手机短信验证码
            this.getModel().setValue("yem_phonesid", sidStr); //将值赋值给动态表单上
        }
        if (data.containsKey("ewm") && data.getString("ewm") != null) {
            String ewm = data.getString("ewm");
            Base64.Decoder decoder = Base64.getDecoder();
            // 去掉base64前缀
            ewm = ewm.substring(ewm.indexOf(",") + 1);
            byte[] decode = decoder.decode(ewm);
            InputStream inputStream = new ByteArrayInputStream(decode);
            //封装要上传的对象,并指定上传服务器的位置
            FileService imageFileService = FileServiceFactory.getImageFileService();
            FileItem fileItem = new FileItem(filePath, "/images/qrCodeTemporary/" + filePath, inputStream); //自己新建文件夹
            String imageKey = imageFileService.upload(fileItem);
            this.getModel().setValue("yem_qrpicture", imageKey);
            this.getView().updateView("yem_qrpicture");
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
