<template>
  <div class="app-container">
    <el-form ref="addForm" :model="addForm">
      <el-form-item :label-width="formLabelWidth" label="标题 *">
        <el-input v-model="addForm.title"/> <!-- @keyup.delete="getFocus" -->
      </el-form-item>
      <el-form-item :label-width="formLabelWidth" label="权重 *">
        <el-input v-model="addForm.sort"/>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth" label="生效时间 *">
        <el-date-picker
          v-model="addForm.effTime"
          type="date"
          placeholder="选择日期时间"/>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth" label="失效时间 *">
        <el-date-picker
          v-model="addForm.expTime"
          type="date"
          placeholder="选择日期时间"/>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth" label="banner图 *">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          class="avatar-uploader"
          action="http://106.14.20.193:8086/operate-api/uploadimage"
          name="uploadFiles">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth" label="banner位 *">
        <el-select v-model="addForm.bannerPosition" placeholder="请选择位置">
          <!-- <el-option label="请选择位置" value="-1"/> -->
          <el-option
            v-for="item in bannerPositionArr"
            :key="item.id"
            :label="item.value"
            :value="item.id"
          />
          <!-- <el-option v-for="item in bannerPositionArr" label="item.value" value="item.id"/> -->
        </el-select>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth" label="投放社区 *">
        <el-select v-model="addForm.communityId" placeholder="请选择社区">
          <!-- <el-option label="请选择社区" value="-1"/> -->
          <el-option v-for="item in communityList" :key="item.id" :value="item.id" :label="item.communityName"/>
          <!-- <el-option label="区域一" value="shanghai"/> -->
        </el-select>
      </el-form-item>
      <!-- <el-form-item :label-width="formLabelWidth" label="跳转描述">
        <el-input
          v-model="addForm.bannerDescription"
          :autosize="{ minRows: 2, maxRows: 4}"
          type="textarea"
          placeholder="请输入跳转描述"/>
      </el-form-item> -->
      <el-form-item :label-width="formLabelWidth" label="banner跳转 *">
        <el-radio v-model="addForm.bannerType" label="1" @change="showContent">外部超链接</el-radio>
        <el-radio v-model="addForm.bannerType" label="2" @change="showContent">自写文章</el-radio>
      </el-form-item>
      <el-form-item v-if="showURLVisible" :label-width="formLabelWidth" label="跳转链接 *">
        <el-input v-model="addForm.externalLink" placeholder="跳转链接"/>
      </el-form-item>
      <div v-if="showContentVisible">
        <el-form-item :label-width="formLabelWidth" label="内容标题 *">
          <el-input v-model="addForm.bannerTitle" placeholder="内容标题"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="内容详情 *">
          <!-- <el-input v-model="addForm.bannerContent" placeholder="内容详情"/> -->
          <div id="father">
            <wangeditor @wangeditorEvent="wangeditorValue"/>
          </div>
        </el-form-item>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogForm('0')">取 消</el-button>
      <el-button type="primary" @click="dialogForm('1')">确 定</el-button>
    </div>
  </div>
</template>

<script>
// import { updateArticle, createBanner } from '@/api/banner' // getBanner
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: 'AddBanner',
  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,
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      communityQuery: {
        pageNum: 1,
        pageSize: 300,
        communityId: undefined,
        communityName: undefined,
        provinceId: undefined,
        cityId: undefined,
        districtId: undefined
      },
      imageUrl: '', // 图片预览
      listQuery: [], // 接收查询参数,在返回给首页
      addForm: {
        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' },
        { id: 3, value: '广告banner' }
      ]
    }
  },
  computed: {
    ...mapState('community', {
      communityList: s => s.list
    })
  },
  created() {
    this.listQuery = this.$route.query.listQuery
    this.getCommuniryList()
  },
  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.addForm.title = ''
      this.addForm.sort = '1'
      this.addForm.bannerCover = ''
      this.addForm.bannerPosition = '-1'
      this.addForm.communityId = '-1'
      this.addForm.effTime = ''
      this.addForm.expTime = ''
      this.addForm.bannerType = '1'
      this.addForm.externalLink = ''
      this.addForm.bannerTitle = ''
      this.addForm.bannerContent = ''
      this.addForm.bannerDescription = ''
    },
    wangeditorValue(value) {
      console.log('富文本内容:' + value)
      this.addForm.bannerContent = value // 在这里接受子组件传过来的参数，赋值给data里的参数
    },
    dialogForm(isVaule) {
      if (isVaule === '0') {
        this.$router.push({ name: 'banner-index', query: { listQuery: this.listQuery }})
      } else {
        this.createData()
        // console.log('添加banner的数据: ', this.addForm)
      }
    },
    showContent() {
      if (this.addForm.bannerType === '1') {
        this.showContentVisible = false
        this.showURLVisible = true
      } else {
        this.showContentVisible = true
        this.showURLVisible = false
      }
    },
    createData() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.$store.dispatch('AddBanner', this.addForm).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'
              })
            }
          })
        }
      })
    },
    getCommuniryList() {
      this.listLoading = true
      this.FetchCommunityList(this.communityQuery).then(() => {
        this.listLoading = false
      }).catch(() => {
        this.loading = false
        console.log('get list error')
      })
    },
    getFocus(e) {
      e.focus()
    }
  }
}
</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>

