<!-- 推广广告位列表 -->
<template>
  <el-form :inline="true">
    <el-form-item label="广告位名称">
      <el-input v-model="pages.keyword" placeholder="输入广告位关键词" clearable />
    </el-form-item>
    <!-- <el-form-item label="状态">
      <el-select filterable clearable v-model="pages.status" style="width: 200px">
        <el-option
          v-for="item in statusList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item> -->
    <el-form-item label="站点">
      <el-select
        filterable
        clearable
        v-model="pages.mediaId"
        placeholder="站点"
        style="width: 200px"
      >
        <el-option
          v-for="item in SiteList"
          :key="item.mediaId"
          :label="item.mediaName"
          :value="item.mediaId"
        />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">搜索</el-button>
      <el-button type="primary" link @click="creatEditPlan">创建广告位</el-button>
    </el-form-item>
  </el-form>

  <el-table :data="tableData" stripe style="width: 100%">
    <el-table-column prop="slotName" label="名称" />
    <el-table-column prop="createdTime" label="站点">
      <template #default="scope">
        {{ SiteDec(scope.row.mediaId) }}
      </template>
    </el-table-column>
    <el-table-column prop="createdTime" label="栏目">
      <template #default="scope">
        {{ scope.row.catalog ? scope.row.catalog.catalogName : '' }}
      </template>
    </el-table-column>
    <el-table-column prop="createdTime" label="最近更新">
      <template #default="scope">
        {{ formatDateSite(scope.row.updatedTime, 'Y-M-D') }}
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-popconfirm @confirm="deleteAsSpaceFun(scope.row.slotId)" title="确定删除该广告位吗?">
          <template #reference>
            <el-button link type="primary" size="small">删除</el-button>
          </template>
        </el-popconfirm>
        <el-button link type="primary" size="small" @click="() => creatEditPlan(scope.row, true)">
          修改
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <br />
  <el-pagination
    background
    layout="prev, pager, next"
    :total="pages.total"
    @current-change="page"
  />

  <el-dialog v-model="dialogVisible" title="广告位">
    <el-form ref="ruleFormRef" :rules="rules" :model="form" label-width="auto">
      <el-form-item label="广告位名称" prop="slotName">
        <el-input v-model="form.slotName" />
      </el-form-item>
      <el-form-item label="站点" prop="mediaId">
        <el-select
          filterable
          v-model="form.mediaId"
          :disabled="isUpdate"
          placeholder="站点"
          size="large"
          @change="changeSite"
        >
          <el-option
            v-for="item in SiteList"
            :key="item.mediaId"
            :label="item.mediaName"
            :value="item.mediaId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="栏目" prop="catalogId">
        <el-tree-select
          :disabled="isUpdate"
          v-model="form.catalogId"
          :data="CatalogTreeData"
          :render-after-expand="false"
        />
      </el-form-item>
      <el-form-item label="宽" prop="width">
        <el-input-number v-model="form.width" :min="0" /> px
      </el-form-item>
      <el-form-item label="高" prop="height">
        <el-input-number v-model="form.height" :min="0" /> px
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="subCreateSpace(ruleFormRef)">确定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { CatalogTree, CatalogTreeOri, IAsSpace, AsSpaceItem } from '@/types/AsSpace'
import type { SiteList, SiteItem } from '@/types/Site'
import type { Pages } from '@/types/Tool'
import {
  createAsSpace,
  getSiteList,
  getAsTree,
  getAsSpaceList,
  deleteAsSpace,
  updateAsSpace,
} from '@/api/index'
import { formatDateSite } from '@/tool/index'
import { ElMessage } from 'element-plus'
import { ref, reactive } from 'vue'

// import { statusList } from '@/tool'

const dialogVisible = ref(false)
const ruleFormRef = ref<FormInstance>()
const form = ref<IAsSpace>({})
const isUpdate = ref(false)

const rules = reactive<
  FormRules<{ slotName: string; mediaId: number; catalogId: number; width: number; height: number }>
>({
  slotName: [{ required: true, message: '请输入广告位名称', trigger: 'blur' }],
  mediaId: [{ required: true, message: '请选择站点', trigger: 'change' }],
  catalogId: [{ required: true, message: '请选择栏目', trigger: 'change' }],
  width: [{ required: true, message: '请输入广告位宽度', trigger: 'blur' }],
  height: [{ required: true, message: '请输入广告位高度', trigger: 'blur' }],
})

const pages = reactive<Pages>({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  status: 10,
})

const SiteList = ref<SiteList>([])
const CatalogTreeData = ref<CatalogTree[]>([])

const tableData = ref([])

const changeSite = (val: number) => {
  getAsTree(val).then(({ data }) => {
    CatalogTreeData.value = toValueLabel(data)
  })
}

const SiteDec = (mediaId: number): string | void => {
  const item: SiteItem = SiteList.value.find((item) => item.mediaId === mediaId) || {}
  return item.mediaName
}

const deleteAsSpaceFun = (id: number) => {
  deleteAsSpace(id).then(() => {
    ElMessage.success('删除成功')
    onSubmit()
  })
}

const toValueLabel = (data: CatalogTreeOri[]): CatalogTree[] => {
  return data.map((item: CatalogTreeOri) => {
    const p: CatalogTree = {
      label: item.catalogName,
      value: item.catalogId,
    }
    if (item.children !== undefined) p.children = toValueLabel(item.children)
    return p
  })
}

const onSubmit = () => {
  getAsSpaceList({
    pageNum: pages.pageNum,
    pageSize: pages.pageSize,
    keyword: pages.keyword ? pages.keyword : null,
    status: pages.status,
    mediaId: typeof pages.mediaId === 'number' ? pages.mediaId : null,
  }).then(({ data }) => {
    tableData.value = data.records || []
    pages.total = data.total
  })
}

const page = (val: number) => {
  pages.pageNum = val
  onSubmit()
}

const creatEditPlan = (data: AsSpaceItem, isUpdateF = false) => {
  if (data != undefined) {
    form.value = {
      mediaId: data.mediaId,
      catalogId: data.catalogId,
      slotName: data.slotName,
      width: data.width,
      height: data.height,
      adType: data.adType,
      slotId: data.slotId,
    }
  }
  dialogVisible.value = !dialogVisible.value
  if (typeof data.mediaId === 'number') changeSite(data.mediaId)
  isUpdate.value = isUpdateF
}

const subCreateSpace = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (!valid) return
    if (!isUpdate.value)
      createAsSpace(form.value).then(() => {
        ElMessage({
          message: '创建成功',
          type: 'success',
        })
        dialogVisible.value = !dialogVisible.value
        onSubmit()
      })
    else
      updateAsSpace({
        slotId: form.value.slotId,
        slotName: form.value.slotName,
        width: form.value.width,
        height: form.value.height,
      }).then(() => {
        ElMessage({
          message: '修改成功',
          type: 'success',
        })
        dialogVisible.value = !dialogVisible.value
        onSubmit()
      })
  })
}

getSiteList().then((res) => {
  SiteList.value = res.data || []
  pages.mediaId = res.data[0].mediaId
  onSubmit()
})
</script>

<style></style>
