<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="节点" prop="nodeValue">
        <el-select clearable v-model="queryParams.nodeValue" placeholder="请选择节点类型">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SYSTEM_SMS_NODE_NODE)"
                     :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="运输方式" prop="transportId">
        <el-select clearable v-model="queryParams.transportId" :placeholder="$t('请选择运输方式类型')">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.ECW_TRANSPORT_TYPE)"
                     :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
          <el-option key="0" label="其他" :value="parseInt(0)" />
        </el-select>
      </el-form-item>
      <el-form-item label="国家" prop="countryId">
        <el-select filterable clearable v-model="queryParams.countryId" :placeholder="$t('请选择国家')">
          <el-option key="0" label="全部" :value="parseInt(0)" />
          <el-option key="1" label="其他" :value="parseInt(1)" />
          <el-option v-for="dict in countryList"
                      :key="dict.id" :label="$l(dict, 'name')" :value="parseInt(dict.id)" />
        </el-select>
      </el-form-item>
      <el-form-item label="启用状态" prop="status">
        <el-select v-model="queryParams.status" :placeholder="$t('请选择开启状态')" clearable>
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="是否匹配运输方式" prop="isTransport" label-width="134px">
        <el-select clearable v-model="queryParams.isTransport">
          <el-option key="0" label="否" :value="parseInt(0)" />
          <el-option key="1" label="是" :value="parseInt(1)" />
        </el-select>
      </el-form-item>
      <el-form-item label="多订单" prop="isOrders">
        <el-select clearable v-model="queryParams.isOrders">
          <el-option key="0" label="否" :value="parseInt(0)" />
          <el-option key="1" label="是" :value="parseInt(1)" />
        </el-select>
      </el-form-item>
      <el-form-item label="目的仓" prop="extra">
        <el-cascader
          :options="regionTreeList2"
          collapse-tags
          v-model="queryParams.extra2"
          :props="cascaderProps"
          clearable>
        </el-cascader>
      </el-form-item>
      <el-form-item :label="$t('创建时间')">
        <el-date-picker v-model="dateRangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd"
                        type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['system:sms-node:create']">新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['system:sms-node:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="编号" align="center" prop="id" />

      <el-table-column label="节点" align="center" prop="nodeValue">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.SYSTEM_SMS_NODE_NODE" :value="scope.row.nodeValue" />
        </template>
      </el-table-column>
      <el-table-column label="运输方式" align="center" prop="transportId">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.TRANSPORT_TYPE" :value="scope.row.transportId" />
          {{ scope.row.transportId==0?'其他':'' }}
        </template>
      </el-table-column>
      <el-table-column label="国家" align="center" prop="countryId">
        <template slot-scope="scope">
          {{ scope.row.countryId | guojia(countryMap) }}
        </template>
      </el-table-column>

      <el-table-column label="国家区号" align="center" prop="countryCode" />
      <el-table-column label="启用状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="是否匹配运输方式" align="center" prop="isTransport" width="130">
        <template slot-scope="scope">
          {{ scope.row.isTransport == 0 ?'否':'是' }}
        </template>
      </el-table-column>
      <el-table-column label="多订单" align="center" prop="isOrders">
        <template slot-scope="scope">
          {{ scope.row.isOrders == 0 ?'否':'是' }}
        </template>
      </el-table-column>
      <el-table-column label="模板1" align="center" prop="templateIdOne" width="130">
        <template slot-scope="scope">
          <el-link type="primary" @click="look(smsTemplateMap.get(scope.row.templateIdOne))">
            {{ scope.row.templateIdOne!=null?smsTemplateMap.get(scope.row.templateIdOne)!=null?smsTemplateMap.get(scope.row.templateIdOne).name:'':'' }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="模板2" align="center" prop="templateIdTwo" width="130">
        <template slot-scope="scope">
          <el-link type="primary" @click="look(smsTemplateMap.get(scope.row.templateIdTwo))">
            {{ scope.row.templateIdTwo!=null?smsTemplateMap.get(scope.row.templateIdTwo)!=null?smsTemplateMap.get(scope.row.templateIdTwo).name:'':'' }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="模板3" align="center" prop="templateIdThree" width="130">
        <template slot-scope="scope">
          <el-link type="primary" @click="look(smsTemplateMap.get(scope.row.templateIdThree))">
            {{ scope.row.templateIdThree!=null?smsTemplateMap.get(scope.row.templateIdThree)!=null?smsTemplateMap.get(scope.row.templateIdThree).name:'':'' }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="模板4" align="center" prop="templateIdFour" width="130">
        <template slot-scope="scope">
          <el-link type="primary" @click="look(smsTemplateMap.get(scope.row.templateIdFour))">
            {{ scope.row.templateIdFour!=null?smsTemplateMap.get(scope.row.templateIdFour)!=null?smsTemplateMap.get(scope.row.templateIdFour).name:'':'' }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="目的仓" align="center"  width="200">
        <template slot-scope="scope" v-if="scope.row.extra!=null">
          <el-cascader
            style="width: 180px"
            :options="regionTreeList2"
            collapse-tags
            v-model="JSON.parse(scope.row.extra).receiveAddrList"
            :props="cascaderProps">
          </el-cascader>
        </template>
      </el-table-column>
      <el-table-column :label="$t('创建时间')" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('备注')" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="test(scope.row)">测试</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:sms-node:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:sms-node:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="节点" prop="nodeValue">
          <el-select v-model="form.nodeValue" placeholder="请选择节点类型" @change="handleChangeNode">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SYSTEM_SMS_NODE_NODE)"
                       :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="是否匹配运输方式" prop="isTransport">
          <el-select v-model="form.isTransport" @change="handleChangeIsTransport">
            <el-option key="0" label="否" :value="parseInt(0)" />
            <el-option key="1" label="是" :value="parseInt(1)" />
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('运输方式')" prop="transportId">
          <el-select v-model="form.transportId" :placeholder="$t('请选择运输方式类型')"  @change="handleChangeTransportId">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.ECW_TRANSPORT_TYPE)"
                       :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
            <el-option key="0" label="其他" :value="parseInt(0)" />
          </el-select>
        </el-form-item>

        <el-form-item label="多订单" prop="isOrders">
          <el-select v-model="form.isOrders">
            <el-option key="0" label="否" :value="parseInt(0)" />
            <el-option key="1" label="是" :value="parseInt(1)" />
          </el-select>
        </el-form-item>

        <el-form-item label="国家" prop="countryIds">
          <el-select filterable clearable multiple v-model="form.countryIds" :placeholder="$t('请选择国家')">
            <el-option key="0" label="全部" :value="parseInt(0)" />
            <el-option key="-1" label="其他" :value="parseInt(1)" />
            <el-option v-for="dict in countryList"
                        :key="dict.id" :label="$l(dict, 'name')" :value="parseInt(dict.id)" />
          </el-select>
        </el-form-item>
        <el-form-item label="国家区号" prop="countryCode">
          {{form.countryCode}}
        </el-form-item>

        <el-form-item label="目的仓" prop="receiveAddrList">
          <el-cascader
            :disabled="cascaderState"
            style="width: 300px"
            :options="regionTreeList"
            @change="selectHandle"
            collapse-tags
            v-model="form.receiveAddrList"
            :props="cascaderProps"
            clearable>
          </el-cascader>
        </el-form-item>

        <el-form-item :label="$t('开启状态')" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)"
                      :key="dict.value" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="模板1" prop="templateIdOne">
          <el-select filterable clearable v-model="form.templateIdOne" placeholder="请选择模板1">
            <el-option v-for="dict in smsTemplateList2"
                        :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板2" prop="templateIdTwo">
          <el-select filterable clearable v-model="form.templateIdTwo" placeholder="请选择模板2">
            <el-option v-for="dict in smsTemplateList2"
                        :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板3" prop="templateIdThree">
          <el-select filterable clearable v-model="form.templateIdThree" placeholder="请选择模板3">
            <el-option v-for="dict in smsTemplateList2"
                        :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板4" prop="templateIdFour">
          <el-select filterable clearable v-model="form.templateIdFour" placeholder="请选择模板4">
            <el-option v-for="dict in smsTemplateList2"
                        :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('备注')" prop="remark">
          <el-input v-model="form.remark" :placeholder="$t('请输入备注')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 对话框(发送短信) -->
    <el-dialog :title="$t('测试发送短信')" :visible.sync="sendSmsOpen" width="500px" append-to-body>
      <el-form ref="sendSmsForm" :model="sendSmsForm" :rules="sendSmsRules" label-width="140px">
        <el-form-item :label="$t('发送类型')" prop="messageType">
          <el-select v-model="sendSmsForm.messageType" placeholder="请选择发送类型">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SYSTEM_SMS_TEMPLATE_MESSAGE_TYPE)"
                       :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('区号')" prop="countryCode">
          <el-input v-model="sendSmsForm.countryCode" :placeholder="$t('请输入区号')" />
        </el-form-item>
        <el-form-item :label="$t('手机号')" prop="mobile">
          <el-input v-model="sendSmsForm.mobile" :placeholder="$t('请输入手机号')" />
        </el-form-item>
        <el-form-item label="模板序号" prop="nodeTemplateSn">
          <el-input v-model="sendSmsForm.nodeTemplateSn" placeholder="请输入模板序号" />
        </el-form-item>
        <el-form-item label="参数(JSON)" prop="templateParams">
          <el-input v-model="sendSmsForm.templateParams" type="textarea"/>
        </el-form-item>
        <el-form-item label="目的仓" prop="receiveAddrList">
          <el-cascader
            style="width: 300px"
            :options="regionTreeList"
            collapse-tags
            v-model="sendSmsForm.receiveAddrList"
            :props="cascaderProps"
            clearable>
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSendSmsForm">{{ $t('确 定') }}</el-button>
        <el-button @click="cancelSendSms">{{ $t('取 消') }}</el-button>
      </div>
    </el-dialog>

    <!-- 预览模板 -->
    <el-dialog :visible.sync="open2" width="500px" append-to-body>
      <el-form label-width="140px">
        <el-form-item :label="$t('短信渠道编号')" prop="channelId">
          <el-select v-model="form2.channelId" :placeholder="$t('请选择短信渠道编号')">
            <el-option v-for="channel in channelOptions"
                       :key="channel.id" :value="channel.id"
                       :label="channel.signature + '【' + getDictDataLabel(DICT_TYPE.SYSTEM_SMS_CHANNEL_CODE, channel.code) + '】'" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('发送类型')" prop="messageType">
          <el-select v-model="form2.messageType" placeholder="请选择发送类型">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SYSTEM_SMS_TEMPLATE_MESSAGE_TYPE)"
                       :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('短信类型')" prop="type">
          <el-select v-model="form2.type" :placeholder="$t('请选择短信类型')">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SYSTEM_SMS_TEMPLATE_TYPE)"
                       :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="节点" prop="nodeValue">
          <el-select v-model="form2.nodeValue" placeholder="请选择节点类型">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SYSTEM_SMS_NODE_NODE)"
                       :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('运输方式')" prop="transportId">
          <el-select v-model="form2.transportId" :placeholder="$t('请选择运输方式类型')">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.ECW_TRANSPORT_TYPE)"
                       :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
            <el-option key="0" label="无" :value="parseInt(0)" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('模板编号')" prop="code">
          <el-input v-model="form2.code" :placeholder="$t('请输入模板编号')" />
        </el-form-item>
        <el-form-item :label="$t('模板名称')" prop="name">
          <el-input v-model="form2.name" :placeholder="$t('请输入模板名称')" />
        </el-form-item>


        <el-form-item :label="$t('开启状态')" prop="status">
          <el-radio-group v-model="form2.status">
            <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)"
                      :key="dict.value" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="短信API模板编号" prop="apiTemplateId">
          <el-input v-model="form2.apiTemplateId" placeholder="请输入短信 API 的模板编号" />
        </el-form-item>
        <el-form-item :label="$t('模板内容')" prop="content">
          <el-input type="textarea" v-model="form2.content" :placeholder="$t('请输入模板内容')" />
        </el-form-item>
        <el-form-item :label="$t('备注')" prop="remark">
          <el-input v-model="form2.remark" :placeholder="$t('请输入备注')" />
        </el-form-item>
        <el-form-item label="语言" prop="language">
          <el-select v-model="form2.language" placeholder="请选择语言">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SYSTEM_SMS_TEMPLATE_LANGUAGE)"
                       :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-dialog>


  </div>
</template>

<script>
import { createSmsNode, updateSmsNode, deleteSmsNode, getSmsNode, getSmsNodePage, exportSmsNodeExcel, testSms } from "@/api/system/sms/smsNode";
import {getCountryListAll} from '@/api/ecw/country'
import {getSmsTemplateList} from '@/api/system/sms/smsTemplate'
import {  getSimpleSmsChannels } from "@/api/system/sms/smsChannel";
import { getRegionTreeList } from "@/api/ecw/memberManagement"
import { deepClone } from "@/utils/index"

export default {
  name: "SmsNode",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 短信节点列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dateRangeCreateTime: [],
      countryList: [],
      smsTemplateList: [],
      smsTemplateList2: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        nodeValue: null,
        transportId: null,
        countryId: null,
        countryCode: null,
        status: null,
        templateIdOne: null,
        templateIdTwo: null,
        templateIdThree: null,
        templateIdFour: null,
        isTransport: null,
        isOrders: null,
        extra2: []
      },
      // 表单参数
      form: {},
      form2: {},
      open2: false,
      // 短信渠道
      channelOptions: [],
      // 表单校验
      rules: {
        nodeValue: [{ required: true, message: "节点不能为空", trigger: "blur" }],
        transportId: [{ required: true, message: "运输方式不能为空", trigger: "blur" }],
        countryIds: [{ required: true, message: "国家不能为空", trigger: "blur" }],
        status: [{ required: true, message: "启用状态不能为空", trigger: "change" }],
        templateIdOne: [{ required: true, message: "模板1不能为空", trigger: "change" }],
        isTransport: [{ required: true, message: "是否匹配运输方式不能为空", trigger: "change" }],
        isOrders: [{ required: true, message: "多订单不能为空", trigger: "change" }],
      },
      countryMap: new Map(),
      smsTemplateMap: new Map(),
      sendSmsOpen: false,
      sendSmsForm: {},
      sendSmsRules: {
        mobile: [{ required: true, message: this.$t("手机不能为空"), trigger: "blur" }],
        countryCode: [{ required: true, message: "区号不能为空", trigger: "blur" }],
        messageType: [{ required: true, message: "发送类型不能为空", trigger: "blur" }],
        nodeTemplateSn: [{ required: true, message: "模板序号不能为空", trigger: "blur" }],
        templateParams: [{ required: true, message: "参数(JSON)不能为空", trigger: "blur" }],
      },
      node: {},
      cascaderState: true,
      regionTreeList: [],
      regionTreeList2: [],
      lastSelectedList: [], //上一次选中数据
      oneDimensionalList: [],
    };
  },
  created() {
    const that = this
    this.getList();
    getCountryListAll().then(res => {
      this.countryList = res.data.map(item => {
        item.tel = item.tel.replace('+', '')
        that.countryMap.set(item.id,item)
        return item
      })
    })
    this.countryMap.set(0,{id:0,nameZh: '全部',tel:0})
    this.countryMap.set(1,{id:1,nameZh: '其他',tel:1})
    getSmsTemplateList().then(res => {
      this.smsTemplateList = res.data
      for(var i=0;i<res.data.length;i++){
        this.smsTemplateMap.set(res.data[i].id,res.data[i])
      }
    })
    // 获得短信渠道
    getSimpleSmsChannels().then(response => {
      this.channelOptions = response.data;
    })
    getRegionTreeList().then((res) => {
      this.regionTreeList = res.data
      this.regionTreeList2 = JSON.parse(JSON.stringify(res.data))
      this.regionTreeList2.unshift({
        id: 0,
        labelZh: "全选",
        labelEn: "select ALL",
        children: [
          {
            id: 0,
            labelZh: "全选",
            labelEn: "select ALL",
            children: [
              {
                id: 0,
                labelZh: "全选",
                labelEn: "select ALL"
              }
            ]
          }
        ]
      })
      this.regionTreeList.unshift({
        id: "000",
        labelZh: "全选",
        labelEn: "select ALL"
      })
    })
  },
  filters: {
    guojia: function(value,countryMap) {
      if(!value) return ''
      var lists = value.split(',')
      var text = ""
      for(var i=0;i<lists.length;i++) {
        if(text.length ==0) {
          text = countryMap.get(lists[i]*1)!=undefined?countryMap.get(lists[i]*1).nameZh:''
        } else {
          text = text + "," + countryMap.get(lists[i]*1)!=undefined?countryMap.get(lists[i]*1).nameZh:''
        }
      }
      return text
    }
  },
  computed: {
    isChinese() {
      return this.$i18n.locale === "zh_CN"
    },
    cascaderProps() {
      const label = this.isChinese ? "labelZh" : "labelEn"
      return { multiple: true, value: "id", label }
    }
  },
  methods: {
    selectHandle(val, defaultStatus = false) {
      this.form.receiveAddrList = []
      let current = [] // 获取当前选中的哪个数据
      if (val.length >= this.lastSelectedList.length) {
        let keys = this.lastSelectedList.map((item) => JSON.stringify(item))
        current = val.filter((item) => !keys.includes(JSON.stringify(item)))
      } else {
        // 取消选中
        let keys = val.map((item) => JSON.stringify(item))
        current = this.lastSelectedList.filter((item) => !keys.includes(JSON.stringify(item)))
      }

      const currentValue = current.length > 0 ? current[0][0] || "" : ""
      if (currentValue == "000") {
        if (this.judgetAllSelected(val)) {
          this.traverseTree(this.regionTreeList) //获取全选时回显的数据
        } else {
          this.form.receiveAddrList = [] //不选
        }
      } else {
        this.form.receiveAddrList = val //半选
      }
      if (!defaultStatus) {
        this.checkIsAddAllSelected()
      }

      // this.$nextTick(() => {
      //
      this.lastSelectedList = this.form.receiveAddrList
      // });
    },
    checkIsAddAllSelected() {
      //这里你要判断好你的dom是否正确
      let label1 = document.querySelectorAll(".el-cascader-panel")[0].querySelector(".el-cascader-menu__wrap").querySelectorAll("li")[0].querySelectorAll("label")[0]
      let span1 = document.querySelectorAll(".el-cascader-panel")[0].querySelector(".el-cascader-menu__wrap").querySelectorAll("li")[0].querySelectorAll("label")[0].querySelectorAll("span")[0]
      // 获取所有的数据
      let list = this.regionTreeList // 原始数据列表
      if (this.oneDimensionalList.length === 0) {
        this.getTreeList(list) // 把所有的父子级平铺成一个一级列表
      }

      let origin = [...this.oneDimensionalList].filter((item) => !item.children) //获取所有的叶子节点
      let nowList = [...this.form.receiveAddrList].filter((item) => item[0] !== "000")

      // 半选时, 如果有之前选过全选,要把全选过滤掉
      if (origin.length > nowList.length && nowList.length != 0) {
        this.form.receiveAddrList = deepClone(this.form.receiveAddrList.filter((item) => item[0] !== "000"))
        //设置半选样式，setTimeout可以解决样式渲染不上的问题
        setTimeout(function () {
          label1.className = "el-checkbox"
          span1.className = "el-checkbox__input is-indeterminate"
        }, 1)
      } else if (nowList.length == 0) {
        //不选时, 如果有之前选过全选,要把全选过滤掉
        this.form.receiveAddrList = deepClone(this.form.receiveAddrList.filter((item) => item[0] !== "000"))
        label1.className = "el-checkbox"
        span1.className = "el-checkbox__input"
      } else {
        // 当所有的数据都选择时, 要自动把全选勾选上  最后这种是：origin.length == nowList.length
        if (this.form.receiveAddrList[0] && this.form.receiveAddrList[0][0] !== "000") {
          this.form.receiveAddrList = [["000"], ...this.form.receiveAddrList]
          label1.className = "el-checkbox"
          span1.className = "el-checkbox__input is-checked"
        }
      }
    },
    getTreeList(list) {
      let _this = this
      for (let i = 0; i < list.length; i++) {
        let a = list[i]
        if (a.id !== "000") {
          this.oneDimensionalList.push(list[i])
        }
        if (a.children && a.children.length > 0) {
          let res = _this.getTreeList(a.children)
          if (res) {
            return res
          }
        }
      }
    },
    judgetAllSelected(node) {
      // 判断是否是全选,也就是看已选择的选中中包不包含"全选"
      let isAllSelected = false
      for (let i = 0; i < node.length; i++) {
        if (node[i][0] == "000") {
          isAllSelected = true
          break
        }
      }
      return isAllSelected
    },
    traverseTree(list, parentNode = []) {
      list.length > 0 &&
        list.forEach((e) => {
          let pNode = deepClone(parentNode)
          if (e.children && e.children.length > 0) {
            pNode.push(e.id) // 1 11
            this.traverseTree(e.children, pNode)
          } else {
            if (parentNode.length > 0) {
              this.form.receiveAddrList.push([...parentNode, e.id])
            } else {
              this.form.receiveAddrList.push([e.id])
            }
          }
        })
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = {...this.queryParams};
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      console.log(this.queryParams)
      params['extra'] = JSON.stringify(this.queryParams.extra2)
      // 执行查询
      getSmsNodePage(params).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.cascaderState = true
      this.form = {
        id: undefined,
        nodeValue: undefined,
        transportId: undefined,
        countryId: undefined,
        countryCode: undefined,
        status: undefined,
        templateIdOne: undefined,
        templateIdTwo: undefined,
        templateIdThree: undefined,
        templateIdFour: undefined,
        isTransport: undefined,
        isOrders: undefined,
        receiveAddrList: [],
        extra: undefined,
        remark: undefined
      };
      this.lastSelectedList = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.smsTemplateList2 = []
      this.reset();
      this.open = true;
      this.title = "添加短信节点";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getSmsNode(id).then(response => {
        this.smsTemplateList2 = this.smsTemplateList.filter(a=>(a.nodeValue == response.data.nodeValue)&&(a.transportId == response.data.transportId))
        if (response.data.receiveAddrList!=null&&response.data.receiveAddrList.length>0&&response.data.receiveAddrList[0].toString() == "0,0,0") {
          response.data.receiveAddrList = [["000"]]
        }
        this.form = response.data;
        this.open = true;
        this.title = "修改短信节点";
        if(this.form.isTransport==1) {
          this.cascaderState = false
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        var countryCodes=[];
        var countryIds = this.form.countryIds
        for(var i = 0; i < countryIds.length; i++) {
          countryCodes.push(this.countryMap.get(countryIds[i]).tel)
        }
        this.form.countryId = [...this.form.countryIds].join(',')
        this.form.countryCode = [...countryCodes].join(',')
        if (this.form.receiveAddrList.length>0 &&this.form.receiveAddrList[0][0] == "000") {
          this.form.receiveAddrList = [[0, 0, 0]]
        }
        // 修改的提交
        if (this.form.id != null) {
          updateSmsNode(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createSmsNode(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除短信节点编号为"' + id + '"的数据项?').then(function() {
          return deleteSmsNode(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行导出
      this.$modal.confirm('是否确认导出所有短信节点数据项?').then(() => {
          this.exportLoading = true;
          return exportSmsNodeExcel(params);
        }).then(response => {
          this.$download.excel(response, '${table.classComment}.xls');
          this.exportLoading = false;
        }).catch(() => {});
    },
    // 切换节点
    handleChangeNode(val) {
      this.smsTemplateList2 = this.smsTemplateList.filter(a=>(a.nodeValue == this.form.nodeValue)&&(a.transportId == this.form.transportId))
    },
    handleChangeIsTransport(val) {
      this.form.receiveAddrList = []
      if(val==1) {
        this.cascaderState = false
      } else {
        this.cascaderState = true
      }
    },
    handleChangeTransportId(val) {
      this.smsTemplateList2 = this.smsTemplateList.filter(a=>(a.nodeValue == this.form.nodeValue)&&(a.transportId == this.form.transportId))
    },
    test(row) {
      this.sendSmsForm = {
        mobile:'',
        countryCode: '',
        templateParams: '',
        messageType: null,
        nodeTemplateSn: 1,
        receiveAddrList: []
      }
      this.node = row
      this.sendSmsOpen = true
    },
    /** 取消发送短信 */
    cancelSendSms() {
      this.sendSmsOpen = false;
    },
    /** 提交按钮 */
    submitSendSmsForm() {
      this.$refs["sendSmsForm"].validate(valid => {
        if (!valid) {
          return;
        }
        var node = JSON.parse(JSON.stringify(this.node))
        node['countryCode'] = this.sendSmsForm.countryCode
        node['mobile'] = this.sendSmsForm.countryCode +''+this.sendSmsForm.mobile
        node['templateParams'] = JSON.parse(this.sendSmsForm.templateParams)
        node['messageType'] = this.sendSmsForm.messageType
        node['nodeTemplateSn'] = this.sendSmsForm.nodeTemplateSn
        if (this.sendSmsForm.receiveAddrList.length>0) {
          if(this.sendSmsForm.receiveAddrList[0][0] == "000") {
            node['receiveAddrList'] = [[0, 0, 0]]
          } else {
            node['receiveAddrList'] = this.sendSmsForm.receiveAddrList
          }
        } else {
          node['receiveAddrList'] = [[1, 1, 1]]
        }

        // 添加的提交
        testSms(node).then(response => {
          this.$modal.msgSuccess("提交发送成功！");
          this.sendSmsOpen = false;
        });
      });
    },
    look(rows) {
      this.form2 = rows
      this.open2 = true
    }
  }
};
</script>
