<template>
  <basic-container>
    <el-row :span="24">
      <el-col :md="24">
        <avue-crud ref="crud"
                   :page="page"
                   :data="tableData"
                   :permission="permissionList"
                   :table-loading="tableLoading"
                   :option="tableOption"
                   @refresh-change="refreshChange"
                   @sort-change="sortChange"
                   @size-change="sizeChange"
                   @current-change="currentChange"
                   @search-change="searchChange">
          <template slot-scope="scope" slot="menuLeft">
            <div class="add_but">
              <el-button type="primary"
                         v-if="permissions.mp_wxsmartqa_add"
                         @click="handleAdd"
                         size="mini">新 增
              </el-button>
            </div>
          </template>
          <template slot-scope="scope" slot="menu">
            <el-button type="text"
                       v-if="permissions.mp_wxsmartqa_edit"
                       icon="el-icon-edit"
                       size="small"
                       plain
                       @click="handleEdit(scope.row)">编辑
            </el-button>
            <el-button type="text"
                       v-if="permissions.mp_wxsmartqa_del"
                       icon="el-icon-delete"
                       size="small"
                       plain
                       @click="handleDel(scope.row)">删除
            </el-button>
          </template>
        </avue-crud>
        <el-dialog :title="dialogTitle" :visible.sync="dialog1Visible" width="50%">
<!--          {{ objData }}-->
          <el-form label-width="100px">
            <el-form-item label="关键词">
              <el-input placeholder="请输入内容" v-model="objData.keyword" clearable></el-input>
            </el-form-item>
            <el-form-item label="回复消息">
              <WxSmartQA
                :objData="objData"
                :typeList="typeList"
                :handleType="handleType"
                v-if="hackResetWxSmartQA"
                ref="wxsmartqa"
              >
              </WxSmartQA>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
          <el-button @click="dialog1Visible = false">取 消</el-button>
          <el-button v-if="permissions.mp_wxsmartqa_add" type="primary" @click="handleSubmit">确 定</el-button>
        </span>
        </el-dialog>
      </el-col>
    </el-row>
  </basic-container>
</template>

<script>
  import { addMessage, getPage, delObj, updateMessage } from '@/api/mp/wxsmartqa'
  import { tableWxSmartQA } from '@/const/crud/mp/wxsmartqa'
  import WxSmartQA from '@/components/wechat/WxSmartQA'
  import { mapGetters } from 'vuex'

  export default {
    name: 'wxsmartqa',
    components: {
      WxSmartQA
    },
    data() {
      return {
        tableData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20, // 每页显示多少条
          ascs: [],//升序字段
          descs: []//降序字段
        },
        paramsSearch: {},
        tableLoading: false,
        tableOption: tableWxSmartQA,
        dialog1Visible: false,
        objData: {
          keyword: '', // 关键字
          type: 'text',    // 消息类型（1：文字，2：图片，3：视频，4：图文消息）
          enableFlag: 1,   // 是否生效（0：未生效，1：生效）
          mediaList: [{
            mediaType: 0, // 素材类型（0：文字，1：图片，2：视频）
            content: '',   // 内容
          }] // 微信自动回复消息素材
        },
        typeList: ['text', 'image', 'video', 'news'], // 支持的回复消息类型
        handleType: null,
        hackResetWxSmartQA: false,
        currentEditId: '' // 当前编辑项的id
      }
    },
    created() {
      this.getPage(this.page)
    },
    watch: {
      'objData.type': function (newVal) { // 根据回复消息类型初始化数据格式
        if (newVal === 'text') {
          this.objData = {
            keyword: '',
            type: 'text',
            enableFlag: 1,
            mediaList: [{
              mediaType: 0,
              content: ''
            }]
          }
        } else if (newVal === 'image') {
          this.objData = {
            keyword: '',
            type: 'image',
            enableFlag: 1,
            mediaList: [{
              mediaType: 1,
              wxMediaId: '',
              url: ''
            }]
          }
        } else if (newVal === 'video') {
          this.objData = {
            keyword: '',
            type: 'video',
            enableFlag: 1,
            mediaList: [{
              mediaType: 2,
              title: '',
              introduction: '',
              wxMediaId: '',
              url: ''
            }]
          }
        } else if (newVal === 'news') {
          this.objData = {
            keyword: '',
            type: 'news',
            enableFlag: 1,
            mediaList: []
          }
        }
      }
    },
    computed: {
      ...mapGetters(['permissions']),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permissions.mp_wxsmartqa_add, false),
          delBtn: this.vaildData(this.permissions.mp_wxsmartqa_del, false),
          editBtn: this.vaildData(this.permissions.mp_wxsmartqa_edit, false)
        };
      },
      dialogTitle() {
        return this.handleType === 'add' ? '新增智能问答' : this.handleType === 'edit' ? '编辑智能问答' : ''
      }
    },
    methods: {
      handleAdd() {
        this.hackResetWxSmartQA = false//销毁组件
        this.$nextTick(() => {
          this.hackResetWxSmartQA = true//重建组件
        })
        this.handleType = 'add'
        this.dialog1Visible = true
        Object.assign(this.$data.objData, this.$options.data().objData)
      },
      handleEdit(row) {
        this.currentEditId = row.id
        this.hackResetWxSmartQA = false//销毁组件
        this.handleType = 'edit'
        this.dialog1Visible = true
        const typeMappingArr = ['text', 'image', 'video', 'news',]
        this.objData.type = typeMappingArr[row.type]
        this.$nextTick(() => {
          this.$set(this.objData, 'keyword', row.keyword)
          if (this.objData.type === 'text') {
            this.$set(this.objData.mediaList[0], 'content', row.mediaList[0]['content'])
          } else if (this.objData.type === 'image') {
            this.$set(this.objData.mediaList[0], 'wxMediaId', row.mediaList[0]['wxMediaId'])
            this.$set(this.objData.mediaList[0], 'url', row.mediaList[0]['url'])
            this.$set(this.objData.mediaList[0], 'name', row.mediaList[0]['name'])
          } else if (this.objData.type === 'video') {
            this.$set(this.objData.mediaList[0], 'wxMediaId', row.mediaList[0]['wxMediaId'])
            this.$set(this.objData.mediaList[0], 'title', row.mediaList[0]['title'])
            this.$set(this.objData.mediaList[0], 'introduction', row.mediaList[0]['introduction'])
            this.$set(this.objData.mediaList[0], 'name', row.mediaList[0]['name'])
            this.$set(this.objData.mediaList[0], 'url', row.mediaList[0]['url'])
          } else if (this.objData.type === 'news') {
            if (row.mediaList && row.mediaList.length > 0) {
              this.objData.mediaList = []
              row.mediaList.forEach(ele => {
                if (ele.mediaType === 0) { // 文本
                  this.objData.mediaList.push({ mediaType: 0, content: ele.content })
                } else if (ele.mediaType === 1) { // 图片
                  this.objData.mediaList.push({ mediaType: 1, wxMediaId: ele.wxMediaId, url: ele.url, name: ele.name })
                }
              })
            }
          }
          this.hackResetWxSmartQA = true//重建组件
        })
      },
      searchChange(params, done) {
        this.paramsSearch = params
        this.page.currentPage = 1
        this.getPage(this.page, params)
        done()
      },
      sortChange(val) {
        let prop = val.prop ? val.prop.replace(/([A-Z])/g, "_$1").toLowerCase() : '';
        if (val.order == 'ascending') {
          this.page.descs = []
          this.page.ascs = prop
        } else if (val.order == 'descending') {
          this.page.ascs = []
          this.page.descs = prop
        } else {
          this.page.ascs = []
          this.page.descs = []
        }
        this.getPage(this.page)
      },
      getPage(page, params) {
        this.tableLoading = true
        getPage(Object.assign({
          current: page.currentPage,
          size: page.pageSize
        }, params, this.paramsSearch)).then(response => {
          this.tableData = response.data.data.records
          this.page.total = response.data.data.total
          this.page.currentPage = page.currentPage
          this.page.pageSize = page.pageSize
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      },
      handleDel: function (row, index) {
        var _this = this
        this.$confirm('是否确认删除此数据', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return delObj(row.id)
        }).then(data => {
          _this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
          this.getPage(this.page)
        }).catch(function (err) {
        })
      },
      handleSubmit() {
        if (this.objData.keyword.trim() === '') return this.$message.warning('请输入关键词！')
        const typeMapping = {
          'text': 0,
          'image': 1,
          'video': 2,
          'news': 3
        }
        const params = Object.assign({}, this.objData)
        params['type'] = typeMapping[params['type']]
        if (this.objData.type === 'image') { // 图片
          const imageList = this.$refs.wxsmartqa.fileList
          if (imageList.length === 0) {
            return this.$message.warning('请选择图片！')
          }
          params['mediaList'][0]['wxMediaId'] = imageList[0]['mediaId']
          params['mediaList'][0]['url'] = imageList[0]['picUrl']
          params['mediaList'][0]['name'] = imageList[0]['name']
        }
        if (this.objData.type === 'news') { // 图文
          const newsList = this.$refs.wxsmartqa.imageTextList
          if (newsList.length === 0) {
            return this.$message.warning('请选择内容！')
          }
          params.mediaList = []
          newsList.forEach(ele => {
            if (ele.type === 'text' && ele.content.trim().length !== 0) {
              params.mediaList.push({ mediaType: 0, content: ele.content })
            }else if (ele.type === 'image' && ele.fileList.length !== 0) {
              params.mediaList.push({ mediaType: 1, wxMediaId: ele.fileList[0].mediaId, url: ele.fileList[0].picUrl, name: ele.fileList[0].name })
            }
          })
        }
        if (this.objData.type === 'video') { // 视频
          const videoList = this.$refs.wxsmartqa.videoFileList
          if (videoList.length === 0) {
            return this.$message.warning('请上传视频！')
          }
          params['mediaList'][0]['wxMediaId'] = videoList[0]['mediaId']
          params['mediaList'][0]['name'] = videoList[0]['name']
          params['mediaList'][0]['url'] = videoList[0]['url']
        }
        if (this.handleType === 'add') {
          addMessage(params).then(data => {
            this.$message.success('添加成功')
            this.getPage(this.page)
            this.dialog1Visible = false
          })
        }
        if (this.handleType === 'edit') {
          params.id = this.currentEditId
          // console.log(params);
          updateMessage(params).then(data => {
            this.$message.success('修改成功')
            this.getPage(this.page)
            this.dialog1Visible = false
          })
        }
      },
      refreshChange() {
        this.getPage(this.page)
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
        this.getPage(this.page)
      },
      currentChange(current) {
        this.page.currentPage = current
        this.getPage(this.page)
      }
    }
  }
</script>
