<template>
  <div v-if="show">
    <el-dialog
      title="自动回复"
      center
      append-to-body
      :visible.sync="show"
      width="800px">
      <div v-loading="loading">
        <el-form ref="form" :model="form" :rules="rules" >
          <el-row>
            <el-col :span="4"><label>关键词</label></el-col>
            <el-col :span="8">
              <el-form-item  prop="value">
                <el-input v-model="form.value"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4"><label>回复内容</label></el-col>
            <el-col :span="20">
              <template v-if="form.desc">
                <div v-for="(item, index) in JSON.parse(form.desc)" class="msg-item">
                  <span class="msg-text" v-if="item.type==='text'">{{item.content}}</span>
                  <img v-else-if="item.type==='image' && item.content" :src="item.content"/>
                  <span  v-else-if="item.variable" class="msg-text">我的老师二维码</span>
                  <i class="el-icon-edit" @click="onEditText(item, index)"></i>
                  <i class="el-icon-delete" @click="onDelText(item, index)"></i>
                </div>
              </template>
              <div class="msg_sender_wrp">
                <div>
                  <i class="el-icon-circle-plus-outline" @click="onAddContent"></i>
                </div>
                <el-dialog
                  width="30%"
                  :title="title"
                  :visible.sync="showType"
                  :close-on-click-modal="false"
                  :close-on-press-escape="false"
                  :show-close="false"
                  append-to-body>
                  <div>
                    <el-tabs v-if="showType" v-model="type" type="card">
                      <el-tab-pane label="文字" name="text"></el-tab-pane>
                      <el-tab-pane label="图片" name="image"></el-tab-pane>
                    </el-tabs>
                    <!--<ul class="weui-desktop-msg-sender__tabs" v-if="showType">-->
                    <!--&lt;!&ndash;<li class="weui-desktop-msg-sender__tab weui-desktop-msg-sender__tab_appmsg" @click="getMediaList('news')">图文消息</li>&ndash;&gt;-->
                    <!--<li class="weui-desktop-msg-sender__tab weui-desktop-msg-sender__tab_text" @click="onChangeTab('text')">文字</li>-->
                    <!--<li class="weui-desktop-msg-sender__tab weui-desktop-msg-sender__tab_img" @click="onChangeTab('image')">图片</li>-->
                    <!--&lt;!&ndash;<li class="weui-desktop-msg-sender__tab weui-desktop-msg-sender__tab_audio" @click="getMediaList('voice')">语音</li>&ndash;&gt;-->
                    <!--&lt;!&ndash;<li class="weui-desktop-msg-sender__tab weui-desktop-msg-sender__tab_video" @click="getMediaList('video')">视频</li>&ndash;&gt;-->
                    <!--</ul>-->
                    <div v-if="showType" class="more-info clear-both">
                      <template v-if="type=== 'text'">
                        <el-input
                          type="textarea"
                          :autosize="{ minRows: 4, maxRows: 8}"
                          placeholder="请输入内容"
                          v-model="content">
                        </el-input>
                        <div style="float: right">
                          <el-popover
                            placement="bottom-end"
                            width="400"
                            :offset="10"
                            trigger="hover"
                            v-model="showEmotion">
                            <div>
                              <emotion @emotion="handleEmotion" :height="200" ></emotion>
                            </div>
                            <el-button @click="showEmotion = !showEmotion" slot="reference" type="text">
                              <span class="icon_emotion emotion_switch"></span>
                            </el-button>
                          </el-popover>
                          <el-button @click="addTeacherName" type="warning" plain>添加老师名字</el-button>
                          <el-button @click="addTeacherAlias" type="success" plain>添加老师别名</el-button>
                        </div>
                      </template>
                      <template v-if="type==='image'">
                        <div v-if="imageContent.url" class="img">
                          <img :src="imageContent.url"/>
                          <i class="el-icon-delete" @click="imageContent={url:'',media_id:''}"></i>
                        </div>
                        <div v-if="imageContent.variable" class="img my-teacher">
                          <div>老师二维码</div>
                          <i class="el-icon-delete" @click="imageContent={url:'',media_id:'',variable:''}"></i>
                        </div>
                        <div class="display-b">
                          <div class="choose_item" style="color: #888;" @click="getMediaList('image')">+从素材库中选择</div>
                          <div class="choose_item" style="color: #888;" @click="addTeacherQrcode">+添加老师二维码</div>
                        </div>
                        <div v-if="showMedia && mediaList.length > 0">
                          <el-table
                            :data="mediaList"
                            @row-click="onChooseMedia"
                            style="width: 100%">
                            <el-table-column
                              prop="name"
                              label="名称">
                            </el-table-column>
                            <el-table-column
                              prop="media_id"
                              label="mediaId">
                            </el-table-column>
                            <el-table-column
                              label="URL">
                              <template slot-scope="scope">
                                <a :href="scope.row.url">
                                  <img style="width: 60px;" :src="scope.row.url"/>
                                </a>
                              </template>
                            </el-table-column>
                          </el-table>
                          <page :total="total" v-model="nowPage" :limit="limit" @pageChange="onPageChange"/>
                        </div>
                      </template>
                      <div class="tool_bar">
                        <el-button @click="close">取 消</el-button>
                        <el-button class="weui-desktop-btn weui-desktop-btn_primary" @click="confirm">确定</el-button>
                      </div>
                    </div>
                  </div>
                </el-dialog>
              </div>
            </el-col>
          </el-row>
        </el-form>

        <span slot="footer" class="dialog-footer">
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </span>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  import {updateConfigApi,saveConfigApi,getMediaListApi,getTeacherListApi} from "../../service/api";
  import page from '../framework/page'
  import emotion from '../framework/Emotion/index'
  export default {
    name: "dialogObj",
    props:[
      'dialogObj'
    ],
    data(){
      return{
        editIndex: -1,
        title: '',
        show:false,
        showEmotion: false,
        id: '',
        loading:true,
        showType: false,
        showTextContent: false,
        total:0,
        nowPage:1,
        limit: 5,
        type:'text',
        form:{
          key:'keywords_reply',
          value:'',
          desc:''
        },
        teacher_id: '',
        start_at: '',
        textContent: '',
        mediaList:  [],
        showMedia: false,
        teacherList: [],
        content: '',
        imageContent: {
          url: '',
          media_id: ''
        },
        pickerOptions1: {
          disabledDate(time) {
            return !(time.getTime() > Date.now());
          }
        },
        rules:{
          value:[
            { required: true, message: '请输入规则名称', trigger: 'change' }
          ],
          desc:[
            { required: true, message: '请输入回复内容', trigger: 'change' }
          ],
          qr:[
            { required: true, message: '请输入二维码', trigger: 'change' }
          ]
        }
      }
    },
    components:{
      page,
      emotion
    },
    methods:{
      getTeacher(){
        getTeacherListApi({page: 1, limit: 1000}).then(res=>{
          this.teacherList = res.list
        })
      },
      save(){
        let json = {
          key:this.form.key,
          value:this.form.value,
          desc:this.form.desc
        }
        if(this.dialogObj.id){
          this.$refs['form'].validate((valid) => {
            if(valid){
              updateConfigApi(this.id,json).then(res=>{
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
                this.$emit("reflash");
                this.show = false;
              })
            }
          });
        }else{
          this.$refs['form'].validate((valid) => {
            if(valid){
              saveConfigApi(json).then(res=>{
                this.$message({
                  type: 'success',
                  message: '新增成功!'
                });
                this.$emit("reflash");
                this.show = false;
              })
            }
          });
        }
      },
      addContent(type, content, mediaId, my_teacher) {
        let _form = this.form;
        let _desc = _form.desc ? JSON.parse(_form.desc) : [];
        let obj = {
            type: type
        };
        if (content) {
            obj.content = content
        }
        if (mediaId) {
            obj.media_id = mediaId;
        }
        if (my_teacher) {
          obj.variable = my_teacher
        }
        if (this.editIndex > -1) {
          _desc.splice(this.editIndex,1,obj);
        } else {
          _desc.push(obj);
        }
        _form.desc = JSON.stringify(_desc);
        this.form = _form;
        this.showType = false;
      },
      initDialog(){
        this.show = this.dialogObj.show;
        if (this.dialogObj.id) {
          this.id = this.dialogObj.id;
        }
        this.form.value = this.dialogObj.value;
        this.form.desc = this.dialogObj.desc;
        this.loading = false;
        this.showType = false;
      },
      onPageChange(val){
        this.nowPage = val
        this.getMediaList(this.type)
      },
      onChangeTab(type){
          this.type = type;
      },
      onAddContent(){
        this.editIndex = -1;
        this.title = '添加回复';
        this.content='';
        this.imageContent = {
          url: '',
          media_id: '',
          variable: ''
        };
        this.teacher_id = '';
        this.start_at = '';
        this.showType = true;
      },
      onEditText(item, index) {
        this.title = '编辑回复';
        this.type = item.type;
        this.editIndex = index;
        if (this.type === 'text') {
          this.content=item.content;
        } else {
            if(item.content) {
              this.imageContent = {
                url: item.content,
                media_id: item.media_id
              };
            }
            if (item.variable) {
              this.imageContent = {
                variable: item.variable
              };
            }
        }
        this.showType = true;
      },
      close(){
        this.content='';
        this.imageContent = {
          url: '',
          media_id: ''
        };
        this.teacher_id = '';
        this.start_at = '';
        this.showType = false;
      },
      confirm(){
        if(this.type === 'text') {
          if(!this.content){
            this.$message({
              showClose: true,
              message: '请输入文本内容'
            });
          } else {
            this.addContent('text', this.content, '','');
          }
        } else if (this.type === 'image') {
          if (!this.imageContent.url && !this.imageContent.variable) {
            this.$message({
              showClose: true,
              message: '请选择图片'
            });
          } else {
            let _myTeacher = this.imageContent.variable ? this.imageContent.variable : '';
            let _url = this.imageContent.url ? this.imageContent.url : '';
            let _mediaId = this.imageContent.media_id ? this.imageContent.media_id : '';
            this.addContent(this.type, _url, _mediaId,_myTeacher);
          }
        }
      },
      getMediaList(type){
        let json = {
          type: type,
          page: this.nowPage,
          limit: this.limit
        };
        this.loading = true;
        this.showMedia = true;
        getMediaListApi(json).then(res=>{
          this.loading = false;
          this.type = type;
          this.mediaList = res.item;
          this.total = res.total_count;
          if (this.total === 0 ) {
            this.$message({
              showClose: true,
              message: '暂无数据'
            });
          }
        }).catch(() => {
          this.loading = false;
        })
      },
      editContent() {
        this.$prompt('请输入文本', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({value}) => {
          this.addContent('text', value, '','');
        })
      },
      onDelText(item, index) {
        let _form = this.form;
        this.$confirm('此操作将删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let _desc = JSON.parse(_form.desc);
          _desc.splice(index,1);
          _form.desc = JSON.stringify(_desc);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
        this.form = _form;
      },
      onChooseMedia(val){
        this.imageContent = val
        this.showMedia = false;
      },
      addTeacherQrcode(){
        this.showMedia = false;
        this.imageContent = {
          variable:'my_teacher'
        }
      },
      handleEmotion (i) {
        this.content += i
      },
      addTeacherName(){
        this.content += '{my_teacher_name}'
      },
      addTeacherAlias(){
        this.content += '{my_teacher_alias}'
      },
    },
    watch:{
      dialogObj:{
        handler: function () {
          this.loading = true;
          this.initDialog();
          this.getTeacher();
        },
        deep: true
      },
      show(value){
        this.$emit("changeShow",value);
      }
    }
  }
</script>

<style scoped lang="less">
  @import "../../util/public";
  .emotion_switch {
    float: left;
    height: 28px;
    line-height: 999em;
    overflow: hidden;
    background: transparent url(https://res.wx.qq.com/mpres/en_US/htmledition/pages/modules/reply/images/icon_emotion_switch.png) no-repeat 0 0;
    width: 20px;
    height: 20px;
    vertical-align: middle;
    display: inline-block;
  }
  .msg-item {
    margin-bottom: 10px;
    img {
      width: 20%;
    }
  }
  .msg-text {
    margin-right: 20px;
  }
  .dialog-footer{
    display: block;
    text-align: center;
    margin-top: 30px;
  }
  .msg_sender_wrp {
    /*display: flex;*/
    /*flex-flow: row wrap;*/
    /*justify-content: flex-start;*/
    /*align-items: center;*/
    /*height: 48px;*/
    /*position: absolute;*/
    /*left: 100%;*/
    /*top: 50%;*/
    /*width: 500px;*/
    /*z-index: 500;*/
    /*-ms-transform: translateY(-50%);*/
    /*transform: translateY(-50%);*/
    /*background: #FFFFFF;*/
    /*box-shadow: 0 1px 20px 0 #E4E8EB;*/
    /*border-radius: 2px;*/
  }
  .el-icon-circle-plus-outline {
    font-size: 28px;
  }
  .weui-desktop-msg-sender__tabs {
    line-height: 38px;
    background-color: #FFFFFF;
  }
  ul, ol {
    padding-left: 0;
    list-style-type: none;
  }
  .weui-desktop-msg-sender__tab {
    padding: 0 15px;
    float: left;
    cursor: pointer;
  }
  .weui-desktop-msg-sender__tab_appmsg:before {
    background: transparent url(https://mp.weixin.qq.com/mpres/en_US/htmledition/pages/modules/msg_sender/svg/default/sender_appmsg3f92fe.svg) no-repeat 0 0;
  }
  .weui-desktop-msg-sender__tab:before {
    content: " ";
    display: inline-block;
    width: 22px;
    height: 20px;
    vertical-align: middle;
    margin: -0.2em 5px 0 0;
  }
  .weui-desktop-msg-sender__tab_text:before {
    background: transparent url(https://mp.weixin.qq.com/mpres/en_US/htmledition/pages/modules/msg_sender/svg/default/sender_text3f92fe.svg) no-repeat 0 0;
  }
  .weui-desktop-msg-sender__tab_img:before {
    background: transparent url(https://mp.weixin.qq.com/mpres/en_US/htmledition/pages/modules/msg_sender/svg/default/sender_img3f92fe.svg) no-repeat 0 0;
  }
  .weui-desktop-msg-sender__tab_audio:before {
    background: transparent url(https://mp.weixin.qq.com/mpres/en_US/htmledition/pages/modules/msg_sender/svg/default/sender_audio3f92fe.svg) no-repeat 0 0;
  }
  .weui-desktop-msg-sender__tab_video:before {
    background: transparent url(https://mp.weixin.qq.com/mpres/en_US/htmledition/pages/modules/msg_sender/svg/default/sender_video3f92fe.svg) no-repeat 0 0;
  }
  .more-info {

  }
  .img {
    position: relative;
    width: 25%;
    img {
      width: 100%;
    }
    .el-icon-delete {
      position: absolute;
      top: 50%;
      left: 50%;
      display: none;
    }
  }
  .img:hover img{
    opacity: 0.3;
  }
  .img:hover .el-icon-delete{
    display: block;
  }
  .tool_bar {
    float: right;
    margin-top: 20px;
  }
  .choose_item {
    margin-bottom: 25px;
    color: rgb(136, 136, 136);
    height: 80px;
    line-height: 80px;
    width: 45%;
    border: 1px dashed;
    text-align: center;
  }
  .display-b {
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    align-items: center;
  }
  .my-teacher {
    width: 25%;
    height: 80px;
    background-color: #eee;
    line-height: 80px;
    text-align: center;
    margin-bottom: 10px;
  }
</style>
