<template>
  <div id="app" class="app-container">
    <el-form ref="form" :model="form">
      <el-form-item :label-width="formLabelWidth" label="标题">
        <span>{{ form.title }}</span>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth" label="权重">
        <span>{{ form.sort }}</span>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth" label="生效时间">
        <span>{{ formatDate(form.effTime) }}</span>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth" label="失效时间">
        <span>{{ formatDate(form.expTime) }}</span>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth" label="banner图">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <span v-else >无Banner图</span>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth" label="banner位">
          <span>{{ getBanner(form.bannerPosition) }}</span>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth" label="投放社区">
        <span>{{ getCommunity(form.communityId) }}</span>
      </el-form-item>
      <!-- <el-form-item :label-width="formLabelWidth" label="跳转描述">
        <el-input
          v-model="form.bannerDescription"
          :autosize="{ minRows: 2, maxRows: 4}"
          type="textarea"
          placeholder="请输入跳转描述"/>
      </el-form-item> -->
      <el-form-item :label-width="formLabelWidth" label="banner跳转">
        <span v-show="showURLVisible" label="1" @change="showContent">外部超链接</span>
        <span v-show="showContentVisible" label="2" @change="showContent">自写文章</span>
      </el-form-item>
      <el-form-item v-if="showURLVisible" :label-width="formLabelWidth" label="跳转链接">
        <span><a :href="form.externalLink" style="color: #409EFF;cursor: pointer" target="_blank">{{ form.externalLink }}</a></span>
      </el-form-item>
      <div v-if="showContentVisible">
        <el-form-item :label-width="formLabelWidth" label="内容标题">
          <span>{{ form.bannerTitle }}</span>
        </el-form-item>
        <!-- <el-form-item :label-width="formLabelWidth" label="内容详情">
          <el-input v-model="form.bannerContent" placeholder="内容详情"/>
        </el-form-item> -->
        <el-form-item :label-width="formLabelWidth" label="内容详情" id="bannerContent">
          <div id="father" v-html="this.form.bannerContent"></div>
        </el-form-item>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="updateBanner" type="primary">修 改</el-button>
      <el-button @click="dialogForm('0')">返 回</el-button>
    </div>
  </div>
</template>

<script>
// import { updateArticle, createBanner } from '@/api/banner' // Banner
import { mapState, mapActions } from 'vuex'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import Wangeditor from '@/components/Wangeditor'
const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]
// arr to obj ,such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})
export default {
  name: 'UpdateBanner',
  components: { Pagination, Wangeditor },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      imageUrl: '', // 图片预览
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      communityQuery: {
        pageNum: 1,
        pageSize: 300,
        communityId: undefined,
        communityName: undefined,
        provinceId: undefined,
        cityId: undefined,
        districtId: undefined
      },
      listQuery: [],
      form: {
        id: '',
        title: '',
        sort: '1',
        bannerCover: '',
        bannerPosition: '',
        communityId: '',
        effTime: '',
        expTime: '',
        bannerType: '1',
        externalLink: '',
        bannerTitle: '',
        bannerContent: '',
        bannerDescription: ''
      },
      dialogStatus: '',
      downloadLoading: false,
      formLabelWidth: '120px',
      showContentVisible: false,
      showURLVisible: true,
      bannerPositionArr: [
        { id: 1, value: '首页banner' },
        { id: 2, value: '服务banner' }
      ]
    }
  },
  computed: {
    ...mapState('community', {
      communityList: s => s.list
    })
  },
  created() {
    this.getCommuniryList()
    this.getByBannerId(this.$route.params.id)
    this.listQuery = this.$route.params.listQuery
  },
  mounted() {
    window.addEventListener('beforeunload', e => {
      this.$router.push({ name: 'banner-index', params: { listQuery: this.listQuery }})
    })
  },
  methods: {
    ...mapActions('community', [
      'FetchCommunityList',
      'CreateCommunity',
      'UpdateCommunity'
    ]),
    handleAvatarSuccess(res, file) { // 上传成功回调
      this.imageUrl = URL.createObjectURL(file.raw)
      this.addForm.bannerCover = res.data[0]
    },
    dialogAddForm() {
      this.dialogFormVisible = true
      this.form.title = ''
      this.form.sort = '1'
      this.form.bannerCover = ''
      this.form.bannerPosition = '-1'
      this.form.communityId = '-1'
      this.form.effTime = ''
      this.form.expTime = ''
      this.form.bannerType = '1'
      this.form.externalLink = ''
      this.form.bannerTitle = ''
      this.form.bannerContent = ''
      this.form.bannerDescription = ''
    },
    wangeditorValue(value){
      console.log("富文本内容:" + value)
      this.form.bannerContent = value      //在这里接受子组件传过来的参数，赋值给data里的参数
    },
    dialogForm(isVaule) {
      if (isVaule === '0') {
        this.$router.push({ name: 'banner-index', params: { listQuery: this.listQuery }})
      } else {
        this.updateData()
      }
    },
    showContent() {
      if (this.form.bannerType === '1') {
        this.showContentVisible = false
        this.showURLVisible = true
      } else {
        this.showContentVisible = true
        this.showURLVisible = false
      }
    },
    updateBanner() {
      this.$router.push({ name: 'banner-edi', params: { id: this.form.id, listQuery: this.listQuery }})
    },
    updateData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$store.dispatch('UpdateBanner', this.form).then((res) => {
            if (res.code === '0') {
              this.$message({
                message: res.message,
                type: 'success'
              })
              this.$router.push({ name: 'banner-index', params: { listQuery: this.listQuery }})
            } else {
              this.$message({
                message: res.message,
                type: 'warning'
              })
            }
          })
        }
      })
    },
    padDate(value) {
      value = value < 10 ? '0' + value : value
      return value
    },
    formatDate(val) {
      var value = new Date(val)
      var year = value.getFullYear()
      var month = this.padDate(value.getMonth() + 1)
      var day = this.padDate(value.getDate())
      var hour = this.padDate(value.getHours())
      var minutes = this.padDate(value.getMinutes())
      var seconds = this.padDate(value.getSeconds())
      // return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds
      return year + '-' + month + '-' + day
    },
    getByBannerId(bannerId) {
      this.$store.dispatch('GetByBannerId', bannerId).then(res => {
        this.form = res
        this.imageUrl = this.form.bannerCover
        // this.catchData(this.form.bannerContent)
        this.showContent()
      })
    },
    getCommuniryList() {
      this.listLoading = true
      this.FetchCommunityList(this.communityQuery).then(() => {
        this.listLoading = false
      }).catch(() => {
        this.loading = false
        console.log('get list error')
      })
    },
    getBanner(bannerId) {
      const bannerPosition = this.bannerPositionArr
      for (const i in bannerPosition) {
        if (bannerPosition[i].id === bannerId) {
          return bannerPosition[i].value
        }
      }
    },
    getCommunity(communityId) {
      const community = this.communityList
      for (const i in community) {
        if (community[i].id === communityId) {
          return community[i].communityName
        }
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  width: 50%;
  margin: auto;
}
.dialog-footer {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>


