<template>
  <view class="content">
    <wd-toast />
    <wd-cell-group style="padding: 30rpx 20rpx" title="" border>
      <wd-cell title="事件ID" title-width="100%" :label="form.id" />
      <wd-cell title="事件类型" title-width="100%" :label="form.ext2.lx" />
      <wd-cell title="发生时间" title-width="100%" :label="form.createTimeFormat" />
      <wd-cell
        title="事件等级"
        :label="eventLevel.filter((item) => item.value == form.level)[0]?.label"
      />
      <wd-cell title="桩号" :label="form.ext2.zh" />
      <wd-cell title="地点描述" title-width="100%" :label="form.addr" />
      <wd-cell title="现场画面" title-width="100%">
        <template #label>
          <wd-img
            v-for="item in form.imgList"
            :key="item"
            :width="80"
            :height="80"
            :radius="4"
            :src="item"
            :enable-preview="true"
            style="margin-right: 20rpx"
          />
        </template>
      </wd-cell>
      <wd-cell title="现场视频" title-width="100%">
        <template #label>
          <view class="videos">
            <view
              v-for="(item, index) in form.videoList"
              :key="index"
              :id="`dplayer${index}`"
            ></view>
          </view>
        </template>
      </wd-cell>
    </wd-cell-group>
    <view class="report-btn">
      <img @click="generateClick" src="/static/images/report.svg" alt="" />
    </view>
    <wd-cell-group v-show="showReport" style="padding: 0 10rpx 20rpx" title="">
      <wd-cell title="报告内容:" title-width="100%">
        <template #label>
          <view class="report-editor">
            <editor
              id="editor"
              class="ql-container"
              placeholder="开始输入..."
              @ready="onEditorReady"
            >
            </editor>
          </view>
        </template>
      </wd-cell>
      <wd-picker
        :columns="fileTypeOptions"
        label="格式选择："
        v-model="reportForm.type"
        align-right
      />
      <wd-message-box custom-class="custom-dialog" selector="wd-message-box-slot">
        <wd-form ref="reportFormRef" :model="reportForm">
          <wd-cell-group border>
            <wd-input
              label="期数"
              prop="seq"
              v-model="reportForm.seq"
              placeholder="请输入"
              :rules="[{ required: true, message: '请输入' }]"
            />
            <wd-input
              label="发送范围"
              prop="fw"
              v-model="reportForm.fw"
              placeholder="请输入"
              :rules="[{ required: true, message: '请输入' }]"
            />
            <wd-input
              label="备案号"
              prop="ba"
              v-model="reportForm.ba"
              placeholder="请输入"
              :rules="[{ required: true, message: '请输入' }]"
            />
            <wd-input
              label="值班员"
              prop="zby"
              v-model="reportForm.zby"
              placeholder="请输入"
              :rules="[{ required: true, message: '请输入' }]"
            />
            <wd-input
              label="审核"
              prop="sh"
              v-model="reportForm.sh"
              placeholder="请输入"
              :rules="[{ required: true, message: '请输入' }]"
            />
            <wd-input
              label="签发"
              prop="qf"
              v-model="reportForm.qf"
              placeholder="请输入"
              :rules="[{ required: true, message: '请输入' }]"
            />
          </wd-cell-group>
        </wd-form>
      </wd-message-box>
      <wd-button
        type="success"
        :round="false"
        style="background: #2ab55c; margin-left: 20rpx; margin-top: 20rpx"
        @click="htmlToPdfFn"
        >导出报告</wd-button
      >
    </wd-cell-group>
  </view>
</template>
<script setup>
  import DPlayer from 'dplayer'
  import { useMessage, useToast } from 'wot-design-uni'
  import { downloadFile } from '@/utils/download.js'
  import { encodeBase64, decodeBase64 } from '@/utils/cryptoJs.js'
  const message = useMessage('wd-message-box-slot')
  const toast = useToast()
  const { API_EVENT_GEN, API_EVENT_GET, API_EVENT_UPDATE, API_CONFIG_GET, API_CONFIG_UPDATE } =
    useRequest()
  const editorCtx = ref({})
  const valueHtml = ref('')
  const reportFormRef = ref(null)
  const eventLevel = [
    {
      label: '内部掌握',
      value: '1'
    },
    {
      label: '建议上报',
      value: '2'
    }
  ]
  const fileTypeOptions = [
    {
      value: 'pdf',
      label: 'pdf'
    },
    {
      value: 'docx',
      label: 'word'
    }
  ]
  const showReport = ref(false)
  const form = ref({
    ext2: {
      lx: '',
      zh: ''
    }
  })
  const reportSeq = ref(1)
  const reportForm = reactive({
    year: '',
    seq: 1,
    title: '',
    month: '',
    day: '',
    content: '',
    fw: '市委、市政府总值班室',
    qf: '朱劲',
    sh: '宗仁',
    ps: '',
    ba: 'KB608',
    zby: '83194295',
    tpl: 'sg.docx',
    type: 'pdf'
  })
  onLoad(async (data) => {
    API_EVENT_GET(data.id).then(({ code, data }) => {
      if (code === 200) {
        data.ext1 = JSON.parse(data.ext1) || []
        data.ext2 = JSON.parse(data.ext2) || {}
        data.status = data.status || '2'
        let imgList = []
        let videoList = []
        if (data.ext1 && data.ext1.length) {
          videoList = data.ext1
            .filter((item) => item.includes('mp4'))
            .map((item) => `${import.meta.env.VITE_APP_API_BASEURL}/api/oss/local/upload/${item}`)
          imgList = data.ext1
            .filter((item) => !item.includes('mp4'))
            .map((item) => `${import.meta.env.VITE_APP_API_BASEURL}/api/oss/local/upload/${item}`)
        }
        form.value = data
        Object.assign(form.value, { imgList, videoList })
        nextTick(() => {
          form.value.videoList.forEach((item, index) => {
            new DPlayer({
              container: document.getElementById(`dplayer${index}`),
              video: {
                url: item
              }
            })
          })
        })
        const { content, ext2 } = form.value
        if (content) {
          showReport.value = true
          dealReportData(decodeBase64(content), ext2.reportTime)
        }
      }
    })
  })
  const generateClick = () => {
    toast.loading('正在生成AI报告...')
    API_EVENT_GEN(form.value.id).then(async ({ code, msg }) => {
      toast.close()
      if (code === 200 && msg) {
        showReport.value = true
        const { report, time } = JSON.parse(msg).data.outputs
        const reportHtml = report.replace(/```/g, '').replace(/html\n/, '')
        API_EVENT_UPDATE({
          id: form.value.id,
          content: encodeBase64(reportHtml),
          ext2: JSON.stringify({
            ...form.value.ext2,
            reportTime: time
          })
        })
        dealReportData(reportHtml, time)
        toast.success('报告生成成功')
      } else {
        toast.error('报告生成失败')
      }
    })
  }
  const extractDate = (dateStr) => {
    // 统一处理两种格式的正则表达式
    const match = dateStr.match(/(\d{4})[^\d]*(\d{1,2})[^\d]*(\d{1,2})/)

    if (!match) return null

    return {
      year: parseInt(match[1]),
      month: parseInt(match[2]),
      day: parseInt(match[3])
    }
  }
  const dealReportData = async (reportHtml, time) => {
    const res = await API_CONFIG_GET('report_seq')
    reportSeq.value = Number(res.data)
    valueHtml.value = reportHtml
    const { year, month, day } = extractDate(time)
    reportForm.year = year
    reportForm.month = month
    reportForm.day = day
    reportForm.seq = reportSeq.value
    editorCtx.value.setContents({
      html: valueHtml.value
    })
  }
  const extractTitleAndContents = (htmlString) => {
    // 提取标题（从 <h2><strong> 中获取）
    const titleMatch = htmlString.match(/<h2[^>]*>.*?<strong>(.*?)<\/strong>.*?<\/h2>/is)
    const title = titleMatch ? titleMatch[1].trim() : ''

    // 提取所有 <p> 内容（从 <p><span> 中获取）
    const contentMatches = [
      ...htmlString.matchAll(/<p[^>]*>.*?<span[^>]*>(.*?)<\/span>.*?<\/p>/gis)
    ]
    const contents = contentMatches.map((match) => match[1].trim())

    return {
      title,
      contents
    }
  }
  const htmlToPdfFn = async () => {
    message
      .confirm({
        title: '',
        beforeConfirm: ({ resolve }) => {
          reportFormRef.value.validate().then(({ valid, errors }) => {
            if (valid) {
              toast.loading('正在导出...')
              editorCtx.value.getContents({
                success: ({ html }) => {
                  const { title, contents } = extractTitleAndContents(html)
                  reportForm.title = title
                  reportForm.content = contents.join('')
                  downloadFile(`loadFile/generate`, {
                    method: 'POST',
                    data: reportForm,
                    filename: `${reportForm.title}.${reportForm.type}`,
                    onProgress: (percent) => {
                      console.log(percent)
                      if (percent === 100) {
                        toast.close()
                        resolve(true)
                        toast.success('报告导出成功')
                        API_CONFIG_UPDATE('report_seq', reportSeq.value + 1)
                      }
                    }
                  })
                }
              })
            }
          })
        }
      })
      .then(() => {})
  }
  const onEditorReady = () => {
    uni
      .createSelectorQuery()
      .select('#editor')
      .context((res) => {
        editorCtx.value = res.context
        console.log(editorCtx.value)
      })
      .exec()
  }
</script>
<style lang="scss" scoped>
  .videos {
    display: flex;
    flex-wrap: wrap;

    view {
      height: 400rpx;
      border-radius: 8rpx;
      margin-top: 20rpx;
    }
  }

  .report-btn {
    padding: 10rpx 50rpx 20rpx;
  }

  .report-editor {
    margin-top: 20rpx;
    padding: 10rpx;
    border: 1rpx solid #d9d9d9;
    height: 600rpx;
    .ql-container {
      height: 100%;
    }
  }
  .content {
    min-height: 100vh;
    :deep(.wd-message-box__body.is-no-title) {
      padding: 30rpx 0px 0px;
    }
    // :deep(.wd-message-box__content) {
    //   max-height: 700rpx;
    // }
  }
</style>
