<template>
  <p class="sub_back" @click="handleBack">&#60;返回</p>
  <p class="sub_title">个案辅导</p>
  <el-card class="account-container">
    <img class="edge" src="@/assets/edge1.png" alt="">
    <div class="base">
      <p class="info"><span>姓名：</span>{{info.name}}</p>
      <p class="info"><span>性别：</span>{{info.male}}</p>
      <p class="btn" @click="handleView">基本信息</p>
    </div>
    <p class="info" v-if="info.class"><span>年级：</span>{{info.class}}</p>
    <p class="info"><span>咨询问题：</span>{{info.bookTypeName}}</p>
    <p class="info"><span>咨询描述：</span>{{info.bookDescription}}</p>
    <p class="info"><span>时间：</span>{{info.timeDescription}}</p>
    <p class="history" @click="handleInterview">访谈记录</p>
    <!-- <p class="item_title">开始评估</p> -->
    <p class="item_title">咨询结果</p>
    <div class="result">
      <div class="result_item" :class="level==1?'active':''" @click="level=1">
        <p class="title">一类危机学生</p>
        <p class="des">不需要备案，但班主任需要掌握</p>
      </div>
      <div class="result_item" :class="level==2?'active':''" @click="level=2">
        <p class="title">二类危机学生</p>
        <p class="des">需要在校心理辅导</p>
      </div>
      <div class="result_item" :class="level==3?'active':''" @click="level=3">
        <p class="title">三类危机学生</p>
        <p class="des">加入学生危机预警库，向上级教育行政部门和上级心理健康教育指导中心备案</p>
      </div>
      <div class="result_item" :class="level==4?'active':''" @click="level=4">
        <p class="title">其他</p>
        <p class="des"></p>
      </div>
    </div>
    <template v-if="level==2||level==3">
      <p class="item_title">是否需要转介</p>
      <div>
        <el-radio v-model="info.isNeedsHospital" :label="true">是</el-radio>
        <el-radio v-model="info.isNeedsHospital" :label="false">否</el-radio>
      </div>
      <p class="item_title">评估文件</p>
      <el-upload class="uploader" action="" :file-list="fileList" list-type="picture-card" :http-request="fileUpload" :beforeUpload="beforeUpload" :on-preview="handlePreview" :on-remove="handleRemove">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog v-model="previewImg">
        <img class="preview" :src="formatImg(previewImgUrl)" alt="">
      </el-dialog>
    </template>
    <p class="item_title">留言</p>
    <el-input class="leave" type="textarea" :input-style="{'background':'#F5F7FA','border':'none'}" v-model="leave" placeholder="请输入..." :autosize="{minRows: 5}" resize="none"></el-input>
    <el-button class="book_btn" type="primary" @click="submitCounse">提交</el-button>
    <p class="item_title alllist">历史记录</p>
    <template v-for="(item,index) in historyList" :key="index">
      <div class="history_item" v-if="item.detailId!=detailId">
        <p class="history_title">时间：<span>{{item.timeDescription}}</span></p>
        <p class="history_title">是否需要转介：<span>{{item.isNeedsHospital?'是':'否'}}</span></p>
        <p class="history_title">咨询结果:</p>
        <div class="result">
          <div class="result_item" v-if="item.level==1">
            <p class="title">一类危机学生</p>
            <p class="des">不需要备案，但班主任需要掌握</p>
          </div>
          <div class="result_item" v-if="item.level==2">
            <p class="title">二类危机学生</p>
            <p class="des">需要在校心理辅导</p>
          </div>
          <div class="result_item" v-if="item.level==3">
            <p class="title">三类危机学生</p>
            <p class="des">加入学生危机预警库，向上级教育行政部门和上级心理健康教育指导中心备案</p>
          </div>
          <div class="result_item" v-if="item.level==4">
            <p class="title">其他</p>
            <p class="des"></p>
          </div>
        </div>
        <p class="history_title">留言：<span>{{item.leave}}</span></p>
      </div>
    </template>

  </el-card>
</template>

<script>
import { getCurrentInstance,onMounted, reactive, toRefs, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from '@/utils/axios'
export default {
  name: 'Assessment',
  components: {
  },
  setup () {
    const route = useRoute()
    const router = useRouter()
    const { detailId, UserId } = route.query
     const internalInstance = getCurrentInstance()
    const state = reactive({
      info: '',
      previewImg: false,
      previewImgUrl: '',
      fileList: [],
      uploadFileList: [],
      level: '',
      leave: '',
      isNeedsHospital: false,
      historyList: []
    })
    onMounted(() => {
      getCounseDiagnosis()
      getHistoryCounseDiagnosis()
    })
    // 获取诊断反馈记录
    const getCounseDiagnosis = () => {
      axios.get(`/Counse/Diagnosis?detailId=${detailId}&userId=${UserId}`).then(res => {
        // console.log('诊断反馈记录:', res)
        state.info = res;
        state.uploadFileList = res.fileLocation?.split('|') || [];
        let fileLocation = res.fileLocation?.split('|') || [];
        let fileList = []
        for (let i in fileLocation) {
          fileList.push({ url: formatImg(fileLocation[i]) })
        }
        state.fileList = fileList;
        state.level = res.level;
        state.leave = res.leave;
        state.isNeedsHospital = res.isNeedsHospital;
      }).catch(err => {
        console.log('err', err)
      })
    }
    // 获取历史诊断反馈记录
    const getHistoryCounseDiagnosis = () => {
      axios.get(`/Counse/Diagnosis/List?userId=${UserId}`).then(res => {
        console.log('历史诊断反馈记录:', res)
        state.historyList = res
      }).catch(err => {
        console.log('err', err)
      })
    }
    // 提交
    const submitCounse = () => {
      console.log(state.level)
      console.log(state.fileList)
      if (!state.level) {
        ElMessage.error('请选择评级')
        return;
      }
        let FileLocation = []
        for(let i in state.fileList){
          FileLocation.push(unFormatImg(state.fileList[i].url))
        }
      if (state.info?.diagnosisId == 0) {
        // 新建
        axios.post('/Counse/Diagnosis', {

          "DetailId": detailId,
          "Id": 0,
          "UserId": UserId,
          "Level": state.level,
          "IsNeedsHospital": state.info.isNeedsHospital,
          "FileLocation": FileLocation.join('|'),
          "Leave": state.leave
        }).then(() => {
          ElMessage.success('提交成功')
          handleBack()
        })
      } else {
        // 修改
        axios.put('/Counse/Diagnosis', {
          "DetailId": detailId,
          "Id": state.info.diagnosisId,
          "UserId": UserId,
          "Level": state.level,
          "IsNeedsHospital": state.info.isNeedsHospital,
          "FileLocation": FileLocation.join('|'),
          "Leave": state.leave
        }).then(() => {
          ElMessage.success('修改成功')
          handleBack()
        })
      }
    }
    // 查看基本信息
    const handleView = () => {
      router.push({ path: '/infoDetail', query: { UserId: UserId } })
    }
    // 查看访谈记录
    const handleInterview = () => {
      router.push({ path: '/interview', query: { detailId: detailId } })
    }
    // 上传前拦截
    const beforeUpload = (file) => {
      if (file.type !== 'image/png' && file.type !== 'image/jpeg') {
        ElMessage.error('请上传图片文件')
        return false;
      }
    }
    // 上传告家长书
    const fileUpload = (param) => {
      const formData = new FormData()
      formData.append('file', param.file)
      axios.post('/Upload/CounseFile', formData, { headers: { "Content-Type": "multipart/form-data" } }).then(res => {
        state.fileList.push({url:formatImg(res.urlAddress)})
        console.log(state.fileList)
      })
    }

    const formatImg = (url) => {
      let apiUrl = internalInstance.appContext.config.globalProperties.apiUrl

      return url.replace('D:\\网站\\PyhsicalAdmin\\wwwroot\\wwwroot\\UploadCounseFile', `${apiUrl}UploadCounseFile`)
    }
    const unFormatImg = (url) => {
      let apiUrl = internalInstance.appContext.config.globalProperties.apiUrl
      return url.replace( `${apiUrl}UploadCounseFile`,'D:\\网站\\PyhsicalAdmin\\wwwroot\\wwwroot\\UploadCounseFile')
    }
    const handleRemove = (file, fileList) => {
      console.log('handleRemove', file, fileList)
      state.fileList = fileList
    }
    const handlePreview = (file, fileList) => {
      console.log('handlePreview', file, fileList)
      state.previewImgUrl = file.url
      state.previewImg = true
    }
    const handleBack = () => {
      router.back()
    }
    return {
      ...toRefs(state),
      submitCounse,
      handleBack,
      fileUpload,
      handleInterview,
      beforeUpload,
      formatImg,
      handleView,
      handleRemove,
      handlePreview,
      detailId
    }
  }
}
</script>
<style lang="scss" scoped>
.account-container {
  position: relative;
}
.book_btn {
  display: block;
  margin: 30px auto;
}
.info {
  font-size: 15px;
  padding: 15px 0;
  margin: 0;
  span {
    display: inline-block;
    width: 130px;
    color: #999;
  }
}
.base {
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
  margin-bottom: 20px;
  .info {
    display: inline-block;
    margin-right: 50px;
    span {
      width: auto;
    }
  }
  .btn {
    display: inline-block;
    cursor: pointer;
    text-decoration: underline;
    color: #3a84ff;
  }
}
.history {
  font-size: 17px;
  color: #3a84ff;
  text-decoration: underline;
  margin: 30px 0;
  cursor: pointer;
}
.item_title {
  font-size: 17px;
  font-weight: bold;
  padding: 20px 0;
  margin: 0;
}
.result {
  position: relative;
  .result_item {
    display: inline-block;
    vertical-align: top;
    width: 148px;
    height: 167px;
    font-size: 14px;
    background: #f5f6fa;
    border: 2px solid #f5f6fa;
    margin-right: 30px;
    margin-bottom: 30px;
    box-sizing: border-box;
    padding: 10px;
    &.active {
      background: #fff;
      border: 2px solid #3a84ff;
    }
    .title {
      text-align: center;
      margin: 0;
    }
    .des {
      margin: 0;
      color: #999;
      margin-top: 17px;
      text-align: justify;
    }
  }
}
.uploader {
  position: relative;
}
.preview {
  width: 100%;
}
.leave {
  width: 70%;
}
.alllist {
  margin-top: 50px;
}
.history_item {
  margin-bottom: 30px;
}
.edge {
  width: 289px;
  position: absolute;
  bottom: 30px;
  right: 30px;
  z-index: 0;
}
</style>
<style lang="scss">
.el-upload-list__item {
  transition: none !important;
}
</style>