<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" :rules="searchRule"
        @keyup.enter="onSubmit">
        <el-form-item label="关键字" prop="keyword">
          <el-input v-model="searchInfo.keyword" :clearable="true" />
        </el-form-item>
        <el-form-item label="创建日期" prop="createdAt">
          <template #label>
            <span>
              创建日期
              <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
                <el-icon>
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始日期"
            :disabled-date="time => searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"></el-date-picker>
          —
          <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束日期"
            :disabled-date="time => searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"></el-date-picker>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="searchInfo.status" clearable placeholder="请选择"
            @clear="() => { searchInfo.status = undefined }">
            <el-option v-for="(item, key) in activityStatusOptions" :key="key" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openDialog">新增</el-button>
        <el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length"
          @click="deleteRows">删除</el-button>
      </div>
      <el-table ref="multipleTable" style="width: 100%" tooltip-effect="dark" :data="tableData" row-key="ID"
        @selection-change="handleSelectionChange">
        <el-table-column type="expand">
          <template #default="scope">
            <div style="max-width: 1200px; width: 80%;">
              <div class="gva-table-expand">
                <el-text tag="b">简介</el-text>
              </div>
              <div class="gva-table-expand">
                <rich-view v-model="scope.row.brief" style="width: 100%; height: 300px;" />
              </div>
              <div class="gva-table-expand">
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="指导单位">
                    {{ scope.row.guid || '无' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="主办单位">
                    {{ scope.row.organizer || '无' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="协办单位">
                    {{ scope.row.coOrganizer || '无' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="支持单位">
                    {{ scope.row.support || '无' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="参与企业">
                    {{ scope.row.companies || '无' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="参与人员">
                    {{ scope.row.participants || '无' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="报名链接">
                    {{ scope.row.signUrl || '无' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="直播链接">
                    {{ scope.row.liveUrl || '无' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="创建时间">
                    {{ formatDate(scope.row.CreatedAt) }}
                  </el-descriptions-item>
                  <el-descriptions-item label="更新时间">
                    {{ formatDate(scope.row.UpdatedAt) }}
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed type="selection" width="55" />
        <el-table-column label="封面" width="150">
          <template #default="scope">
            <el-image style="width: 120px; height: 100px" :src="getUrl(scope.row.cover)" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="类型" prop="kind" width="80">
          <template #default="scope">
            {{ filterDict(scope.row.kind, activityKindOptions) }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="标题/标识" prop="label" min-width="350">
          <template #default="scope">
            <p><el-text tag="b">标题：</el-text><el-text>{{ scope.row.title }}</el-text></p>
            <p><el-text tag="b">标识：</el-text><el-text>{{ scope.row.label }}</el-text></p>
          </template>
        </el-table-column>
        <el-table-column align="left" label="活动地址/联系方式" prop="label" min-width="350">
          <template #default="scope">
            <p><el-text tag="b">活动地址：</el-text><el-text>{{ scope.row.activeAddr }}</el-text></p>
            <p><el-text tag="b">联系方式：</el-text><el-text>{{ scope.row.contact }}</el-text></p>
          </template>
        </el-table-column>
        <el-table-column align="left" label="时间" width="220">
          <template #default="scope">
            <p><el-text tag="b">开始：</el-text><el-text>{{ formatDate(scope.row.startTime) }}</el-text></p>
            <p><el-text tag="b">结束：</el-text><el-text>{{ formatDate(scope.row.endTime) }}</el-text></p>
          </template>
        </el-table-column>
        <el-table-column align="left" label="状态" prop="status" width="80">
          <template #default="scope">
            {{ filterDict(scope.row.status, activityStatusOptions) }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="创建日期" width="180">
          <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
        </el-table-column>
        <el-table-column align="left" label="操作" fixed="right" min-width="240">
          <template #default="scope">
            <el-button type="primary" link icon="edit" class="table-button" @click="updateRow(scope.row)">修改</el-button>
            <el-button type="danger" link icon="delete" @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination layout="total, sizes, prev, pager, next, jumper" :current-page="page" :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]" :total="total" @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </div>
    </div>

    <el-drawer size="920" v-model="dialogFormVisible" :show-close="false" :before-close="closeDialog"
      :close-on-click-modal="false" :close-on-press-escape="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ type === 'create' ? '添加' : '修改' }}</span>
          <div>
            <el-button type="primary" @click="enterDialog">确 定</el-button>
            <el-button @click="closeDialog">取 消</el-button>
          </div>
        </div>
      </template>
      <el-form :model="formData" label-position="top" ref="elFormRef" :inline="true" :rules="rule" label-width="100px">
        <el-form-item label="封面" prop="cover" style="width: 850px">
          <el-upload class="avatar-uploader" :action="`${imgUploadPath}/cms/mediaFile/upload?category=activity_imgs`"
            :show-file-list="false" :on-success="uploadSuccess" :on-error="uploadFailure" :before-upload="beforeUpload">
            <img v-if="formData.cover" :src="formData.cover" class="avatar"
              style="object-fit: cover;max-width: 300px;max-height:200px">
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="活动标识" prop="label" style="width: 400px">
          <el-input v-model="formData.label" :clearable="true" placeholder="请输入活动标识，例如：会议的界别等" />
        </el-form-item>
        <el-form-item label="类型" prop="kind" style="width: 400px">
          <el-select v-model="formData.kind" placeholder="请选择类型" style="width:100%" :clearable="true">
            <el-option v-for="(item, key) in activityKindOptions" :key="key" :label="item.label"
              :value="parseInt(item.value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title" style="width: 400px">
          <el-input v-model="formData.title" :clearable="true" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime" style="width: 185px">
          <el-date-picker v-model="formData.startTime" type="datetime" style="width:100%" placeholder="选择日期"
            :clearable="true" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime" style="width: 185px">
          <el-date-picker v-model="formData.endTime" type="datetime" style="width:100%" placeholder="选择日期"
            :clearable="true" />
        </el-form-item>
        <el-form-item label="活动地址" prop="activeAddr" style="width:830px">
          <el-input v-model="formData.activeAddr" :clearable="true" placeholder="请输入活动地址" />
        </el-form-item>
        <el-form-item label="活动简介" prop="brief" style="width: 830px">
          <RichEdit v-model="formData.brief" media-category="activity_imgs" style="height: 320px" />
        </el-form-item>
        <el-form-item label="指导单位" prop="guid" style="width: 400px">
          <el-input type="textarea" rows="3" v-model="formData.guid" :clearable="true" placeholder="请输入指导单位" />
        </el-form-item>
        <el-form-item label="主办单位" prop="organizer" style="width: 400px">
          <el-input type="textarea" rows="3" v-model="formData.organizer" :clearable="true" placeholder="请输入主办单位" />
        </el-form-item>
        <el-form-item label="协办单位" prop="coOrganizer" style="width: 400px">
          <el-input type="textarea" rows="3" v-model="formData.coOrganizer" :clearable="true" placeholder="请输入协办单位" />
        </el-form-item>
        <el-form-item label="支持单位" prop="support" style="width: 400px">
          <el-input type="textarea" rows="3" v-model="formData.support" :clearable="true" placeholder="请输入支持单位" />
        </el-form-item>
        <el-form-item label="参与企业" prop="companies" style="width: 400px">
          <el-input type="textarea" rows="4" v-model="formData.companies" :clearable="true" placeholder="请输入参与企业" />
        </el-form-item>
        <el-form-item label="参与人员" prop="participants" style="width: 400px">
          <el-input type="textarea" rows="4" v-model="formData.participants" :clearable="true" placeholder="请输入参与人员" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contact" style="width: 830px">
          <el-input type="textarea" rows="4" v-model="formData.contact" :clearable="true" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="报名链接地址" prop="signUrl" style="width: 400px">
          <el-input v-model="formData.signUrl" :clearable="true" placeholder="请输入报名链接地址" />
        </el-form-item>
        <el-form-item label="直播链接地址" prop="liveUrl" style="width: 400px">
          <el-input v-model="formData.liveUrl" :clearable="true" placeholder="请输入直播链接地址" />
        </el-form-item>
        <el-form-item label="状态" prop="status" style="width: 400px">
          <el-select v-model="formData.status" placeholder="请选择状态" style="width:100%" :clearable="true">
            <el-option v-for="(item, key) in activityStatusOptions" :key="key" :label="item.label"
              :value="parseInt(item.value)" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import {
  createActivity,
  deleteActivity,
  deleteActivityByIds,
  updateActivity,
  findActivity,
  getActivityList
} from '@/api/activity'
import { isUrl } from '@/utils/validator'
import { getUrl } from '@/utils/image'
import { isImageMime } from '@/utils/image'
// 富文本组件
import RichEdit from '@/components/richtext/rich-edit.vue'
import RichView from '@/components/richtext/rich-view.vue'
// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, filterDict } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'

defineOptions({
  name: 'Activity'
})

const imgUploadPath = ref(import.meta.env.VITE_BASE_API)
const beforeUpload = (file) => {
  console.log(file)
  const isLt500K = file.size / 1024 / 1024 < 0.5 // 500K, @todo 应支持在项目中设置
  const isImage = isImageMime(file.type)
  if (!isImage) {
    ElMessage.error('上传图片只能是 jpg,png,svg,webp 格式!')
    return false
  }
  if (!isLt500K && isImage) {
    ElMessage.error('未压缩的上传图片大小不能超过 500KB，请使用压缩上传')
    return false
  }
  return true
}
const uploadSuccess = (res) => {
  const { code, data, msg } = res
  if (code !== 0) {
    ElMessage({ type: 'error', message: msg })
    return
  }
  if (!data.mediaFile) {
    ElMessage({ type: 'error', message: '返回错误，上传失败' })
    return
  }
  formData.value.cover = data.mediaFile.url
}
const uploadFailure = () => {
  ElMessage({
    type: 'error',
    message: '上传失败'
  })
}

// 自动化生成的字典（可能为空）以及字段
const activityStatusOptions = ref([])
const activityKindOptions = ref([])
const formData = ref({
  cover: '',
  kind: 1,
  label: '',
  title: '',
  brief: '',
  guid: '',
  organizer: '',
  coOrganizer: '',
  support: '',
  companies: '',
  participants: '',
  activeAddr: '',
  contact: '',
  signUrl: '',
  liveUrl: '',
  startTime: '',
  endTime: '',
  status: 1,
})

const isDateEndGtStart = (rule, value, callback) => {
  if (value < formData.value.startTime) {
    callback(new Error(rule.message))
  } else {
    callback()
  }
}
// 验证规则
const rule = reactive({
  label: [
    { required: true, message: '', trigger: ['input', 'blur'] },
    { whitespace: true, message: '不能只输入空格', trigger: ['input', 'blur'] }
  ],
  kind: [
    { required: true, message: '', trigger: ['input', 'blur'] },
  ],
  title: [
    { required: true, message: '', trigger: ['input', 'blur'] },
    { whitespace: true, message: '不能只输入空格', trigger: ['input', 'blur'] }
  ],
  activeAddr: [
    { required: true, message: '', trigger: ['input', 'blur'] },
    { whitespace: true, message: '不能只输入空格', trigger: ['input', 'blur'] }
  ],
  startTime: [
    { required: true, message: '', trigger: ['input', 'blur'] },
  ],
  endTime: [
    { required: true, message: '', trigger: ['input', 'blur'] },
    { validator: isDateEndGtStart, message: '有效截止日期必须大于起始日期', trigger: 'blur' }
  ],
  signUrl: [
    { validator: isUrl, message: '请输入正确的URL地址', trigger: 'blur' }
  ],
  liveUrl: [
    { validator: isUrl, message: '请输入正确的URL地址', trigger: 'blur' }
  ]
})

const searchRule = reactive({
  createdAt: [
    {
      validator: (rule, value, callback) => {
        if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
          callback(new Error('请填写结束日期'))
        } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
          callback(new Error('请填写开始日期'))
        } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
          callback(new Error('开始日期应当早于结束日期'))
        } else {
          callback()
        }
      }, trigger: 'change'
    }
  ],
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async (valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    getTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async () => {
  const table = await getActivityList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () => {
  activityStatusOptions.value = await getDictFunc('activityStatus')
  activityStatusOptions.value.map((item) => { item.value = parseInt(item.value); return item })
  activityKindOptions.value = await getDictFunc('activityKind')
  activityKindOptions.value.map((item) => { item.value = parseInt(item.value); return item })
}

// 获取需要的字典 可能为空 按需保留
setOptions()

// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteActivityFunc(row)
  })
}

// 多选删除
const deleteRows = async () => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const IDs = []
    if (multipleSelection.value.length === 0) {
      ElMessage({
        type: 'warning',
        message: '请选择要删除的数据'
      })
      return
    }
    multipleSelection.value &&
      multipleSelection.value.map(item => {
        IDs.push(item.ID)
      })
    const res = await deleteActivityByIds({ IDs })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      if (tableData.value.length === IDs.length && page.value > 1) {
        page.value--
      }
      getTableData()
    }
  })
}

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')
// 编辑弹窗控制标记
const dialogFormVisible = ref(false)
// 更新行
const updateRow = async (row) => {
  const res = await findActivity({ id: row.ID })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data.item
    dialogFormVisible.value = true
  }
}
// 打开编辑弹窗
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}
// 关闭编辑弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    label: '',
    kind: 1,
    title: '',
    guid: '',
    organizer: '',
    coOrganizer: '',
    support: '',
    companies: '',
    participants: '',
    activeAddr: '',
    signUrl: '',
    liveUrl: '',
    startTime: new Date(),
    endTime: new Date(),
    status: 1,
  }
}
// 编辑弹窗确定
const enterDialog = async () => {
  elFormRef.value?.validate(async (valid) => {
    if (!valid) return
    let res
    switch (type.value) {
      case 'create':
        res = await createActivity(formData.value)
        break
      case 'update':
        res = await updateActivity(formData.value)
        break
      default:
        res = await createActivity(formData.value)
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: type.value === 'create' ? '创建成功' : '更改成功'
      })
      closeDialog()
      getTableData()
    }
  })
}

// 删除行
const deleteActivityFunc = async (row) => {
  const res = await deleteActivity({ id: row.ID })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}

</script>
