<script setup>
import { computed, getCurrentInstance, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { showFailToast, showLoadingToast, showSuccessToast } from 'vant';

const base_url = '/sgsafe/KeyMattersRecord';
const { proxy } = getCurrentInstance();

/* 返回上一级页面 */
const router = useRouter();
const route = useRoute();
const onClickLeft = () => {
  router.go(-1);
};

const lowerReportForm = ref({
  keyMattersId: ''
})

const reportingForm = ref({
  itemManifestId: '',
  completionReporting: '',
  completionCount: '1',
  completionTime: ''
});

/**
 * 获取日期
 */
const timeVisible = ref(false);
const timeArr = ref([]);
const formattedTime = computed(() => {
  if (timeArr.value.length === 0) {
    return '';
  }
  const date = timeArr.value;
  if (!date) return '';
  const d = new Date(date);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
});
const onConfirmTime = () => {
  timeVisible.value = false;
  reportingForm.value.completionTime = formattedTime.value;
};


const dataList = ref([])
const queryLowerReporting = () => {
  const url = '/sgsafe/KeyMattersRecord/viewReport'
  const param = {
    json: JSON.stringify(lowerReportForm.value)
  }
  proxy.$axios.post(url, param).then(res => {
    if (res.data.code === 0) {
      dataList.value = res.data.data;
    } else {
      showFailToast('查询下级部门汇报失败')
    }
  })
}

const onSubmit = async (values) => {
  const loadingToast = showLoadingToast({
    duration: 0,
    message: '加载中',
    forbidClick: true
  });
  const url = base_url + '/save';
  const params = {
    json: JSON.stringify(reportingForm.value)
  };
  proxy.$axios.post(url, params).then(res => {
    if (res.data.code === 0) {
      loadingToast.close();
      showSuccessToast('保存成功');
      onClickLeft();
    } else {
      loadingToast.close();
      showFailToast('操作失败!' + res.data.msg);
    }
  });
};

/*const rowAnalysisText = ref('')
const generateRowAnalysis = (row) => {
  // 设置当前行的加载状态
  row.analysisLoading = true

  // 构造提示词
  let prompt = `请总结下面一段话：` + row.completionReporting

  // 构造消息对象
  const messages = [
    {
      role: "user",
      content: prompt
    }
  ]

  // 调用后端AI接口，避免暴露API密钥
  callAIStream(
    messages,
    (content, isEnd) => {

      row.aiAnalysis = content
      if (content) {
        rowAnalysisText.value = content
      }
      // console.log('111',row.aiAnalysis)
      // 如果是最终结果，停止加载状态
      if (isEnd) {
        row.analysisLoading = false
      }
    }
  )
}
const callAIStream = async (messageHistory, callback) => {
  try {
    const url = `${import.meta.env.VITE_BASE_API}/sgsafe/deepseek/chat-stream`

    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'token': localStorage.getItem('token') || '',
        'userId': localStorage.getItem('userId') || ''
      },
      body: JSON.stringify({
        messages: messageHistory
      })
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    if (!response.body) {
      throw new Error('ReadableStream not supported in this browser.')
    }

    // 处理流式响应
    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')
    let buffer = ''
    let fullResponse = ''

    try {
      while (true) {
        const {done, value} = await reader.read()

        if (done) {
          callback(fullResponse, true)
          break
        }

        const chunk = decoder.decode(value, {stream: true})
        buffer += chunk

        // 处理缓冲区数据
        const lines = buffer.split('\n')
        let remainingBuffer = lines.pop() // 保留不完整的行

        for (const line of lines) {
          if (line.trim() === '') continue

          if (line.startsWith('data:')) {
            const data = line.slice(5).trim()

            if (data === '[DONE]') {
              callback(fullResponse, true)
              return
            }

            if (data === '') continue

            try {
              const jsonData = JSON.parse(data)

              if (jsonData.choices?.[0]?.delta) {
                let content = ''
                if (jsonData.choices[0].delta.reasoning_content) {
                  content += jsonData.choices[0].delta.reasoning_content
                }
                if (jsonData.choices[0].delta.content) {
                  content += jsonData.choices[0].delta.content
                }

                if (content) {
                  fullResponse += content
                  callback(fullResponse, false)
                }
              }
            } catch (parseError) {
              console.error('JSON解析错误:', parseError, '数据:', data)
            }
          }
        }

        buffer = remainingBuffer
      }
    } catch (error) {
      console.error('处理流响应失败:', error)
      callback('处理响应时发生错误: ' + error.message, true)
    }
  } catch (error) {
    console.error('AI调用失败:', error)
    callback('AI调用失败: ' + error.message, true)
  }
}*/

const keyMatter = ref({});
const isQuantified = ref(false);
onMounted(() => {
  if (route.query.keyMatter) {
    keyMatter.value = JSON.parse(route.query.keyMatter);
    if (!keyMatter.value.id) {
      showFailToast('数据错误，请联系管理员');
      onClickLeft();
    }
    // console.log(keyMatter.value);
    reportingForm.value.itemManifestId = keyMatter.value.id;
    lowerReportForm.value.keyMattersId = keyMatter.value.id;
    isQuantified.value = keyMatter.value.isQuantified;
  }
  queryLowerReporting()
})

</script>

<template>
  <div class="page-container">
    <van-sticky>
      <van-nav-bar title="重点事项汇报">
      </van-nav-bar>
    </van-sticky>

    <div
      v-for="(report, index) in dataList"
      :key="index"
      class="mobile-report-card"
    >
      <div class="card-header">
        <h4>汇报部门: {{ report.reportingDeptName }}</h4>
      </div>
      <p><strong>汇报内容:</strong> {{ report.completionReporting }}</p>
      <p><strong>完成次数:</strong> {{ report.completionCount }}</p>
      <p><strong>完成时间:</strong> {{ report.completionTime }}</p>
    </div>

  <van-form @submit="onSubmit">
    <van-field
      v-model="reportingForm.completionReporting"
      label="汇报内容"
      type="textarea"
      name="completionReporting"
      required
      placeholder="请输入汇报内容"
      :rules="[{required: true, message: '请输入汇报内容'}]"
    />

    <van-field
      v-if="isQuantified"
      v-model="reportingForm.completionCount"
      type="number"
      label="完成次数"
      name="completionCount"
      required
      :rules="[{required: true, message: '请输入完成次数'},
           { pattern: /^[1-9]\d*$/, message: '必须为正整数' }]"
    />

    <van-field
      readonly
      v-model="formattedTime"
      label="完成时间"
      name="formattedTime"
      placeholder="请选择完成时间"
      required
      :rules="[{required: true, message: '请选择完成时间'}]"
      @click="timeVisible = true"
    />

    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">提交</van-button>
    </div>
  </van-form>

  <van-popup
    :close-on-click-overlay="false"
    v-model:show="timeVisible"
    position="bottom"
    :teleport="false"
  >
    <van-date-picker
      v-model="timeArr"
      type="date"
      @confirm="onConfirmTime"
      @cancel="timeVisible = false"
    />
  </van-popup>
  </div>
</template>

<style scoped>
.page-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.scroll-container {
  flex: 1;
  overflow: auto;
  -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
}

/* 可选：隐藏滚动条（视觉优化） */
.scroll-container::-webkit-scrollbar {
  display: none;
}

.mobile-report-card {
  display: flex;
  flex-direction: column;
  gap: 12px;
  background-color: #ffffff;
  padding: 16px;
  margin: 0 12px 12px;
  border-radius: 8px;
  word-break: break-word;
}

.mobile-report-card .card-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #323233;
}

.mobile-report-card p {
  margin: 0;
  font-size: 14px;
  color: #646566;
  line-height: 1.5;
}

.mobile-report-card p strong {
  color: #323233;
  font-weight: 500;
  margin-right: 4px;
}

</style>
