<template>
  <div class="p10">
    <el-form ref="form" label-position="top" inline>
      <el-form-item label="时间" prop="time">
        <el-select size="medium" v-model="form.time">
          <el-option
            v-for="item in timeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="是否标注" prop="time">-->
      <!--        <el-select size="medium" v-model="form.time"></el-select>-->
      <!--      </el-form-item>-->
      <el-form-item label="搜索" prop="keyWord">
        <el-input size="medium" v-model="form.keyWord"></el-input>
      </el-form-item>
      <!--      <el-form-item label="排序" prop="time">-->
      <!--        <el-select size="medium" v-model="form.time"></el-select>-->
      <!--      </el-form-item>-->
    </el-form>

    <r-table
      :columns="columns"
      :data="tableConfig.tableData"
      :deletion="false"
      :total="tableConfig.total"
      @currentChange="handleCurrentChange"
      @sizeChange="handleSizeChange"
      :currentPage="tableConfig.pageNum"
      :pageSize="tableConfig.pageSize"
    ></r-table>
  </div>
</template>
<script>
import { conversationLog } from '@/views/intelligent-agent/children/Logs&overview/components/API'
import { timeOptions } from '@/assets/js/utils/utilOptions'
import '@/assets/js/business-common'

export default {
  name: 'logs',
  data() {
    return {
      form: {
        time: '9',
        keyWord: ''
      },
      timeOptions,
      tableConfig: {
        tableData: [],
        pageSize: 10,
        pageNum: 1,
        total: 0
      }
    }
  },
  props: {},
  watch: {},
  components: {},
  filters: {},
  methods: {
    /**
     * 根据 value 返回对应的时间范围
     * @param {string} value - 选项值，如 '2', '3', ..., '8'
     * @returns {{startDate: string, endDate: string}}
     */
    getDateRangeByValue(value) {
      const today = new Date()

      // 辅助函数：格式化日期为 yyyy-MM-dd
      function formatDate(date) {
        const y = date.getFullYear()
        const m = String(date.getMonth() + 1).padStart(2, '0')
        const d = String(date.getDate()).padStart(2, '0')
        return `${y}-${m}-${d}`
      }

      let startDate = ''
      let endDate = ''

      switch (value) {
        case '1': // 今天
          endDate = startDate = formatDate(today)
          break
        case '2': // 过去7天
          startDate = formatDate(
            new Date(today.getTime() - 6 * 24 * 60 * 60 * 1000)
          )
          endDate = formatDate(today)
          break
        case '3': // 过去4周（28天）
          startDate = formatDate(
            new Date(today.getTime() - 27 * 24 * 60 * 60 * 1000)
          )
          endDate = formatDate(today)
          break
        case '4': // 过去3个月（约90天）
          startDate = formatDate(
            new Date(today.getTime() - 89 * 24 * 60 * 60 * 1000)
          )
          endDate = formatDate(today)
          break
        case '5': // 过去12个月（约365天）
          startDate = formatDate(
            new Date(today.getTime() - 364 * 24 * 60 * 60 * 1000)
          )
          endDate = formatDate(today)
          break
        case '6': // 本月至今
          startDate = formatDate(
            new Date(today.getFullYear(), today.getMonth(), 1)
          )
          endDate = formatDate(today)
          break
        case '7': // 本季度至今
          const quarterStartMonth = Math.floor(today.getMonth() / 3) * 3
          startDate = formatDate(
            new Date(today.getFullYear(), quarterStartMonth, 1)
          )
          endDate = formatDate(today)
          break
        case '8': // 本年至今
          startDate = formatDate(new Date(today.getFullYear(), 0, 1))
          endDate = formatDate(today)
          break
        default:
          startDate = endDate = formatDate(today)
          break
      }

      return { startDate, endDate }
    },
    handleCurrentChange(val) {
      this.tableConfig.pageNum = val
      this.load()
    },
    handleSizeChange(val) {
      this.tableConfig.pageNum = 1
      this.tableConfig.pageSize = val
      this.load()
    },
    load() {
      let params = {
        page: this.tableConfig.pageNum,
        pageSize: this.tableConfig.pageSize,
        appId: this.$route.query.appId,
        keyword: this.form.keyWord
      }
      if (this.form.time !== '9') {
        let times = this.getDateRangeByValue(this.form.time)
        params.startDate = times.startDate
        params.endDate = times.endDate
      }

      conversationLog(params).then(res => {
        if (res) {
          this.tableConfig.tableData = res.content.content.list
          this.tableConfig.total = res.content.content.total
        }
      })
    }
  },
  created() {},
  mounted() {
    this.load()
  },
  computed: {
    columns: () => {
      return [
        {
          title: '标题',
          prop: 'name'
        },
        // {
        //   label: '用户',
        //   prop: 'time'
        // },
        {
          label: '状态',
          prop: 'content',
          render: (h, params) => {
            let text = ''
            let color = ''
            if (params.row.status_count.success === params.row.message_count) {
              text = 'SUCCESS'
              color = 'green'
            } else {
              text = 'FAILED'
              color = 'red'
            }
            return h(
              'div',
              {
                style: {
                  color: color
                }
              },
              text
            )
          }
        },
        {
          label: '消息数',
          prop: 'message_count',
          render: (h, params) => {
            return h('SPAN', params.row.message_count)
          }
        },
        {
          label: '用户反馈',
          prop: 'operation',
          render: (h, params) => {
            return h('SPAN', 'N/A')
          }
        },
        {
          label: '管理员反馈',
          prop: 'operation',
          render: (h, params) => {
            return h('SPAN', 'N/A')
          }
        },
        {
          label: '更新时间',
          prop: 'operation',
          render: (h, params) => {
            let data = new Date(Number(params.row.updated_at + '000')).format(
              'yyyy-MM-dd hh:mm'
            )
            return h('SPAN', data)
          }
        },
        {
          label: '创建时间',
          prop: 'operation',
          render: (h, params) => {
            let data = new Date(Number(params.row.created_at + '000')).format(
              'yyyy-MM-dd hh:mm'
            )
            return h('SPAN', data)
          }
        }
      ]
    }
  }
}
</script>
<style scoped lang="scss">
#logs-container {
}
</style>
