<template>
  <div class="index">
    <el-row>
      <el-col :span="24" class="main" v-loading="loading">
        <el-col :span="24" class="one">
          <div class="one_left" @click="toAdd">发布行业动态</div>
          <div class="one_right">
            <el-input v-model="searchForm.title" style="width: 250px" size="large" placeholder="搜索" @change="search" :suffix-icon="Search" />
          </div>
        </el-col>
        <el-col :span="24" class="two">
          <el-table :data="list" style="width: 100%" size="large" :header-cell-style="{ backgroundColor: '#edf3ff' }">
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
            <el-table-column prop="title" align="center" label="标题" />
            <el-table-column prop="time" align="center" label="发布时间" width="180" />
            <el-table-column prop="status" align="center" label="状态" width="180">
              <template #default="scope">
                <div>{{ getDict(scope.row.status, 'status') }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="180">
              <template #default="{ row }">
                <el-link v-if="row.status == '-2'" :underline="false" type="warning" size="mini" @click="toExam(row)" style="margin-right: 10px">提交审核</el-link>
                <el-link :underline="false" type="primary" size="mini" @click="toEdit(row)" style="margin-right: 10px">修改</el-link>
                <el-link :underline="false" type="danger" size="mini" @click="toDelete(row)"> 删除 </el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="24" class="thr">
          <el-pagination background layout="prev, pager, next" :total="total" :page-size="limit" v-model:current-page="currentPage" @current-change="changePage" @size-change="sizeChange" />
        </el-col>
      </el-col>
    </el-row>
    <el-dialog v-model="dialog.show" :title="dialog.title" :destroy-on-close="false" @close="toClose">
      <el-row>
        <el-col :span="24" v-if="dialog.type == '1'">
          <custom-form v-model="form" :fields="formFields" :rules="rules" @save="toSave" @draftSave="toDraftSave">
            <template #logo>
              <custom-upload model="logo" :list="form.logo" :limit="1" url="/files/web/cxyy_news/upload" @change="onUpload" listType="picture-card"></custom-upload>
            </template>
            <template #is_use>
              <el-radio v-for="i in isUseList" :key="i.id" :label="i.value">{{ i.label }}</el-radio>
            </template>
            <template #tags>
              <el-select v-model="form.tags" multiple filterable allow-create default-first-option :reserve-keyword="false" placeholder="请选择标签" style="width: 100%">
                <el-option v-for="item in tagsList" :key="item.id" :label="item.title" :value="item.title" />
              </el-select>
            </template>
            <template #content>
              <WangEditor v-model="form.content" />
            </template>
          </custom-form>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup>
import moment from 'moment'
import { Search } from '@element-plus/icons-vue'
import { cloneDeep, get } from 'lodash-es'
const $checkRes = inject('$checkRes')
import { UserStore } from '@/store/user'
const userStore = UserStore()
const user = computed(() => userStore.user)
// 接口
import { NewsStore } from '@/store/api/platform/news'
import { DictDataStore } from '@/store/api/system/dictData'
import { TagsStore } from '@/store/api/system/tags'
const store = NewsStore()
const dictDataStore = DictDataStore()
const tagsStore = TagsStore()
// 加载中
const loading = ref(false)

const searchForm = ref({})
// 列表
const list = ref([])
let skip = 0
let limit = inject('limit')
const total = ref(0)
const currentPage = ref(1)
// 字典表
const isUseList = ref([])
const statusList = ref([])
const tagsList = ref([])

const form = ref({ logo: [], type: '2' })
const dialog = ref({ type: '1', show: false, title: '发布行业动态' })
const formFields = ref([
  { label: '封面', model: 'logo', custom: true },
  { label: '标题', model: 'title' },
  { label: '标签', model: 'tags', custom: true },
  { label: '发布人', model: 'person', options: { disabled: true } },
  { label: '发布时间', model: 'time', type: 'date', options: { disabled: true } },
  { label: '浏览量', model: 'number', options: { disabled: true } },
  { label: '是否公开', model: 'is_use', type: 'radio' },
  { label: '内容', model: 'content', custom: true }
])
const rules = reactive({
  logo: [{ required: true, message: '请上传封面', trigger: 'blur' }],
  name: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
})
// 请求
onMounted(async () => {
  loading.value = true
  await searchOther()
  await search()
  loading.value = false
})
const search = async (query = { skip, limit }) => {
  skip = query.skip
  limit = query.limit
  const info = {
    skip: query.skip,
    limit: query.limit,
    user: user.value.id,
    type: '2',
    ...searchForm.value
  }
  const res = await store.query(info)
  if (res.errcode == '0') {
    list.value = res.data
    total.value = res.total
  }
}
const searchOther = async () => {
  let result
  // 是否使用
  result = await dictDataStore.query({ code: 'isUse', is_use: '0' })
  if ($checkRes(result)) isUseList.value = result.data
  // 状态
  result = await dictDataStore.query({ code: 'examStatus', is_use: '0' })
  if ($checkRes(result)) statusList.value = result.data
  // 标签
  result = await tagsStore.query({ is_use: '0' })
  if ($checkRes(result)) tagsList.value = result.data
}
// 字典数据转换
const getDict = (data, model) => {
  if (data) {
    let res
    if (model == 'status') res = statusList.value.find((f) => f.value == data)
    return get(res, 'label')
  }
}
// 添加
const toAdd = () => {
  form.value = { status: '0', type: '2', user: user.value.id, time: moment().format('YYYY-MM-DD'), person: user.value.nick_name }
  dialog.value = { type: '1', show: true, title: '发布行业动态' }
}
// 修改
const toEdit = (data) => {
  form.value = data
  dialog.value = { type: '1', show: true, title: '修改行业动态' }
}
// 删除
const toDelete = (data) => {
  ElMessageBox.confirm(`您确认删除${data.name}该数据?`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
    .then(async () => {
      const res = await store.del(data.id)
      if ($checkRes(res, true)) {
        search({ skip, limit })
      }
    })
    .catch(() => {})
}
const toSave = async () => {
  const data = cloneDeep(form.value)
  const other = { status: '0', type: '2', user: user.value.id, time: moment().format('YYYY-MM-DD'), person: user.value.nick_name }
  let res
  if (get(data, 'id')) res = await store.update({ ...data, ...other })
  else res = await store.create({ ...data, ...other })
  if ($checkRes(res, true)) {
    search({ skip, limit })
    toClose()
  }
}
const toDraftSave = async () => {
  const data = cloneDeep(form.value)
  const other = { status: '-2', type: '2', user: user.value.id, time: moment().format('YYYY-MM-DD'), person: user.value.nick_name }
  let res
  if (get(data, 'id')) res = await store.update({ ...data, ...other })
  else res = await store.create({ ...data, ...other })
  if ($checkRes(res, true)) {
    search({ skip, limit })
    toClose()
  }
}
// 审核保存
const toExam = async (row) => {
  ElMessageBox.confirm(`您确认保存并提交审核该数据?`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
    .then(async () => {
      const data = cloneDeep(row)
      let res = await store.update({ id: data.id, status: '0', user: user.value.id })
      if ($checkRes(res, true)) {
        search({ skip, limit })
        toClose()
      }
    })
    .catch(() => {})
}
const toClose = () => {
  form.value = { logo: [], type: '2' }
  dialog.value = { show: false }
}
// 上传图片
const onUpload = (e) => {
  const { model, value } = e
  form.value[model] = value
}
// 分页
const changePage = (page = currentPage.value) => {
  search({ skip: (page - 1) * limit, limit: limit })
}
const sizeChange = (limits) => {
  limit = limits
  currentPage.value = 1
  search({ skip: 0, limit: limit })
}
</script>
<style scoped lang="scss">
.main {
  .one {
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 0 0 10px 0;
    .one_left {
      background: #1875df;
      padding: 0 10px;
      height: 30px;
      color: #fff;
      line-height: 30px;
      text-align: center;
      font-size: 16px;
      cursor: default;
    }
  }
  .thr {
    display: flex;
    justify-content: center;
    margin: 20px 0 0 0;
  }
}
</style>
