<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        placeholder="归属系统"
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="item in permissionsSysOriginPlatforms"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
          <span style="float: left;">
            <sys-origin-icon
              :icon="item.value"
              :desc="item.value"
            /></span>
          <span style="float: left;margin-left:10px">{{ item.label }}</span>
        </el-option>
      </el-select>
      <el-select
        v-model="listQuery.shelfStatus"
        placeholder="状态"
        style="width: 120px"
        class="filter-item"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="(item, index) in productConfigShowcase"
          :key="index"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <el-select
        v-model="listQuery.announcement"
        placeholder="发布状态"
        style="width: 120px"
        class="filter-item"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="(item, index) in announcementArray"
          :key="index"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <div class="filter-item">
        <el-date-picker
          v-model="rangeDate"
          value-format="timestamp"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="创建日期开始"
          end-placeholder="创建日期结束"
        />
      </div>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        新增
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column label="封面" align="center">
        <template slot-scope="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="scope.row.cover"
            :preview-src-list="[scope.row.cover]"
          />
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" align="center" />
      <el-table-column label="来源系统" align="center">
        <template slot-scope="scope">
          <sys-origin-icon
            :icon="scope.row.sysOrigin"
            :desc="scope.row.sysOrigin"
          />
        </template>
      </el-table-column>
      <el-table-column prop="link" label="链接" align="center" />
      <el-table-column prop="description" label="描述" align="center" />
      <el-table-column prop="announcement" label="发布状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.announcement"
            @change="handleSwitchAnnouncementChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="announcementTime"
        label="发布时间"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.announcementTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column prop="shelfStatus" label="上架状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.shelfStatus"
            @change="handleSwitchShelfStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="200">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click.native="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            type="text"
            @click.native="handlDel(scope.row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.cursor"
      :limit.sync="listQuery.limit"
      @pagination="renderData"
    />
    <el-dialog
      :title="textOptTitle"
      :visible.sync="formVisible"
      :before-close="handleClose"
      width="450px"
    >
      <div v-loading="submitLoading">
        <el-form ref="form" :model="form" :rules="rules" label-width="110px">
          <el-form-item label="封面">
            <el-upload
              class="upload-demo"
              action=""
              :http-request="httpRequest"
              :show-file-list="false"
              accept="image/png,image/jpg,image/jpeg"
            >
              <el-image
                v-if="form.cover"
                :src="form.cover"
                fit="fill"
                style="width: 50px; height: 50px"
              />
              <el-button
                v-loading="uploadLoading"
                size="small"
                type="primary"
              >点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="系统" prop="sysOrigin">
            <el-select
              v-model="form.sysOrigin"
              placeholder="系统"
              style="width:100%;"
              class="filter-item"
            >
              <el-option
                v-for="item in permissionsSysOriginPlatforms"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <span style="float: left;">
                  <sys-origin-icon
                    :icon="item.value"
                    :desc="item.value"
                  /></span>
                <span style="float: left;margin-left:10px">{{
                  item.label
                }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标题" prop="title">
            <el-input v-model.trim="form.title" type="text" />
          </el-form-item>
          <el-form-item label="链接">
            <el-input v-model.trim="form.link" type="text" />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model.trim="form.description"
              type="textarea"
              :rows="8"
              maxlength="300"
              @input="descInput"
            />
            <span
              class="numberV"
              style="position: absolute; right: 10px;bottom: 0;"
            >{{ txtVal }}/300</span>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm()">保存</el-button>
            <el-button @click="handleClose()">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  noticeMessageTable,
  updateNoticeMessage,
  deleteNoticeMessage,
  addNoticeMessage,
  changeAnnouncementStatus,
  changeShelfStatus
} from '@/api/notice-message'
import Pagination from '@/components/Pagination'
import { getAddressUrl } from '@/api/oss'
import { productConfigShowcase, announcementArray } from '@/constant/type'
import { pickerOptions } from '@/constant/el-const'
import { mapGetters } from 'vuex'
function getFormData() {
  return {
    id: '',
    cover: '',
    sysOrigin: '',
    title: '',
    link: '',
    description: ''
  }
}
export default {
  components: { Pagination },
  data() {
    return {
      announcementArray,
      productConfigShowcase,
      pickerOptions,
      txtVal: 0,
      activeGiftId: '',
      pushTextHistoryLoading: false,
      pushTextHistoryVisible: false,
      pushTextHistory: [],
      list: [],
      delarr: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        sysOrigin: '',
        startTime: '',
        endTime: ''
      },
      formVisible: false,
      textOptTitle: '',
      form: getFormData(),
      submitLoading: false,
      rules: {
        sysOrigin: [{ required: true, message: '请选择系统', trigger: 'blur' }],
        title: [{ required: true, message: '请填写标题', trigger: 'blur' }],
        description: [
          { required: true, message: '请填写描述', trigger: 'blur' }
        ]
      },
      rangeDate: '',
      listLoading: true,
      uploadLoading: false
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatforms'])
  },
  watch: {
    rangeDate: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.listQuery.startTime = newVal[0]
          this.listQuery.endTime = newVal[1]
          return
        }
        this.listQuery.startTime = ''
        this.listQuery.endTime = ''
      }
    }
  },
  created() {
    const that = this
    const querySystem = this.permissionsSysOriginPlatforms[0]
    if (!querySystem) {
      return
    }
    that.listQuery.sysOrigin = querySystem.value
    that.renderData()
  },
  methods: {
    renderData() {
      const that = this
      that.listLoading = true
      noticeMessageTable(that.listQuery).then(res => {
        const { body } = res
        that.total = body.total || 0
        that.list = body.records
        that.listLoading = false
      })
    },
    handleSearch() {
      this.renderData()
    },
    handleSwitchAnnouncementChange(row) {
      const that = this
      if (!row.announcement) {
        this.$message({
          message: '不可以取消发布',
          type: 'error'
        })
        row.announcement = true
        return
      }
      that
        .$confirm('确认发布公告吗？发布后不可以取消！', '提示', {
          type: 'warning'
        })
        .then(() => {
          that.listLoading = true
          changeAnnouncementStatus(row.id)
            .then(res => {
              this.listLoading = false
              this.$message({
                message: '发布成功',
                type: 'success'
              })
              this.renderData()
            })
            .catch(() => {})
        })
        .catch(() => {
          if (!row.announcement) {
            row.announcement = true
          } else if (row.announcement) {
            row.announcement = false
          }
        })
    },
    handleSwitchShelfStatusChange(row) {
      changeShelfStatus(row.id, row.shelfStatus)
        .then(res => {
          this.$message({
            message: row.shelfStatus ? '上架 成功' : '下架 成功',
            type: 'success'
          })
        })
        .catch(er => {
          if (row.status === 0) {
            row.status = 1
          } else if (row.status === 1) {
            row.status = 0
          }
        })
    },
    renderDataSuccess() {
      this.$message({
        message: 'Successful',
        type: 'success'
      })
      this.renderData()
    },
    queryUserDetails(row) {
      this.userDeatilsDrawer = true
      this.thatSelectedUserId = row.id
    },
    submitForm() {
      const that = this
      that.$refs.form.validate(valid => {
        if (valid) {
          that.submitLoading = true
          if (that.form.id) {
            updateNoticeMessage(that.form)
              .then(res => {
                that.submitLoading = false
                that.formVisible = false
                that.form = getFormData()
                that.renderData()
              })
              .catch(er => {
                that.submitLoading = false
                that.$emit('fial', er)
              })
            return
          }
          addNoticeMessage(that.form)
            .then(res => {
              that.submitLoading = false
              that.formVisible = false
              that.form = getFormData()
              that.renderData()
            })
            .catch(er => {
              that.submitLoading = false
              console.error(er)
              that.$emit('fial', er)
            })
        } else {
          console.error('error submit!!')
          return false
        }
      })
    },
    // 删除
    handlDel(id) {
      this.$confirm('确认删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.listLoading = true
          deleteNoticeMessage(id).then(res => {
            this.listLoading = false
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.renderData()
          })
        })
        .catch(() => {})
    },
    handleClose() {
      this.formVisible = false
    },
    descInput() {
      this.txtVal = this.form.description.length
    },
    httpRequest(file) {
      const that = this
      that.uploadLoading = true
      this.$simpleUploadFlie(file)
        .then(res => {
          that.uploadLoading = false
          getAddressUrl(res.name).then(result => {
            that.form.cover = result.body
          })
        })
        .catch(er => {
          that.uploadLoading = false
        })
    },
    handleCreate() {
      this.formVisible = true
      this.textOptTitle = '添加'
      this.form = getFormData()
    },
    handleUpdate(row) {
      this.textOptTitle = '修改'
      this.formVisible = true
      this.form = Object.assign(this.form, row)
    }
  }
}
</script>
