<template>
  <div class="layout-no-flex">
    <el-toolbar>
      <el-button @click="goBack" type="primary" size="medium" round class="shadow-primary"><i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <el-button type="button" class="el-button el-button--default save" :priv="isEdit ? 'Weixin.Manage.Menu_Edit':'Weixin.Manage.Menu_Add'" @click="save" v-loading="saveLoading"><span><i class="fa fa-save"></i>保存</span></el-button>
    </el-toolbar>

    <!-- start -->
    <el-form :model="tmpMenu" :rules="menuCheck" ref="menuForm" label-width="130px" v-loading="dialogLoading" style="margin:auto;width:550px;">
      <!--搜索框-->
      <el-form-item label="菜单名称：" prop="name" :verify="['NotNull']">
        <el-input v-model="tmpMenu.name" style="width:330px;"></el-input>
      </el-form-item>
      <!--下拉框 父级菜单-->
      <el-form-item label="父菜单：" prop="parentID" placeholder="请选择">
        <el-select v-model="tmpMenu.parentID" clearable>
          <el-option v-for=" item in firstLevelMenu" :key="item.ID" :label="item.name" :value="item.ID"></el-option>
        </el-select>
      </el-form-item>
      <!--下拉框 菜单类型-->
      <el-form-item label="菜单类型：" prop="type" :verify="['NotNull']">
        <el-select v-model="tmpMenu.type">
          <el-option v-for="item in menuTypeList" :key="item.key" :label="item.value" :value="item.key"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="事件Key：" v-if="tmpMenu.type !== 'view'">
        <el-input v-model="tmpMenu.menuKey" placeholder="请输入事件Key" style="width:330px;"></el-input>
      </el-form-item>
      <!-- 素材 -->
      <!--图文需要拿第一个栏目的数据,暂时未完成-->
      <el-form-item label="素材：" v-if="tmpMenu.type !== 'view'">
        <div style="width:330px;">
          <el-tabs type="border-card" v-model="activeTab">
            <el-tab-pane name="articles">
              <span slot="label">
                <i class="fa fa-file-image-o" aria-hidden="true"></i>图文消息</span>
              <div class="media-item" v-if="tmpMenu.mediaID">
                <el-card class="table-card">
                  <div v-for="val in mediaData.articles" :key="val.ID">
                    <div v-if="val.index === 0" class="appmsg-title">
                      <a href="javascript:void(0);" onclick="return false;" target="_blank">
                        <h4 class="appmsg_title">{{val.title}}</h4>
                      </a>
                      <img :src="mediaData.prefix + val.logoFile" onerror="this.src='@static/assets/images/picture.png'" width="208" height="165px"
                      />
                    </div>
                    <div v-else class="appmsg-div">
                      <el-row>
                        <el-col :span="16">
                          <a onclick="return false;" href="javascript:void(0);" target="_blank">{{val.title}}</a>
                        </el-col>
                        <el-col :span="8">
                          <img :src="mediaData.prefix + val.logoFile" onerror="this.src='@static/assets/images/picture.png'" width="78" height="78px"
                          />
                        </el-col>
                      </el-row>
                    </div>
                  </div>
                </el-card>
                <div style="text-align:right; font-size:12px;">
                  <a href="javascript:void(0);" @click="deleteMedia">删除</a>
                </div>
              </div>
              <div v-else class="select-div">
                <a href="javascript:void(0);" @click="mediaSelectModal = true">从素材库中选择</a>
              </div>
            </el-tab-pane>
            <el-tab-pane name="text">
              <span slot="label">
                <i class="fa fa-pencil" aria-hidden="true"></i>文字</span>
              <el-input type="textarea" :rows="8" placeholder="请输入内容" v-model="tmpMenu.memo"></el-input>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-form-item>
      <!--暂时未链接按钮-->
      <el-form-item label="URL：" v-if="tmpMenu.type === 'view'" prop="URL">
        <el-input v-model="tmpMenu.linkName" disabled style="width:80%;"></el-input>
        <div>
          <el-button @click="selectContent">链接到内容</el-button>
          <el-button @click="selectCatalog">链接到栏目</el-button>
          <el-button @click="bindUser">微信用户绑定</el-button>
          <el-button @click="contribute">我要投稿</el-button>
          <el-button @click="myContributes">我的稿件</el-button>
          <el-button @click="checkContent">内容审核</el-button>
          <el-button @click="inputUrl">外部地址</el-button>
        </div>
        <el-input v-model="tmpMenu.URL" style="width:80%;"></el-input>
      </el-form-item>
    </el-form>
    <!-- end     -->

    <el-dialog title="外部地址" :visible.sync="inputURLModal" class="input-url-dialog">
      <el-form label-width="100px;">
        <el-form-item label="地址：" :rules="{ required: true, message: '不能为空', trigger: 'blur' }">
          <el-input v-model="inputURL" style="width:80%"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="inputURLModal = false">取 消</el-button>
        <el-button type="primary" @click="confirmURL">确定</el-button>
      </div>
    </el-dialog>

    <content-selector title="选择内容记录" :show.sync="contentSelectorModal" @callback="contentSelectorCallback"></content-selector>

    <media-select-dialog :show.sync="mediaSelectModal" @callback="mediaSelectCallback"></media-select-dialog>

    <catalog-selector-dialog :show.sync="catalogSelectorModal" input-type="radio" title="选择栏目" @callback="catalogSelectorCallback"></catalog-selector-dialog>

  </div>
</template>
<script>
import ContentSelector from '@src/components/contentComponent/ContentSelector.vue'
import catalogSelector from '../contentcore/components/CatalogSelector.vue'
import mediaSelectDialog from './mediaSelectDialog.vue'
import util from '@src/common/util.js'

export default {
  components: {
    'media-select-dialog': mediaSelectDialog,
    'catalog-selector-dialog': catalogSelector,
    'content-selector': ContentSelector
  },
  props: {
    ID: {
      default: 0
    }
  },
  data() {
    var checkURL = (rule, value, callback) => {
      if (this.tmpMenu.type === 'view' && !value) {
        return callback(new Error('不能为空'))
      } else {
        callback()
      }
    }
    return {
      isEdit: false,
      dialogLoading: false,
      saveLoading: false,
      contentSelectorModal: false,
      catalogSelectorModal: false,
      tmpMenu: {
        URL: null,
        linkName: null,
        mediaID: null,
        mediaType: null,
        menuKey: null,
        name: null,
        parentID: null,
        type: null,
        siteID: 0
      },
      tmpMenuBak: {},
      menuCheck: {
        URL: [{ required: true, validator: checkURL, trigger: 'blur' }]
      },
      firstLevelMenu: [],
      menuTypeList: [],
      activeTab: 'articles',
      mediaSelectModal: false,
      mediaData: {},
      inputURL: '',
      inputURLModal: false
    }
  },
  mounted() {
    this.isEdit = this.ID !== 'new'
    this.loadData()
  },
  watch: {
    'tmpMenu.mediaID': {
      handler: async function(val) {
        if (!val) {
          this.mediaData = []
          return
        }
        let res = await axios.get('/ui/wechat/medias/init', {
          params: {
            ID: this.tmpMenu.mediaID
          }
        })
        this.mediaData = res.data.data
      },
      deep: true
    }
  },
  created() {
    Object.assign(this.tmpMenuBak, this.tmpMenu)
  },
  methods: {
    goBack() {
      this.$router.back()
    },

    async loadData() {
      this.saveLoading = false
      this.dialogLoading = true
      this.activeTab = 'articles'
      let getFirstLevelMenu = ''
      let menuType = ''
      try {
        getFirstLevelMenu = await axios.get('/ui/wechatmenu/getfirstlevelmenu', {
          params: {
            weiXinID: this.$route.params.weiXinID
          }
        })
        menuType = await axios.get('/ui/wechatmenu/menutype')
      } catch (e) {
        util.showErrorMessageBox(e)
        this.dialogLoading = false
        return
      }
      this.firstLevelMenu = getFirstLevelMenu.data.data
      this.menuTypeList = menuType.data.data
      if (this.isEdit) {
        let init
        try {
          init = await axios.get('/ui/wechatmenu/init', {
            params: {
              ID: this.isEdit ? this.ID : null
            }
          })
        } catch (e) {
          util.showErrorMessageBox(e)
          this.dialogLoading = false
          return
        }
        this.tmpMenu = init.data.data
        if (!this.tmpMenu.parentID) {
          this.tmpMenu.parentID = null
        }
      } else {
        Object.assign(this.tmpMenu, this.tmpMenuBak)
      }
      this.dialogLoading = false
    },

    selectContent() {
      this.contentSelectorModal = true
    },

    selectCatalog() {
      this.catalogSelectorModal = true
    },

    contentSelectorCallback(row) {
      if (!row.ID) {
        return
      }
      this.tmpMenu.linkName = row.contentTypeID + '：' + row.title
      this.tmpMenu.URL = row.link
    },

    catalogSelectorCallback(row) {
      this.tmpMenu.linkName = '栏目：' + row.name
      this.tmpMenu.URL = row.link
    },

    bindUser() {
      this.tmpMenu.linkName = '微信用户绑定'
      this.tmpMenu.URL = '{FrontAppContext}api/wechat/users/bindinit?maid={MEDIA_ACCOUNT_ID}'
    },
    myContributes() {
      this.tmpMenu.linkName = '我的稿件'
      this.tmpMenu.URL = '{FrontAppContext}api/wechat/contributes/me?maid={MEDIA_ACCOUNT_ID}'
    },
    contribute() {
      this.tmpMenu.linkName = '我要投稿'
      this.tmpMenu.URL = '{FrontAppContext}api/wechat/contributes/init?maid={MEDIA_ACCOUNT_ID}'
    },

    inputUrl() {
      this.inputURL = 'http://'
      this.inputURLModal = true
    },

    confirmURL() {
      this.tmpMenu.linkName = this.inputURL
      this.tmpMenu.URL = this.inputURL
      this.inputURLModal = false
    },

    checkContent() {
      this.tmpMenu.linkName = '内容审核'
      this.tmpMenu.URL = '{FrontAppContext}api/wechat/pendingcontributes?maid={MEDIA_ACCOUNT_ID}'
    },

    mediaSelectCallback(ID) {
      Vue.delete(this.tmpMenu, 'mediaID')
      Vue.set(this.tmpMenu, 'mediaID', ID)
    },

    deleteMedia() {
      Vue.delete(this.tmpMenu, 'mediaID')
      Vue.set(this.tmpMenu, null)
    },

    async save() {
      this.saveLoading = true
      try {
        await util.validateForm(this.$refs['menuForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        this.saveLoading = false
        return
      }

      let firstLevelNum = this.firstLevelMenu.length
      if (!this.tmpMenu.parentID && firstLevelNum >= 3) {
        this.$alert('最多只能包括三个一级菜单 ！', '系统提示')
        return
      }

      let res
      try {
        this.tmpMenu.weiXinID = this.$route.params.weiXinID
        if (this.isEdit) {
          res = await axios.put('/ui/wechatmenu/edit', this.tmpMenu)
        } else {
          res = await axios.post('/ui/wechatmenu', this.tmpMenu)
        }
      } catch (e) {
        util.showErrorMessageBox(e)
        this.saveLoading = false
        return
      }
      this.saveLoading = false
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.$emit('callback')
        this.goBack()
      }
    }
  }
}
</script>
<style>
/* 在一般情况下dialog宽为600像素，在逻辑分辨率480像素以下dialog宽为96% */

.menu-dialog .el-dialog {
  width: 600px;
}

@media (max-width: 480px) {
  .menu-dialog .el-dialog {
    width: 96%;
  }
}

.input-url-dialog .el-dialog {
  width: 400px;
}

@media (max-width: 480px) {
  .input-url-dialog .el-dialog {
    width: 86%;
  }
}
</style>
<style scoped>
.el-button + .el-button {
  margin-left: 5px;
}

.select-div {
  width: 100%;
  height: 180px;
  border: 2px dashed #ccc;
  text-align: center;
  padding-top: 80px;
}

.select-div a {
  color: #ccc;
  font-weight: 400;
}

.select-div a:hover {
  color: #777;
  text-decoration: underline;
}

.media-item {
  max-width: 278px;
  margin: 10px 0 0 10px;
  float: left;
}

.appmsg-title {
  position: relative;
  margin: 0 15px 15px 15px;
}

.appmsg-title a {
  font-size: 16px;
  padding: 0px 10px 0 0;
  display: block;
  color: #8d8d8d;
  line-height: 24px;
}

.appmsg_title {
  background: rgba(0, 0, 0, 0.6) !important;
  position: absolute;
  bottom: 10px;
  width: 100%;
  padding: 15px 8px 10px 8px;
}

.appmsg-div {
  padding: 15px;
  border-top: 1px solid #ccc;
}

.appmsg-div a {
  font-size: 16px;
  padding: 24px 10px 0 0;
  display: block;
  color: #8d8d8d;
}

.appmsg-div a:hover {
  color: black;
  text-decoration: none;
}

.appmsg-div img {
  float: right;
}
</style>
