<!--
 * @Date: 2022-08-08 10:09:47
 * @LastEditors: JinxChen
 * @LastEditTime: 2023-01-05 14:49:38
 * @FilePath: \TelpoUserManageAdmin\src\views\message-manage\main\add-mass\index.vue
 * @description: 添加群发
-->

<template>
    <div class="home-container">
      <div class="form-container">
        <!-- 表单 -->
        <el-form ref="form" :model="form" label-width="100px" :rules="rules">
          <el-form-item label="消息主题:" size="small" prop="subject">
            <el-input v-model="form.subject" class="input-width-400" clearable ></el-input>
          </el-form-item>
          <el-form-item label="选择模板:" size="small" prop="tempId">
            <!-- 动态生成模板 -->
            <el-select v-model="form.tempId" placeholder="选择模板" clearable filterable @change="onSelectTemp">
                <el-option :label="item.label" :value="item.value" v-for="(item, index) in templateMsgList" :key="index"/>
            </el-select>
          </el-form-item>
          <el-form-item label="模板内容:" size="small" required>
            <el-form-item v-for="(item, index) in templateMsgCon" :key="index">
              <el-form-item>
                <p>{{item.name}}</p>
                <el-input v-model="templateInput[item.key]" class="input-width-600" clearable type="textarea" autosize></el-input>
              </el-form-item>
            </el-form-item>
          </el-form-item>
          <el-form-item label="内容链接:" size="small" class="inline-form-item" required>
            <el-form-item  prop="articleContent" >
              <el-input v-model="form.articleContent" placeholder="请输入正确的外部URL" class="input-width-400" clearable @clear="onClearUrl"></el-input>
              <!-- <el-select v-model="article" placeholder="选择文章" clearable filterable @change="onSelectArt" @clear="onClearSelect">
                <el-option :label="item.label" :value="item.value" v-for="(item, index) in articleList" :key="index"/>
              </el-select> -->
            </el-form-item>
          </el-form-item>

          <el-form-item label="群发对象:" size="small" prop="selfGroupId">
            <el-select v-model="form.selfGroupId" placeholder="选择分组" clearable filterable @change="onSelectMass">
              <el-option :label="item.label" :value="item.value" v-for="(item, index) in groupList" :key="index"/>
            </el-select>
            <el-button type="primary" @click="onCheckList" disabled>查看名单</el-button>
          </el-form-item>
          <div class="footer-container">
        <el-button type="primary" v-for="(item, index) in footBtnList" :key="index" @click="item.click">{{item.name}}</el-button>
      </div>
        </el-form>
      </div>
      <!-- 底部操作按钮 -->
      <!-- 预览dialog -->
      <el-dialog title="预览信息" :visible.sync="previewShow">
        <div class="preview-container">
          <div class="top">
            <p>{{templateInput.first}}</p>
            <p v-for="(item, index) in previewData" :key="index">
              {{item.name}}：{{item.value}}
            </p>
            <p>{{templateInput.remark}}</p>
          </div>
          <div class="fot" @click="onOpenUrl">
            <p>详情</p>
            <p>></p>
          </div>
        </div>
        <div class="preview-btn">
          <el-button type="primary" @click="onConfirm">确认</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
import { initTime } from '@/utils/index.js';
import { APIWechatFans } from '@/api/wechat-fans.js';
export default {
  name: 'add-mass',
  components: {  },
  data(){
    const checkUrl = (rule, value, callback) => {
      let urlrReg = /^((https?|ftp):\/\/)?([\da-z.-]+)\.([a-z.]{2,6})(\/\w\.-]*)*\/?/;
      if(urlrReg.test(value)) {
        callback();
      } else if (this.form.articleId !== '') {
        callback();
      } else {
        callback(`请输入正确的网址`);
      }
    };
   return {
     buttonList: [], // 头部按钮，例子：  {name: '添加', type: 'primary', icon: 'el-icon-circle-plus', click: () => { this.AddDialog();}}
     firstData: '{{first.DATA}}:',
     keyword1Data: '{{keyword1DATA}}:',
     keyword2Data: '{{keyword2DATA}}:',
     keyword3Data: '{{keyword3DATA}}:',
     remarkData: '{{remarkDATA}}:',
     form: {
       subject: '' /* || '财商学习通知' */, //发送主题
       templateId: 1, //模板id
       articleContent: '', //文章内容
       articleId: '', //文章id
       selfGroupId: '', //分组id
       first: '' /* || '家长您好，您孩子所需的财商学习内容有更新' */, //内容模板标题
       keyword1: '' /* || 'csds' */, //学习账号
       keyword2: '' /* || '财商36问' */, //更新内容
       keyword3: '',
       remark: '' /* || '请点击内容查看详情' */, //内容详情
       tempId: '' /* || '-kOhlwJPhO7v3WW3rAdmNs76lR7ZpQEJtbVSY8Y35Eg' */, //模板id
     },
     article: '', //选择文章
    //  文章列表
     articleList: [],
    //  用户分组
    groupList: [],
    // 底部操作按钮
    footBtnList: [
      { name: '立即发送', click: () => { this.onSend()}},
      { name: '保存', click: () => { this.onSave()} },
      { name: '预览', click: () => { this.onPreview()} },

    ],
    // 预览dialog
    previewShow: false,
    // 要预览的页面字段
    previewData: [],
    // form验证
    rules: {
      subject: [
        { required: true, message: '请输入消息主题', trigger: 'blur' },
      ],
      tempId: [
        { required: true, message: '请选择模板消息', trigger: 'blur' },
      ],
      /* first: [
        { required: true, message: '请填写消息模板内容', trigger: 'blur' },
      ],
      keyword1: [
        { required: true, message: '请填写消息模板内容', trigger: 'blur' },
      ],
      keyword2: [
        { required: true, message: '请填写消息模板内容', trigger: 'blur' },
      ],
      keyword3: [
        { required: true, message: '请填写消息模板内容', trigger: 'blur' },
      ],
      keyword4: [
        { required: true, message: '请填写消息模板内容', trigger: 'blur' },
      ],
      keyword5: [
        { required: true, message: '请填写消息模板内容', trigger: 'blur' },
      ],
      remark: [
        { required: true, message: '请填写消息模板内容', trigger: 'blur' },
      ], */
      articleContent: [
        { required: true, validator: checkUrl, message: '请输入正确的外部URL', trigger: 'blur' },
      ],
      selfGroupId: [
        { required: true, message: '请选择群发分组', trigger: 'blur' },
      ],
    },
    // 模板消息列表
    templateMsgList: [],
    // 模板内容
    templateMsgCon: [
      {
        key: 'first',
        name: '{{first.DATA}}',
      },
      {
        key: 'keyword1',
        name: '消息类别：{{keyword1.DATA}}',
      },
      {
        key: 'keyword2',
        name: '通知用户：{{keyword2.DATA}}',
      },
      {
        key: 'keyword3',
        name: '通知内容：{{keyword3.DATA}}',
      },
      {
        key: 'remark',
        name: '{{remark.DATA}}'
      }
    ],
    // 动态生成的input
    templateInput: {},
    tempData: [] || [
      {first: 'first', remark: 'remark'}
    ]
   }
  },
  computed: {
    // 初始弹窗更新时间
    initUpdateTime() {
       return initTime(new Date(), 'ymdhm'); //更新时间
    },
  },
  activated() {
    this.getSelfGroups();
    this.getArticlesGroup();
    this.getTemplateMsgList();
  },
  mounted() {
  },
  created() {
    this.getSelfGroups();
    this.getTemplateMsgList();
    this.getArticlesGroup();
  },
  methods: {
    // 获取自定义分组
    getSelfGroups() {
      let reqBody =  {
        page_index: 1,
        page_size: 10
      }
      APIWechatFans.SelfGroups(reqBody)
        .then(res => {
          let data = res.data;
          this.groupList = data.rows.map(item => {
            return {
              label: item.name,
              value: item.id
            }
          })
          console.log("data", data);
        })
    },
    // 获取文章列表
    getArticlesGroup() {
      let reqBody =  {
        page_index: 1,
        page_size: 100000
      }
      APIWechatFans.getArticlesGroup(reqBody)
        .then(res => {
          let data = res.data;
          console.log("文章data", data);
          this.articleList = data.rows.map(item => {
            return {
              label: item.title,
              value: item.id
            }
          })
      })
    },
    // 查看白名单
    onCheckList() {},
    // objectToArray
    objectToArray(obj) {
      let arr = [];
      for(let i in obj) {
        // arr.push (obj[i] )  //返回属性值
        arr.push(obj[i])  //返回键名
      };
      return arr;
    },
    // 立即发送
    onSend() {
      this.tempData.push(this.templateInput);
      console.log("tempData", JSON.stringify(this.templateInput));
      // 拼接所需字段
      let reqBody = {
        send_now: true, //true 是立即发送， false是保存
        subject: this.form.subject,
        template_id: this.form.tempId,
        self_group_id: this.form.selfGroupId,
        article_id: this.form.articleId || 0,
        mptemplate_content: JSON.stringify(this.templateInput),
        url: this.form.articleContent
      };
      this.$refs['form'].validate((valid) => {
        if(valid) {
          const isCanSave = this.checkTemplateInput();
          if(!isCanSave) {
            this.$message({
                type: "error",
                message: "请完善模板内容"
            });
            return
          }
          this.addGroupSender(reqBody, '群发');
        } else {
          this.$message({
            type: "error",
            message: "请完善群发消息"
          });
        }
      });
    },
    // 验证动态模板
    checkTemplateInput() {
      console.log("templateInput", this.templateInput);
      // 获取模板输入框的实际数量
      let tempInputLen = this.templateMsgCon.length;
      console.log("tempInputLen", tempInputLen);
      // 计算模板输入的数量
      let tempLen = (Object.keys(this.templateInput).length);
      if( tempLen !== tempInputLen) {
        return false
      } else {
        return true
      }
    },
    // 保存
    onSave() {
      // 定义接口所需字段
      let reqBody = {
        send_now: false, //true 是立即发送， false是保存
        subject: this.form.subject, //消息主题
        template_id: this.form.tempId, // 模板id
        self_group_id: this.form.selfGroupId, //发送分组id
        article_id: this.form.articleId || 0, //文章id
        mptemplate_content: JSON.stringify(this.templateInput), //模板消息内容
        url: this.form.articleContent, //文章链接
      };
      this.$refs['form'].validate((valid) => {
        if(valid) {
          const isCanSave = this.checkTemplateInput();
          if(!isCanSave) {
            this.$message({
                type: "error",
                message: "请完善模板内容"
            });
            return
          }
          this.addGroupSender(reqBody, '保存');
        } else {
          this.$message({
            type: "error",
            message: "请完善群发消息"
          });
        }
      });
    },
    // 添加群发
    addGroupSender(reqBody, action) {
      const loading = this.$loading({
        text: `${action}中`
      });
      APIWechatFans.addGroupSender(reqBody)
        .then(res => {
          console.log("res", res);
          if(res.code === 20000) {
            this.$message({
              type: "success",
              message: `${action}成功!`
            });
          } else {
            this.$message({
              type: "error",
              message: `${action}失败!${res.message}`
            });
          }
        }).catch(error => {
          this.$message({
              type: "error",
              message: '出错了！请联系管理员。'
            });
        }).finally(() => {
          loading.close();
        })
    },
    // 预览
    onPreview() {
      const isCanSave = this.checkTemplateInput();
        if(!isCanSave) {
          this.$message({
            type: "error",
            message: "请先完善模板内容"
        });
        return
      }
      this.previewShow = true;
      this.tempData.push(this.templateInput);
      let previewArr = this.objectToArray(this.tempData[0]).slice(1, this.objectToArray(this.tempData[0]).length - 1);
      this.previewData.forEach((value, index) => {
        value['value'] = previewArr[index];
      });
    },
    // 预览确认
    onConfirm() {
      this.previewShow = false;
    },
    // 选择文章
    onSelectArt(value) {
        if(value) {
            this.form.articleId = value;
            this.form.articleContent = this.articleList.filter(item => {
              return item.value === value;
            }).map(item => {
              return item.label;
            }).toString();
        }
    },
    // 选择群发对象分组
    onSelectMass(value) {
        if(value) {
            this.form.selfGroupId = value;
            console.log("选择的对象分组", value);
        }
    },
    // 获取消息模板列表
    getTemplateMsgList() {
      APIWechatFans.getTemplateMsgList()
        .then(res => {
          let telpData = res.data;
          this.templateMsgList = telpData.map(item => {
            return {
              label: item.title,
              value: item.template_id
            }
          });
          // 默认显示第一个模板id
          this.getTemplateMsgListById(this.templateMsgList[0].value);
        })
    },
    // 根据模板id获取对应模板消息
    getTemplateMsgListById(id) {
      APIWechatFans.getTemplateById(id)
        .then(res => {
          console.log("res", res);
          let data = res.data;
          let splitData = data.content.split('\\n');
          this.templateMsgCon = splitData.map(item => {
            return {
              name: item,
              key: item.substring( item.indexOf("{{") + 2, item.indexOf(".DATA"))
            }
          });
          this.previewData = splitData.splice(1,  splitData.length - 2 ).map(item => {
            return {
              name: item.substring( 0, item.indexOf("：")),
              key: item.substring( item.indexOf("{{") + 2, item.indexOf(".DATA"))
            }
          });
        })
    },
    // 选择模板消息
    onSelectTemp(value) {
      console.log("选择了模板消息", value);
      this.form.tempId = value;
      this.templateInput = {};
      this.getTemplateMsgListById(value);
    },
    // 清空url填写
    onClearUrl() {
      this.form.articleContent = '';
      if( this.form.articleId ) {
        this.form.articleId = '';
      }
    },
    onClearSelect() {
      this.form.articleContent = '';
    },
    onOpenUrl() {
      window.open(this.form.articleContent);
    }
  }
}
</script>

<style scoped lang="scss">
    .home-container {
      height: 600px;
      padding: 0 20px;
      //overflow-y: scroll;
      overflow-x: hidden;
      border: none;
      box-shadow: none;
      overflow-y: scroll;
      .form-container {
        height: 600px;
        padding: 5px 0;
        border: 1px solid #d8dce5;
        display: flex;
        justify-content: center;
        //align-items: center;
        overflow: scroll;
        p {
          margin: 5px 0;
        }
        .input-width-400 {
          width: 400px;
        }
        .input-width-600 {
          width: 600px;
        }
        .inline-form-item {
          display: inline-block;
        }
      }
      .footer-container {
        height: 60px;
        display: flex;
        justify-content: center;
        align-items: center;
        .el-button {
          width: 120px;
        }
      }
      .preview-container {
        //height: 400px;
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        flex-direction: column;
        margin: 20px;
        border: 1px solid #d8dce5;
        .top {
          width: 100%;
          display: flex;
          justify-content: flex-start;
          align-items: flex-start;
          flex-direction: column;
          padding: 0 40px;
          border-bottom: 1px solid #d8dce5 ;
          overflow-y: scroll;
        }
        .fot {
          width: 100%;
          padding: 0 40px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          &:hover {
            cursor: pointer;
          }
        }
      }
      .preview-btn {
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
</style>
