package com.dgtly.wxportal.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dgtly.common.annotation.ApiPassToken;
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.core.domain.Ztree;
import com.dgtly.common.utils.StringUtils;
import com.dgtly.common.utils.bean.EnDecoderUtil;
import com.dgtly.common.utils.bean.HexUtils;
import com.dgtly.common.utils.http.HttpUtils;
import com.dgtly.common.utils.security.EncryptPassWordClass;
import com.dgtly.system.service.ISysConfigService;
import com.dgtly.system.service.ISysUserOrderAuthorService;
import com.dgtly.wxportal.mapper.WxSendMessageMapper;
import com.dgtly.wxportal.domain.SendOrderNoticeTaskModel;
import com.dgtly.wxportal.utils.qywxutils.QyWxSendMessageUtil;
import com.dgtly.wxportal.utils.qywxutils.QyWxUserUtil;
import com.dgtly.system.domain.SysUser;
import com.dgtly.system.service.ISysUserService;
import com.dgtly.wxportal.service.IWxQyUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import static com.dgtly.common.utils.bean.EnDecoderUtil.DESdecode;
import static com.dgtly.common.utils.bean.EnDecoderUtil.DESencode;


@Api(tags = "企业微信相关API", description = "提供企业微信相关的AP")
@RequestMapping("wx")
@RestController
@ApiPassToken
public class WxController extends ApiBaseController {

    private static final Logger log = LoggerFactory.getLogger(WxController.class);
    @Autowired
    private QyWxUserUtil qyWxUserUtil;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IWxQyUserService wxQyUserService;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private QyWxSendMessageUtil qyWxSendMessageUtil;

    @Value(value = "${libang.getUserByTicket}")
    private String getUserByTicketUrl;

    @Autowired
    private WxSendMessageMapper wxSendMessageMapper;

    @Autowired
    private ISysUserOrderAuthorService sysUserOrderAuthorService;


    @ApiOperation(value = "获取微信授权跳转url",notes = "参数：{url:www.baidu.com}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("getOauthUrl")
    public Object getOauthUrl(){
        ParameterObject obj =  getParameterObject();
        obj.checkParameterNotNull("url");
        String oauth2Url =  qyWxUserUtil.getOauth2Url(obj.getString("url"),null);
        return AjaxResult.success().putKV("oauth2Url",oauth2Url);
    }


    @ApiOperation(value = "根据微信coed获取用户信息",
            notes = "参数：{code:123} code微信跳转回来的携带的用户code" +
                    "错误：301 当前用户不是当前企业用户成员" +
                    "错误：302 当前用户不属于DIY用户或经销商用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("getWxUserInfo")
    public Object getWxUserInfo(){
        ParameterObject obj =  getParameterObject();
        logger.info("获取用户微信信息开始{}", JSON.toJSON(obj));
        obj.checkParameterNotNull("code");
        String code = obj.getString("code");
        JSONObject json = new JSONObject();
        try{
            json =  qyWxUserUtil.getUserId(code);
        }catch (Exception e){
            logger.error("获取用户微信信息异常");
        }
        String userId ="";
        if(!json.containsKey("UserId")){
            return AjaxResult.error(301,"当前用户不是企业成员");
        }
        userId = json.getString("UserId");
        log.info("当前企业用户登录名称："+userId);
        SysUser user = sysUserService.selectUserByLoginName(userId);
        List<Map<String, Object>> result = new ArrayList<>();
        List<Map<String, Object>> loginTypeList = jdbcTemplate.queryForList("select dict_label shopType,dict_value shopTypeValue  from sys_dict_data where  dict_type='system_login_type'  ");
        if(user==null){
            return AjaxResult.error(302,"当前用户:"+userId+",不属于TUC事业群用户或TUC生态用户");
        }else if(user.getRoles().size()==0){
            return AjaxResult.error(302,"当前用户:"+userId+",企业微信尚未分配用户权限,请联系管理员！");
        }else{
            if ("1".equals(user.getIsShopAccount())) {
                for (int i = 0; i < loginTypeList.size(); i++) {
                    Map m = new HashMap();
                    m.put("shopType", loginTypeList.get(i).get("shopType"));
                    m.put("shopTypeValue", loginTypeList.get(i).get("shopTypeValue"));
                    List<Map<String, Object>> shopList = jdbcTemplate.queryForList("select shop_code,shop_name,sales_level from sys_user_shop_ext where  user_id=? and is_shop_type=? and del_flag='0'", user.getUserId(), loginTypeList.get(i).get("shopTypeValue"));
                    m.put("shopList", shopList);
                    result.add(m);
                }
                user.setLoginTypeInfo(loginTypeList);
                user.setLoginTypeList(result);
            }else{
                user.setLoginTypeInfo(loginTypeList);
                user.setLoginTypeList(result);
            }
            List<Ztree>  author = sysUserOrderAuthorService.userAuthorTreeDataFmt(user.getUserId());
            if (author.size() > 0 && author.get(0).getChildren().size() > 1) {
                user.setAuthorType("TUC");
            } else if (author.size() > 0 && author.get(0).getChildren().size() == 1) {//设置BUSINESS_UNIT
                user.setAuthorType(author.get(0).getChildren().get(0).getCode());
            }else{
                user.setAuthorType("DIY");//默认diy
            }
            user.setAuthor(author);
            return AjaxResult.success().putKV("sysUser",user);
        }
    }

    @ApiOperation(value = "根据用户经销商customer_code发送收货文本",
            notes = "参数：{\"deliveryNumber\":\"123456\"" +
                    ",\"shipmentNumber\":\"123456\"" +
                    ",\"belongTo\":\"123456\"" +
                    ",\"orderNumber\":\"123456\"}" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("sendDeliveryMessage")
    public Object sendDeliveryMessage(){

        ParameterObject obj =  getParameterObject();
        obj.checkParameterNotNull("belongTo,deliveryNumber,shipmentNumber,orderNumber");
        String customerCode = obj.getString("belongTo");
        String deliveryNumber = obj.getString("deliveryNumber");
        String tmsShipmentNumber = obj.getString("shipmentNumber");
        String orderNumber = obj.getString("orderNumber");
        String pagetitle = obj.getString("belongToName");
        logger.info("收到需要通知收货的请求参数："+obj.toString());
        if(pagetitle==null){
            pagetitle = "经销商";
        }

        /*ParameterObject obj =  getParameterObject();
        obj.checkParameterNotNull("orderNumber,tmsShipmentNumber,customerCode,deliveryNumber");
        String pagetitle = obj.getString("pagetitle");
        String orderNumber = obj.getString("orderNumber");
        String tmsShipmentNumber = obj.getString("tmsShipmentNumber");
        String customerCode = obj.getString("customerCode");
        String deliveryNumber = obj.getString("deliveryNumber");

        logger.info("收到需要通知收货的请求参数："+obj.toString());
        if(pagetitle==null){
            pagetitle = "经销商";
        }*/
        Set<String> customerCodes = new HashSet<>();
        customerCodes.add(customerCode);
        logger.info("收到需要通知的经销商组织代码："+customerCode);
        Map<String,Map<String,Object>> maps = sysUserService.selectLoginNamesByCostumerCode(customerCodes);
        String temple =configService.selectConfigByKey("wx.notification.delivery");

        //消息
        String message = String.format(temple,pagetitle,orderNumber,tmsShipmentNumber,customerCode,deliveryNumber);
        if(customerCodes.size()>0){
            qyWxSendMessageUtil.sendDeliveryMessage(customerCodes,maps,message);
        }

        return AjaxResult.success();
    }

    @ApiOperation(value = "同步数据失败",
            notes = "" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "path")
    })
    @RequestMapping("sendSyncDataMessage")
    public Object sendSyncDataMessage(String jobId) {
        String message;
        Integer type = 1;
        if ("salesOrderCustomerJob".equalsIgnoreCase(jobId)) {
            message = "经销商销售目标与达成，随身邦执行同步失败请检查";
        } else if ("salesOrderGroupJob".equalsIgnoreCase(jobId)) {
            message = "部门级别销售目标与达成，随身邦执行同步失败请检查";
            type = 2;
        } else {
            return AjaxResult.error("error for jobId " + jobId);
        }
        logger.info("sendSyncDataMessage jobId ：" + jobId);
        String users = sysUserService.selectSyncDateUser(type);
        qyWxSendMessageUtil.sendApproveProcessMessage(users, message, "15");
        return AjaxResult.success();
    }

    @ApiOperation(value = "加急审批通过",
            notes = "" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("sendUrgentApproveMessage")
    public Object sendApproveMessage() {

        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("users,chain,order,time,customerCode,customerName");
        String users = obj.getString("users");
        String chain = obj.getString("chain");
        String order = obj.getString("order");
        String customerName = obj.getString("customerName");
        String time = obj.getString("time");
        String customerCode = obj.getString("customerCode");
        String temple = configService.selectConfigByKey("wx.notification.approve.one");
        String orderFormat = getOrderFormat(order, customerName);
        String message = String.format(temple, chain, orderFormat, time);
        qyWxSendMessageUtil.sendApproveProcessMessage(users, message, "11");

        //发给经销商
        Set<String> customerCodes = new HashSet<>();
        customerCodes.add(customerCode);
        logger.info("收到需要通知的经销商组织代码："+customerCode);
        Map<String,Map<String,Object>> maps = sysUserService.selectLoginNamesByCostumerCode(customerCodes);
        //消息
        if(customerCodes.size()>0){
            qyWxSendMessageUtil.sendMsgToCustomer(customerCodes,maps,message, "11");
        }
        return AjaxResult.success();
    }


    private String getOrderFormat(String order, String customerName){
        String templeDetail = configService.selectConfigByKey("wx.notification.order.detail");

        List<String> strList = new ArrayList<>();
        String[] orderArrays = order.split(",");
        for (int i = 0; i < orderArrays.length; i++) {
            String orderStr = orderArrays[i];
            String messageDetail = String.format(templeDetail, orderStr, customerName, orderStr);
            strList.add(messageDetail);
        }
        return strList.stream().collect(Collectors.joining(","));
    }

    @ApiOperation(value = "小吨位审批通过",
            notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @PostMapping("sendSmallTonApproveMessage")
    public Object sendSmallTonApproveMessage() {

        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("users,chain,order,time,customerCode,customerName");
        String users = obj.getString("users");
        String chain = obj.getString("chain");
        String customerName = obj.getString("customerName");
        String order = obj.getString("order");
        String time = obj.getString("time");
        String customerCode = obj.getString("customerCode");
        String temple = configService.selectConfigByKey("wx.notification.approve.two");

        String orderFormat = getOrderFormat(order, customerName);
        String message = String.format(temple, chain, orderFormat, time);

        qyWxSendMessageUtil.sendApproveProcessMessage(users, message, "12");

        //发给经销商
        Set<String> customerCodes = new HashSet<>();
        customerCodes.add(customerCode);
        logger.info("收到需要通知的经销商组织代码："+customerCode);
        Map<String,Map<String,Object>> maps = sysUserService.selectLoginNamesByCostumerCode(customerCodes);
        //消息
        if(customerCodes.size()>0){
            qyWxSendMessageUtil.sendMsgToCustomer(customerCodes,maps,message, "12");
        }
        return AjaxResult.success();
    }

    @ApiOperation(value = "订单交货通知",
            notes = "" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("sendOrderDeliverMessage")
    public Object sendOrderDeliverMessage() {

        ParameterObject obj = getParameterObject();
        logger.info("发送订单通知:{}"+obj);
        obj.checkParameterNotNull("chain,order,customerName");
        String chain = obj.getString("chain");
        String customerName = obj.getString("customerName");
        String order = obj.getString("order");
        String temple = configService.selectConfigByKey("wx.notification.order.complete");
        String orderFormat = getOrderFormat(order, customerName);
        String message = String.format(temple, orderFormat, chain);
        Set<String> customerCodes = new HashSet<>();
        customerCodes.add(chain);
        logger.info("收到需要通知的经销商组织代码："+chain);
        logger.info("收到需要通知的经销商组织order："+order);
        Map<String,Map<String,Object>> maps = sysUserService.selectLoginNamesByCostumerCode(customerCodes);
        //消息
        if(customerCodes.size()>0){
            qyWxSendMessageUtil.sendMsgToCustomer(customerCodes,maps,message, "13");
        }
        return AjaxResult.success();
    }

    @ApiOperation(value = "TMS运单出厂通知",
            notes = "" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("sendApproveTMSMessage")
    public Object sendApproveTMSMessage() {

        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("chain,order");
        String chain = obj.getString("chain");
        String order = obj.getString("order");
        String temple = configService.selectConfigByKey("wx.notification.tms.leave.factory");


        String templeDetail = configService.selectConfigByKey("wx.notification.order.detail");


        String orderFormat = null;
        String[] orderArrays = order.split(",");
        String customerName = sysUserService.getCustomNameByCode(chain);
        List<String> strList = new ArrayList<>();
        for (int i = 0; i < orderArrays.length; i++) {
            String orderStr = orderArrays[i];
            String messageDetail = String.format(templeDetail, orderStr, customerName, orderStr);
            strList.add(messageDetail);
        }
        orderFormat = strList.stream().collect(Collectors.joining(","));

        String message = String.format(temple, orderFormat, chain);
        Set<String> customerCodes = new HashSet<>();
        customerCodes.add(chain);
        logger.info("收到需要通知的经销商组织代码："+chain);
        Map<String,Map<String,Object>> maps = sysUserService.selectLoginNamesByCostumerCode(customerCodes);
        //消息
        if(customerCodes.size()>0){
            qyWxSendMessageUtil.sendMsgToCustomer(customerCodes,maps,message, "14");
        }
        return AjaxResult.success();
    }


//    @ApiOperation(value = "根据用户经销商组织代码 customer_code发送文本",
//            notes = "参数：{\"XXX\":\"123，456\"}（说明:key是经销商code 值是订单编号列表）" )
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "params" , paramType = "body")
//    })
//    @PostMapping("sendTextMessageByCustomerCode")
//    public Object sendTextMessage(){
//
//        ParameterObject obj =  getParameterObject();
//        JSONObject jobj = obj.getJSONObject();
//        Set<String> customerCodes = jobj.keySet();
//        logger.info("收到需要通知过信息的请求参数："+jobj.toString());
//        logger.info("收到需要通知的经销商组织代码："+customerCodes.toString());
//        Map<String,Map<String,Object>> maps = sysUserService.selectLoginNamesByCostumerCode(customerCodes);
//        if(customerCodes.size()>0){
//            qyWxSendMessageUtil.sendNoticeMessage(customerCodes,obj.getJSONObject(),maps);
//        }
//        return AjaxResult.success();
//    }


    @ApiOperation(value = "发送过信用未确认要货，未过信用通知",
            notes = "" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("sendCreditMessage")
    public Object sendCreditMessage(@RequestBody SendOrderNoticeTaskModel model){
        logger.info("收到需要通知的确认要货及未过信用通知参数："+model.toString());
        //异步通知
        qyWxSendMessageUtil.sendCreditMessage(model);

        return AjaxResult.success();
    }



//    @ApiOperation(value = "根据用户userId发送文本",
//            notes = "参数：{userId:123," +
//                    "content:\"XXXXXXXXXXXXXXXXXX\"} " +
//                    "错误：301 当前用户未绑定企业微信")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "params" , paramType = "body")
//    })
//    @PostMapping("sendTextMessage")
//    public Object sendTextMessage(){
//        ParameterObject obj =  getParameterObject();
//        obj.checkParameterNotNull("userId,content");
//        Long userId = obj.getLong("userId");
//        SysUser sysUser = sysUserService.selectUserById(userId);
//        if(sysUser==null){
//            logger.error("发送企业微信细信息对象为空");
//            return AjaxResult.error(301,"未找到相应对象");
//        }
//        QyWxTextMessage qyWxTextMessage = new QyWxTextMessage();
//        qyWxTextMessage.setTouser(sysUser.getLoginName());
//        qyWxTextMessage.setText(obj.getString("content"));
//
//        qyWxSendMessageUtil.sendMessage(qyWxTextMessage);
//        return AjaxResult.success();
//    }
//
//    @ApiOperation(value = "根据用户userId发送文本card",
//            notes = "参数：{userId:123," +
//                    "title:\"标题，不超过128个字节\"," +
//                    "description:\"描述，不超过512个字节\"" +
//                    "url:\"点击后跳转的链接。\"," +
//                    "btntxt:\"按钮文字。 默认为“详情”， 不超过4个文字\"} " +
//                    "错误：301 当前用户未绑定企业微信")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "params" , paramType = "body")
//    })
//    @PostMapping("sendTextCardMessage")
//    public Object sendTextCardMessage(){
//        ParameterObject obj =  getParameterObject();
//        obj.checkParameterNotNull("userId,title,description,url");
//        Long userId = obj.getLong("userId");
//
//        QyWxTextCard tc = obj.parseBean(QyWxTextCard.class);
//
//        SysUser sysUser = sysUserService.selectUserById(userId);
//        if(sysUser==null){
//            logger.error("发送企业微信细信息对象为空");
//            return AjaxResult.error(301,"未找到相应对象");
//        }
//        QyWxTextCardMessage q = new QyWxTextCardMessage();
//
//        q.setTouser(sysUser.getLoginName());
//        q.setTextcard(tc);
//        qyWxSendMessageUtil.sendMessage(q);
//        return AjaxResult.success();
//    }

    @ApiOperation(value = "根据立邦微信基建返回的Ticket获取用户信息",notes = "参数：{'Ticket':1}=" +
            " 错误：301 根据Ticket获取用户信息失败" +
            "错误：302 当前用户可能不属于此企业" +
            "错误：303 当前用户可能不属于DIY人员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("/getUserByTicket")
    public Object getUserByTicket(){
        ParameterObject obj =  getParameterObject();
        obj.checkParameterNotNull("Ticket");
        JSONObject json  =new JSONObject();
        json.put("Ticket",obj.getString("Ticket"));
        String res = HttpUtils.sendJsonPost(getUserByTicketUrl,json);
        logger.info("根据Ticket获取的用户信息为{}",res);
        json = JSONObject.parseObject(res);
        if(json.containsKey("Code")&&json.getInteger("Code")==0){
            if(json.containsKey("Data")&&json.getJSONObject("Data")!=null){
                json =  json.getJSONObject("Data");
                if(json.containsKey("Number")&&json.getString("Number")!=null&&!json.getString("Number").trim().equals("")){
                    String emplyeeId = json.getString("Number");
                    SysUser user = sysUserService.selectUserByEmplyeeId(emplyeeId);
                    if(user!=null){
                        return AjaxResult.success().putKV("sysUser",user);
                    }else{
                        return AjaxResult.error(303,"当前用户可能不是DIY人员");
                    }
                }else{
                    return AjaxResult.error(302,"当前用户可能不属于此企业");
                }
            }
        }
        return AjaxResult.error(301,"根据Ticket获取用户信息失败");
    }




    @Autowired
    JdbcTemplate jdbcTemplate;
    @ApiOperation(value = "根据账户密码获取用户信息",notes = "参数：{'username':'1','password':'xxx'}" +
            " 错误：301 密码错误" +
            "错误：302  查无此人")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("/getUserByPassWord")
    public Object getUserByPassWord() {
        ParameterObject obj = getParameterObject();
        logger.info("收到登录参数：{}",JSON.toJSON( obj));
        obj.checkParameterNotNull("username,password");
        String username = obj.getString("username");
        String password = obj.getString("password");
        SysUser user = sysUserService.selectUserByLoginName(username);
        if (user == null) {
            return AjaxResult.error(302, "查无此人");
        }
        String pass = EncryptPassWordClass.encryptPassword(user.getLoginName(), password, user.getSalt());
        List<Map<String, Object>> result = new ArrayList<>();
        List<Map<String, Object>> loginTypeList = jdbcTemplate.queryForList("select dict_label shopType,dict_value shopTypeValue  from sys_dict_data where  dict_type='system_login_type'  ");

        if (pass.equals(user.getPassword())) {
            if ("1".equals(user.getIsShopAccount())) {
                for (int i = 0; i < loginTypeList.size(); i++) {
                    Map m = new HashMap();
                    m.put("shopType", loginTypeList.get(i).get("shopType"));
                    m.put("shopTypeValue", loginTypeList.get(i).get("shopTypeValue"));
                    List<Map<String, Object>> shopList = jdbcTemplate.queryForList("select shop_code,shop_name,sales_level from sys_user_shop_ext where  user_id=? and is_shop_type=? and del_flag='0'", user.getUserId(), loginTypeList.get(i).get("shopTypeValue"));
                    m.put("shopList", shopList);
                    result.add(m);
                }
                user.setLoginTypeInfo(loginTypeList);
                user.setLoginTypeList(result);
            }else{
                user.setLoginTypeInfo(loginTypeList);
                user.setLoginTypeList(result);
            }
                List<Ztree> author = sysUserOrderAuthorService.userAuthorTreeDataFmt(user.getUserId());
                if (author.size() > 0 && author.get(0).getChildren().size() > 1) {
                    user.setAuthorType("TUC");
                } else if (author.size() > 0 && author.get(0).getChildren().size() == 1) {//设置BUSINESS_UNIT
                    user.setAuthorType(author.get(0).getChildren().get(0).getCode());
                } else {
                    user.setAuthorType("DIY");//默认diy
                }
                user.setAuthor(author);
                return AjaxResult.success().putKV("sysUser", user);
            } else {
                return AjaxResult.error(301, "密码错误");
            }
        }

    @ApiOperation(value = "JS-SDK使用权限签名算法", notes = "参数：agent，非必填值为1获取应用签名， 否则获取企业签名")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", paramType = "body")
    })
    @GetMapping("/ticket")
    public Object getJsApiTicket(String url, String agent) {
        return AjaxResult.success(JSON.parseObject(qyWxUserUtil.getJsApiTicket(url, agent)));
    }

    @ApiOperation(value = "自提收货通知",
            notes = "" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("sendSelfTMSMessage")
    public Object sendSelfTMSMessage() {

        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("chain,order");
        String chain = obj.getString("chain");
        String order = obj.getString("order");
        String temple = configService.selectConfigByKey("wx.notification.tms.self");
        String orderFormat = null;
        String[] orderArrays = order.split(",");
        String customerName = sysUserService.getCustomNameByCode(chain);
        List<String> strList = new ArrayList<>();
        for (int i = 0; i < orderArrays.length; i++) {
            String orderStr = orderArrays[i];
            String messageDetail = String.format(temple, orderStr, customerName);
            strList.add(messageDetail);
        }
        orderFormat = strList.stream().collect(Collectors.joining(","));

        String message = String.format(temple, orderFormat, chain);
        Set<String> customerCodes = new HashSet<>();
        customerCodes.add(chain);
        logger.info("收到需要通知的经销商组织代码："+chain);
        Map<String,Map<String,Object>> maps = sysUserService.selectLoginNamesByCostumerCode(customerCodes);
        //消息
        if(customerCodes.size()>0){
            qyWxSendMessageUtil.sendMsgToCustomer(customerCodes,maps,message, "38");
        }
        return AjaxResult.success();
    }

    /**
     * @description: BMD经销商登录
     * @param:
     * @return:
     * @author: njs
     * @date: 2023/5/4 9:30
     */
    @ApiOperation(value = "根据账户密码获取用户信息",notes = "参数：{'token':'xxx','callbackUrl':'xxx'}" +
            " 错误：303 无识别令牌" +
            "错误：302  查无此人")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("/getUserBmdByNameAndToken")
    public Object getUserBmdByNameAndToken() throws UnsupportedEncodingException {
        ParameterObject obj =  getParameterObject();
        obj.checkParameterNotNull("token");
        String token = obj.getString("token");
        String url = obj.getString("callbackUrl");
        String callbackUrl = URLDecoder.decode(url, "UTF-8");
        logger.info("收到BMD跳转信息令牌和回调："+token+callbackUrl);
        Map result=new HashMap();
        if(callbackUrl !=null && !("").equals(callbackUrl) ){
            result.put("callbackUrl", callbackUrl);
        }
        if(token ==null || ("").equals(token) ){
            return AjaxResult.error(303,"BMD无识别令牌",result);
        }
        String name=DESdecode(token,"SSB2023BMD");
        if(name==null || ("").equals(name)){
            return AjaxResult.error(302,"BMD查无此人",result);
        }
        SysUser user = sysUserService.selectUserByLoginName(name);
        if(user==null){
            return AjaxResult.error(302,"BMD查无此人",result);
        }
       // String pass = EncryptPassWordClass.encryptPassword(user.getLoginName(),user.getLoginName(),user.getSalt());
        List<Ztree>  author = sysUserOrderAuthorService.userAuthorTreeDataFmt(user.getUserId());
            if (author.size() > 0 && author.get(0).getChildren().size() > 1) {
                user.setAuthorType("TUC");
            } else if (author.size() > 0 && author.get(0).getChildren().size() == 1) {//设置BUSINESS_UNIT
                user.setAuthorType(author.get(0).getChildren().get(0).getCode());
            }else{
                user.setAuthorType("DIY");//默认diy
            }
            user.setAuthor(author);
            return AjaxResult.success().putKV("sysUser",user).putKV("callbackUrl", callbackUrl);
    }

    @ApiOperation(value = "用户取消自提预约通知",
            notes = "" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("sendUserSelfCancelOrderMessage")
    public Object sendUserSelfCancelOrderMessage() {

        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("chain,order,day");
        String chain = obj.getString("chain");
        String order = obj.getString("order");
        String day = obj.getString("day");
        String temple = configService.selectConfigByKey("wx.notification.selfOrder.userCancel");
        String message = String.format(temple, order,day);
        //发给经销商
        Set<String> customerCodes = new HashSet<>();
        customerCodes.add(chain);
        logger.info("收到需要通知的经销商组织代码："+chain);
        Map<String,Map<String,Object>> maps = sysUserService.selectLoginNamesByCostumerCode(customerCodes);
        //消息
        if(customerCodes.size()>0){
            qyWxSendMessageUtil.sendMsgToCustomer(customerCodes,maps,message, "2000");
        }
        return AjaxResult.success();

    }

    @ApiOperation(value = "系统取消自提预约通知",
            notes = "" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("sendSystemSelfCancelOrderMessage")
    public Object sendSystemSelfCancelOrderMessage() {

        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("chain,order,day");
        String chain = obj.getString("chain");
        String order = obj.getString("order");
        String day = obj.getString("day");
        String temple = configService.selectConfigByKey("wx.notification.selfOrder.systemCancel");
        String message = String.format(temple, order,day);
        //发给经销商
        Set<String> customerCodes = new HashSet<>();
        customerCodes.add(chain);
        logger.info("收到需要通知的经销商组织代码："+chain);
        Map<String,Map<String,Object>> maps = sysUserService.selectLoginNamesByCostumerCode(customerCodes);
        //消息
        if(customerCodes.size()>0){
            qyWxSendMessageUtil.sendMsgToCustomer(customerCodes,maps,message, "2001");
        }
        return AjaxResult.success();

    }

    @ApiOperation(value = "系统取消要货通知",
            notes = "" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("sendSystemSelfDeliveryMessage")
    public Object sendSystemSelfDeliveryMessage() {

        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("chain,order,day");
        String chain = obj.getString("chain");
        String order = obj.getString("order");
        String day = obj.getString("day");
        String sendType = obj.getString("messageType");
        String temple="";
        if("0".equals(sendType)){
             temple = configService.selectConfigByKey("wx.notification.selfDelivery.systemMessage");
        }else if("1".equals(sendType)){
            temple = configService.selectConfigByKey("wx.notification.selfDelivery.sendMessage");
        }
        String message = String.format(temple, order,day);
        //发给经销商
        Set<String> customerCodes = new HashSet<>();
        customerCodes.add(chain);
        logger.info("收到需要通知的经销商组织代码："+chain);
        Map<String,Map<String,Object>> maps = sysUserService.selectLoginNamesByCostumerCode(customerCodes);
        //消息
        if(customerCodes.size()>0){
            qyWxSendMessageUtil.sendMsgToCustomer(customerCodes,maps,message, "2002");
        }
        return AjaxResult.success();

    }


    @ApiOperation(value = "企微服务商用户信息变更调用ssb", notes = "" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("stoneLikePaintByQwData")
    public Object stoneLikePaintByQwData() {

        ParameterObject obj = getParameterObject();
        JSONObject stoneUserJson = obj.getJSONObject("data");
        if(stoneUserJson !=null ){
            logger.info("收到企微服务商用户信息变更数据："+stoneUserJson.toJSONString());
            //0TUC仿石漆服务商人员
            Boolean i = sysUserService.buildStoneLikePaintByQwData(stoneUserJson);
            if(i){
                return AjaxResult.success("数据处理成功");
            }else{
                return AjaxResult.error("数据处理失败");
            }

        }

        return AjaxResult.error("数据解析json异常，请核查数据");

    }



}
