<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
  <%@ include file="/common/taglibs.jsp"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
    <!DOCTYPE html>
    <html>

    <head>
      <title>发布微信消息</title>
      <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
      <!-- bootstrap 3.0.2 -->
      <link href="<c:url value='/scripts/lib/layui/layui.css'/>" rel="stylesheet" type="text/css" />

      <!-- Theme style -->
      <link href="<c:url value='/styles/AdminLTE.css'/>" rel="stylesheet" type="text/css" />
      <link href="<c:url value='/styles/notice/noticeWxPublish.css?v=43535'/>" rel="stylesheet" type="text/css" />
      
      

      <script type="text/javascript" src="<c:url value='/scripts/lib/jquery-1.8.2.min.js'/>"></script>
      <script type="text/javascript" src="<c:url value='/scripts/lib/layui/layui.js'/>"></script>
        <script type="text/javascript" src="<c:url value='/scripts/lib/template-native.js'/>"></script>
        <script type="text/javascript" src="<c:url value='/scripts/admin/cjqt.js'/>"></script>

        <script src="<c:url value='/scripts/admin/notice/element/vue.js?v=1234'/>"></script>
      <link rel="stylesheet" href="//superdesk.avic-s.com/avicfile/theme/theme-chalk.css">
        <script src="<c:url value='/scripts/admin/notice/element/element.js?v=1234'/>"></script>
        <!-- <script src = "//cdn.polyfill.io/v2/polyfill.min.js"></script> -->
         <script src="<c:url value='/scripts/admin/notice/element/polyfill.js?v=12345555'/>"></script>
      <style type="text/css">
       .el-input__inner{
        height: 33px !important;
        line-height: 33px !important;
      }
      .el-radio__input{
        width: 20px !important;
        height: 20px !important;
      }
      .dialog-pop .el-input__inner{
        height: 40px !important;
        line-height: 40px !important;
      }
      .dialog-pop{
        display: none;
      }
      .checkbox-item-cb{
        font-size: 14px;
      color: #333;
      font-weight: 600;
      }
      .choose-tip-name{
        display: inline-block;
        font-size: 15px;
        font-weight: 600;
       color: #333333;
       padding: 12px 0;
      }
      .tag-item-name{
        position: relative;
        margin: 0 8px 6px 0;
        padding: 0 28px 0 9px;
        display: inline-block;
        height: 30px;
        line-height: 30px;
        min-width: 70px;
        background: #EEEEEE;
        border-radius: 15px;
        font-size: 14px;
        color: #333333;
      }
      .btn-blue-width90{
        padding: 0;
        width: 90px;
        text-align: center;
        height: 40px;
        line-height: 40px;
        border: 1px solid #158DF5;
        color: #158DF6!important;
        font-size: 14px;
        border-radius: 4px;
        cursor: pointer;
        background: #fff;
      }
      .el-checkbox__input.is-checked + .el-checkbox__label{
        color: #333 !important;
      }
      .cell-box{
        padding: 12px 0;
        font-size: 15px;
        color: #333;
        border-bottom: 1px solid #ddd;
      }
      .el-menu-item.is-active {
    color: #409EFF !important;
    font-size: 16px;
    font-weight: 600;
      }
      .tag-size{
        display: flex !important;
      }
      .sub-item-name{
        flex: 1;
      }
      .icon-check-item{
        font-size: 20px;
        color: #409EFF;
        font-weight: 600;
        margin-right: 20px;
      }
      .tag-css{
        margin: 5px;
      }
      .custom-tree-node{
        width: 100%;
        display: flex;
      }
      .el-tree-node-name{
        flex: 1;
      }
      .search-input{
        height: 40px !important;
        line-height: 40px !important;
      }
      .img-sup-icon{
        width: 18px;
        height: 18px;
        margin-right: 10px;
      }
      
      .tv-choose-content{
         margin-top:5px;
         color: #333;
        font-size: 15px;
        max-width: 600px;
        word-break:break-all;       
        word-wrap:break-word; 
        line-height: 25px;   
       }
       .submit-btn{
         margin-left: 20px;
       }
       .el-radio__inner{
        width: 20px !important;
        height: 20px !important;
	      }
       .el-radio__input.is-checked .el-radio__inner::after {
      content: "";
      width: 10px;
      height: 5px;
      border: 2px solid white;
      border-top: transparent;
      border-right: transparent;
      text-align: center;
      display: block;
      position: absolute;
	    top: 4px;
      left: 3px;
      vertical-align: middle;
      transform: rotate(-45deg);
      border-radius: 0px;
      background: none;
    }
        /*文件夹图标*/
      .span-button.ico_open {
        background-position: -110px -16px;
      }

      /*文件图标*/
      .span-button.ico_docu {
        background-position: -110px -32px;
      }
      /*按钮图片组*/
      .span-button {
        line-height: 0;
        margin: 0;
        width: 16px;
        height: 16px;
        display: inline-block;
        vertical-align: middle;
        border: 0 none;
        cursor: pointer;
        outline: none;
        background-color: transparent;
        background-repeat: no-repeat;
        background-attachment: scroll;
        background-image: url("http://wx.palmnest.com/avicfile/2019/ysf/zTreeStandard.png");
      }
      .search-rs-title{
        margin-top: 15px;
        font-size: 15px;
        color: #333;
        background: #eee;
        padding: 8px 10px;
      }

      </style>

    </head>

    <body>
      <div id="app">
      <div class="bread-wp">
      		公告通知 >  发布公告消息  > 微信模板消息
      </div>
      <div class="right-content">
        <input type="hidden" value="${ctx}" id="contextPath">
         <ul class="third-tabs">
	          <li class="third-tab ">
	            <a href="noticeAppPublish">公告</a>
	          </li>
	          <li class="third-tab active">
	            <a href="wxPublish">微信模板消息</a>
	          </li>
	          <li class="third-tab">
	            <a href="msgPublish">短信消息</a>
	          </li>
	          <li class="third-tab">
	            <a href="emailPublish">邮件消息</a>
	          </li>
        </ul>
        <!-- 微信模板消息 -->
        <div class="main-content-mode-wp" id="main-content-mode-wp">
          <div class="wx-temp-wp">
            <el-form :inline="true" :model="dataForm" >
              <el-form-item label="选择项目"  v-if="orgOptions.length>1" >
                <el-select v-model="dataForm.orgId" filterable clearable placeholder="选择项目" @change="getTypeByOrgId">
                  <el-option
                  v-for="item in orgOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
               <el-form-item label="微信公众号" >
                <el-select v-model="dataForm.wxItem" filterable clearable placeholder="选择微信公众号"  @change="getTemplist">
                  <el-option
                    v-for="item in wxOptions"
                    :key="item.ID"
                    :label="item.name"
                    :value="item.ID">
                  </el-option>
                </el-select>
              </el-form-item>
               <el-form-item label="消息模板" >
                <el-select v-model="dataForm.templeId" filterable clearable placeholder="选择消息模板" @change="getTemplistContent">
                  <el-option
                    v-for="item in templeOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            <el-form-item label="审核类型"  v-if="isOpenApprove==1">
                <el-select v-model="dataForm.approvalId" filterable clearable placeholder="请选择审核类型">
                  <el-option
                    v-for="item in approvalOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          <div class="choose-infor-list-add">
            <div v-for="item in templeContentOptions" :key="item.id">
            <div class="choose-infor-item clearfloat">
              <span class="wx-tips">
                <span style="color: red;">*</span>
                {{item.name}}
              </span>
              <input type="text" v-model="item.value" class="wx-input wx-title" placeholder="请输入" />
            </div>
          </div>
            <div class="choose-infor-item clearfloat">
              <span class="wx-tips">原文链接</span>
              <input type="text" class="wx-input wx-link" placeholder="请输入原文链接"  v-model="linkUrl" />
            </div>
            <div class="choose-infor-item clearfloat" v-if="dataForm.templeId">
              <span class="wx-tips">发送对象</span>
              <div class="public-item-con">

                <el-radio-group v-model="checkRadio" @change="changeValue">
                  <el-radio :label="1" class="radio-top-content p-t-1">
                    <div class="radio-inner-name radio-title-name">项目所有用户<span style="font-weight:normal">（登录过楼宇之窗的用户才会受到公众号推送）</span></div>
                  </el-radio>
                  <el-radio :label="2" class="radio-top-content p-t-2">
                    <div class="radio-inner-name  radio-title-name">项目部分用户</div>
                  </el-radio>
                  <el-radio :label="3" class="radio-top-content p-t-3">
                    <div class="radio-inner-inport-user">
                      <div class="radio-title-name">导入用户</div>
                      <input  type="file" class="file-btn-input"  @change="handleFileChange"  multiple="multiple"/>
                      <button class="btn-blue-stp  file-btn-handler" @click="importExcel">导入</button>
                      <button class="btn-blue-stp download-mode-file" @click="downExcel">下载模板</button>
                    </div>
                   
                  </el-radio>
                  <el-radio :label="4" class="radio-top-content p-t-4">
                    <div class="radio-inner-choose-dep">
                      <div class="radio-title-name">部门分组发送 </div>
                      <button class="btn-blue-stp choose-dep-stp" @click="chooseDep">选择部门/分组</button>
                    </div>  
                   
                  </el-radio>
                </el-radio-group>
                <div class="tv-choose-content" v-if="checkRadio==4">
                  <el-tag
                  class="tag-css tag-top"
                  v-for="(item, index) in chooseDepList"  :key="index"
                  closable
                  :disable-transitions="false"
                    @close="deleteResultDepHandler(item, index)">
                  {{item.name}}
                </el-tag>
                </div>
                <div class="search-wp-warp" v-if="checkRadio==2">
                <div  >
                  <el-input placeholder="请输入内容" v-model="inputUser" class="input-with-select">
                  <el-button slot="append" icon="el-icon-search" @click="getProjectSearch"></el-button>
                </div>
                  <div>
                    <span class="choose-tip-name">已选用户:</span>
                    <div>
                      <el-tag
                      class="tag-item-name"
                      closable
                    @close="deleteUserHandler(item, index)"
                      v-for="(item, index) in chooseList"  :key="index"
                      :disable-transitions="false"
                    >
                      {{item.name +' '+item.mobile}}
                    </el-tag>
                    </div>
                    
                  </div>
                  <div class="content-user-wrap">
                    <el-checkbox-group v-model="checkedUsers" >
                      <el-checkbox v-for="item in userList" :label="item.userId" :key="item.id" 
                       class="checkbox-item-cb" @change="val => handleChecked(val,item)"
                      >{{item.name + ' '+ item.mobile+' '+item.orgName}}</el-checkbox>
                    </el-checkbox-group>

                  </div>
                </div>

                <div class="import-list-wp" v-if="checkRadio==3 && inportUseList.length>0">
                  <div class="clear-btn-text"  @click="clearUsers">清空</div>
                  <el-checkbox-group v-model="checkedInportUsers" >
                    <el-checkbox v-for="item in inportUseList" :label="item.id" :key="item.id" 
                     class="checkbox-item-cb" @change="val => handleCheckedUser(val,item)"
                    >{{item.name + ' '+ item.mobile+' '+item.virtName}}</el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>

            </div>
          </div>
          <div class="btns-wp">
               <button class="btn-blue-width90 cancle-btn" @click="cancleHandler">取消</button>
	            <button class="btn-red-width90 submit-btn" @click="ajaxWxSubmit">提交发送</button>
			</div>
      </div>
       </div>
       <div class="dialog-pop">
      <el-dialog
		:title="titleName"
		:close-on-click-modal="false"
		width="800px"
		:visible.sync="isDislagVisable"
		>
    <div style="float: left">
      <div style="float:left;width: 480px;height: 500px;">
            <div style="display: flex">
              <el-input
                class="search-input"
                placeholder="请输入部门、分组名称搜索"
                prefix-icon="el-icon-search" clearable @change="changeInput"
                v-model.trim="searchText">
              </el-input>
              <el-button slot="append" icon="el-icon-search" @click="searchDeptOrSup"></el-button>
            </div>
          <div class="search-data-wrap" v-show="false">
            <div style="overflow-y: scroll;height: 440px;">
              <div v-if=" searchDataList.deptList && searchDataList.deptList.length>0">
              <div class="search-rs-title">部门</div>
              <div class="list-box click-cursor" v-for="(item, index) in searchDataList.deptList" :key="item.id" 
                :class="{'line-top': index != 0}">
                <div class="cell-box">
                  <div class="tag-size" v-on:click="searchDataHandler(item)">
                    <img src="http://wx.palmnest.com/avicfile/2019/ysf/img_docum.png" class="img-sup-icon"/>
                    <span class="sub-item-name">{{item.name}}</span>
                <span v-if="backSelectedHandler(item.id)" class="radio-icon el-icon-check icon-check-item"></span>
                  </div>
                </div>
              </div>
            </div>
              <div v-if="searchDataList.groupList&&searchDataList.groupList.length>0">
              <div class="search-rs-title" >分组</div>
              <div class="list-box click-cursor" v-for="(item, index) in searchDataList.groupList" :key="item.id" 
                :class="{'line-top': index != 0}">
                <div class="cell-box">
                  <div class="tag-size" v-on:click="searchDataHandler(item)">
                    <img src="../../../../super_service/images/admin/tag-icon.png" class="img-sup-icon"/>
                    <span class="sub-item-name">{{item.name}}</span>
                <span v-if="backSelectedHandler(item.id)" class="radio-icon el-icon-check icon-check-item"></span>
                  </div>
                </div>
              </div>
            </div>
            </div>
          </div>
         <div class="default-data-wrap" v-show="true"> 
        <div class="tree-group-box box-top10 box-right15">
          <el-menu :default-active="activeIndex" mode="horizontal" @select="handleSelect">
            <el-menu-item index="1" v-if="indexType == 1||indexType == 0">部门</el-menu-item>
            <el-menu-item index="2" v-if="indexType == 2||indexType == 0">分组</el-menu-item>
          </el-menu>
        </div>
        <div style="overflow-y: scroll;height: 400px;" v-if="activeIndex == 1">
            <el-tree :data="dataTree"  default-expand-all node-key="id" @node-click="handleNodeClick"
            :filter-node-method="filterNodeHandler"  :expand-on-click-node="false"
                ref="tree" highlight-current  :props="defaultProps"> 
          <span class="custom-tree-node" slot-scope="{node, data}">
          <span @mouseover="showTip(data.id)" @mouseout="hideTip"  class="el-tree-node-name">
            <span v-if="data.childList&&data.childList.length>0||data.levels==0"
                class="span-button ico_open"></span>
            <span v-else class="span-button ico_docu"></span>
            <span>{{node.label}}</span>
            </span>
            <span v-if="backSelectedDepHandler(data.id)" class="radio-icon el-icon-check icon-check-item"></span> 
          </span>
          </el-tree>
        </div>
        <div style="overflow-y: scroll;height: 385px;" v-if="activeIndex == 2">
          <div class="list-box click-cursor" v-for="(item, index) in tagList" :key="item.id" 
		        :class="{'line-top': index != 0}">
            <div class="cell-box">
              <div class="tag-size" v-on:click="tagBtnHandler(item)">
                <img src="../../../../super_service/images/admin/tag-icon.png" class="img-sup-icon"/>
                <span class="sub-item-name">{{item.name}}</span>
				    <span v-if="backSelectedHandler(item.id)" class="radio-icon el-icon-check icon-check-item"></span>
              </div>
            </div>
          </div>
        </div>
       </div>  
      </div>
      <div style="margin-left:10px;float: left;width: 1px;height: 480px; background: #F3F3F3"></div>
      <div style="margin-left:10px;float:left;width: 250px;">
        <div style="width: 100%">已选择</div>
        <div style="width: 100%;height: 460px;overflow-y: scroll;">
          <el-tag
            class="tag-css tag-top"
            v-for="(item, index) in identityList"  :key="index"
            closable
            :disable-transitions="false"
		    	@close="deleteTagHandler(item, index)">
            {{item.name}}
          </el-tag>
        </div>
      </div>
    </div>
        <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogCancle">返回</el-button>
        <el-button size="small" type="primary" @click="chooseDataSubmit">确定</el-button>
        </span>
     </el-dialog>
    </div>
    </div>
     
<script type="text/javascript">
  // 在页面加载好后就初始化vue实例,也可以在外面直接初始化
  $(document).ready(function(){
    const vm = new Vue({
      el:'#app',
      data(){
        return {
          editId:'',
          contextBasePath:'',
          searchDataList:{},
          inputUser:'',
          userList:[],
          checkedUsers:[],//选择的用户
          chooseList:[],
          ifShowSearch:false,
          checkRadio:0,
          isOpenApprove:0,///判断是否开启了多级审核 1.开启了多级审核 2，没有开启多级审核
          titleName: '请选择部门和分组',
          searchNote: '',
          activeIndex: '1',
          indexType: '0',
          isDislagVisable: false,
          identityList:[],// 弹框右边选中的数据
          chooseDepList:[],//选中的数据
          templeTitle:'',
          dataForm:{
            approvalId:'',
            templeId:'',
            wxItem:'',
            orgId:'',
          },
          radioCkeck:0,
          orgOptions:[],
          wxOptions:[],
          approvalOptions:[],
          templeOptions:[],
          templeContentOptions:[],
          checkedInportUsers:[],
          inportUseList:[],
          linkUrl:'',
          dataTree: [],
          tagList: [],
            selectedId: '',
          searchText: '',
          defaultProps: {
          children: 'childList',
          label: 'nameinfo'
          },
         
        }
      },
      //监听搜索框的查询参数变化，然后进行过滤
    watch:{
      searchText(val) {
        if(this.activeIndex==1){
          setTimeout(() => {
            this.$refs.tree.filter(val)
          }, 1000);
        }else{
          this.getSubgroupList(val)
        }
        }
    },
      methods:{
        changeInput(value){
          if(value){
            this.ifShowSearch=true
          }else{
            this.ifShowSearch=false
          }
        },
          filterNodeHandler(value, data, node) {
          if (!value) {
            return true
          }
          let level = node.level
          let _array = [] //这里使用数组存储 只是为了存储值。
          this.getReturnNode(node, _array, value)
          let result = false
          _array.forEach(item => {
            result = result || item
          })
          return result
        },
        getReturnNode(node, _array, value) {
          let isHasData = node.data && node.data.nameinfo && node.data.nameinfo.indexOf(value) !== -1
          isHasData ? _array.push(isHasData) : ''
          if (!isHasData && node.level != 1 && node.parent) {
            this.getReturnNode(node.parent, _array, value)
          }
        },
        cancleHandler(){
          window.location.href = '/super_service/notice/audit/noticeWxVerify';
        },
        //清除导入的用户
        clearUsers(){
          this.inportUseList=[]
          this.checkedUsers=[]
        },
        handleFileChange (e) {
          console.log("e",e)
          const input = e.target;
          const files = e.target.files;
          if(files && files[0]) {
              const file = files[0];
              this.uploadUsers(file,this.dataForm.orgId)
          }
       },
          uploadUsers: function(file,orgId){
            let _this=this
            var formData = new FormData();
            formData.append("orgId", orgId);
            formData.append("excelFile", file);
            $.ajax({
              url:  '/super_service/notice/publicno/importUserInfo',
              type: "POST",
              data: formData,
              cache: false, // 不缓存
              processData: false, // 告诉jQuery不要去处理发送的数据
              contentType: false, // 告诉jQuery不要去设置Content-Type请求
              success: function (data) {
                if(data.code == 200 || data.code ==300){
                  var res = data.data;
                  if(res.length>0){
                    res.forEach(val =>{
                      _this.checkedUsers.push(val.id)
                    })
                  }
                  _this.inportUseList=res
                  _this.inportUseList=[..._this.inportUseList]
                  
                      
              }else{
              }
            },
            error: function(err){
            }
          });
        },
          handleChecked(val,rule){
            console.log("checkedUsers",this.checkedUsers)
          console.log("选择的",val ,rule)
          if(val){
            this.chooseList.push(rule)
          }else{
            this.deleteItem(rule.userId,this.chooseList)
          }
        },
        handleCheckedUser(val,rule){
          console.log("选择的",val ,rule)
          if(val){
            this.chooseList.push(rule)
          }else{
            this.deleteItem(rule.userId,this.chooseList)
          }
        },
        deleteUserHandler(data, index){
          console.log("deleteUserHandler",data,index)
          console.log("checkedUsers",this.checkedUsers)
          this.chooseList.splice(index, 1);
          // this.checkedUsers.
          this.checkedUsers.splice( this.checkedUsers.findIndex(item => item === data.userId), 1)

        },
        deleteItem (item, list) {
        for (var key in list) {
          if (list[key].userId === item) {
              list.splice(key, 1)
          }
        }
       },
        chooseDep(){
          if(this.checkRadio==4){
            this.getDeptTreeList();
            this.getSubgroupList('');
            this.isDislagVisable=true
            this.searchText=""
            let newArr=[]
            if(this.chooseDepList && this.chooseDepList.length>0){
              for (const key in this.chooseDepList) {
              newArr.push(this.chooseDepList[key])
             }
            }
            this.identityList=newArr
            $(".dialog-pop").show();
            
          }
         
        },
        dialogCancle(){
          this.isDislagVisable=false
          this.identityList=[]
        },
        chooseDataSubmit(){
          console.log("已选中的数据",this.identityList)
          this.isDislagVisable=false
          let newArr=[]
          if(this.identityList.length>0){
            for (const key in this.identityList) {
              newArr.push(this.identityList[key])
             }
          }
          this.chooseDepList=newArr
          console.log("已选中的数据最后的展示",this.chooseDepList)
        },
        //弹框搜索
        searchDeptOrSup(){
          let _this = this;
          // _this.ifShowSearch=true
         
          // if(_this.activeIndex==1 &&  _this.searchText){
          //   _this.dataTree=_this.filterNodeHandler(_this.searchText , _this.dataTree)
          //     console.log("_this.dataTree",_this.dataTree)
          // }else {
          //   _this.getDeptTreeList()
          // }

          if(_this.activeIndex==2 ){
              _this.getSubgroupList(_this.searchText)
          }
        },
        getDeptTreeList(){
            var _this = this;
              if (!_this.dataForm.orgId) {
                _this.$message({message: '请选择项目!', type: 'error'});
                return false;
              };
            $.ajax({
              // url: "http://wx.palmnest.com/super_cloud/api/organisation/department/getDeptTree",
              url:   '/super_cloud/api/organisation/department/getDeptTree',
              type: "POST",
              dataType: "json",
              data: {
                orgId:_this.dataForm.orgId,//项目Id 
                virtId: _this.inputUser,//
              },
              success: function (data) {
                // console.log("部门返回",data)
                if(data.code == 200 && data.data){
                  _this.dataTree=data.data
                }else{
                  _this.dataTree=[]
                }
              },
              error: function(err){

              }
            });
        },
        //分组数据
        getSubgroupList(val){
              var _this = this;
            if (!_this.dataForm.orgId) {
              _this.$message({message: '请选择项目!', type: 'error'});
              return false;
            };
          $.ajax({
            // url:  'http://wx.palmnest.com/super_cloud/api/organisation/subgroup/getAll',
            url:  '/super_cloud/api/organisation/subgroup/getAll',
            type: "POST",
            dataType: "json",
            data: {
              pageSize:1,
              pageNo:1000,
              "conditions['orgId']":_this.dataForm.orgId,//项目Id 以逗号分隔 最后面不要带逗号
              "conditions['name']": val,//姓名、手机号、项目名 模糊搜索，默认传""
            },
            success: function (data) {
              // console.log("分组返回",data)
              if(data.code == 200 && data.data){
                _this.tagList=data.data
              }else{
                _this.tagList=[]
              }
            },
            error: function(err){

            } 
          });
        },
          // 递归获取所有节点数据
       getAllNodeId (expandedKeys, moduleDataList) {
        for (let i = 0; i < moduleDataList.length; i++) {
          expandedKeys.push({
            id: moduleDataList[i].id,
            levels: moduleDataList[i].levels,
            nameinfo: moduleDataList[i].nameinfo,
            orgInfo: moduleDataList[i].orgInfo,
            parentid: moduleDataList[i].parentid,
            rank: moduleDataList[i].rank,
            visible: moduleDataList[i].visible,
            childList: [],
          });
          if (moduleDataList[i].childList) {
            expandedKeys = this.getAllNodeId(expandedKeys, moduleDataList[i].childList)
          }
        }
        return expandedKeys
      },
         // 处理选中数据
         processSelectedData(data, backData) {
        let dataList = [];
        if (data.id) {
          dataList = this.getAllNodeId(dataList, [data]);
          backData(dataList)
        } else {
          backData([])
        }
      },

        handleNodeClick(data,node,inde){
          this.processSelectedData(data, backData => {
            console.log('backData', backData);
            if (this.backSelectedDepHandler(data.id)) {
              backData.forEach(item => {
                let indexRow = this.backSelectedDepHandler(item.id, true);
                this.identityList.splice(indexRow, 1);
              })
            } else {
              this.identityList = this.unique(this.identityList.concat(backData))
            }
            console.log("最后选中的列表",this.identityList)

            let newArr=[]
          for (const data of this.identityList) {
            let resultObj={}
           resultObj['id']=data.id
           resultObj['name']= data.name?data.name:data.nameinfo
           if(data.levels==0){
            resultObj['type']=1
           }else{
            resultObj['type']=2
           }
           newArr.push(resultObj)
          }
           this.identityList=[...newArr]
           
          console.log("最后选中11111",this.identityList)
     
          });
        },

         // 数据根据id去重
      unique(arr) {
        const res = new Map();
        return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1));
      },
        getCheckedKeys() {
          console.log(this.$refs.tree.getCheckedKeys());
        },
        setCheckedKeys() {
          this.$refs.tree.setCheckedKeys([3]);
        },

            //鼠标经过树节点时触发
        showTip() {

        },
        //鼠标离开树节点时触发
        hideTip() {

        },
        submit(){
          this.isDislagVisable=true
        },
        getProjectSearch(){
			   var _this = this;
         if (!_this.dataForm.orgId) {
          _this.$message({message: '请选择项目!', type: 'error'});
          return false;
        };
			$.ajax({
				url:   '/super_service/notice/publicno/getUserByOrgId',
				type: "POST",
				dataType: "json",
				data: {
					orgIds:_this.dataForm.orgId,//项目Id 以逗号分隔 最后面不要带逗号
					name: _this.inputUser,//姓名、手机号、项目名 模糊搜索，默认传""
				},
				success: function (data) {
					if(data.code == 200 && data.data){
					_this.userList=data.data
          console.log("1",_this.userList)
					}else{
					
					}
				},
				error: function(err){

				}
			});
    },
        deleteResultDepHandler(data, index){
          console.log('弹框删除 deleteResultDepHandler',data ,this.chooseDepList)
          this.chooseDepList.splice(index, 1);
        },
        deleteTagHandler(data, index){
          this.identityList.splice(index, 1);
          console.log('弹框删除',data ,this.chooseDepList)
        },
        handleSelect(val) {
          this.activeIndex = val;
          if(this.activeIndex==1){
          setTimeout(() => {
            this.$refs.tree.filter(this.searchText)
          }, 1000);
        }else{
          this.getSubgroupList(this.searchText)
        }
        },
        backSelectedDepHandler(id, isIndex = false){
          let isYN = false;
          let seleIndex = -1;
          this.identityList.every((item, index) => {
          if (item.id == id) {
            seleIndex = index;
            isYN = true;
            return false;
          } else {
            return true;
          }
          })
          if (isIndex) {
          return seleIndex;
          } else {
          return isYN;
          }
        } ,  
        backSelectedHandler(id, isIndex = false) {
          let isYN = false;
          let seleIndex = -1;
          this.identityList.every((item, index) => {
          if (item.id == id) {
            seleIndex = index;
            isYN = true;
            return false;
          } else {
            return true;
          }
          })
          if (isIndex) {
          return seleIndex;
          } else {
          return isYN;
          }
      },  
      //搜索选中的情况下
      searchDataHandler(data){
        if (this.backSelectedHandler(data.id)) {
          let indexRow = this.backSelectedHandler(data.id, true);
          if (indexRow != -1) {
            this.identityList.splice(indexRow, 1);
          }
          } else {
            let newArr=[]
           let resultObj={}
           resultObj['id']=data.id
           resultObj['name']=data.name
           resultObj['type']=3
           newArr.push(resultObj)
          this.identityList=[...this.identityList,...newArr]
          }
      },
       // 点击选中项
       tagBtnHandler(data) {
          if (this.backSelectedHandler(data.id)) {
          let indexRow = this.backSelectedHandler(data.id, true);
          if (indexRow != -1) {
            this.identityList.splice(indexRow, 1);
          }
          } else {
            let newArr=[]
           let resultObj={}
           resultObj['id']=data.id
           resultObj['name']=data.name
           resultObj['type']=3
           newArr.push(resultObj)
          this.identityList=[...this.identityList,...newArr]
          }
        },
        getTypeByOrgId(val){
          this.dataForm.wxItem=""
          this.dataForm.templeId=""
          this.templeOptions=[]
          this.templeContentOptions=[]
          this.renderWxNum(val);

        },
        changeValue(value){
          console.log("changeValue",value)
          this.checkRadio=value
          this.inputUser=""
          this.userList=[]
          this.chooseList=[]
        },
        importExcel(){

        },
        downExcel(){
          var contextPath = $("#contextPath").val()
          console.log("contextPath",contextPath)
          location.href=contextPath+"/upload/NoticeUser.xlsx";
        },
        /**
     * 获取url的参数
     * @paran name 参数名称
     */
      getQueryString: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
      },
      ajaxDetail: function (id) {
      var _this = this;
      $.ajax({
        type: "post",
        url:  "/super_service/notice/wxtemplateMessage/getDetail",
        data: {
          "id": id
        },
        success: function (data) {
          var data = JSON.parse(data);
          if (data.code == 200) {
            var result = data.data;
            _this.getProjectList();
            _this.dataForm.approvalId=result.data1.approvalType
            _this.dataForm.orgId=result.orgId
            _this.dataForm.wxItem=result.data3.id
            _this.dataForm.templeId=result.data4.id
            _this.templeContentOptions=result.data2
            _this.checkRadio=result.data1.receive_type
            _this.renderTemp(_this.dataForm.wxItem)
            _this.linkUrl=result.data1.url
            _this.chooseDepList=result.deptGroupList
            console.log("orgid",_this.dataForm.orgId)
            //获取选择的用户数据
            if(_this.checkRadio==2){
              _this.getChooseUserByOrgid(_this.dataForm.orgId,result.data1.receive_user_id,result.data1.receive_type);
            }
            if(_this.checkRadio==3){//设置选中的数据
              _this.inportUseList=result.data5
              result.data5.forEach(val =>{
                _this.checkedInportUsers.push(Number(val.id))
              })
              
            }
           
            _this.renderWxNum(result.data1.orgId, 'update', result.data3.id, result.data4.id, result.data2, result.data1.url,result)
          } else {
           
          }
        },
        error: function (error) {
         
        }
      });
    },
    getChooseUserByOrgid(orgid,userid,radioType){ 
      var _this = this;
			$.ajax({
				url:   '/super_service/notice/publicno/getUserByOrgId',
				type: "POST",
				dataType: "json",
				data: {
					orgIds:orgid,//项目Id 以逗号分隔 最后面不要带逗号
					name: '',//姓名、手机号、项目名 模糊搜索，默认传""
				},
				success: function (data) {
					if(data.code == 200 && data.data){
            console.log("用户数据", userid)
					_this.userList=data.data
          var newUserArr=userid.split(",");
          data.data.forEach(val =>{
            for (const key in newUserArr) {
              if(val.userId==newUserArr[key]){
              _this.chooseList.push(val)
              _this.checkedUsers.push(Number(userid))
             }
            }
           
          })
          console.log("选择的用户数据组", _this.chooseList ,_this.checkedUsers)
					}else{
					
					}
				},
				error: function(err){

				}
			});

    },
      renderWxFirst: function () {
      var _this = this;
      var id = this.getQueryString("id");
      console.log("id",id)
      _this.editId=id
      // _this.renderOrgList();
      // _this.getProjectList();
      
      if (!!id) {
        _this.ajaxDetail(id);
      }else{
        _this.getProjectList();
      }
     },
     //调用项目列表接口，如果是1个的话就显示审核
		getProjectList(){
      var	_this = this
			$.ajax({
				type: "post",
				url:  "/super_service/admin/templ/getOrgList",
				success: function (data) {
					if (data.code == 200) {
            _this.orgOptions=data.data
						if(data.data.length==1){
              _this.dataForm.orgId=data.data[0].id
							_this.getIfCanApproval(data.data[0].id)
              _this.renderWxNum(data.data[0].id);
						}
					} else {
					}
				},
				error: function (error) {
				
				}
			});
		},
    getIfCanApproval(orgid){
      var _this=this
			$.ajax({
				type: "post",
				url:  "/super_service/notice/approval/getSetByOrgId",
				data: {
					"orgId":  orgid
				},
				success: function (data) {
					if (data.code == 200) {
						if(data.data.isOpen==1){//显示审核下拉列表
              _this.getApproveTypeIsOpen(orgid)
						}
					} else {
					}
				},
				error: function (error) {
				}
			});
		},
    	//判断是否开启了审核
			getApproveTypeIsOpen(orgId){
				var _this=this
				$.ajax({
					type: "post",
					url:  "/super_service/notice/approval/getApprovalSetDto",
					data: {
						"orgId": orgId
					},
					success: function (data) {
						if (data.code == 200) {
							if(data.data.isOpen==1){
								_this.isOpenApprove=1
								_this.getApprovalTypeList(orgId)
							}else {
								_this.isOpenApprove=2
							}
						} else {
						}
					},
					error: function (error) {
					}
				});
			},
      getApprovalTypeList(orgid){
      var _this=this
			$.ajax({
				type: "post",
				url:  "/super_service/notice/approval/getApprovalType",
				data: {
					"orgId": orgid
				},
				success: function (data) {
					if (data.code == 200) {
						_this.approvalOptions=data.data
					} else {
					}
				},
				error: function (error) {
				}
			});
		},
    ajaxWxSubmit: function () {
      let _this = this;
      //微信消息id
      var id =_this.editId;
      console.log("id",id)
      //项目id
      if (!_this.dataForm.orgId) {
        _this.$message({message: '请选择项目!', type: 'error'});
        return false;
      };
      //微信公众号
      if (!_this.dataForm.wxItem) {
        _this.$message({message: '请选择微信公众号!', type: 'error'});
        return false;
      };
      //消息模板
      if (!_this.dataForm.templeId) {
        _this.$message({message: '请选择消息模板!', type: 'error'});
        return false;
      };
      //审核类型
      if (!_this.dataForm.approvalId &&_this.isOpenApprove==1) {
        _this.$message({message: '请选择审核类型!', type: 'error'});
        return false;
      };
      //原文链接
      var url = _this.linkUrl;
      console.log("URL",url)
      if (url) {
        var regTxt = url.match(/^http:\/\//);
        var regTxts = url.match(/^https:\/\//);
        if (!regTxt && !regTxts) {
          _this.$message({message: '请输入有效链接', type: 'error'});
          flag = false
          return false;
        }
      }

      console.log("URL",_this.templeContentOptions)
      //其他参数
      var param1, param2, param3, param4, param5, param6, param7,
        key1, key2, key3, key4, key5, key6, key7,
        value1, value2, value3, value4, value5, value6, value7;
      var flag = true;
      for (const j in _this.templeContentOptions) {
        let  value=_this.templeContentOptions[j].value
        let  key=_this.templeContentOptions[j].param_key
        let  param=_this.templeContentOptions[j].name
        if (!value) {
          _this.$message({message: '除原文链接外所有项都为必填', type: 'error'});
          flag = false
          return false;
        }
        flag = true;
        if(j == 0){
          param1 = param
          key1 = key
          value1 = value
        }else if(j == 1){
          param2 = param
          key2 = key
          value2 = value
        }else if(j == 2){
          param3 = param
          key3 = key
          value3 = value
        }else if(j == 3){
          param4 = param
          key4 = key
          value4 = value
        }else if(j == 4){
          param5 = param
          key5 = key
          value5 = value
        }else if(j == 5){
          param6 = param
          key6 = key
          value6 = value
        }else if(j == 6){
          param7 = param
          key7 = key
          value7 = value
        }
      }
      
      if (!flag) {
        return false;
      }
      var userIds = "";
      var deptGroupJson=""
      var receiveType = null;
      if(_this.checkRadio==0){
        _this.$message({message: '请选择发布对象', type: 'error'});
        return false;
      }else if(_this.checkRadio==2){
        console.log("this.chooseList",_this.chooseList)
        if(_this.chooseList.length==0){
          _this.$message({message: '请选择用户,且用户不得少于1个！！', type: 'error'});
          return false;
        }else{
          var useridArr =[];
          _this.chooseList.forEach(val =>{
            useridArr.push(val.userId)
          })
          userIds = useridArr.join(",");
          receiveType = 2
        }
      }else if(_this.checkRadio==3){
        if(_this.checkedInportUsers.length==0){
          _this.$message({message: '请选择导入用户！', type: 'error'});
          return false;
        }else{
          userIds = _this.checkedInportUsers.join(",");
          receiveType = 3
        }

      }else if(_this.checkRadio==4){
        receiveType=4
        if(_this.chooseDepList.length>0){
          deptGroupJson=JSON.stringify(_this.chooseDepList)
          }else {
            _this.$message({message: '请选择部门或者分组！', type: 'error'});
          return false;
          }

      }else if(_this.checkRadio==1){
        receiveType = 1
      }
    for (const key in _this.templeOptions) {
      if (_this.templeOptions[key].id==_this.dataForm.templeId) {
        _this.templeTitle=_this.templeOptions[key].name
        
      }
    }

      $.ajax({
        type: "post",
        url:  "/super_service/notice/wxtemplateMessage/saveOrUpdate",
        data: {
          wechat_template_id: _this.dataForm.templeId,
          orgId: _this.dataForm.orgId,
          title: _this.templeTitle,
          url: url,
          receive_user_id: userIds,
          receive_type: receiveType,
          approvalType: _this.dataForm.approvalId,
          "param1": param1,
          "key1": key1,
          "value1": value1,
          "param2": param2,
          "key2": key2,
          "value2": value2,
          "param3": param3,
          "key3": key3,
          "value3": value3,
          "param4": param4,
          "key4": key4,
          "value4": value4,
          "param5": param5,
          "key5": key5,
          "value5": value5,
          "param6": param6,
          "key6": key6,
          "value6": value6,
          "param7": param7,
          "key7": key7,
          "value7": value7,
          id: !!id ? id : '',
          deptGroupJson:deptGroupJson,
        },
        success: function (data) {
          console.log("返回值",data.code)
          if (data.code == '200') {
            if (!!id) {
              _this.$message({message: '发布成功', type: 'success'});
              window.location.href = '/super_service/notice/audit/noticeWxVerify';
            } else {
              _this.$message({message: '发布成功', type: 'success'});
              window.location.href =  '/super_service/notice/audit/noticeWxVerify';
              // $(".main-content-mode-wp").find("select,input").not("input#orgId").val("");
              // $("#main-content-mode-wp .public-extra-wp").hide();
              // $("#main-content-mode-wp").find("input:checkbox[name='public']").prop('checked', false);
              // $("#main-content-mode-wp").find("input:radio[name='public']:first").prop('checked', true);
              // $("#main-content-mode-wp .search-wp").remove();
              // $("#main-content-mode-wp  .export-list-wp").remove()
            }

          } else {
            _this.$message({message: data.msg, type: 'error'});
          }
        },
        error: function () {
         
        }
      });
    },
    bindEvent: function () {
      var _this = this;
  	
      // 模糊搜索
      _this.search_fuzzy()
     },
     // 模糊搜索事件
    search_fuzzy: function(){
      $('body').on("input",'#orgId',function(event){
        var _this = $(this)
        cjqt.search_fuzzy.event_input(_this,'org__id','org__span',contextPath,'/admin/templ/getOrgListByName')
      });
      $('body').on("focus",'#orgId',function(event){
        var _this = $(this)
        cjqt.search_fuzzy.event_focus(_this,'org__id','org__span',contextPath,'/admin/templ/getOrgListByName')
      });
      $('body').on('blur','#orgId',function(event) {
        var _this = $(this)
        cjqt.search_fuzzy.event_blur(_this,'org__id')
      });
      $('body').on('click','.select_wrap>.org__span', function(event) {
        event.preventDefault();
        event.stopPropagation();
        /* Act on the event */
        var _this = $(this)
        cjqt.search_fuzzy.event_click(_this,'org__id','#orgId')
      });
    },
    renderOrgList: function () {
      var _this = this;
      $(".org-list").on("change", function () {
        var id = $(this).val();
        if (id) {
         
        } else {
          
        }

      })
    },
    /**
     * 渲染公众号
     * @param orgId
     * @param type 'update' 修改微信消息 'add'或者'' 新增微信消息
     * @param wxId 公众号id
     * @param templateId 模板id
     * @param tempalteData 模板数据
     * @param url 原文链接
     * @param allData 详情全部数据
     */
     renderWxNum: function (orgId, type, wxId, templateId, tempalteData, url,allData) {
      var _this = this;
      $.ajax({
        type: "post",
        url:  "/super_service/notice/wxtemplateMessage/getPublicList",
        data: {
          orgIds: orgId
        },
        success: function (data) {
          var res = JSON.parse(data);
          _this.wxOptions=res.data
        },
        error: function (error) {
        }
      });
    },
    getTemplist(val){
      this.dataForm.templeId=''
      this.renderTemp(val)
    },
    getTemplistContent(val){
      this.renderProperty(val)
    },
    renderProperty: function (id, tempalteData, url,allData) {
      var _this = this;
        $.ajax({
          type: "post",
          url:  "/super_service/notice/wxtemplateMessage/getTemplateConfig",
          data: {
            id: id
          },
          success: function (data) {
            var data = JSON.parse(data);
            if (data.code == '200') {
              data.data.forEach( val =>{
                val['value']=''
              })
              _this.templeContentOptions=data.data
            
            } else {
            }
          },
          error: function (error) {
          }
        });
    },
    /**
     * 渲染模板
     * @param id 公众哈id
     *  @param templateId 模板id
     * @param tempalteData 模板数据
     * @param url 原文链接
     */
    renderTemp: function (id, templateId, tempalteData, url,allData) {
      var _this = this;
      $.ajax({
        type: "post",
        url: "/super_service/notice/wxtemplateMessage/getTemplateList",
        data: {
          id: id
        },
        success: function (data) {
          var data = JSON.parse(data);
          if (data.code == '200') {
            _this.templeOptions=data.data
          } else {
          }
        },
        error: function (error) {
        }
      });
    },
        
      },
      created(){
        this.renderWxFirst()
        this.bindEvent();
        this.contextBasePath = $("#contextPath").val().split("super_service")[0]+"super_cloud"
        if(this.contextBasePath=='/super_cloud'){
          this.contextBasePath="http://wx.palmnest.com/super_cloud"
        }
					console.log("contextBasePath",this.contextBasePath)
        
        
        
      },
    })
  })
    </script>
    <!-- <script type="text/javascript" src="<c:url value='/scripts/admin/notice/noticeWxPublish.js?v=3453534534'/>"></script> -->
    </body>

    </html>