package com.dgtly.wxportal.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dgtly.common.annotation.ApiPassToken;
import com.dgtly.common.config.ServerConfig;
import com.dgtly.common.core.controller.ApiBaseController;
import com.dgtly.common.core.domain.AjaxResult;
import com.dgtly.common.core.domain.ParameterObject;
import com.dgtly.common.utils.StringUtils;
import com.dgtly.system.domain.*;
import com.dgtly.system.service.*;
import com.dgtly.system.util.AuthType;
import com.dgtly.system.util.ResultUtil;
import com.dgtly.wxportal.config.ESignConfig;
import com.dgtly.wxportal.domain.ESignUpPDFModal;
import com.dgtly.wxportal.domain.OrderFile;
import com.dgtly.wxportal.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.digester.ArrayStack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:e签宝认证
 * @author:qxm
 * @date:2020/10/12 16:18
 */
@Api(tags = "e签宝相关API", description = "提供e签宝服务API")
@RequestMapping("eSign")
@RestController
@ApiPassToken
@Slf4j
public class EsignController extends ApiBaseController {

    @Autowired
    private IEsignPersonRealnVerifyService personRealnVerifyService;
    @Autowired
    private IEsignOrganRealVerifyService organRealVerifyService;
    @Autowired
    private IEsignSignService signService;
    @Autowired
    private IOrderFileService orderFileService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysUserExtService userExtService;
    @Autowired
    private ICustomersExtService customersExtService;
    @Autowired
    private ESignService eSignService;
    @Autowired
    private ESignConfig eSignConfig;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private IAssRelcustomerinfoService assRelcustomerinfoService;
    @Autowired
    private ICustomersCodeService customersService;
    @Autowired
    private ISysUserCustomerAuthorizationService authorizationService;

    @Autowired
    private IEsignCorpAuthSignRecordService iEsignCorpAuthSignRecordService;
    /**
     * @description: 经销商订单签收方法
     * 没有注册就注册，注册完就认证，然后再点击签署按钮，获取经销商用户id，对应主体id
     * E签宝一步发起签署
     * @param: []
     * @return: java.lang.Object
     * @author: qxm
     * @date: 2022/4/27 10:59
     */

    @ApiOperation(value = "订单签收", notes = "参数：{'orderId':'xxx','userId':'xxx','deliveryNumber':'xxx','shipmentNumber':'xxx','belongTo':'xxx','redirectUrl':'xxx','wareHouseCode':'xxx','wareHouseName':'xxx'}" +
            "\n（orderId：订单编号" +
            "\n（tmsShipNumber：运单号" +
            "\n（customerCode：经销商编号" +
            "\n（deliveryNumber：交货单号" +
            "\n（shipmentNumber：运单号" +
            "\n（belongTo：经销商代号" +
            "\n（userId：用户id" +
            "\n（wareHouseCode：仓库代号" +
            "\n（wareHouseName：仓库名称" +
            "\n redirectUrl:签署完成跳转地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @PostMapping("dealerSign")
    public Object dealerSign() {

        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("orderId,userId,deliveryNumber,tmsShipmentNumber,customerCode,redirectUrl");
        String orderId = obj.getString("orderId");
        String tmsShipNumber = obj.getString("tmsShipmentNumber");
        String customerCode = obj.getString("customerCode");
        String userId = obj.getString("userId");
        String deliveryNumber = obj.getString("deliveryNumber");
//        String shipmentNumber = obj.getString("shipmentNumber");
//        String belongTo = obj.getString("belongTo");
        String wareHouseCode = obj.getString("wareHouseCode");
        String wareHouseName = obj.getString("wareHouseName");
        String redirectUrl = obj.getString("redirectUrl");
        logger.info("签署订单开始参数：{}","orderId="+orderId+"&tmsShipNumber="+tmsShipNumber+"&customerCode="+customerCode+"&userId="+userId+"&deliveryNumber="+deliveryNumber);
        logger.info("签署完成跳转地址：{}",redirectUrl);


        String businessScene = "订单签收";
        //String fileName = orderId+"_签收订单.pdf";
        String fileName = tmsShipNumber+"_签收订单.pdf";
        /*根据userId查询个人注册后accountId*/
        String signerAccountId = "";
        try {
            SysUser sysUser = userService.selectUserById(Long.parseLong(userId));
            if (sysUser!=null){
                signerAccountId=sysUser.getAccountId();
            }
            /*根据订单id关联查询企业注册后id*/
            String authorizedAccountId =customersExtService.selectOrgIdByOrderId(orderId);
            logger.info("签署人认证id：{}",authorizedAccountId);
            /* 根据订单id关联查询企业代号*/
//        String chainsCode = customersExtService.selectChainsCodeByOrderId(orderId);
            /*首先根据订单id-orderId查询订单是否已被签署*/
//        OrderFile orderFlag = orderFileService.selectOrderFileById(orderId);
            String customerName = customersService.selectCustomerNameByCustomerCode(customerCode);
            ESignUpPDFModal fileModal = eSignService.upload(orderId,tmsShipNumber,customerCode,customerName,sysUser.getUserName());
            /*1、根据传入订单id，查询订单相关信息生成PDF，调用e签宝上传方法返回文件fileId*/
            Object fileId =fileModal.getFileId();
            logger.info("签署订单返回文件id：{}",fileId);
            /*2、调用E签宝接口一步发起流程，得到返回的流程id*/
            String flowId = signService.oneStepFlow(businessScene, fileId.toString(),fileModal.getX(),fileModal.getY(), fileName, signerAccountId, authorizedAccountId,redirectUrl);
            logger.info("签署订单一步发起完成流程id：{}",flowId);
            /*3、调用E签宝获取签署地址*/
//            String result = signService.processExecuteUrl(flowId, signerAccountId, authorizedAccountId);
            /*4、保存订单id和flowId*/
            OrderFile orderFile = new OrderFile();
            orderFile.setOrderId(orderId);
            orderFile.setDeliveryNumber(deliveryNumber);
            orderFile.setShipmentNumber(tmsShipNumber);
            orderFile.setWareHouseCode(wareHouseCode);
            orderFile.setWareHouseName(wareHouseName);
            orderFile.setChainsCode(customerCode);
            orderFile.setCustomersCode(authorizedAccountId);
            orderFile.setSignerId(signerAccountId);
            orderFile.setSignerName(sysUser.getUserName());
            orderFile.setFlowId(flowId);
            orderFile.setTypes(2);
            orderFileService.insertOrderFile(orderFile);
            logger.info("保存签署订单附件");
            try{
                File f = new File(fileModal.getFilePath());
                f.delete();
            }catch (Exception e){
                logger.error("删除文件出错：",e);
            }
            logger.info("签署订单完成");
            return AjaxResult.success("签收成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("签署订单失败：{}",e.getMessage());
            return AjaxResult.error("签收失败");
        }
    }

    /**
     * 指派司机授权
     *
     *      * 没有注册就注册，注册完就认证，然后再点击签署按钮，获取经销商用户id，对应主体id
     */
    @ApiOperation(value = "指派司机授权", notes = "参数：{'orderId':'xxx','userId':'xxx', 'phone':'xxx', 'customerCode':'xxx','entrustName':'xxx','beentrustName':'xxx','bId':'xxx','carNumber':'xxx','deliveryNumber':'xxx','runTime':'xxx','redirectUrl':'xxx'}"+
            "\n（orderId：订单编号" +
            "\n（userId： 用户id" +
            "\n（phone： 手机号" +
            "\n（customerCode： 经销商编号" +
            "\n（entrustName： 委托人" +
            "\n（beentrustName：受托（提货）人" +
            "\n（bId：身份证号码" +
            "\n（carNumber：车牌" +
            "\n（deliveryNumber：交货单号" +
            "\n（runTime：提货时间"+
            "\n redirectUrl:签署完成跳转地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @PostMapping("dealerSignDriver")
    public Object dealerSignDriver() {

        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("orderId,userId,customerCode,entrustName,phone,beentrustName,bId,carNumber,deliveryNumber,runTime,redirectUrl");
        String orderIds = obj.getString("orderId");
        String orderId=StringUtils.strip(orderIds,"[]");
        orderId=orderId.replace("\"", "");
        // String[] s = orderIds.split(",");
        try {
       /* for(String orderId : s) {*/
        String userId = obj.getString("userId");
        String customerCode = obj.getString("customerCode");
        String entrustName = obj.getString("entrustName");
        String beentrustName = obj.getString("beentrustName");
        String bId = obj.getString("bId");
        String phone = obj.getString("phone");
        String runTime=obj.getString("runTime");
        String carNumber = obj.getString("carNumber");
        String deliveryNumbers = obj.getString("deliveryNumber");
        String deliveryNumber=StringUtils.strip(deliveryNumbers,"[]");
        deliveryNumber= deliveryNumber.replace("\"", "");
     /*   String[] d= deliveryNumbers.split(",");
        for(String deliverredirectUrlyNumber : d) {*/
        String redirectUrl = obj.getString("redirectUrl");
        logger.info("签署完成跳转地址：{}",redirectUrl);

        String businessScene = "司机授权";
        String fileName = UUID.randomUUID()+businessScene+".pdf";
        /*根据userId查询个人注册后accountId*/
        String signerAccountId = "";
            SysUser sysUser = userService.selectUserById(Long.parseLong(userId));
            if (sysUser!=null){
                signerAccountId=sysUser.getAccountId();
            }
            /*根据订单id关联查询企业注册后id*/
            String authorizedAccountId =customersExtService.selectChainsCodeByOrderId(customerCode);
            // authorizedAccountId = "563c540b67354026a5f84f6c5b9d8eb0";
//            signService.signAuth(authorizedAccountId);
            logger.info("签署人认证id：{}",authorizedAccountId);
            /* 根据订单id关联查询企业代号*/
//        String chainsCode = customersExtService.selectChainsCodeByOrderId(orderId);
            /*首先根据订单id-orderId查询订单是否已被签署*/
//        OrderFile orderFlag = orderFileService.selectOrderFileById(orderId);
            /*3、调用E签宝获取签署地址*/
//            String result = signService.processExecuteUrl(flowId, signerAccountId, authorizedAccountId);
            /*4、保存订单id和flowId*/
                OrderFile orderFile = new OrderFile();
                orderFile.setOrderId(orderId);
                orderFile.setPhone(phone);
                orderFile.setDeliveryNumber(deliveryNumber);
                orderFile.setChainsCode(customerCode);
                orderFile.setCustomersCode(authorizedAccountId);
                orderFile.setSignerId(signerAccountId);
                orderFile.setSignerName(sysUser.getUserName());
                orderFile.setBeentrustName(beentrustName);
                orderFile.setCarNumber(carNumber);
                orderFile.setbId(bId);
                orderFile.setTypes(1);
                orderFile.setEntrustName(entrustName);
                //截取-之前区间字符串
                String startTime =runTime.substring(0,16);
                orderFile.setRun_time(startTime);
                ESignUpPDFModal fileModal = eSignService.uploadDriver(orderFile);
                /*1、根据传入订单id，查询订单相关信息生成PDF，调用e签宝上传方法返回文件fileId*/
                Object fileId = fileModal.getFileId();
                logger.info("签署授权返回文件id：{}",fileId);
                /*2、调用E签宝接口一步发起流程，得到返回的流程id*/
                String flowId = signService.oneStepFlowDriver(businessScene, fileId.toString(),fileModal.getX(),fileModal.getY(),fileModal.getX2(),fileModal.getY2(), fileName, signerAccountId, authorizedAccountId,redirectUrl);
                logger.info("签署授权一步发起完成流程id：{}",flowId);
                orderFile.setFlowId(flowId);
                orderFileService.insertOrderFile(orderFile);
                logger.info("保存授权签署附件");
                File f = new File(fileModal.getFilePath());
                f.delete();
            //}
           // }
            logger.info("授权成功");
            return AjaxResult.self("授权成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("授权失败：{}",e.getMessage());
            return AjaxResult.error("授权失败");
        }
    }

    /**
     * 收货/自主下单/自提授权
     *
     *      * 没有注册就注册，注册完就认证，然后再点击签署按钮，获取经销商用户id，对应主体id
     */
    @ApiOperation(value = "收货/自主下单/自提授权", notes = "参数：{'userId':'xxx','customerCode':'xxx','customerName':'xxx','clientName':'xxx','clientPost':'xxx','trusteeName':'xxx','trusteePost':'xxx','authType':'xxx','redirectUrl':'xxx'}"+
            "\n（userId：用户id" +
            "\n（customerCode：经销商编码" +
            "\n（customerName：经销商名称" +
            "\n（clientName： 委托人名称" +
            "\n（clientPost： 委托人职务" +
            "\n（trusteeName： 受托人名称" +
            "\n（trusteePost： 受托人职务" +
            "\n（authType：委托标记" +
            "\n（redirectUrl：签署完成跳转地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @PostMapping("empowerByAuth")
    public Object empowerByAuth() {

        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("userId,customerCode,customerName,clientName,clientPost,trusteeName,trusteePost,authType,redirectUrl");
        try {
            String authName="";
            String authType = obj.getString("authType");
            if(AuthType.IS_CONSIGNEE.equals(authType)){
                authName=AuthType.IS_CONSIGNEE_NAME;
            }else if(AuthType.IS_INDEPENDENTLY.equals(authType)){
                authName=AuthType.IS_INDEPENDENTLY_NAME;
            }else if(AuthType.IS_SELFDELIVERY.equals(authType)){
                authName=AuthType.IS_SELFDELIVERY_NAME;
            }
            String userId = obj.getString("userId");
            String customerCode = obj.getString("customerCode");
            String customerName = obj.getString("customerName");
            String clientName = obj.getString("clientName");
            String clientPost = obj.getString("clientPost");
            String trusteeName = obj.getString("trusteeName");
            String trusteePost=obj.getString("trusteePost");
            String redirectUrl = obj.getString("redirectUrl");
            logger.info("签署完成跳转地址：{}",redirectUrl);

            String businessScene = "委托授权";
            String fileName = UUID.randomUUID()+businessScene+"_授权.pdf";
            /*根据userId查询个人注册后accountId*/
            String signerAccountId = "";
            SysUser sysUser = userService.selectUserById(Long.parseLong(userId));
            if (sysUser!=null){
                signerAccountId=sysUser.getAccountId();
            }
            /*根据订单id关联查询企业注册后id*/
            String authorizedAccountId =customersExtService.selectChainsCodeByOrderId(customerCode);
            // authorizedAccountId = "563c540b67354026a5f84f6c5b9d8eb0";
//            signService.signAuth(authorizedAccountId);
            logger.info("签署人认证id：{}",authorizedAccountId);

            /*4、保存订单id和flowId*/
            OrderFile orderFile = new OrderFile();
            orderFile.setChainsCode(customerCode);
            orderFile.setCustomersCode(authorizedAccountId);
            orderFile.setSignerId(signerAccountId);
            orderFile.setSignerName(sysUser.getUserName());
            String trusteePostName=trusteePost.replaceAll("1","经销商负责人 ").replaceAll("2"," 财务 ").replaceAll("3"," 仓管 ").replaceAll("0","").replaceAll("4","").replaceAll("5","").replaceAll("6","").replaceAll("7","").replaceAll("8","").replaceAll("9","").replaceAll(",","");
            orderFile.setBeentrustPost(trusteePostName);
            String clientPostName=clientPost.replaceAll("1","经销商负责人 ").replaceAll("2"," 财务 ").replaceAll("3"," 仓管 ").replaceAll("0","").replaceAll("4","").replaceAll("5","").replaceAll("6","").replaceAll("7","").replaceAll("8","").replaceAll("9","").replaceAll(",","");
            orderFile.setEntrustPost(clientPostName);
            orderFile.setAuthType(authType);
            orderFile.setTypes(3);
            orderFile.setEntrustName(clientName);
            orderFile.setBeentrustName(trusteeName);
            orderFile.setChainsName(customerName);
            orderFile.setAuthName(authName);

            ESignUpPDFModal fileModal = eSignService.uploadEmpowerByAuth(orderFile);
            /*1、根据传入订单id，查询订单相关信息生成PDF，调用e签宝上传方法返回文件fileId*/
            Object fileId = fileModal.getFileId();
            logger.info("签署授权返回文件id：{}",fileId);
            /*2、调用E签宝接口一步发起流程，得到返回的流程id*/
            String flowId = signService.oneStepFlowempowerByAuth(businessScene, fileId.toString(),fileModal.getX(),fileModal.getY(),fileName, signerAccountId, authorizedAccountId,redirectUrl);
            logger.info("签署授权一步发起完成流程id：{}",flowId);
            orderFile.setFlowId(flowId);
            orderFileService.insertOrderFile(orderFile);
            logger.info("保存授权签署附件");
            File f = new File(fileModal.getFilePath());
            f.delete();
            logger.info("授权成功");
            return AjaxResult.success("授权成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("授权失败：{}",e.getMessage());
            return AjaxResult.error("授权失败");
        }
    }


    /**
     * 经销商通过签署地址签署后，回调此方法，通过flowId得到签署后的文件下载地址并保存url
     */
    @ApiOperation(value = "经销商通过签署地址签署后，回调此方法")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @PostMapping("updateOrderFile")
    public Object updateOrderFile() throws IOException {
        ParameterObject obj = getParameterObject();
        String businessScence =obj.getString("businessScence");
        String signResult="";
        if(!("司机授权").equals(businessScence)){
            obj.checkParameterNotNull("flowId,signResult");
             signResult = obj.getString("signResult");
        }else{
                signResult= obj.getString("flowStatus");
        }
        String flowId = obj.getString("flowId");
        OrderFile orderFlag = orderFileService.selectOrderFileByFlowId(flowId);
        if ("2".equals(signResult)) {
            /*异步保存文件*/
            signService.saveFile(flowId, orderFlag);
            /*异步调用回调接口*/
            if(businessScence!=null &&!("司机授权").equals(businessScence)){
                signService.callbackNotice(orderFlag);

            }


//            String fileUrl = signService.processDocumentDownload(flowId);
            /*下载保存签署后的文件，返回文件存储地址*/
//            fileDownloadUtil.downloadFile(Global.getPdfPath(), orderFlag.getOrderId() + "_签收订单.pdf", fileUrl);
//            OrderFile orderFile = new OrderFile();
//            orderFile.setFlowId(flowId);
//            orderFile.setFileUrl(Constants.RESOURCE_PREFIX+"/"+"pdf/"+orderFlag.getOrderId() + "_签收订单.pdf");
//            orderFileService.updateOrderFileByFlowId(orderFile);
        }
        return AjaxResult.success();
    }


    /**
     * 查看已签署PDF历史文件
     */
    @ApiOperation(value = "查看已签署PDF历史文件",notes = "参数：{'orderId':'xxx','deliveryNumber':'xxxx','shipmentNumber':'xxx'}" +
            "\n（orderId：订单编号" +
            "\n（deliveryNumber：交货单号" +
            "\n（shipmentNumber：运单号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @PostMapping("getHisFile")
    public Object getHisFile() {
        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("orderId,deliveryNumber,shipmentNumber");
        String orderId = obj.getString("orderId");
        String deliveryNumber = obj.getString("deliveryNumber");
        String shipmentNumber = obj.getString("shipmentNumber");
        String customersCode = obj.getString("customerCode");
        OrderFile orderFile = orderFileService.selectOrderFileByParam(orderId,deliveryNumber,shipmentNumber,customersCode);
        if(orderFile != null){
            return AjaxResult.success().putKV("url",serverConfig.getUrl()+orderFile.getFileUrl());
        }else{
            return AjaxResult.error(301,"文件不存在");
        }

    }

    @ApiOperation(value = "E签宝个人认证", notes = "参数：{'userId':'XXXXXXX','redirectUrl':'xxxx'}" +
            "\n（userId：待认证用户id" +
            "\n redirectUrl:认证结束后页面跳转地址url）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @PostMapping("personRealnVerify")
    public Object personRealnVerify() {
        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("userId,redirectUrl");
        String userId = obj.getString("userId");
        String redirectUrl = obj.getString("redirectUrl");
        logger.info("个人认证结束后页面跳转地址：{}",redirectUrl);
        SysUser sysUser = userService.selectUserById(Long.parseLong(userId));
        String result="";
        if (sysUser!=null){
            result = personRealnVerifyService.personRealnVerify(sysUser.getAccountId(),redirectUrl);
        }
        return result;
    }

    @ApiOperation(value = "E签宝个人认证成功回调接口（修改认证状态）",
                notes = "参数：{" +
                        "userId:'123'}" +
                        "错误：" +
                        "500 修改个人认证状态失败" +
                        "301 个人认证失败" +
                        "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("/updateUserIsAuthentication")
    public Object updateUserIsAuthentication(){
        ParameterObject obj =  getParameterObject();
        String accountId = obj.getString("accountId");
        Boolean success = obj.getBoolean("success");
        if (success) {
            int result = userService.updateIsAuthentication("1", accountId);
            /*设置静默签署*/
            signService.signAuth(accountId);
            if (result > 0) {
                return AjaxResult.success().putKV("result", result);
            } else {
                return AjaxResult.error(500, "修改个人认证状态失败");
            }
        }else {
            return AjaxResult.error(301,"个人认证失败");
        }
    }


    @ApiOperation(value = "E签宝企业认证", notes = "参数：{'userId':'XXXXXXX','redirectUrl':'xxxxx'}" +
            "\n（userId：待认证e签宝用户id" +
            "\n redirectUrl:企业认证成功跳转URl）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @PostMapping("organRealVerify")
    public Object organRealVerify() {
        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("userId,redirectUrl");
        String userId = obj.getString("userId");
        String redirectUrl = obj.getString("redirectUrl");
        logger.info("企业认证结束后页面跳转地址：{}",redirectUrl);
        SysUser sysUser = userService.selectUserById(Long.parseLong(userId));
        String result="";
        if (sysUser!=null){
            CustomersExt customersExt = customersExtService.selectCustomersExtById(sysUser.getSysUserExt().getOrgCode());
            if (customersExt!=null){
                result = organRealVerifyService.organRealVerify(sysUser.getAccountId(), customersExt.getOrgId(),redirectUrl);
            }
        }
        return result;
    }

    /*调用修改数据库企业认证状态*/
    @ApiOperation(value = "E签宝企业认证成功回调接口（修改认证状态）",
            notes = "参数：{" +
                    "userId:'123'}" +
                    "错误：" +
                    "500 修改企业认证状态失败" +
                    "301 企业认证失败" +
                    "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("/updateCustomersIsAuthentication")
    public Object updateCustomersIsAuthentication(){
        ParameterObject obj =  getParameterObject();
        String accountId = obj.getString("accountId");
        Boolean success = obj.getBoolean("success");
        if (success) {
            /*设置静默签署*/
            signService.signAuth(accountId);
            int result = customersExtService.updateCustomersIsAuthentication("1", accountId);
            if (result > 0) {
                return AjaxResult.success().putKV("result", result);
            } else {
                return AjaxResult.error(500, "修改企业认证状态失败");
            }
        }else {
            return AjaxResult.error(301,"企业认证失败");
        }
    }

    /**
     * @descption: 个人注册
     * @param:
     * @return:
     * @auther: ZhangDing
     * @date: 2020-10-12 14:04
     */

    @ApiOperation(value = "E签宝个人注册返回认证接口",
            notes = "参数：{" +
                    "userId:'123','redirectUrl':'跳转url（http://baidu.com）'}" +
                    "错误：" +
                    "301  用户已经注册且认证" +
                    "500 注册失败" +
                    "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @ApiPassToken
    @PostMapping("/createPersonalAccount")
    public Object createPersonalAccount(){
        ParameterObject obj =  getParameterObject();
        //判断参数
        obj.checkParameterNotNull("userId,redirectUrl");
        String userId = obj.getString("userId");
        String redirectUrl = obj.getString("redirectUrl");
        logger.info("个人认证2结束后页面跳转地址：{}",redirectUrl);
        //根据用户loginName查询用户信息
        SysUser user = userService.selectUserById(Long.parseLong(userId));
//        user.setUserName(userName);
        //判断是否注册
        if (user.getAccountId()!=null&&!user.getAccountId().equals("")){//已经注册
            //判断是否认证
            if ("1".equals(user.getIsAuthentication())){//已经认证
                return AjaxResult.error(301,"用户已经注册且认证");
            }else {//没有认证
                /*调用E签宝修改用户认证信息*/
//                int result = eSignService.updatePersonalAccount(user);
                    //获取认证路径
                    String url = personRealnVerifyService.personRealnVerify(user.getAccountId(),redirectUrl);
                    return AjaxResult.success("url",url);
            }
        }else {//没有注册
            /*首先根据user.getLoginName()查询E签宝是否存在此账户*/
            String accountId = eSignService.getAccountIdByThirdId(user.getLoginName());
            log.info("查询E签宝accountId："+accountId);
            SysUser euser = new SysUser();
            if( accountId != null ){
                /*保存已注册信息*/
                euser.setUserId(Long.parseLong(userId));
                euser.setAccountId(accountId);
                int i = userService.updateUserInfo(euser);
            }else{
                //去注册
                 euser = eSignService.createPersonalAccount(user);
            }
            if (euser != null) {
                //注册完以后获取认证路径
                String url = personRealnVerifyService.personRealnVerify(euser.getAccountId(),redirectUrl);
                return AjaxResult.success("url", url);
            }else {
                return AjaxResult.error(500,"注册失败");
            }
        }
    }


    @ApiOperation(value = "修改个人信息（手机号）",
            notes = "参数：{" +
                    "userId:'123','redirectUrl':'跳转url（http://baidu.com）'}" +
                    "错误：" +
                    "301  用户已经注册且认证" +
                    "500 注册失败" +
                    "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @ApiPassToken
    @PostMapping("/updatePersonalAccount")
    public Object updatePersonalAccount(){
        ParameterObject obj =  getParameterObject();
        //判断参数
//        obj.checkParameterNotNull("userId,redirectUrl");
        String userId = obj.getString("userId");
        String phone = obj.getString("phone");
        String accountId = obj.getString("accountId");
        String redirectUrl = obj.getString("redirectUrl");
        logger.info("个人认证2结束后页面跳转地址：{}",redirectUrl);
        //根据用户loginName查询用户信息
        SysUser user = new SysUser();
        user.setPhonenumber(phone);
        user.setAccountId(accountId);
        /*调用E签宝修改用户认证信息*/
        int result = eSignService.updatePersonalAccount(user);
        //获取认证路径
        String url = personRealnVerifyService.personRealnVerify(user.getAccountId(),redirectUrl);
        return AjaxResult.success("url",url);


    }

    /**
     * @descption: 公司注册
     * @param:
     * @return:
     * @auther: ZhangDing
     * @date: 2020-10-12 15:26
     */
    @ApiOperation(value = "E签宝企业注册返回认证接口",
            notes = "参数：{" +
                    "userId:'123','redirectUrl':'认证成功跳转url'}" +
                    "错误：" +
                    "301  企业已经注册且认证" +
                    "201  个人未注册" +
                    "500 注册失败" +
                    "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @ResponseBody
    @PostMapping("/createThirdParty")
    public Object createThirdParty(){
        ParameterObject obj =  getParameterObject();
        obj.checkParameterNotNull("userId,redirectUrl");
        Long userId = obj.getLong("userId");
        String redirectUrl = obj.getString("redirectUrl");
        logger.info("企业认证2结束后页面跳转地址：{}",redirectUrl);
        SysUser user = userService.selectUserById(userId);
//        CustomersExt customersExt = obj.parseBean(CustomersExt.class);
        CustomersExt customersExt = customersExtService.selectCustomersExtById(user.getSysUserExt().getOrgCode());
        log.info("11111111111：{}", JSON.toJSON(customersExt));
        if (customersExt==null){
            customersExt = new CustomersExt();
            if (user.getAccountId()!=null&&!user.getAccountId().equals("")) {
                customersExt.setCreator(user.getAccountId());
            }else {
                return AjaxResult.error(201,"个人未注册");
            }
            log.info("sss{}",JSON.toJSON(user));
            log.info("fff{}",JSON.toJSON(user.getSysUserExt().getOrgCode()));
            customersExt.setChainsCode(user.getSysUserExt().getOrgCode());
        }
        log.info("222222222222：{}", JSON.toJSON(customersExt));
        //判断是否注册
        if (customersExt.getOrgId()!=null&&!customersExt.getOrgId().equals("")){//已经注册
            //判断是否认证
            if ("1".equals(customersExt.getIsAuthentication())){//已认证
                return AjaxResult.error(301,"企业已经注册且认证");
            }else {//未认证
                /*修改企业注册信息*/
//                int result = eSignService.updateThirdParty(customersExt);
                    //获取认证路径
                    String url = organRealVerifyService.organRealVerify(customersExt.getOrgId(),user.getAccountId(),redirectUrl);
                    return AjaxResult.success("url",url);
            }
        }else {//未注册
            /*首先根据customersExt.getChainsCode()查询E签宝是否存在此账户*/
                String orgId = eSignService.getOrgIdByThirdId(customersExt.getChainsCode());
                log.info("查询E签宝orgId："+orgId);
                CustomersExt ecustomersExt=null;
                if(orgId!=null){
                    ecustomersExt = customersExtService.selectCustomersExtById(user.getSysUserExt().getOrgCode());
                    if (ecustomersExt!=null){
                        ecustomersExt.setOrgId(orgId);
                        /*修改企业id*/

                        customersExtService.updateCustomersExt(ecustomersExt);
                    }else {
                        ecustomersExt = new CustomersExt();
                        ecustomersExt.setOrgId(orgId);
                        ecustomersExt.setCreator(user.getAccountId());
                        ecustomersExt.setChainsCode(user.getSysUserExt().getOrgCode());
                        customersExtService.insertCustomersExt(ecustomersExt);
                    }
                }else {
                    //去注册
                    ecustomersExt = eSignService.createThirdParty(customersExt);
                }
            if (ecustomersExt!=null) {
                //注册完以后获取认证路径
                String url = organRealVerifyService.organRealVerify(ecustomersExt.getOrgId(),user.getAccountId(),redirectUrl);
                return AjaxResult.success("url", url);
            }else {
                return AjaxResult.error(500,"注册失败");
            }
        }
    }

    @ApiOperation(value = "获取企业\\个人认证情况信息", notes = "参数：{'userId':'XXXXXXX'}" +
            "\n（userId：用户id）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @PostMapping("getOrgOrPersonalVerify")
    public Object getOrgOrPersonalVerify() {
        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("userId");
        String userId = obj.getString("userId");
        Map map = new HashMap(5);
        SysUser sysUser = userService.selectUserById(Long.parseLong(userId));
//       /*根据org_code查询多个经销商列表*/
        List<SysUserExt> sysUserExtList = new ArrayStack<>();
        List<AssRelcustomerinfo>  assRelcustomerinfoList= assRelcustomerinfoService.selectRelcustomerinfoListByorgCode(sysUser.getSysUserExt().getOrgCode(),sysUser.getUserId().toString());
        if (assRelcustomerinfoList.size()>0){
            for (AssRelcustomerinfo ar:assRelcustomerinfoList) {
                SysUserExt sysUserExt = new SysUserExt();
                sysUserExt.setUserId(sysUser.getSysUserExt().getUserId());
                sysUserExt.setOrgCode(ar.getMainkunnr());
                sysUserExt.setOrgName(ar.getMainname1());
                sysUserExt.setSalesLevel(sysUser.getSysUserExt().getSalesLevel());
                sysUserExt.setBossEmployeeId(sysUser.getSysUserExt().getBossEmployeeId());
                sysUserExt.setBossName(sysUser.getSysUserExt().getBossName());
                sysUserExt.setSapEmployeeId(sysUser.getSysUserExt().getSapEmployeeId());
                sysUserExt.setCustomerCode(sysUser.getSysUserExt().getCustomerCode());
                sysUserExt.setIsCustomerManager(sysUser.getSysUserExt().getIsCustomerManager());
                sysUserExt.setPostCode(sysUser.getSysUserExt().getPostCode());
                sysUserExt.setPostName(sysUser.getSysUserExt().getPostName());
                sysUserExtList.add(sysUserExt);
            }

            for (AssRelcustomerinfo ar:assRelcustomerinfoList) {
                SysUserExt sysUserExt = new SysUserExt();
                sysUserExt.setUserId(sysUser.getSysUserExt().getUserId());
                sysUserExt.setOrgCode(ar.getKunnr());
                sysUserExt.setOrgName(ar.getName1());
                sysUserExt.setSalesLevel(sysUser.getSysUserExt().getSalesLevel());
                sysUserExt.setBossEmployeeId(sysUser.getSysUserExt().getBossEmployeeId());
                sysUserExt.setBossName(sysUser.getSysUserExt().getBossName());
                sysUserExt.setSapEmployeeId(sysUser.getSysUserExt().getSapEmployeeId());
                sysUserExt.setCustomerCode(sysUser.getSysUserExt().getCustomerCode());
                sysUserExt.setIsCustomerManager(sysUser.getSysUserExt().getIsCustomerManager());
                sysUserExt.setPostCode(sysUser.getSysUserExt().getPostCode());
                sysUserExt.setPostName(sysUser.getSysUserExt().getPostName());
                sysUserExtList.add(sysUserExt);
            }
            /*SysUserExt sysUserExt = new SysUserExt();
            sysUserExt.setUserId(sysUser.getSysUserExt().getUserId());
            sysUserExt.setOrgCode(assRelcustomerinfoList.get(0).getMainkunnr());
            sysUserExt.setOrgName(assRelcustomerinfoList.get(0).getMainname1());
            sysUserExt.setSalesLevel(sysUser.getSysUserExt().getSalesLevel());
            sysUserExt.setBossEmployeeId(sysUser.getSysUserExt().getBossEmployeeId());
            sysUserExt.setBossName(sysUser.getSysUserExt().getBossName());
            sysUserExt.setSapEmployeeId(sysUser.getSysUserExt().getSapEmployeeId());
            sysUserExt.setCustomerCode(sysUser.getSysUserExt().getCustomerCode());
            sysUserExt.setIsCustomerManager(sysUser.getSysUserExt().getIsCustomerManager());
            sysUserExt.setPostCode(sysUser.getSysUserExt().getPostCode());
            sysUserExt.setPostName(sysUser.getSysUserExt().getPostName());
            sysUserExtList.add(sysUserExt);*/
        }else{
            //只有是经销商级别的存入sysUserExtList中
            if(null != sysUser.getSysUserExt() &&
                    StringUtils.isNotEmpty( sysUser.getSysUserExt().getSalesLevel())&&
                    sysUser.getSysUserExt().getSalesLevel().equals("customer_level"))
            {
                sysUserExtList.add(sysUser.getSysUserExt());
            }
        }
        ArrayList<SysUserExt> resultList = sysUserExtList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(SysUserExt::getOrgCode))), ArrayList::new));

        sysUser.setSysUserExtLsit(resultList);
        if (sysUser!=null){
            map.put("user",sysUser);
            List<CustomersExt> customersExtList = new ArrayStack<>();
            for (SysUserExt sysUserExt:resultList) {
                CustomersExt customersExt = customersExtService.selectCustomersExtById(sysUserExt.getOrgCode());
                if (customersExt!=null){
                    if (StringUtils.isNotEmpty(sysUserExt.getOrgCode())){
                        EsignCorpAuthSignRecord esignCorpAuthSignRecord = iEsignCorpAuthSignRecordService.selectByCustomeCode(sysUserExt.getOrgCode());
                        if (esignCorpAuthSignRecord != null){
                            customersExt.setCustomerStatus(esignCorpAuthSignRecord.getStatus());
                        }else {
                            customersExt.setCustomerStatus(0);
                        }
                    }
                    customersExtList.add(customersExt);
                }
            }
            map.put("customersExtList",customersExtList);
            //用户授权列表
            SysUserCustomerAuthorization authorization = new SysUserCustomerAuthorization();
            authorization.setUserId(sysUser.getUserId());
            List<SysUserCustomerAuthorization> authorizationList = authorizationService.selectSysUserCustomerAuthorizationList(authorization);
            map.put("authorizationList",authorizationList);
            return AjaxResult.success(map);
            /*if (customersExtList.size()>0){
                map.put("customersExtList",customersExtList);
                return AjaxResult.success(map);
            }else{
                return AjaxResult.success(map);
            }*/
        }else{
            return AjaxResult.error("用户不存在");
        }
    }
//    /**
//     * @descption: e签宝修改个人信息
//     * @param:
//     * @return:
//     * @auther: ZhangDing
//     * @date: 2020-10-13 13:31
//     */
//    @ResponseBody
//    @PostMapping("/updatePersonalAccount")
//    public Object updatePersonalAccount(){
//        ParameterObject obj = getParameterObject();
//        obj.checkParameterNotNull("accountId");
//        SysUser user = obj.parseBean(SysUser.class);
//        return toAjax(eSignService.updatePersonalAccount(user));
//    }
//
//    /**
//     * @descption: e签宝修改公司信息
//     * @param:
//     * @return:
//     * @auther: ZhangDing
//     * @date: 2020-10-13 14:32
//     */
//    @ResponseBody
//    @PostMapping("/updateThirdParty")
//    public Object updateThirdParty(){
//        ParameterObject obj = getParameterObject();
//        obj.checkParameterNotNull("orgId");
//        CustomersExt customersExt = obj.parseBean(CustomersExt.class);
//        return toAjax(eSignService.updateThirdParty(customersExt));
//    }

    @ApiOperation(value = "企业认证删除",
            notes = "参数：{'chainsCode':'XXXXXXX'}" +
                    " （chainsCode：经销商编号）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @ApiPassToken
    @PostMapping("/delOrganizations")
    public Object delOrganizations() {
        ParameterObject obj = getParameterObject();
        String chainsCode = obj.getString("chainsCode");
        CustomersExt customersExt = customersExtService.selectCustomersExtById(chainsCode);
        if(customersExt == null ){
            return AjaxResult.error("chainsCode error ");
        }
        JSONObject result = eSignService.delOrganizations(customersExt.getOrgId());
        if (result.getInteger("code") == 0) {
            customersExtService.deleteCustomersExtById(chainsCode);
            return AjaxResult.success();
        } else {
            return AjaxResult.error(result.getString("message"));
        }
    }

    /**
     * 发起企业授权书签署任务
     *
     * @param param 请求参数（JSON Body）
     * @return Result，data 中包含 taskId 和 signUrl
     *
     * 请求示例：
     * POST /order/esign/corpAuthSign
     * {
     *   "accountId"           : "机构账号ID（创建机构签署账号接口返回的orgId）",
     *   "transactorAccountId" : "经办人个人账号ID（创建个人签署账号接口返回的accountId）",
     *   "authorizedType"      : 1,
     *   "sendNotice"          : true,
     *   "validDate"           : 20271231,
     *   "notifyUrl"           : "https://your-domain.com/esign/notify",
     *   "redirectUrl"         : "https://your-domain.com/esign/redirect"
     * }
     *
     * 参数说明：
     *   accountId            必填，机构账号ID
     *   transactorAccountId  必填，经办人个人账号ID
     *   authorizedType       可选，1=授权至平台（默认），2=授权至经办人
     *   authorizedAccountId  可选，被授权人账号ID（authorizedType=2 时必填）
     *   sendNotice           可选，是否发送通知，默认 true
     *   validDate            必填，授权有效期截止时间（yyyyMMdd格式，如 20271231）
     *   notifyUrl            可选，授权结果回调通知地址
     *   redirectUrl          可选，签署完成后跳转页面
     */
    @PostMapping("/corpAuthSign")
    @ResponseBody
    public Result corpAuthSign(@RequestBody ESignCorpAuthParam param) {
        try {
            return eSignService.initiateCorpAuthSign(param);
        } catch (IOException e) {
            log.error("[ESign] 发起企业授权书签署任务异常, accountId={}", param != null ? param.getAccountId() : "null", e);
            return ResultUtil.error(500,"发起企业授权书签署任务异常：" + e.getMessage());
        }
    }

    /**
     * 获取授权流程签署URL
     *
     * 接口：POST /v1/signAuthApi/signUrl
     *
     * 请求参数：
     *   authId      String  是   授权流程ID
     *   needLogin   boolean 否   是否需要登录打开链接，默认 true（true=需要登录，false=免登录）
     *   clientType  String  否   客户端类型：H5（移动端）/ PC（PC端）/ ALL（自动适配，默认）
     *   redirectUrl String  否   授权签署完成后跳转页面
     *   appScheme   String  否   AppScheme，用于唤起 App，示例：esign://demo/signBack
     *
     * 响应 data：
     *   shortUrl  String  授权流程签署短链接（链接90天内有效）
     *   longUrl   String  授权流程签署长链接（链接90天内有效）
     */
    @ApiOperation(value = "获取授权流程签署URL",
            notes = "参数：{'authId':'xxx','needLogin':true,'clientType':'ALL','redirectUrl':'xxx','appScheme':'xxx'}" +
                    "\n authId：授权流程ID（必填）" +
                    "\n needLogin：是否需要登录打开链接，默认true（true=需要登录，false=免登录）" +
                    "\n clientType：客户端类型，H5/PC/ALL（默认ALL）" +
                    "\n redirectUrl：授权签署完成后跳转页面" +
                    "\n appScheme：AppScheme，用于唤起App，示例：esign://demo/signBack")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @PostMapping("/getSignUrl")
    @ResponseBody
    public Result getSignUrl() {
        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("authId");
        String authId = obj.getString("authId");
        Boolean needLogin = obj.getBoolean("needLogin");
        String clientType = obj.getString("clientType");
        String redirectUrl = obj.getString("redirectUrl");
        String appScheme = obj.getString("appScheme");
        try {
            return eSignService.getSignUrl(authId, needLogin, clientType, redirectUrl, appScheme);
        } catch (IOException e) {
            log.error("[ESign] 获取授权流程签署URL异常, authId={}", authId, e);
            return ResultUtil.error(500, "获取授权流程签署URL异常：" + e.getMessage());
        }
    }

    /**
     * 查询授权结果
     *
     * 接口：GET /v1/signAuthApi/queryAuthResult?authId=XXX
     *
     * 请求参数：
     *   authId  String  是  授权流程ID（Query 参数）
     *
     * 响应 data：
     *   authId             String  授权流程ID
     *   status             int     授权状态：1=进行中 2=授权成功 3=授权失败 4=取消授权
     *   failReason         String  授权说明（授权失败时返回原因）
     *   effectiveStartTime long    授权生效时间（格式 yyyyMMdd，如 20260101）
     *   effectiveEndTime   long    授权失效时间（格式 yyyyMMdd，如 20260101）
     *   authDownloadUrl    String  授权书下载链接（有效期60分钟，仅 status=2 授权成功时返回）
     */
    @ApiOperation(value = "查询授权结果",
            notes = "参数：{'authId':'xxx'}" +
                    "\n authId：授权流程ID（必填）" +
                    "\n 响应 data.status：1=进行中 2=授权成功 3=授权失败 4=取消授权" +
                    "\n 响应 data.authDownloadUrl：授权书下载链接（有效期60分钟，仅授权成功时返回）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @PostMapping("/queryAuthResult")
    @ResponseBody
    public Result queryAuthResult() {
        ParameterObject obj = getParameterObject();
        String authId = obj.getString("authId") == null ? "" : obj.getString("authId");
        obj.checkParameterNotNull("customeCode");
        String customeCode = obj.getString("customeCode");
        try {
            return eSignService.queryAuthResult(authId,customeCode);
        } catch (IOException e) {
            log.error("[ESign] 查询授权结果异常, authId={}", authId, e);
            return ResultUtil.error(500, "查询授权结果异常：" + e.getMessage());
        }
    }

}
