<template>
  <div class="NCC-common-layout">
    <div class="NCC-common-layout-center">
      <!-- 搜索区域 -->
      <el-row class="NCC-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item label="事件标题">
              <el-input v-model="query.title" placeholder="请输入事件标题" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="事件类型">
              <el-select v-model="query.eventType" placeholder="请选择事件类型" clearable>
                <el-option
                  v-for="item in eventTypeList"
                  :key="item.Id"
                  :label="item.TypeName"
                  :value="item.Id"
                >
                  <span class="type-dot" :style="{ background: item.Color }"></span>
                  {{ item.TypeName }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开始时间">
              <el-date-picker v-model="query.startTime" type="date" placeholder="选择开始时间"
                value-format="yyyy-MM-dd" clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>

      <!-- 主要内容区域 -->
      <div class="NCC-common-layout-main NCC-flex-main">
        <!-- 操作按钮区域 -->
        <div class="NCC-common-head">
          <div>
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd()">新增事件</el-button>
            <el-button type="success" icon="el-icon-setting" @click="handleManageType()">事件类型管理</el-button>
            <el-button type="text" icon="el-icon-download" @click="exportData()">导出</el-button>
          </div>
          <div class="NCC-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh NCC-common-head-icon" :underline="false"
                @click="reset()" />
            </el-tooltip>
            <screenfull isContainer />
          </div>
        </div>

        <!-- 事件列表表格 -->
        <NCC-table v-loading="listLoading" :data="list" has-c @selection-change="handleSelectionChange">
          <el-table-column prop="Title" label="事件标题" align="left" show-overflow-tooltip />
          <el-table-column label="事件类型" align="center" width="120">
            <template slot-scope="scope">
              <span class="type-dot" :style="{ background: scope.row.EventTypeColor }"></span>
              {{ scope.row.EventTypeName }}
            </template>
          </el-table-column>
          <el-table-column prop="Date" label="日期" align="center" width="120" />
          <el-table-column label="时间" align="center" width="150">
            <template slot-scope="scope">
              {{ formatTimeRange(scope.row.Start, scope.row.End) }}
            </template>
          </el-table-column>
          <el-table-column prop="Store" label="门店/地点" align="center" width="150" show-overflow-tooltip />
          <el-table-column prop="Remark" label="备注" align="left" show-overflow-tooltip />
          <el-table-column prop="CreateTime" label="创建时间" align="center" width="160"
            :formatter="ncc.tableDateTimeFormat" />
          <el-table-column label="操作" align="center" width="180" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="handleView(scope.row)">查看</el-button>
              <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" class="NCC-common-error-color" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </NCC-table>

        <!-- 分页组件 -->
        <pagination v-show="total > 0" :total="total" :page.sync="query.currentPage"
          :limit.sync="query.pageSize" @pagination="getList" />
      </div>
    </div>

    <!-- 新增/编辑事件弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form ref="eventForm" :model="eventForm" :rules="eventRules" label-width="100px" size="small">
        <el-form-item label="事件标题" prop="title">
          <el-input v-model="eventForm.title" placeholder="请输入事件标题" />
        </el-form-item>
        <el-form-item label="事件类型" prop="eventType">
          <el-select v-model="eventForm.eventType" placeholder="请选择事件类型" style="width: 100%">
            <el-option
              v-for="item in eventTypeList"
              :key="item.Id"
              :label="item.TypeName"
              :value="item.Id"
            >
              <span class="type-dot" :style="{ background: item.Color }"></span>
              {{ item.TypeName }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="eventForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="eventForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="门店/地点">
          <el-select
            v-model="eventForm.storeId"
            placeholder="请选择门店"
            filterable
            clearable
            style="width: 100%"
            @change="handleStoreChange"
          >
            <el-option
              v-for="item in storeList"
              :key="item.id"
              :label="item.fullName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="事件描述">
          <el-input v-model="eventForm.description" type="textarea" :rows="3" placeholder="请输入事件描述" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="eventForm.remark" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            :action="uploadUrl"
            :headers="uploadHeaders"
            :file-list="fileList"
            :on-success="handleUploadSuccess"
            :on-remove="handleUploadRemove"
            :before-upload="beforeUpload"
            multiple
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">支持上传图片、文档等文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="small" :loading="submitLoading" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看详情弹窗 -->
    <el-dialog
      title="事件详情"
      :visible.sync="detailVisible"
      width="520px"
      append-to-body
    >
      <div v-if="selectedEvent" class="detail-content">
        <div class="detail-row">
          <span class="detail-label">主题</span>
          <span class="detail-value">{{ selectedEvent.Title || '无' }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">类型</span>
          <span class="detail-value">
            <span class="type-dot" :style="{ background: selectedEvent.EventTypeColor }"></span>
            {{ selectedEvent.EventTypeName }}
          </span>
        </div>
        <div class="detail-row">
          <span class="detail-label">日期</span>
          <span class="detail-value">{{ selectedEvent.Date }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">时间</span>
          <span class="detail-value">{{ formatTimeRange(selectedEvent.Start, selectedEvent.End) }}</span>
        </div>
        <div class="detail-row" v-if="selectedEvent.Store">
          <span class="detail-label">门店/地点</span>
          <span class="detail-value">{{ selectedEvent.Store }}</span>
        </div>
        <div class="detail-row" v-if="selectedEvent.Desc">
          <span class="detail-label">内容</span>
          <span class="detail-value detail-value--multiline">{{ selectedEvent.Desc }}</span>
        </div>
        <div class="detail-row" v-if="selectedEvent.Remark">
          <span class="detail-label">备注</span>
          <span class="detail-value detail-value--multiline">{{ selectedEvent.Remark }}</span>
        </div>
        <div class="detail-row" v-if="selectedEvent.Attachments">
          <span class="detail-label">附件</span>
          <span class="detail-value">
            <div v-for="(att, idx) in parseAttachments(selectedEvent.Attachments)" :key="idx" class="attachment-item">
              <i class="el-icon-document"></i>
              <a v-if="att.url" :href="att.url" target="_blank">{{ att.name || att.fileName }}</a>
              <span v-else>{{ att.name || att.fileName }}</span>
            </div>
            <span v-if="!parseAttachments(selectedEvent.Attachments).length">无</span>
          </span>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleEdit(selectedEvent)">编 辑</el-button>
        <el-button size="small" @click="detailVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 事件类型管理弹窗 -->
    <EventTypeDialog
      v-if="eventTypeDialogVisible"
      :visible.sync="eventTypeDialogVisible"
      @refresh="loadEventTypeList"
    />
  </div>
</template>

<script>
import {
  getCalendarEvents,
  createCalendarEvent,
  updateCalendarEvent,
  deleteCalendarEvent,
  getEventTypeList
} from '@/api/extend/lqCompanyCalendar'
import { getStoreSelector } from '@/api/extend/store'
import Pagination from '@/components/Pagination'
import EventTypeDialog from './components/EventTypeDialog.vue'
import { getToken } from '@/utils/auth'

export default {
  name: 'CompanyCalendar',
  components: {
    Pagination,
    EventTypeDialog
  },
  data() {
    return {
      query: {
        title: '',
        eventType: '',
        startTime: '',
        currentPage: 1,
        pageSize: 20
      },
      list: [],
      total: 0,
      listLoading: true,
      dialogVisible: false,
      detailVisible: false,
      eventTypeDialogVisible: false,
      isEdit: false,
      submitLoading: false,
      eventForm: {
        id: '',
        title: '',
        eventType: '',
        startTime: '',
        endTime: '',
        storeId: '',
        storeName: '',
        description: '',
        remark: '',
        attachments: ''
      },
      eventRules: {
        title: [{ required: true, message: '请输入事件标题', trigger: 'blur' }],
        eventType: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
        startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
      },
      selectedEvent: null,
      selectedIds: [],
      eventTypeList: [],
      storeList: [],
      fileList: [],
      uploadUrl: '/api/Extend/OssDirectUpload/Upload',
      uploadHeaders: {}
    }
  },
  computed: {
    dialogTitle() {
      return this.isEdit ? '编辑事件' : '新增事件'
    }
  },
  created() {
    this.uploadHeaders = { Authorization: 'Bearer ' + getToken() }
    this.getList()
    this.loadEventTypeList()
    this.loadStoreList()
  },
  methods: {
    // 获取事件列表
    getList() {
      this.listLoading = true
      getCalendarEvents(this.query).then(response => {
        if (response.code === 200) {
          this.list = response.data.List || []
          this.total = response.data.Total || 0
        } else {
          this.$message.error(response.msg || '获取事件列表失败')
        }
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },

    // 加载事件类型列表
    loadEventTypeList() {
      getEventTypeList({}).then(response => {
        if (response.code === 200) {
          this.eventTypeList = response.data || []
        }
      }).catch(() => {})
    },

    // 加载门店列表
    loadStoreList() {
      getStoreSelector().then(response => {
        if (response.code === 200) {
          this.storeList = response.data.list || []
        }
      }).catch(() => {})
    },

    // 搜索
    search() {
      this.query.currentPage = 1
      this.getList()
    },

    // 重置
    reset() {
      this.query = {
        title: '',
        eventType: '',
        startTime: '',
        currentPage: 1,
        pageSize: 20
      }
      this.getList()
    },

    // 新增事件
    handleAdd() {
      this.isEdit = false
      this.eventForm = {
        id: '',
        title: '',
        eventType: '',
        startTime: '',
        endTime: '',
        storeId: '',
        storeName: '',
        description: '',
        remark: '',
        attachments: ''
      }
      this.fileList = []
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.eventForm && this.$refs.eventForm.clearValidate()
      })
    },

    // 查看详情
    handleView(row) {
      this.selectedEvent = row
      this.detailVisible = true
    },

    // 编辑事件
    handleEdit(row) {
      this.isEdit = true
      this.eventForm = {
        id: row.Id,
        title: row.Title,
        eventType: row.EventType,
        startTime: row.Start,
        endTime: row.End,
        storeId: row.StoreId,
        storeName: row.Store,
        description: row.Desc,
        remark: row.Remark,
        attachments: row.Attachments
      }
      this.fileList = this.parseAttachments(row.Attachments)
      this.detailVisible = false
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.eventForm && this.$refs.eventForm.clearValidate()
      })
    },

    // 删除事件
    handleDelete(row) {
      this.$confirm('确定要删除该事件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteCalendarEvent(row.Id)
          this.$message.success('删除成功')
          this.getList()
        } catch (e) {
          console.error('删除失败:', e)
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },

    // 提交表单
    handleSubmit() {
      this.$refs.eventForm.validate(async (valid) => {
        if (!valid) return

        if (new Date(this.eventForm.endTime) <= new Date(this.eventForm.startTime)) {
          this.$message.warning('结束时间必须大于开始时间')
          return
        }

        this.submitLoading = true
        try {
          const data = {
            ...this.eventForm,
            attachments: JSON.stringify(this.fileList)
          }

          if (this.isEdit) {
            await updateCalendarEvent(data)
            this.$message.success('更新成功')
          } else {
            await createCalendarEvent(data)
            this.$message.success('创建成功')
          }
          this.dialogVisible = false
          this.getList()
        } catch (e) {
          console.error('保存失败:', e)
          this.$message.error('保存失败')
        } finally {
          this.submitLoading = false
        }
      })
    },

    // 门店选择变化
    handleStoreChange(storeId) {
      const store = this.storeList.find(x => x.id === storeId)
      this.eventForm.storeName = store ? store.fullName : ''
    },

    // 上传成功
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.fileList.push({
          name: file.name,
          url: response.data.url,
          fileName: file.name
        })
      } else {
        this.$message.error('上传失败')
      }
    },

    // 移除文件
    handleUploadRemove(file, fileList) {
      this.fileList = fileList.map(f => ({
        name: f.name,
        url: f.url || (f.response && f.response.data && f.response.data.url),
        fileName: f.name
      }))
    },

    // 上传前校验
    beforeUpload(file) {
      const maxSize = 10 * 1024 * 1024 // 10MB
      if (file.size > maxSize) {
        this.$message.error('文件大小不能超过10MB')
        return false
      }
      return true
    },

    // 解析附件
    parseAttachments(attachments) {
      if (!attachments) return []
      try {
        return typeof attachments === 'string' ? JSON.parse(attachments) : attachments
      } catch {
        return []
      }
    },

    // 格式化时间范围
    formatTimeRange(start, end) {
      if (!start) return '--'
      const fmt = (dt) => {
        const d = new Date(dt)
        return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
      }
      return `${fmt(start)} - ${fmt(end)}`
    },

    // 管理事件类型
    handleManageType() {
      this.eventTypeDialogVisible = true
    },

    // 选择变化
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(item => item.id)
    },

    // 导出数据
    exportData() {
      this.$message.info('导出功能开发中')
    }
  }
}
</script>

<style lang="scss" scoped>
.type-dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 6px;
  vertical-align: middle;
}

.detail-content {
  padding: 10px 0;
}

.detail-row {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px solid #f1f5f9;
  font-size: 14px;

  &:last-child {
    border-bottom: none;
  }
}

.detail-label {
  width: 90px;
  color: #64748b;
  flex-shrink: 0;
}

.detail-value {
  flex: 1;
  color: #111827;

  &--multiline {
    white-space: pre-wrap;
    word-break: break-word;
  }
}

.attachment-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 0;

  i {
    color: #409eff;
  }

  a {
    color: #409eff;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>
