<template>
  <div class="dm-wrap" v-loading="loading">
    <el-row :gutter="20" class="sms-temp__tipsT">
      <el-col :span="24">
        <p style="color:#1890ff;">1.长度不要超过450字(汉字，字符，数字等可见符号，都按1个字计算)。单条短信长度为70字，超过70字后，按67字/条分割成多条，以长短信的方式发送给用户，即用户收到的是一条长短信，但是按多条计费</p>
        <p>2.营销类短信，请在短信内容后面增加<span style="color:#1890ff;">“回T退订”</span></p>
        <p>3.短信模板内容不能含有【】符号</p>
        <p>4.不能发送房产、移民、贷款、政治、色情、暴力等违法类短信</p>
        <p>5.短信内容中不能输入Enter/换行，否则将导致短信分条发送</p>
        <p>6.请注意：【短信签名】也计入短信字数，请注意计算</p>
        <p>7.请注意：您的积分体系是由GIC侧计算时，积分相关的变量值才可生效（19项、20项），若您的积分体系是由外部（ERP等）计算，则积分变量值插入后将无法生效，请注意设置内容</p>
      </el-col>
    </el-row>
    <el-row :gutter="20" class="mt20">
      <el-form label-width="80px" ref="form" :model="form" :rules="rules">
        <el-col :span="12">
          <el-form-item label="模板名称" prop="title">
            <dm-input v-model="form.title" :maxlength="10"></dm-input>
          </el-form-item>
          <el-form-item label="短信类型" prop="type">
            <el-select v-model="form.type">
              <el-option v-for="(v, i) in typeOptions" :key="i" :value="v.value" :label="v.label"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="短信内容" prop="content" class="pb10">
            <dm-input type="textarea" placeholder="亲爱的{2}，{3}是你的生日，祝您生日快乐，心想事成~" :rows="4" v-model="form.content" :maxlength="450"></dm-input>
            <div class="sms-temp__btns" v-if="userData.wxaLinkFlag == 1">
              <!-- wxaLinkFlag 1：有权限 0：无权限 -->
              <el-button type="text" @click="transferLink.show = true">插入小程序链接</el-button>
              <!-- <el-button type="text" @click="reduceLink.show = true">压缩H5链接</el-button> -->
            </div>
          </el-form-item>
          <el-form-item label="申请说明" prop="remark">
            <dm-input type="textarea" :rows="4" v-model="form.remark" :maxlength="120"></dm-input>
          </el-form-item>
        </el-col>
      </el-form>
      <el-col :span="12" class="sms-temp__tips clearfix">
        <div>模板示列如下，其中{数字}为可插入的变量值，参照表如下：注意考虑变量值的文本长度，以免超出67字/条的文本上限。</div>
        <ul class="fl">
          <li>{1}=姓名</li>
          <li>{2}=姓名+先生/女士</li>
          <li>{3}=生日日期</li>
          <li>{4}=生日天数</li>
          <li>{5}=关注日期</li>
          <li>{6}=关注天数</li>
          <li>{7}=主门店品牌名称</li>
          <li>{8}=主门店名称</li>
          <li>{9}=主门店电话</li>
          <li>{10}=专属导购姓名</li>
          <li>{11}=专属导购手机号</li>
          <li>{12}=开卡日期</li>
          <li>{13}=开卡天数</li>
          <li>{14}=开卡门店名称</li>
        </ul>
        <ul class="fl">
          <li>{15}=会员卡号</li>
          <li>{16}=会员等级名称</li>
          <li>{17}=主门店地址</li>
          <li>{18}=会员等级剩余有效天数</li>
          <li>{19}=积分余额</li>
          <li>{20}=30天内将过期积分额度</li>
          <li>{21}=储值余额</li>
          <li>{22}=消费总额</li>
          <li>{23}=消费次数</li>
          <li>{24}=最近消费日期</li>
          <li>{25}=最近消费间隔</li>
          <li>{26}=最高单笔消费</li>
          <li>{27}=最近消费门店名称</li>
          <li>{28}=最近消费品牌名称</li>
        </ul>
      </el-col>
    </el-row>
    <div class="btn-wrap_fixed" :class="{ on: asideShow }">
      <el-button type="primary" @click="submit('form')">提 交</el-button>
      <el-button @click="$router.go(-1)">返 回</el-button>
    </div>
    <!-- 压缩链接 -->
    <el-dialog :visible.sync="reduceLink.show" title="压缩链接" width="798px" @closed="reduceLink.link = ''">
      <el-form label-width="100px">
        <el-form-item label="请输入网址：">
          <dm-input class="reduce-link-input" type="textarea" :rows="4" v-model="reduceLink.link"></dm-input>
          <p class="reduce-link-tip">如果链接只能在微信环境下打开，则浏览器会提示需要在微信下打开此链接，但是无法直接跳转到微信</p>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button @click="reduceLink.show = false">取消</el-button>
        <el-button type="primary" @click="onReduceLink">生成链接</el-button>
      </template>
    </el-dialog>
    <!-- 插入小程序链接 -->
    <el-dialog :visible.sync="transferLink.show" title="插入小程序链接" width="878px" @closed="onTransferLinkClose">
      <el-form label-width="110px">
        <el-form-item label="链接类型：">
          <el-button @click="selectLink.show = true">{{ selectLink.linkData.name || '设置小程序链接' }}</el-button>
        </el-form-item>
        <el-form-item label="链接有效时长：">
          <el-select v-model="transferLink.type" style="width: 143px;vertical-align: top">
            <!-- 0-短期有效，1-长期有效，2-永久有效 -->
            <el-option label="短期有效" value="0"></el-option>
            <el-option label="长期有效" value="1"></el-option>
            <el-option label="永久有效" value="2"></el-option>
          </el-select>
          <template v-if="transferLink.type != 2">
            <el-input-number v-model="transferLink.dayNum" :min="getMin" :max="getMax" controls-position="right" style="width: 90px"></el-input-number>
            <span class="transfer-link-uint">天</span>
            <span class="transfer-link-tip">{{ transferLink.type == 0 ? `不能大于${getMax}天` : `大于${getMin - 1}天且小于等于${getMax}天` }}</span>
          </template>
          <p class="transfer-link-tip">长期有效链接（>31天且≤365天，包含永久有效链接）每个小程序只支持十万，建议商品详情/礼品详情等非永久页面生成短期有效链接（≤31天）。</p>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button @click="transferLink.show = false">取消</el-button>
        <el-button type="primary" @click="onTransferLink">生成链接</el-button>
      </template>
    </el-dialog>
    <el-dialog :visible.sync="insertLink.show" title="链接生成">
      <div class="insert-link">
        <p class="link-text">{{ insertLink.link }}</p>
        <el-button type="text" v-clipboard:text="insertLink.link">复制</el-button>
      </div>
      <template slot="footer">
        <el-button @click="insertLink.show = false">上一步</el-button>
        <el-button type="primary" @click="onInsert">插入链接</el-button>
      </template>
    </el-dialog>
    <linktools :linkVisible.sync="selectLink.show" :linkData="selectLink.linkData" :remove="[5, 35]" :can-save="true" @linkSelect="onSaveLink" /><!-- 链接小工具 - 转赠 -->
  </div>
</template>
<script>
import linktools from '@/components/linktools-fulls/index';
import { _debounce } from '@/utils/index';
import { saveTempService, LoadTempInfo } from '@/service/api/messageApi.js';
import { compressLink, getTransferLink, getUserLogin } from '@/service/api/commonApi.js';
export default {
  name: 'add-temp',
  components: { linktools },
  data() {
    const valiContent = (rules, value, callback) => {
      // 如果是通过链接小工具生成的链接，并且链接前或者后无空格时，自动补齐空格
      if (Array.isArray(this.insertLink.inserted)) {
        this.insertLink.inserted.forEach(el => {
          // 校验content中所有链接的前面或者后面都有一个空格
          const reg = new RegExp(`${el}`, 'g');
          value = value.replace(reg, (str, index) => {
            if (value[index - 1] != ' ') {
              str = ' ' + str;
            }
            if (value[index + str.length] != ' ') {
              str = str + ' ';
            }
            return str;
          });
        });
      }
      this.form.content = value;
      // 如果是复制的链接，提示链接后面需要保留一个空格，如果用户不添加空格则无法保存
      const urlReg = /(https?|ftp|file):\/\/[-A-Za-z0-9+&@#\/%?=~_|!:,.;]+[-A-Za-z0-9+&@#\/%=~_|]/g;
      let validate = false;
      value.replace(urlReg, (str, $1, index) => {
        if (!validate) {
          validate = value[index - 1] != ' ' || value[index + str.length] != ' ';
        }
      });
      if (validate) {
        return callback(new Error('链接前面和后面需要保留一个空格！'));
      }
      callback();
    };
    return {
      loading: false,
      form: {
        smsRecordlateId: '',
        title: '',
        type: '',
        content: '',
        remark: '',
        gicSmsTemplateId: ''
      },
      typeOptions: [{ value: 0, label: '普通短信' }, { value: 1, label: '营销短信' }], // eslint-disable-line
      rules: {
        title: { required: true, message: '请输入模板名称', trigger: 'blur' },
        type: { required: true, message: '请选择短信类型', trigger: 'blur' },
        content: [
          { required: true, message: '请输入短信内容', trigger: 'blur' },
          { validator: valiContent, trigger: 'blur' }
        ],
        remark: { required: true, message: '请输入申请说明', trigger: 'blur' }
      },
      editFlag: this.$route.meta.type === 'edit',
      userData: {},
      // 压缩链接
      reduceLink: {
        show: false,
        link: ''
      },
      // 插入小程序链接相关
      insertLink: {
        show: false,
        link: '',
        inserted: [] // 已经插入到短信内容的链接，用来校验在短信文本中链接前后是否有空格
      },
      // 转换链接
      transferLink: {
        show: false,
        type: '0', // 0-短期有效，1-长期有效，2-永久有效
        dayNum: '', // 天数
        pageId: '' // pageId
      },
      // 链接小工具选择链接
      selectLink: {
        show: false,
        linkData: {}
      }
    };
  },
  computed: {
    asideShow() {
      return this.$store.state.marketing.asideShow;
    },
    getMin() {
      if (this.transferLink.type == 0) {
        // eslint-disable-next-line
        this.transferLink.dayNum = 1;
      } else {
        // eslint-disable-next-line
        this.transferLink.dayNum = 32;
      }
      return this.transferLink.type == 0 ? 1 : 32;
    },
    getMax() {
      let max = 31;
      if (this.transferLink.type == 0) {
        max = 31;
      } else if (this.transferLink.type == 1) {
        max = 365;
      } else {
        max = Infinity;
      }
      return max;
    }
  },
  created() {
    if (this.editFlag) {
      this.$store.commit('mutations_breadcrumb', [{ name: '营销管理', path: '' }, { name: '短信营销', path: '' }, { name: '模板库', path: '/message/temp' }, { name: '编辑模板', path: '' }]); // eslint-disable-line
      this.LoadTempInfo();
    } else {
      this.$store.commit('mutations_breadcrumb', [{ name: '营销管理', path: '' }, { name: '短信营销', path: '' }, { name: '模板库', path: '/message/temp' }, { name: '新增模板', path: '' }]); // eslint-disable-line
    }
    this.getUserData();
  },
  methods: {
    submit: _debounce(function(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.saveTempService();
        } else {
          return false;
        }
      });
    }),
    async saveTempService() {
      if (this.loading) {
        return;
      }
      try {
        this.loading = true;
        await saveTempService(this.form);
        this.$tips({ type: 'success', message: '操作成功' });
        this.$router.push('/message/temp');
        this.loading = false;
      } catch (err) {
        this.$tips({ type: 'error', message: '操作失败' });
        this.loading = false;
      }
    },
    async LoadTempInfo() {
      this.loading = true;
      let res = await LoadTempInfo({ gicSmsTemplateId: this.$route.params.id });
      this.form = {
        smsTemplateId: res.result.smsTemplateId,
        type: res.result.type,
        content: res.result.content,
        remark: res.result.remark,
        title: res.result.title,
        gicSmsTemplateId: res.result.gicSmsTemplateId
      };
      this.loading = false;
    },
    getUserData() {
      getUserLogin().then(res => {
        this.userData = res.result || {};
      });
    },
    // 生成短连接
    onReduceLink() {
      if (!this.reduceLink.link) {
        return this.$tips({ type: 'error', message: '请输入网址' });
      }
      this.loading = true;
      compressLink({ link: this.reduceLink.link }, false, false, 'post')
        .then(res => {
          this.insertLink.show = true;
          this.insertLink.link = res.result;
        })
        .finally(() => (this.loading = false));
    },
    // 保存链接小工具返回的链接数据
    onSaveLink(linkData) {
      this.selectLink.linkData = linkData;
    },
    onTransferLinkClose() {
      this.selectLink.linkData = {};
      this.transferLink.type = '0';
      this.transferLink.dayNum = 1;
    },
    // 将小程序链接转换成中转页链接
    onTransferLink() {
      if (!this.selectLink.linkData.id) {
        return this.$tips({ type: 'error', message: '请选择小程序链接' });
      }
      this.loading = true;
      const { type, dayNum } = this.transferLink;
      const requestData = { type, dayNum, pageLink: JSON.stringify(this.selectLink.linkData) };
      getTransferLink(requestData, false, false, 'post')
        .then(res => {
          this.insertLink.link = res.result;
          this.insertLink.show = true;
        })
        .finally(() => (this.loading = false));
    },
    onInsert() {
      // 链接插入短信中需要前后有一个空格
      this.form.content = `${this.form.content} ${this.insertLink.link} `;
      this.insertLink.show = false;
      this.reduceLink.show = false;
      this.transferLink.show = false;
      this.insertLink.inserted.push(this.insertLink.link);
    }
  }
};
</script>
<style lang="scss" scoped>
.sms-temp__btns {
  margin-top: 5px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  /deep/ .el-button {
    color: #606266;
    font-size: 12px;
    & + .el-button {
      padding-left: 10px;
      border-left: 1px solid #c0c4cc;
    }
    &:hover {
      color: #303133;
    }
  }
}
.sms-temp__tips {
  padding: 8px 16px;
  line-height: 23px;
  font-size: 12px;
  background: #f4f4f5;
  ul {
    padding-right: 20px;
    li {
      font-size: 12px;
    }
  }
}
.sms-temp__tipsT {
  background: #f4f4f5;
  padding: 8px 16px;
  p {
    line-height: 1.5;
    font-size: 12px;
    color: #606266;
  }
}
.reduce-link-input {
  /deep/ .dm-input__counter {
    display: none;
  }
}
.reduce-link-tip {
  margin-top: 5px;
  text-align: right;
  font-size: 12px;
  color: #606266;
  line-height: 17px;
}
.transfer-link-uint {
  margin: 0 15px 0 8px;
  font-size: 14px;
  color: #303133;
  line-height: 20px;
}
.transfer-link-tip {
  font-size: 12px;
  color: #909399;
  line-height: 17px;
}
.insert-link {
  padding: 18px 12px;
  background: #f3f6f9;
  .link-text {
    display: inline-block;
    vertical-align: middle;
    margin-right: 10px;
    max-width: 80%;
    font-size: 14px;
    font-weight: 400;
    color: #606266;
    line-height: 20px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
