<template>
  <div class="ads 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 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"></el-switch>
          <el-select v-model="row.weight" placeholder="权重" size="mini" :disabled="!hasUpdate || row.audit_status !== 2" @change="handleWeight(row)">
            <el-option v-for="item in 10" :label="item" :value="item" :key="item"></el-option>
          </el-select>
        </div>
      </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="ad_drawer">
      <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.ad_drawer.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"
        ref="auditDialog"
      >
        <audit-form @dialogClose="dialogVisible = false" @auditSubmit="handleAuditSubmit" />
      </el-dialog>
    </el-drawer>
  </div>
</template>
<script>
import TableList from '@/components/TableList'
import DrawerForm from '../components/DrawerForm.vue'
import AuditForm from '../components/AuditForm.vue'
import { getAdList, createAd, updateAd, publishAd, topAd, batchDeleteAd, auditAd } from '@/api/contentManage'
import { dateFormat } from '@/utils/utils'
export default {
  components: { TableList, DrawerForm, AuditForm },
  data() {
    return {
      activeName: '',
      drawerVisible: false,
      drawFormOptions: {
        type: '', // 操作类型，新建/查看/编辑
        pageType: 2, // 页面 1文章，2广告，3图文
        details: {}
      },
      drawItem: '',
      dialogVisible: false,
      multipleSelection: []
    }
  },
  computed: {
    // 权限列表
    permissions() {
      return this.$store.state.user.permissions || []
    },
    // 创建权限
    hasCreate() {
      return this.permissions.includes('content-function-advert-create')
    },
    // 更新权限
    hasUpdate() {
      return this.permissions.includes('content-function-advert-update')
    },
    // 删除权限
    hasDelete() {
      return this.permissions.includes('content-function-advert-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: getAdList,
          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: '150px' },
          {
            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_publish', label: '发布状态', slots: 'publish-status', fixed: 'right' },
          { prop: 'is_top', label: '置顶状态/权重', slots: 'top-status', minWidth: '140px', fixed: 'right' }
        ]
      }
    }
  },
  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) {
      publishAd(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 })
    },
    // 选择
    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.fetchDeleteAd(ids)
        }).catch(() => {});
      } else {
        this.fetchDeleteAd(ids)
      }
    },
    handleCreate() {
      this.drawFormOptions.type = 'create'
      this.drawerVisible = true
    },
    handleDetails(val) {
      console.log(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.fetchCreateAd(val)
      } else {
        this.fetchUpdateAd(val)
      }
    },
    handleAuditSubmit(val) {
      this.fetchAuditAd(val)
    },
    handleTabClick() {
      // true 强制刷新
      this.$refs.tableList.refetch(true)
    },
    fetchCreateAd(val) {
      delete val.is_publish
      createAd(val).then(res => {
        if (res.code === 0 && res.data && res.data.id) {
          this.$message.success('新建广告成功')
          this.$refs.tableList.refetch()
          this.$refs.ad_drawer.closeDrawer()
        } else {
          this.$message.error(res.message || '新建广告失败')
        }
      })
    },
    fetchUpdateAd(val) {
      updateAd(this.drawItem.id, val).then(res => {
        if (res.code === 0 && res.data && res.data.status) {
          this.$message.success('更改广告成功')
          this.$refs.tableList.refetch()
          this.$refs.ad_drawer.closeDrawer()
        } else {
          this.$message.error(res.message || '更改广告失败')
        }
      })
    },
    fetchAuditAd(val) {
      auditAd(this.drawItem.id, val).then(res => {
        if (res.code === 0 && res.data && res.data.status) {
          this.$message.success('审核广告成功')
          this.$refs.tableList.refetch()
          this.$refs.ad_drawer.closeDrawer()
          this.dialogVisible = false
        } else {
          this.$message.error(res.message || '审核广告失败')
        }
      })
    },
    fetchAdTopWeight(id, data) {
      topAd(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)
        }
      })
    },
    fetchDeleteAd(ids) {
      batchDeleteAd({ 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', 2)
  }
}
</script>
<style scoped>
.table-col-top .el-select{
  width:70px;
}
</style>
