<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.search.patientName" prefix-icon="Search" style="width: 240px; margin-right: 10px; margin-bottom: 3px" placeholder="请输入患者姓名"></el-input>
      <el-date-picker
        v-model="data.dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        style="margin-right: 10px; width: 320px"
      />
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin-right: 10px" @click="reset">重置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" plain @click="handleAdd" v-if="data.user && data.user.role === 'patient'">记录症状</el-button>
      <span v-if="data.user && data.user.role === 'doctor'" class="role-tip">您正在查看您的患者症状记录</span>
    </div>

    <div class="card" style="margin-bottom: 5px;">
      <el-table :data="data.tableData" strip>
        <el-table-column label="患者" width="150">
          <template v-slot="scope">
            <div v-if="scope.row.patient">
              <el-image 
                style="width: 40px; height: 40px; border-radius: 50%; display: block" 
                v-if="scope.row.patient.avatar" 
                :src="scope.row.patient.avatar" 
                :preview-src-list="[scope.row.patient.avatar]" 
                preview-teleported>
              </el-image>
              <span style="margin-left: 5px">{{ scope.row.patient.name }}</span>
            </div>
            <span v-else>患者#{{ scope.row.patientId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="症状描述" prop="symptomDesc" show-overflow-tooltip></el-table-column>
        <el-table-column label="严重程度" width="100">
          <template v-slot="scope">
            <el-tag 
              :type="getSeverityTagType(scope.row.severityLevel)"
              effect="dark">
              {{ scope.row.severityLevel }}/10
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="记录时间" width="160">
          <template v-slot="scope">
            {{ formatDate(scope.row.recordTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template v-slot="scope">
            <el-button type="primary" plain @click="handleView(scope.row)">查看</el-button>
            <el-button 
              type="warning" 
              plain 
              @click="handleEdit(scope.row)" 
              v-if="data.user && (data.user.role === 'patient' && data.user.id === scope.row.patientId)">
              编辑
            </el-button>
            <el-button 
              type="danger" 
              plain 
              @click="del(scope.row.id)" 
              v-if="data.user && (data.user.role === 'patient' && data.user.id === scope.row.patientId || data.user.role === 'admin')">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination 
        @current-change="load" 
        background 
        layout="total, prev, pager, next" 
        :page-size="10" 
        v-model:current-page="data.pageNum" 
        :total="data.total"/>
    </div>

    <el-dialog :title="data.formTitle" v-model="data.formVisible" width="60%" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="data.form" label-width="140px" style="padding: 20px">
        <el-form-item label="症状描述" prop="symptomDesc" required>
          <el-input v-model="data.form.symptomDesc" type="textarea" :rows="3" placeholder="请描述您的症状"></el-input>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="严重程度等级" prop="severityLevel" required>
              <el-slider 
                v-model="data.form.severityLevel" 
                :min="1" 
                :max="10" 
                :format-tooltip="value => `${value}/10`"
                show-stops
              >
                <template #marker>
                  <span>{{ data.form.severityLevel }}</span>
                </template>
              </el-slider>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="情绪基线值" prop="emotionScore" required>
              <el-slider 
                v-model="data.form.emotionScore" 
                :min="1" 
                :max="10" 
                :format-tooltip="value => `${value}/10`"
                show-stops
              >
                <template #marker>
                  <span>{{ data.form.emotionScore }}</span>
                </template>
              </el-slider>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活力持续时间" prop="energyDuration" required>
              <el-input-number v-model="data.form.energyDuration" :min="0" :max="24" placeholder="小时"></el-input-number>
              <span style="margin-left: 10px">小时</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="兴趣恢复度" prop="interestRecovery" required>
              <el-input-number v-model="data.form.interestRecovery" :min="0" :max="100" placeholder="%"></el-input-number>
              <span style="margin-left: 10px">%</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入睡所需时间" prop="sleepTime" required>
              <el-input-number v-model="data.form.sleepTime" :min="0" :max="240" placeholder="分钟"></el-input-number>
              <span style="margin-left: 10px">分钟</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="夜间觉醒次数" prop="wakeCount" required>
              <el-input-number v-model="data.form.wakeCount" :min="0" :max="20" placeholder="次数"></el-input-number>
              <span style="margin-left: 10px">次</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="晨醒时间" prop="morningWake" required>
              <el-time-picker v-model="data.form.morningWakeTime" format="HH:mm" placeholder="请选择时间"></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进食完成度" prop="mealCompletion" required>
              <el-input-number v-model="data.form.mealCompletion" :min="0" :max="100" placeholder="%"></el-input-number>
              <span style="margin-left: 10px">%</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="疼痛位置" prop="painLocation">
              <el-input v-model="data.form.painLocation" placeholder="请描述疼痛位置，若无可不填"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="疼痛强度" prop="painIntensity">
              <el-slider 
                v-model="data.form.painIntensity" 
                :min="0" 
                :max="10" 
                :format-tooltip="value => `${value}/10`"
                show-stops
              >
                <template #marker>
                  <span>{{ data.form.painIntensity }}</span>
                </template>
              </el-slider>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="短期记忆测试" prop="memoryTest" required>
              <el-input-number v-model="data.form.memoryTest" :min="0" :max="3" placeholder=""></el-input-number>
              <span style="margin-left: 10px">/3</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="决策耗时" prop="decisionTime" required>
              <el-input-number v-model="data.form.decisionTime" :min="0" :max="120" placeholder="分钟"></el-input-number>
              <span style="margin-left: 10px">分钟</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="注意力跨度" prop="attentionSpan" required>
              <el-input-number v-model="data.form.attentionSpan" :min="0" :max="120" placeholder="分钟"></el-input-number>
              <span style="margin-left: 10px">分钟</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自杀意念频率" prop="suicidalThought" required>
              <el-input-number v-model="data.form.suicidalThought" :min="0" :max="100" placeholder="次数"></el-input-number>
              <span style="margin-left: 10px">次</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="记录时间" prop="recordTime" required v-if="!data.isView">
          <el-date-picker
            v-model="data.form.recordTime"
            type="datetime"
            placeholder="选择日期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save" v-if="!data.isView">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, onMounted, watch } from "vue";
import request from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";

const data = reactive({
  user: JSON.parse(localStorage.getItem("xm-user") || "{}"),
  dateRange: [],
  tableData: [],
  total: 0,
  pageNum: 1,
  pageSize: 10,
  formVisible: false,
  formTitle: "",
  isView: false,
  form: {
    severityLevel: 5,
    emotionScore: 5,
    painIntensity: 0,
    recordTime: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ')
  },
  search: {}
});

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  return dayjs(dateString).format('YYYY-MM-DD HH:mm');
};

// 根据严重程度返回标签类型
const getSeverityTagType = (level) => {
  if (level <= 3) return 'success';
  if (level <= 6) return 'warning';
  return 'danger';
};

// 监听表单中的morningWakeTime变化，转换为字符串保存到morningWake
watch(() => data.form.morningWakeTime, (newVal) => {
  if (newVal) {
    data.form.morningWake = dayjs(newVal).format('HH:mm');
  }
});

// 加载数据
const load = () => {
  request
    .get("/symptomRecord/selectPage", {
      params: {
        pageNum: data.pageNum,
        pageSize: 10,
        patientName: data.search.patientName,
        startDate: data.dateRange && data.dateRange.length > 0 ? data.dateRange[0] : null,
        endDate: data.dateRange && data.dateRange.length > 1 ? data.dateRange[1] : null
      }
    })
    .then((res) => {
      if (res.code === "200") {
        data.tableData = res.data.list || [];
        data.total = res.data.total;
      } else {
        ElMessage.error(res.msg);
      }
    });
};

// 重置查询条件
const reset = () => {
  data.dateRange = [];
  data.search = {};
  load();
};

// 打开新增弹窗
const handleAdd = () => {
  data.formVisible = true;
  data.formTitle = "记录症状";
  data.form = {
    symptomDesc: '',
    severityLevel: 5,
    emotionScore: 5,
    energyDuration: 0,
    interestRecovery: 0,
    sleepTime: 0,
    wakeCount: 0,
    morningWakeTime: null,
    morningWake: '',
    mealCompletion: 0,
    painLocation: '',
    painIntensity: 0,
    memoryTest: 0,
    decisionTime: 0,
    attentionSpan: 0,
    suicidalThought: 0,
    recordTime: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ')
  };
  data.isView = false;
};

// 打开编辑弹窗
const handleEdit = (row) => {
  data.formVisible = true;
  data.formTitle = "编辑症状记录";
  
  // 深拷贝行数据
  const formData = JSON.parse(JSON.stringify(row));
  
  // 处理时间显示
  if (formData.morningWake) {
    formData.morningWakeTime = `2023-01-01T${formData.morningWake}:00`;
  }
  
  // 确保recordTime格式正确
  if (formData.recordTime && typeof formData.recordTime === 'string') {
    if (!formData.recordTime.includes('T')) {
      formData.recordTime = dayjs(formData.recordTime).format('YYYY-MM-DDTHH:mm:ss.SSSZ');
    }
  }
  
  data.form = formData;
  data.isView = false;
};

// 打开查看弹窗
const handleView = (row) => {
  data.formVisible = true;
  data.formTitle = "查看症状记录";
  
  // 深拷贝行数据
  const formData = JSON.parse(JSON.stringify(row));
  
  // 处理时间显示
  if (formData.morningWake) {
    formData.morningWakeTime = `2023-01-01T${formData.morningWake}:00`;
  }
  
  // 确保recordTime格式正确
  if (formData.recordTime && typeof formData.recordTime === 'string') {
    if (!formData.recordTime.includes('T')) {
      formData.recordTime = dayjs(formData.recordTime).format('YYYY-MM-DDTHH:mm:ss.SSSZ');
    }
  }
  
  data.form = formData;
  data.isView = true;
};

// 删除
const del = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗?', '删除确认', { type: 'warning' }).then(() => {
    request.delete(`/symptomRecord/${id}`).then((res) => {
      if (res.code === "200") {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(() => {
    // 取消删除
  });
};

// 新增
const add = () => {
  // 处理时间格式
  if (data.form.morningWakeTime) {
    data.form.morningWake = dayjs(data.form.morningWakeTime).format('HH:mm');
  }
  
  // 确保recordTime是正确的ISO格式
  if (data.form.recordTime && typeof data.form.recordTime === 'string' && !data.form.recordTime.includes('T')) {
    data.form.recordTime = dayjs(data.form.recordTime).format('YYYY-MM-DDTHH:mm:ss.SSSZ');
  }
  
  request.post("/symptomRecord", data.form).then((res) => {
    if (res.code === "200") {
      data.formVisible = false;
      ElMessage.success("添加成功");
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 更新
const update = () => {
  // 处理时间格式
  if (data.form.morningWakeTime) {
    data.form.morningWake = dayjs(data.form.morningWakeTime).format('HH:mm');
  }
  
  // 确保recordTime是正确的ISO格式
  if (data.form.recordTime && typeof data.form.recordTime === 'string' && !data.form.recordTime.includes('T')) {
    data.form.recordTime = dayjs(data.form.recordTime).format('YYYY-MM-DDTHH:mm:ss.SSSZ');
  }
  
  request.put("/symptomRecord", data.form).then((res) => {
    if (res.code === "200") {
      data.formVisible = false;
      ElMessage.success("更新成功");
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 保存
const save = () => {
  // 基本验证
  if (!data.form.symptomDesc) {
    ElMessage.warning("请填写症状描述");
    return;
  }
  
  data.form.id ? update() : add();
};

onMounted(() => {
  load();
});
</script>

<style scoped>
.card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
  background-color: #fff;
  color: #303133;
  margin: 10px 0;
  padding: 10px;
  border-radius: 6px;
}

.role-tip {
  color: #909399;
  font-size: 14px;
}

:deep(.el-slider__button) {
  border: 2px solid #409EFF;
}

:deep(.el-slider__bar) {
  background-color: #409EFF;
}
</style> 