<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="8">
              <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'" :src="item.content"/>
                  <i v-if="item.type === 'text'" 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">
                <i class="el-icon-circle-plus-outline" @click="showType = true"></i>
                <ul class="weui-desktop-msg-sender__tabs" v-if="showType">
                  <!--<li class="weui-desktop-msg-sender__tab weui-desktop-msg-sender__tab_appmsg" @click="getMediaList('news')">图文消息</li>-->
                  <li class="weui-desktop-msg-sender__tab weui-desktop-msg-sender__tab_text" @click="editContent()">文字</li>
                  <li class="weui-desktop-msg-sender__tab weui-desktop-msg-sender__tab_img" @click="getMediaList('image')">图片</li>
                  <!--<li class="weui-desktop-msg-sender__tab weui-desktop-msg-sender__tab_audio" @click="getMediaList('voice')">语音</li>-->
                  <!--<li class="weui-desktop-msg-sender__tab weui-desktop-msg-sender__tab_video" @click="getMediaList('video')">视频</li>-->
                </ul>
              </div>
            </el-col>
          </el-row>
        </el-form>
        <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"/>
        </div>
        <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} from "../../service/api";
  import page from '../framework/page'
  export default {
    name: "dialogObj",
    props:[
      'dialogObj'
    ],
    data(){
      return{
        show:false,
        id: '',
        loading:true,
        showType: false,
        showTextContent: false,
        total:0,
        nowPage:0,
        type:'text',
        form:{
          key:'keywords_reply',
          value:'',
          desc:''
        },
        textContent: '',
        mediaList:  [
//          {
//            "media_id": "hQb3Pbdb4E5Ivxi2sagL5sTdtW5W9pKJNA6Z8nBo6Ao",
//            "name": "xx.jpg",
//            "update_time": 1535351431,
//            "url": "http://mmbiz.qpic.cn/mmbiz_jpg/qNgYSw5sicibUGtiaRYRY9QEZUoqgGdvkTE5Zvg58tUciaAXFslmwuiadgU6turtsF7mXFeicKa9RQTTG1gKSLqPiabpA/0?wx_fmt=jpeg"
//          },
//          {
//            "media_id": "hQb3Pbdb4E5Ivxi2sagL5p2poL7GllXYm4SETNmf210",
//            "name": "z.jpg",
//            "update_time": 1535351316,
//            "url": "http://mmbiz.qpic.cn/mmbiz_jpg/qNgYSw5sicibUGtiaRYRY9QEZUoqgGdvkTE5mTOB0jnmfdH30s54N5FIr2Tsbd9QcBFDiapicYWJ6sCZRMGTIlj179g/0?wx_fmt=jpeg"
//          }
        ],
        showMedia: false,
        rules:{
          value:[
            { required: true, message: '请输入规则名称', trigger: 'change' }
          ],
          desc:[
            { required: true, message: '请输入回复内容', trigger: 'change' }
          ],
          qr:[
            { required: true, message: '请输入二维码', trigger: 'change' }
          ]
        }
      }
    },
    components:{
      page
    },
    methods:{
      save(){
        let json = {}
        console.log('this.form', this.form)
        if(this.dialogObj.id){
          this.$refs['form'].validate((valid) => {
            if(valid){
              json = this.form
              updateConfigApi(this.id,this.form).then(res=>{
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
                this.$emit("reflash");
                this.show = false;
              })
            }
          });
        }else{
          this.$refs['form'].validate((valid) => {
            if(valid){
              saveConfigApi(this.form).then(res=>{
                this.$message({
                  type: 'success',
                  message: '新增成功!'
                });
                this.$emit("reflash");
                this.show = false;
              })
            }
          });
        }
      },
      addContent(type, content, mediaId) {
        let _form = this.form;
        let _desc = JSON.parse(_form.desc);
        let obj = {};
        if (content) {
            obj = {
              type: type,
              content: content
            };
        }
        if (mediaId) {
            obj.media_id = mediaId;
        }
        _desc.push(obj);
        _form.desc = JSON.stringify(_desc);
        this.form = _form;
      },
      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;
      },
      getMediaList(type){
        let json = {
          type: type,
          page: this.nowPage
        };
        this.showType = false;
        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, '');
        })
      },
      onEditText(item, index) {
        let _form = this.form;
        this.$prompt('编辑文本', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: item.content
        }).then(({value}) => {
          let newDesc = JSON.parse(_form.desc);
          let _desc = {
            type: 'text',
            content: value
          };
          newDesc.splice(index,1,_desc);
         _form.desc = JSON.stringify(newDesc);
        })
        this.form = _form;
      },
      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.addContent(this.type, val.url, val.media_id);
        this.showMedia = false;
      }
    },
    watch:{
      dialogObj:{
        handler: function () {
          this.loading = true;
          this.initDialog()
        },
        deep: true
      },
      show(value){
        this.$emit("changeShow",value);
      }
    }
  }
</script>

<style scoped lang="less">
  @import "../../util/public";
  .msg-item {
    margin-bottom: 10px;
  }
  .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;
  }
</style>
