<template>
  <div class="image-text 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"
        ></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="imgTextDrawer">
      <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.imgTextDrawer.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 { getImgTextList, createImgText, updateImgText, auditImgText, publishImgText, batchDeleteImgText } from '@/api/contentManage'
import { dateFormat } from '@/utils/utils'
export default {
  data() {
    return {
      activeName: '',
      drawerVisible: false,
      drawFormOptions: {
        type: '', // 操作类型，新建/查看/编辑
        pageType: 3, // 页面 1文章，2广告，3图文
        details: {}
      },
      drawItem: '',
      dialogVisible: false,
      multipleSelection: []
    }
  },
  computed: {
    // 权限列表
    permissions() {
      return this.$store.state.user.permissions || []
    },
    // 创建权限
    hasCreate() {
      return this.permissions.includes('content-function-imgtext-create')
    },
    // 更新权限
    hasUpdate() {
      return this.permissions.includes('content-function-imgtext-update')
    },
    // 删除权限
    hasDelete() {
      return this.permissions.includes('content-function-imgtext-delete')
    },
    // 项目列表
    projectList() {
      return this.$store.state.user.projects
    },
    // 类型列表
    typeList() {
      return this.$store.state.app.typeList
    },
    drawTitle() {
      const type = this.drawFormOptions.type
      if (type === 'create') return '新建图文'
      else if (type === 'edit') return '编辑图文'
      else return this.drawItem.title || '图文详情'
    },
    tableOptions() {
      return {
        remote: {
          httpRequest: getImgTextList,
          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' }
        ]
      }
    }
  },
  components: { TableList, DrawerForm, AuditForm },
  methods: {
    // 审核状态
    auditStatusText(value) {
      const map = { 1: '待审核', 2: '已通过', 3: '已驳回' }
      return map[value]
    },
    // 接口请求之前，参数处理
    beforeRequest(params) {
      params.audit_status = this.activeName === '0' ? '' : this.activeName
      return params
    },
    // 发布
    handlePublish(row) {
      publishImgText(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)
        }
      })
    },
    // 选择
    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.fetchDeleteImgText(ids)
        }).catch(() => {});
      } else {
        this.fetchDeleteImgText(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) {
      Object.keys(val).forEach(key => {
        if (val[key] === '') delete val[key]
      })
      if (this.drawFormOptions.type === 'create') {
        this.fetchCreateImgText(val)
      } else {
        this.fetchUpdateImgText(val)
      }
    },
    handleAuditSubmit(val) {
      auditImgText(this.drawItem.id, val).then(res => {
        if (res.code === 0 && res.data && res.data.status) {
          this.$message.success('审核图文成功')
          this.$refs.tableList.refetch()
          this.dialogVisible = false
          this.$refs.imgTextDrawer.closeDrawer()
        } else {
          this.$message.error(res.message || '审核图文失败')
        }
      })
    },
    handleTabClick() {
      // true 强制刷新
      this.$refs.tableList.refetch(true)
    },
    fetchCreateImgText(val) {
      createImgText(val).then(res => {
        if (res.code === 0 && res.data && res.data.id) {
          this.$message.success('新建图文成功')
          this.$refs.tableList.refetch()
          this.$refs.imgTextDrawer.closeDrawer()
        } else {
          this.$message.error(res.message || '新建图文失败')
        }
      })
    },
    fetchUpdateImgText(val) {
      updateImgText(this.drawItem.id, val).then(res => {
        if (res.code === 0 && res.data && res.data.status) {
          this.$message.success('更改图文成功')
          this.$refs.tableList.refetch()
          this.$refs.imgTextDrawer.closeDrawer()
        } else {
          this.$message.error(res.message || '更改图文失败')
        }
      })
    },
    fetchDeleteImgText(ids) {
      batchDeleteImgText({ 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', 3)
  }
}
</script>
<style scoped>
</style>
