<template>
  <div class="article page_container">
    <table-list v-bind="tableOptions" ref="tableList" @selection-change="handleSelectionChange">
      <template #header-aside>
        <el-button type="primary" size="mini" @click="handleCreate" v-if="hasCreate">新建文章</el-button>
      </template>
      <el-tabs v-model="activeName" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="全部" name="0"></el-tab-pane>
        <el-tab-pane label="待审核" name="1"></el-tab-pane>
        <el-tab-pane label="已驳回" name="3"></el-tab-pane>
        <el-tab-pane label="已通过" name="2"></el-tab-pane>
      </el-tabs>
      <!-- 图片 -->
      <template v-slot:image="{ row }">
        <img :src="row.web_img_uri || row.mobile_terminal_img_uri" height="40" />
      </template>
      <template v-slot:table-id="{ row }">
        <span class="details-handle" @click="handleDetails(row)">{{ row.id }}</span>
      </template>
      <!-- 审核状态 -->
      <template v-slot:review-status="{ row }">
        {{ auditStatusText(row.audit_status) }}
      </template>
      <!-- 发布状态 -->
      <template v-slot:publish-status="{ row }">
        <el-switch
          :active-value="1"
          :inactive-value="0"
          v-model="row.is_publish"
          @change="handlePublish(row)"
          :disabled="!hasUpdate || row.audit_status !== 2 || isExpired(row.end_time)">
        ></el-switch>
      </template>
      <!-- 置顶状态 -->
      <template v-slot:top-status="{ row }">
        <div class="table-col-top">
          <el-switch :active-value="1" :inactive-value="0" v-model="row.is_top" @change="handleTop(row)" :disabled="!hasUpdate || row.audit_status !== 2 || isExpired(row.end_time)">></el-switch>
          <el-select v-model="row.weight" placeholder="权重" size="mini" :disabled="!hasUpdate || row.audit_status !== 2 || isExpired(row.end_time)" @change="handleWeight(row)">
            <el-option v-for="item in 10" :label="item" :value="item" :key="item"></el-option>
          </el-select>
        </div>
      </template>
      <!-- 推荐状态 -->
      <template v-slot:recommend-status="{ row }">
        <el-switch
          :active-value="1"
          :inactive-value="0"
          v-model="row.is_recommend"
          @change="handleRecommend(row)"
           :disabled="!hasUpdate || row.audit_status !== 2 || isExpired(row.end_time)">
        ></el-switch>
      </template>

      <template #footer>
        <el-button size="mini" :disabled="!multipleSelection.length" @click="handleRemove" v-if="hasDelete"
          >删除</el-button
        >
      </template>
    </table-list>
    <el-drawer :visible.sync="drawerVisible" size="1100px" :destroy-on-close="true" ref="articleDrawer">
      <template slot="title">
        <h5>
          {{ drawTitle }}
          <el-button
            v-if="drawFormOptions.type !== 'create' && hasUpdate"
            type="primary"
            @click="drawFormOptions.type = 'edit'"
            size="mini"
            style="float: right; margin-right: 30px"
            >编辑</el-button
          >
        </h5>
      </template>
      <drawer-form :options="drawFormOptions" @drawFormSubmit="HandleDrawFormSubmit" @drawFormClose="$refs.articleDrawer.closeDrawer()">
        <template #form-item-review>
          <el-form-item>
            <el-button type="primary" @click="dialogVisible = true" size="small">审核</el-button>
          </el-form-item>
        </template>
      </drawer-form>
      <el-dialog title="审核文章" :visible.sync="dialogVisible" width="460px" append-to-body :destroy-on-close="true">
        <audit-form @dialogClose="dialogVisible = false" @auditSubmit="handleAuditSubmit" />
      </el-dialog>
    </el-drawer>
  </div>
</template>
<script>
import DrawerForm from '../components/DrawerForm.vue'
import TableList from '@/components/TableList'
import AuditForm from '../components/AuditForm.vue'
import { getArticleList, createArticle, updateArticle, auditArticle, publishArticle, topArticle, recommendArticle, batchDeleteArticle } from '@/api/contentManage'
import { dateFormat, formatToDate } from '@/utils/utils'
export default {
  data() {
    return {
      activeName: '',
      drawerVisible: false,
      drawFormOptions: {
        type: '', // 操作类型，新建/查看/编辑
        pageType: 1, // 页面 1文章，2广告，3图文
        details: {}
      },
      drawItem: '',
      dialogVisible: false,
      multipleSelection: []
    }
  },
  computed: {
    // 权限列表
    permissions() {
      return this.$store.state.user.permissions || []
    },
    // 创建权限
    hasCreate() {
      return this.permissions.includes('content-function-acticle-create')
    },
    // 更新权限
    hasUpdate() {
      return this.permissions.includes('content-function-article-update')
    },
    // 删除权限
    hasDelete() {
      return this.permissions.includes('content-function-acticle-delete')
    },
    // 项目列表
    projectList() {
      return this.$store.state.user.projects
    },
    // 类型列表
    typeList() {
      return this.$store.state.app.typeList
    },
    drawTitle() {
      if (this.drawFormOptions.type === 'create') return '新建文章'
      else if (this.drawFormOptions.type === 'edit') return '编辑文章'
      else return this.drawItem.title || '文章详情'
    },
    tableOptions() {
      return {
        remote: {
          httpRequest: getArticleList,
          params: { type_id: '', id_title: '', project_id: '' },
          beforeRequest: this.beforeRequest
        },
        filters: [
          {
            type: 'select',
            placeholder: '项目',
            prop: 'project_id',
            options: this.projectList,
            labelKey: 'name',
            valueKey: 'id'
          },
          { type: 'input', placeholder: '标题/ID', prop: 'id_title' },
          {
            type: 'select',
            placeholder: '类型',
            prop: 'type_id',
            options: this.typeList,
            labelKey: 'name',
            valueKey: 'id'
          }
        ],
        columns: [
          { type: 'selection', visible: this.hasDelete, fixed: 'left' },
          { prop: 'image_url', label: '图片', slots: 'image', minWidth: '80px', fixed: 'left' },
          { prop: 'id', label: '文章ID', slots: 'table-id', minWidth: '95px', fixed: 'left' },
          { prop: 'title', label: '标题', minWidth: '100px' },
          {
            prop: 'start_time',
            label: '开始时间',
            minWidth: '150px',
            computed({ row }) {
              return dateFormat(row.start_time) || '-'
            }
          },
          {
            prop: 'end_time',
            label: '结束时间',
            minWidth: '150px',
            computed({ row }) {
              return dateFormat(row.end_time) || '-'
            }
          },
          { prop: 'project.name', label: '项目', minWidth: '120px' },
          { prop: 'type.name', label: '类型', minWidth: '120px' },
          {
            prop: 'sso_user.real_name',
            label: '创建人',
            minWidth: '100px',
            computed({ row }) {
              return row.sso_user.real_name || row.sso_user.nickname
            }
          },
          {
            prop: 'created_at',
            label: '创建时间',
            minWidth: '150px',
            computed({ row }) {
              return dateFormat(row.created_at) || '-'
            }
          },
          { prop: 'audit_status', label: '审核状态', slots: 'review-status' },
          { prop: 'is_show', label: '发布状态', slots: 'publish-status', fixed: 'right' },
          { prop: 'is_top', label: '置顶状态/权重', slots: 'top-status', minWidth: '140px', fixed: 'right' },
          { prop: 'is_recommend', label: '推荐状态', slots: 'recommend-status', fixed: 'right' }
        ]
      }
    }
  },
  components: { TableList, DrawerForm, AuditForm },
  methods: {
    isExpired(time) {
      if (time === 0) return false
      const now = Date.now()
      time = formatToDate(time).getTime()
      if (now > time) return true
      else return false
    },
    // 审核状态
    auditStatusText(value) {
      const map = { 1: '待审核', 2: '已通过', 3: '已驳回' }
      return map[value]
    },
    // 接口请求之前，参数处理
    beforeRequest(params) {
      params.audit_status = this.activeName === '0' ? '' : this.activeName
      return params
    },
    // 发布
    handlePublish(row) {
      publishArticle(row.id, { is_publish: row.is_publish }).then(res => {
        if (res.code === 0) {
          this.$message.success('更改状态成功')
        } else {
          row.is_publish = row.is_publish ? 0 : 1
          this.$message.error(res.message)
        }
      })
    },
    // 置顶
    handleTop(row) {
      this.fetchAdTopWeight(row.id, { is_top: row.is_top })
    },
    handleWeight(row) {
      this.fetchAdTopWeight(row.id, { weight: row.weight })
    },
    // 推荐
    handleRecommend(row) {
      recommendArticle(row.id, { is_recommend: row.is_recommend }).then(res => {
        if (res.code === 0) {
          this.$message.success('更改状态成功')
        } else {
          row.is_recommend = row.is_recommend ? 0 : 1
          this.$message.error(res.message)
        }
      })
    },
    // 选择
    handleSelectionChange(value) {
      this.multipleSelection = value
    }, // 删除
    handleRemove() {
      let isWarn = false
      const ids = []
      this.multipleSelection.forEach(item => {
        if (item.audit_status === 2 && item.is_publish === 1) {
          isWarn = true
        }
        ids.push(item.id)
      })
      if (isWarn) {
        this.$confirm('选中的项中有已经发布上线的文章, 是否继续执行删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          this.fetchDeleteArticle(ids)
        }).catch(() => {});
      } else {
        this.fetchDeleteArticle(ids)
      }
    },
    handleCreate() {
      this.drawFormOptions.type = 'create'
      this.drawerVisible = true
    },
    handleDetails(val) {
      this.drawItem = val
      this.drawFormOptions.type = 'details'
      this.drawFormOptions.details = val
      this.drawerVisible = true
    },
    HandleDrawFormSubmit(val) {
      if (this.drawFormOptions.type === 'create') {
        this.fetchCreateArticle(val)
      } else {
        this.fetchUpdateArticle(val)
      }
    },
    handleAuditSubmit(val) {
      if (this.isExpired(this.drawItem.end_time) && val.audit_status === 2) {
        this.$message.error('这篇文章结束时间已逾期下架,请驳回重新编辑')
      } else {
        this.fetchAuditArticle(val)
      }
    },
    handleTabClick() {
      // true 强制刷新
      this.$refs.tableList.refetch(true)
    },
    fetchCreateArticle(val) {
      createArticle(val).then(res => {
        if (res.code === 0 && res.data && res.data.id) {
          this.$message.success('新建文章成功')
          this.$refs.tableList.refetch()
          this.$refs.articleDrawer.closeDrawer()
        } else {
          this.$message.error(res.message || '新建文章失败')
        }
      })
    },
    fetchUpdateArticle(val) {
      updateArticle(this.drawItem.id, val).then(res => {
        if (res.code === 0 && res.data && res.data.status) {
          this.$message.success('更改文章成功')
          this.$refs.tableList.refetch()
          this.$refs.articleDrawer.closeDrawer()
        } else {
          this.$message.error(res.message || '更改文章失败')
        }
      })
    },
    fetchAdTopWeight(id, data) {
      topArticle(id, data).then(res => {
        if (res.code === 0) {
          this.$message.success('更改置顶状态成功')
        } else {
          // row.is_top = row.is_top ? 0 : 1
          this.$message.error(res.message)
        }
      })
    },
    fetchAuditArticle(val) {
      auditArticle(this.drawItem.id, val).then(res => {
        if (res.code === 0 && res.data && res.data.status) {
          this.$message.success('审核文章成功')
          this.$refs.tableList.refetch()
          this.$refs.articleDrawer.closeDrawer()
          this.dialogVisible = false
        } else {
          this.$message.error(res.message || '审核文章失败')
        }
      })
    },
    fetchDeleteArticle(ids) {
      batchDeleteArticle({ ids }).then(res => {
        if (res.code === 0) {
          this.$message.success('删除成功')
          this.$refs.tableList.refetch(true)
        } else {
          this.$message.error(res.message)
        }
      })
    }
  },
  beforeMount() {
    this.$store.dispatch('app/getTypeList', 1)
  }
}
</script>
<style scoped>
.table-col-top .el-select{
  width:70px;
}
</style>
