<template>
  <div class="daily-set-wrap">
    <div class="daily-set-content border-box">
      <div class="salutatory-set-wrap m-t-20">
        <el-form label-width="117px" ref="form" :model="form" :rules="rules" refs="form" class="form">
          <el-form-item label="欢迎语标题" prop="title">
            <el-input show-word-limit placeholder="请输入欢迎语标题" type="text" v-model="form.title" maxlength="20" class="w-384"></el-input>
          </el-form-item>
          <el-form-item label="欢迎语内容" prop="welcomeContent" class="welcomeContentItem">
            <el-input placeholder="请输入文本内容" type="textarea" v-model="form.welcomeContent" class="w-384 welcomeContent"></el-input>
            <div class="text-bottom flex w-384">
              <div class="flex flex-wrap flex-align-center">
                <div class="put" @click="putName">插入&lt; 微信昵称 &gt;</div>
                <div class="line"></div>
                <div class="put" @click="addLinkDialogShow">插入#公众号</div>
              </div>
              <el-popover placement="top" width="388" trigger="click">
                <ul class="flex flex-wrap">
                  <li v-for="(item, index) in emojiList" :key="index + 'emoji'">
                    <img :src="item.gifUrl" alt="" @click="selectEmoji(item)" />
                  </li>
                </ul>
                <p slot="reference" style="cursor:pointer;height:24px;">
                  <svg-icon iconname="iconbiaoqing" size="20"> </svg-icon>
                </p>
              </el-popover>
            </div>
            <div class="mediaEcho">
              <div class="flexBoxContainer" v-for="(item, index) in form.welcomeMediaList" :key="index">
                <div class="flexBox">
                  <svg-icon :iconname="iconType[item.mediaType]" size="16" style="margin-right: 13px;"> </svg-icon>
                  <span class="popverText">
                    {{ item.mediaTitle }}
                    <span v-if="item.mediaType == 5">({{ item.miniProgramPage }})</span>
                  </span>
                  <i class="el-icon-close" style="margin-left: 20px;cursor: pointer;" @click="handleDelMedia(item, index)"></i>
                </div>
              </div>
            </div>
            <div class="addInfo" :style="form.welcomeMediaList.length > 0 ? 'border-top: 1px dashed #dcdfe6;' : ''">
              <el-popover placement="top" trigger="click">
                <ul class="flex flex-wrap">
                  <li v-for="(item, index) in uploadList" :key="index" :class="['uploadListBox', form.welcomeMediaList.length >= 9 || (index == 5 && publicAccountDisabled) ? 'disabled' : '']" :style="index == 5 ? 'width: 118px;' : ''" @click="handleUploadList(item, index)">
                    <i :class="['iconfont-hb3', item.icon]" style="font-size:20px"></i>
                    <p>{{ item.title }}</p>
                    <input type="file" :accept="item.fileType" @change="e => handkeFileChange(e, item)" class="upload-input" />
                  </li>
                </ul>
                <div slot="reference" style="cursor: pointer; display: inline-block;">
                  <i class="iconfont-hb3 icontianjiajiahaowubiankuang"></i>
                  <p>添加图片/视频/文件/链接/小程序/带参公众号二维码</p>
                </div>
              </el-popover>
              <p style="font-size:12px;color:#909399">(附件不超过9个，单个大小不超过2M)</p>
            </div>
          </el-form-item>
          <el-form-item label="使用范围" required>
            <el-radio v-model="form.defaultWelcomeFlag" :disabled="defaultWelcomeFlag && echoDefaultWelcomeFlag == 0" :label="1">全体成员</el-radio>
            <el-radio v-model="form.defaultWelcomeFlag" :label="0">部分成员</el-radio>
            <span @click="openScopeDialog" v-if="form.defaultWelcomeFlag == 0" class="color-2f54eb cursor-pointer" style="margin-left:8px;"> {{ form.suitDepartmentAddList.length ? '修改使用范围' : '请选择使用范围' }}</span>
            <div class="scopeContainer" v-if="form.defaultWelcomeFlag == 1">
              <div class="wwTag">
                <span class="font-14 color-2f54eb opacity80 iconfont-hb3  iconqiye-tianchong"></span>
                全体成员
              </div>
            </div>
            <div v-else>
              <div v-show="form.suitDepartmentAddList.length" class="scopeContainer">
                <div class="wwTag" v-for="item in form.suitDepartmentAddList" :key="item.departmentId">
                  <span class="font-14 color-2f54eb opacity80 iconfont-hb3  iconqiye-tianchong"></span>
                  {{ item.departmentName }}
                  <!-- <i class="el-icon-close" style="margin-left: 20px;cursor: pointer;"></i> -->
                </div>
              </div>
            </div>
          </el-form-item>
          <el-button type="primary" style="margin-left:117px;margin-bottom:20px" :loading="submitbtnLoading" @click="submit">保存</el-button>
          <el-button style="margin-bottom:20px" @click="$router.go(-1)">返回</el-button>
        </el-form>
        <div class="iphone">
          <div class="infoList">
            <div class="infoListBox" v-if="form.welcomeContent || form.title">
              <div class="infoAvatar">
                <img src="@/assets/head_default.jpg" />
              </div>
              <div class="textInfo">
                <div class="content" v-html="form.welcomeContent"></div>
              </div>
            </div>
            <div class="infoListBox" v-for="(item, index) in form.welcomeMediaList" :key="index">
              <div>
                <div class="infoAvatar">
                  <img src="@/assets/head_default.jpg" />
                </div>
                <div v-if="item.mediaType == 1 || item.mediaType == 7" class="imgInfo">
                  <img :src="item.mediaUrl" />
                </div>
                <div v-if="item.mediaType == 2" class="videoInfo" @click="blank(item.mediaUrl)">
                  <video :src="item.mediaUrl" />
                </div>
                <div v-if="item.mediaType == 3" class="docInfo">
                  <div class="docTitle">
                    <b>{{ item.mediaTitle }}</b>
                    <p>{{ item.mediaSize }} KB</p>
                  </div>
                  <svg-icon iconname="iconwenjianleixing-wenjian" size="40"> </svg-icon>
                </div>
                <div v-if="item.mediaType == 4" class="urlInfo">
                  <div class="urlTitle">{{ item.mediaTitle }}</div>
                  <div class="urlContent">
                    <b>{{ item.mediaTitle }}</b>
                    <svg-icon iconname="iconwenjianleixing-lianjie" size="40"> </svg-icon>
                  </div>
                </div>
                <div v-if="item.mediaType == 5 || item.mediaType == 6" class="appletsInfo">
                  <div class="appletsTitle">{{ item.miniProgramName }}</div>
                  <div class="appletsTitle" style="font-size:12px">{{ item.mediaTitle }}</div>
                  <img :src="item.mediaUrl" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <el-dialog title="添加公众号" width="585px" class="replay-link-dialog" :visible.sync="addReplayDialog" @closed="onClosed">
        <el-form label-position="right" ref="form" :model="{}" label-width="100px" @submit.native.prevent>
          <el-form-item label="公众号名称">
            <el-input v-model="accountName" @keyup.enter.native="addAcountName"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="">
          <el-button @click="addReplayDialog = false">取消</el-button>
          <el-button type="primary" @click="addAcountName">确定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="添加链接" width="585px" class="replay-link-dialog" :visible.sync="urlDialogVisible" @closed="onClosed">
        <el-form label-position="right" ref="form" :model="{}" label-width="100px" @submit.native.prevent>
          <el-form-item label="链接地址">
            <el-input v-model="url" @keyup.enter.native="addUrl"></el-input>
            <span style="font-size:12px;color:#909399;">以http或https开头</span>
          </el-form-item>
        </el-form>
        <div slot="footer" class="">
          <el-button @click="urlDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addUrl">确认添加</el-button>
        </div>
      </el-dialog>
      <el-dialog title="请选择使用范围" width="886px" class="replay-link-dialog" :visible.sync="scopeVisible">
        <div class="scopeBox">
          <div class="left">
            <el-input placeholder="请输入部门名称" maxlength="50" v-model="filterText" style="width: 398px;" clearable @clear="handlefilterTextClear" @keyup.native="value => toInput(value, searchInput)"> <i slot="prefix" class="el-input__icon el-icon-search"></i> </el-input>
            <el-tree :key="showTree" v-loading="loading" ref="tree" :data="treeData" :check-on-click-node="true" show-checkbox node-key="departmentId" :props="defaultProps" :expand-on-click-node="false" class="tree" :render-after-expand="true" @check-change="handleCheckChange" @check="handleCheck">
              <span class="custom-tree-node" slot-scope="{ node }">
                <span class="font-14  color-2f54eb opacity80 iconfont-hb3  iconqiye-tianchong"></span>
                <span>{{ node.label }}</span>
              </span>
            </el-tree>
          </div>
          <div class="right">
            <div class="right-top">
              <span>已选：{{ selectedTreeData.length }}个部门</span><el-button type="text" v-show="selectedTreeData.length" @click="clearAllSelectedData" :loading="btnLoading">清空</el-button>
            </div>
            <ul v-if="selectedTreeData.length" class="right-content">
              <li class="contact-li" v-for="(item, index) in selectedTreeData" :key="index + 'gic'">
                <div class="li-cell cursor-pointer">
                  <div>
                    <span class="font-14 color-2f54eb opacity80 iconfont-hb3  iconqiye-tianchong"></span>
                    <span class="font-14 color-303133 span-departName"> {{ item.departmentName }}</span>
                  </div>
                  <i class="iconfont-hb3 iconclose" @click="handleSelectedDataCancel(item, index)"></i>
                </div>
              </li>
            </ul>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="treeDialogCancel">取消</el-button>
          <el-button type="primary" @click="addSuitDepartment">确认</el-button>
        </div>
      </el-dialog>
      <el-dialog title="添加小程序" width="640px" :visible.sync="appletDialogVisible" @closed="closeAppletDialog">
        <div class="admin-tip-body">
          <div role="alert" class="el-alert el-alert--info" style="width: 550px;">
            <i class="el-alert__icon el-icon-info"></i>
            <div class="el-alert__content">
              <p class="el-alert__title">
                1、要在欢迎语中发送小程序，需先在【好办后台-企业设置-企业信息-小程序添加】中添加此小程序；<br />
                2、请确保此处欢迎语中所添加的小程序在企业微信后台也已经创建，否则欢迎语在发送的时候会被企微拦截，导致发送失败； <br />
                3、在不同开平的情况下，可选择“带参会员小程序”，以便于“客户”身份与“好友”身份的对应；<br />
              </p>
            </div>
          </div>
        </div>
        <el-form label-position="right" ref="appletForm" :model="appletForm" label-width="120px" style="margin-top:20px" @submit.native.prevent>
          <el-form-item label="小程序配置" required>
            <el-select v-model="appletForm.selectedApple" style="width:458px;">
              <el-option v-for="item in appTableData" :key="item.miniprogramSettingId" :label="item.miniprogramName" :value="item.miniprogramSettingId" :disabled="handleDiabled(item)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="小程序路径" required v-show="appletForm.selectedApple != -1">
            <el-input v-model="appletForm.appletPath" style="width: 458px;" placeholder="请输入小程序跳转路径，例如：/page " />
          </el-form-item>
        </el-form>
        <div slot="footer" class="">
          <el-button @click="closeAppletDialog">取消</el-button>
          <el-button type="primary" @click="addApplet">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getRequest, postForm, postJsonRequest } from '@/api/api';
import { _debounce } from '@/common/js/public';
import limitTextarea from '@/components/limit-textarea.vue';
import { emojiArr } from '@/utils/emoji';
import multUpload from '@/components/mult-upload-img.vue';
import singleUpload from '@/components/single-upload.vue';
export default {
  props: {},
  data() {
    return {
      filterText: '',
      defaultProps: {
        label: 'departmentName'
      },
      appletForm: {
        appletPath: '',
        selectedApple: ''
      },
      form: {
        title: '',
        welcomeContent: '你好，<微信昵称>',
        welcomeMediaList: [],
        suitDepartmentAddList: [],
        suitDepartmentList: [],
        defaultWelcomeFlag: 0
      },
      uploadList: [
        {
          title: '图片',
          icon: 'icontupian',
          fileType: '*'
        },
        {
          title: '视频',
          icon: 'iconshipin',
          fileType: '.mp4'
        },
        {
          title: '文件',
          icon: 'iconwenjian',
          fileType: '*'
        },
        {
          title: '链接',
          icon: 'iconlianjie'
        },
        {
          title: '小程序',
          icon: 'iconxiaochengxu'
        },
        {
          title: '带参公众号二维码',
          icon: 'icongongzhonghao'
        }
      ],
      iconType: {
        1: 'iconwenjianleixingtupian',
        2: 'iconwenjianleixingshipin',
        3: 'iconwenjianleixing-wenjian',
        4: 'iconwenjianleixing-lianjie',
        5: 'iconwenjianleixing-xiaochengxu', // 小程序
        6: 'iconwenjianleixing-xiaochengxu', // 带参小程序
        7: 'icongongzhonghao1' // 带参公众号
      },
      accountName: '',
      rules: {
        title: [{ required: true, message: '请输入欢迎语标题', trigger: 'blur' }],
        welcomeContent: [{ required: true, message: '请输入欢迎语内容', trigger: 'blur' }]
      },
      wxEnterpriseId: '',
      enterpriseId: '',
      emojiList: emojiArr,
      addReplayDialog: false,
      url: '',
      urlDialogVisible: false,
      scopeVisible: false,
      treeData: [],
      treeDataCopy: [],
      loading: false,
      dialogLoading: false,
      btnLoading: false,
      submitbtnLoading: false,
      selectedTreeData: [],
      showTree: true,
      appTableData: [],
      appletDialogVisible: false,
      defaultWelcomeFlag: false,
      isNew: true,
      echoDefaultWelcomeFlag: 0
    };
  },
  watch: {
    selectedTreeData(val) {
      if (!val.length && this.btnLoading) {
        this.btnLoading = false;
      }
    }
  },
  computed: {
    publicAccountDisabled() {
      if (this.form.welcomeMediaList.filter(item => item.mediaType == 7).length) {
        return true;
      } else {
        return false;
      }
    }
  },
  mounted() {
    const userInfos = JSON.parse(sessionStorage.getItem('userInfos'));
    this.wxEnterpriseId = userInfos.wxEnterpriseId;
    this.enterpriseId = userInfos.enterpriseId;
    const { id } = this.$route.query;
    if (id) {
      this.getData();
      this.isNew = false;
    }
    this.getExistDefaultWelcome();
    this.getAppleList();
  },
  components: {
    limitTextarea,
    singleUpload,
    multUpload
  },
  methods: {
    getExistDefaultWelcome(isNew) {
      getRequest('/haoban-manage3-web/welcome/exist-default-welcome', { wxEnterpriseId: this.wxEnterpriseId }).then(res => {
        let resData = res.data;
        if (resData.code == 0) {
          this.defaultWelcomeFlag = res.data.result;
          if (this.isNew) {
            this.form.defaultWelcomeFlag = res.data.result ? 0 : 1;
          }
        }
      });
    },
    handleDiabled(val) {
      console.log('handleDiabled');
      if (this.form.welcomeMediaList.filter(item => item.miniprogramSettingId && item.miniprogramSettingId == val.miniprogramSettingId).length) {
        return true;
      } else {
        return false;
      }
    },
    addApplet(val) {
      if (!this.appletForm.selectedApple) {
        this.$message.error('请选择小程序');
        return;
      }
      if (this.appletForm.selectedApple != -1 && !this.appletForm.appletPath) {
        this.$message.error('请输入小程序跳转路径');
        return;
      }
      const obj = this.appTableData.filter(item => item.miniprogramSettingId == this.appletForm.selectedApple)[0];
      if (!this.form.welcomeMediaList.filter(item => item.miniprogramSettingId && item.miniprogramSettingId == obj.miniprogramSettingId).length) {
        this.form.welcomeMediaList.push({
          miniProgramName: obj.miniprogramName,
          mediaType: obj.miniprogramSettingId == -1 ? 6 : 5,
          mediaUrl: obj.imageUrl,
          miniProgramPage: obj.miniprogramSettingId != -1 ? this.appletForm.appletPath : '',
          mediaTitle: obj.title,
          miniprogramSettingId: obj.miniprogramSettingId
        });
      }
      this.closeAppletDialog();
    },
    closeAppletDialog() {
      this.appletForm.selectedApple = '';
      this.appletForm.appletPath = '';
      this.appletDialogVisible = false;
    },
    getAppleList() {
      // 获取小程序
      getRequest('/haoban-manage3-web/list-miniprogram-setting', {})
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1 && resData.result) {
            this.appTableData = resData.result;
            this.appTableData.push({
              miniprogramName: '带参会员小程序',
              miniprogramSettingId: '-1',
              imageUrl: 'https://other-1251519181.cos.ap-shanghai.myqcloud.com/haoban/20220316151939/1b31e9f76ff1ac4340e5e66497df7cea.png',
              title: '带参会员小程序'
            });
          }
        })
        .catch(function(error) {
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    treeDialogCancel() {
      this.scopeVisible = false;
      this.filterText = '';
    },
    addSuitDepartment() {
      this.form.suitDepartmentAddList = Object.assign([], this.selectedTreeData);
      this.scopeVisible = false;
    },
    clearAllSelectedData() {
      this.btnLoading = true;
      // 清空 右侧 被选中部门树的数据 和 清空 部门树的 选中节点
      setTimeout(() => {
        this.showTree = !this.showTree;
        this.treeData = this.handleTreeData(JSON.parse(JSON.stringify(this.treeDataCopy)));
        this.$nextTick(() => {
          this.$refs.tree.store._getAllNodes()[0].expanded = true;
        });
        this.selectedTreeData = [];
      }, 500);
    },
    handleSelectedDataCancel(item, index) {
      // 删除 右侧 被选中部门树的数据
      this.$refs.tree.setChecked(item.departmentId, false, true);
      this.selectedTreeData = this.$refs.tree.getCheckedNodes();
    },
    handlefilterTextClear() {
      // 清空搜索部门树条件
      this.treeData = this.handleTreeData(JSON.parse(JSON.stringify(this.treeDataCopy)));
      this.$nextTick(() => {
        this.$refs.tree.store._getAllNodes()[0].expanded = true;
        if (this.selectedTreeData.length) {
          this.$refs.tree.setCheckedKeys(this.selectedTreeData.map(item => item.departmentId));
        } else {
          this.$refs.tree.setCheckedKeys([]);
        }
      });
    },
    toInput: _debounce(function(e, value) {
      // 前端搜索部门树
      const that = this;
      if (!that.filterText) {
        that.handlefilterTextClear();
      } else {
        that.getSearchData();
      }
    }, 500),
    getSearchData() {
      // 前端搜索部门树
      this.treeData = this.treeDataCopy.filter(ele => ele.departmentName.indexOf(this.filterText) != -1);
      if (this.selectedTreeData.length) {
        const arr = this.selectedTreeData.map(item => item.departmentId);
        this.$refs.tree.setCheckedKeys(arr);
      } else {
        this.$refs.tree.setCheckedKeys([]);
      }
    },
    handleCheck(data, arr) {
      // 部门树选中时
      const { checkedNodes } = arr;
      if (this.filterText) {
        // 搜索时的树
        const arr = this.selectedTreeData.map(item => item.departmentId);
        checkedNodes.forEach(item => {
          if (!arr.includes(item.departmentId)) {
            this.selectedTreeData.push(item);
          }
        });
      } else {
        this.selectedTreeData = JSON.parse(JSON.stringify(checkedNodes));
      }
    },
    handleCheckChange(data, checked) {
      // 部门树选中变化时
      const obj = JSON.parse(JSON.stringify(data));
      if (!checked) {
        this.$nextTick(() => {
          this.selectedTreeData = this.selectedTreeData.filter(item => item.departmentId !== obj.departmentId);
        });
      }
    },
    /**
     * 获取部门树数据
     */
    getTableList(val) {
      let para = {
        isStore: 0, // 当前页
        parentId: '' // 一页显示个数
      };
      this.loading = true;
      getRequest('/haoban-manage3-web/department-list-cache', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (!!resData.result && resData.result.length) {
              this.treeData = this.handleTreeData(JSON.parse(JSON.stringify(resData.result)));
              this.$nextTick(() => {
                this.$refs.tree.store._getAllNodes()[0].expanded = true;
              });
              this.treeDataCopy = resData.result;
            }
          }
        })
        .catch(function(error) {
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleTreeData(data) {
      let tree = data.filter(father => {
        //循环所有项
        let branchArr = data.filter(child => {
          return father.departmentId == child.parentDepartmentId; //返回每一项的子级数组
        });
        if (branchArr.length > 0) {
          father.hasSonNode = true;
          father.children = branchArr; //如果存在子级，则给父级添加一个children属性，并赋值
        } else {
          father.hasSonNode = false;
        }
        return father.parentDepartmentId == 0; //返回第一层
      });
      return tree;
    },
    openScopeDialog() {
      // 选择范围打开部门树弹窗
      this.getTableList();
      this.scopeVisible = true;
      this.$nextTick(() => {
        this.selectedTreeData = this.form.suitDepartmentAddList;
        this.$refs.tree.setCheckedKeys(this.form.suitDepartmentAddList.map(item => item.departmentId));
      });
    },
    blank(url) {
      window.open(url);
    },
    handleUploadList(item, index) {
      if (['图片', '视频', '文件'].includes(item.title)) {
        document.getElementsByClassName('upload-input')[index].click();
      } else if (item.title == '链接') {
        this.urlDialogVisible = true;
      } else if (item.title == '小程序') {
        this.appletDialogVisible = true;
      } else if (item.title == '带参公众号二维码') {
        this.form.welcomeMediaList.push({
          mediaTitle: '带参公众号',
          mediaType: 7,
          mediaUrl: 'https://other-1251519181.cos.ap-shanghai.myqcloud.com/haoban/20220310143912/abdf84f1112815e936f3ed4f09dba525.png'
        });
      }
    },
    handleDelMedia(row, index) {
      this.form.welcomeMediaList.splice(index, 1);
    },
    handkeFileChange(e, item) {
      const file = e.target.files[0]; // only use files[0]
      let fileType = '';
      if (file.size > 2000000) {
        this.$message.error('单个大小不超过2M');
        return false;
      }
      if (item.title == '图片') {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png';
        if (!isJPG) {
          this.$message.error('请上传图片');
          return false;
        }
        fileType = 'jpg';
      } else if (item.title == '视频') {
        const isVideo = file.type == 'video/mp4';
        if (!isVideo) {
          this.$message.error('请上传mp4类型的视频文件');
          return false;
        }
        fileType = 'mp4';
      } else if (item.title == '文件') {
        fileType = '.doc';
      }
      this.handleRequest(file, fileType);
    },
    handleRequest(file, fileType) {
      let files = new FormData();
      files.append('file', file);
      postForm(`/haoban-manage3-web/upload-file?fileType=${fileType}`, files).then(res => {
        const { data } = res;
        let mediaType = 1;
        if (fileType == 'jpg') {
          mediaType = 1;
        } else if (fileType == 'mp4') {
          mediaType = 2;
        } else if (fileType == '.doc') {
          mediaType = 3;
        }
        if (data.errorCode == 1 && data.result) {
          const obj = {
            mediaTitle: file.name,
            mediaType,
            mediaUrl: data.result.url
          };
          if (mediaType == 3) {
            obj.mediaSize = (data.result.size / 1024).toFixed(2);
          }
          this.form.welcomeMediaList.push(obj);
        }
      });
    },
    onClosed() {
      this.accountName = '';
      this.url = '';
    },
    addAcountName() {
      // 文本链接
      if (this.accountName == '') {
        this.$message({
          message: '请输入公众号名称',
          type: 'error'
        });
        return;
      } else {
        if (this.accountName.indexOf('#公众号：') != -1) {
          console.log('');
        } else {
          this.accountName = '#公众号：' + this.accountName;
        }
        this.addReplayDialog = false;
        this.form.welcomeContent = this.form.welcomeContent + this.accountName;
      }
    },
    addUrl() {
      this.form.welcomeMediaList.push({
        mediaTitle: this.url,
        mediaType: 4,
        mediaUrl: this.url,
        mediaSize: ''
      });
      this.urlDialogVisible = false;
    },
    addLinkDialogShow() {
      this.addReplayDialog = true;
    },
    changeRoute() {
      this.$router.push('/contactsList');
    },
    selectEmoji(item) {
      const that = this;
      const str = that.form.welcomeContent + item.key;
      if (str.length > 1000) {
        this.$message('添加该表情后文本内容将超过字数限制，无法添加！');
      } else {
        that.form.welcomeContent = str;
      }
    },
    putName() {
      const that = this;
      that.form.welcomeContent = that.form.welcomeContent + '<微信昵称>';
    },
    getData() {
      let para = {
        welcomeId: this.$route.query.id,
        enterpriseId: this.enterpriseId || ''
      };
      getRequest('/haoban-manage3-web/welcome/get', para)
        .then(res => {
          let resData = res.data;
          if (resData.code == 0 && resData.result) {
            const { suitDepartmentList, title, welcomeId, welcomeContent, welcomeMediaList, wxEnterpriseId, defaultWelcomeFlag } = resData.result;
            this.form = { suitDepartmentList: suitDepartmentList || [], suitDepartmentAddList: JSON.parse(JSON.stringify(suitDepartmentList)) || [], title, welcomeId, welcomeContent, welcomeMediaList, wxEnterpriseId, defaultWelcomeFlag };
            this.form = Object.assign({}, this.form);
            this.echoDefaultWelcomeFlag = defaultWelcomeFlag;
          }
        })
        .catch(error => {
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    submit() {
      if (!this.form.defaultWelcomeFlag && !this.form.suitDepartmentAddList.length) {
        this.$message.error('请选择使用范围');
        return;
      }
      this.$refs.form.validate(value => {
        if (value) {
          const { suitDepartmentAddList, suitDepartmentList, title, welcomeId, welcomeContent, welcomeMediaList, wxEnterpriseId, defaultWelcomeFlag } = this.form;
          const para = { title, welcomeId, welcomeContent, welcomeMediaList, wxEnterpriseId: wxEnterpriseId || this.wxEnterpriseId, defaultWelcomeFlag };
          const addArr = [];
          const delArr = [];
          suitDepartmentAddList.forEach(ele => {
            if (!suitDepartmentList.filter(item => item.departmentId == ele.departmentId).length) {
              addArr.push(ele);
            }
          });
          suitDepartmentList.forEach(ele => {
            if (!suitDepartmentAddList.filter(item => item.departmentId == ele.departmentId).length) {
              delArr.push(ele);
            }
          });
          para.suitDepartmentAddList = addArr;
          para.suitDepartmentDeleteList = delArr;
          para.suitDepartmentAddList.forEach(item => {
            item.selectType = 1;
          });
          para.suitDepartmentDeleteList.forEach(item => {
            item.selectType = 1;
          });
          console.log(para);
          this.submitbtnLoading = true;
          postJsonRequest('/haoban-manage3-web/welcome/save', para)
            .then(res => {
              let resData = res.data;
              if (resData.code == 0) {
                this.$message({
                  type: 'success',
                  message: '保存成功!'
                });
                this.$router.push('/salutatory');
              }
            })
            .catch(function(error) {
              this.$message.error({
                duration: 1000,
                message: error.message
              });
            })
            .finally(() => {
              this.submitbtnLoading = false;
            });
        }
      });
    }
  }
};
</script>
<style type="text/scss" lang="scss" scoped>
.upload-input {
  display: none;
}
.w-384 {
  width: 555px;
  box-sizing: border-box;
}
.mediaEcho {
  background: #f7f8fa;
  padding-left: 20px;
  padding-top: 14px;
  padding-bottom: 14px;
  .flexBox {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 14px;
    .popverText {
      font-size: 12px;
      line-height: 16px;
      max-width: 80%;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
  .flexBoxContainer:last-child {
    .flexBox {
      margin-bottom: 0;
    }
  }
}
.addInfo {
  padding: 10px 20px;
  width: 555px;
  background: #f7f8fa;
  border-radius: 2px;
  line-height: 20px;
  box-sizing: border-box;
  p {
    display: inline-block;
    margin-left: 5px;
  }
  &:hover {
    color: #2f54eb;
  }
}
.uploadListBox {
  width: 72px;
  height: 60px;
  border-radius: 2px;
  border: 1px solid #dcdfe6;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  box-sizing: border-box;
  &:hover {
    box-shadow: 0px 2px 4px 0px rgba(47, 84, 235, 0.16);
    border: 1px solid #2f54eb;
  }
}
.disabled {
  pointer-events: none;
  opacity: 0.5;
}
.uploadListBox + .uploadListBox {
  margin-left: 20px;
}
.scopeContainer {
  max-height: 500px;
  min-height: 40px;
  overflow-y: auto;
  margin-top: 10px;
  .wwTag {
    background: #ebeffe;
    border-radius: 4px;
    display: inline-block;
    height: 24px;
    line-height: 24px;
    padding: 0 8px;
    box-sizing: border-box;
    margin-left: 8px;
    margin-bottom: 8px;
  }
}
.welcomeContent {
  height: 220px;
  border: 1px solid #dcdfe6;
  border-radius: 2px;
  >>> .el-textarea__inner {
    height: 181px;
    border: none;
    &:focus {
      box-shadow: none;
    }
  }
  >>> .el-input__count {
    bottom: 44px;
  }
}
.daily-set-wrap {
  height: 100%;
  .daily-set-content {
    padding: 20px;
    .table-condition-left {
      font-size: 0;
    }
  }
}
.salutatory-set-wrap {
  >>> .el-input__inner:focus {
    box-shadow: none;
  }
  .welcomeContentItem >>> .el-form-item__content {
    position: relative;
    width: 555px;
    box-sizing: border-box;
    .text-bottom {
      position: absolute;
      top: 180px;
      left: 1px;
      justify-content: space-between;
      align-items: center;
      height: 38px;
      width: 555px;
      box-sizing: border-box;
      padding: 0 9px;
      .put {
        font-size: 12px;
        font-weight: 400;
        line-height: 17px;
        color: #606266;
        cursor: pointer;
      }
      .line {
        width: 1px;
        height: 9px;
        background: #c0c4cc;
        margin: 0 10px;
      }
    }
  }
  .form {
    width: 672px;
    float: left;
  }
  .iphone {
    border-radius: 4px;
    position: relative;
    margin-left: 117px;
    display: inline-block;
    font-size: 0;
    line-height: 0;
    background-image: url('../../assets/iphone2.png');
    background-repeat: no-repeat;
    width: 240px;
    min-height: 495px;
    background-size: 240px auto;
    color: #303133;
    .infoList {
      padding: 0 10px;
      margin-top: 80px;
      border-radius: 6px;
      max-height: 360px;
      overflow: auto;
      .infoListBox {
        .infoAvatar {
          display: inline-block;
          vertical-align: top;
          margin-right: 10px;
          img {
            vertical-align: top;
            width: 26px;
            height: 26px;
          }
        }
        .imgInfo,
        .videoInfo {
          display: inline-block;
          overflow: hidden;
          border-radius: 4px;
          position: relative;
          cursor: default;
          img {
            min-height: 27px;
            max-width: 140px;
          }
        }
        .videoInfo {
          video {
            min-height: 27px;
            max-width: 140px;
            max-height: 250px;
            cursor: pointer;
          }
        }
        .textInfo,
        .docInfo,
        .urlInfo,
        .appletsInfo {
          min-height: 28px;
          background-color: #fff;
          border: 1px solid #e4e6e9;
          max-width: 166px;
          display: inline-block;
          text-align: left;
          padding: 5px 6px;
          border-radius: 4px;
          min-width: 24px;
          box-sizing: border-box;
          position: relative;
          &::before {
            top: 10px;
            display: block;
            content: ' ';
            width: 0;
            line-height: 0;
            font-size: 0;
            border-style: solid;
            border-color: transparent;
            position: absolute;
            left: -6px;
            border-width: 4px 6px;
            border-left: 0;
            border-right-color: #fff;
          }
          .content {
            font-size: 12px;
            word-break: break-all;
            letter-spacing: 0;
            line-height: 18px;
            height: auto;
          }
        }
        .docInfo {
          display: inline-flex;
          align-items: center;
        }
        .docTitle {
          padding-right: 10px;
          max-width: 100px;
          float: left;
          overflow-wrap: break-word;
          b {
            font-size: 12px;
            text-align: left;
            line-height: 16px;
          }
          p {
            margin-top: 5px;
            font-size: 12px;
            color: #787878;
            text-align: left;
            line-height: 14px;
          }
        }
        .urlTitle,
        .appletsTitle {
          font-size: 14px;
          line-height: 20px;
          overflow: hidden;
          text-overflow: ellipsis;
          margin-bottom: 3px;
        }
        .urlInfo {
          .urlContent {
            overflow-wrap: break-word;
            b {
              color: #606266;
              padding-right: 10px;
              font-size: 12px;
              text-align: left;
              line-height: 17px;
              display: -webkit-box;
              -webkit-line-clamp: 3;
              -webkit-box-orient: vertical;
              overflow: hidden;
              max-width: 100px;
              float: left;
            }
          }
        }
        .appletsInfo {
          .appletsTitle {
            color: #606266;
          }
          img {
            width: 144px;
            height: 144px;
          }
        }
      }
      .infoListBox + .infoListBox {
        margin-top: 15px;
      }
    }
  }
}
.el-alert--info {
  align-items: flex-start;
  width: 700px;
  padding-top: 5px;
  font-size: 14px;
  color: #606266;

  background: #f7f8fa;
  border-radius: 2px;
}
.el-icon-info {
  width: 12px;
  font-size: 12px;
  color: #2f54eb;
  margin-top: 5px;
}
.el-alert__content {
  padding-left: 9px;
  .el-alert__title {
    font-size: 13px;
    font-weight: 400;
    color: #303133;
    line-height: 22px;
  }
}
.opacity80 {
  opacity: 0.8;
}
.scopeBox {
  width: 846px;
  height: 522px;
  background: #ffffff;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  display: flex;
  .left {
    padding: 15px;
    width: 50%;
    .tree {
      margin-top: 20px;
      height: 454px;
      overflow-y: auto;
      >>> .el-tree-node__content {
        height: 32px;
      }
    }
  }
  .right {
    width: 50%;
    border-left: 1px solid #dcdfe6;
    height: 522px;
    overflow-y: auto;
    .right-top {
      padding: 10px 15px;
      display: flex;
      justify-content: space-between;
      color: #303133;
      position: fixed;
      box-sizing: border-box;
      line-height: 20px;
      z-index: 1000;
      width: 400px;
      background: #fff;
    }
    .right-content {
      padding: 40px 15px;
      overflow-x: auto;
    }
    .contact-li {
      .li-cell {
        border-radius: 2px;
        line-height: 32px;
        display: inline-flex;
        width: 392px;
        justify-content: space-between;
        padding: 0 4px;
        align-items: center;
        box-sizing: border-box;
        &:hover {
          background: #f7f8fa;
        }
        i {
          width: 20px;
          height: 20px;
          border-radius: 10px;
          font-size: 12px;
          display: inline-flex;
          justify-content: center;
          align-items: center;
          &:hover {
            background: #e5e6eb;
          }
        }
      }
    }
    .contact-li + .contact-li {
      margin-top: 4px;
    }
  }
}
</style>
