<template>
  <div>
    <DoctorHeader :msg="did"/>
  </div>
  <div style="display: flex">

    <div>
      <DoctorAside/>
    </div>


    <div style="flex: 2">



      <div v-show="doctorGlancePatient">
<!--        -->
        <div style="height: 5px"></div>
        <div><el-button @click="loadPatientInfo" type="primary">刷新</el-button></div>
        <el-table :data="patientData" :row-class-name="tableRowClassNameA" style="width: 100%" >
          <el-table-column prop="username" label="患者姓名" />
          <el-table-column prop="userid" style="width: 1px" v-if=false type="userid"></el-table-column>
          <el-table-column prop="gender" label="性别" :formatter="formatSex"/>
          <el-table-column prop="address" label="地址" />
          <el-table-column prop="phonenumber" label="联系方式" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                  size="small"
                  type=""
                  @click="showConcreteInfo(scope.row.username,scope.row.gender,scope.row.address,scope.row.phonenumber,scope.row.userid)"
              >查看详情</el-button
              >
              <el-button
                  size="small"
                  type="primary"
                  @click="startChat(scope.row)"
              >发送消息</el-button
              >
            </template>
          </el-table-column>



        </el-table>

        <el-pagination
            :currentPage="currentPageA"
            :page-size="pageSizeA"
            :page-sizes="[5,10,20]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalA"
            @size-change="handleSizeChangeA"
            @current-change="handleCurrentChangeA"
        />
<!--        -->


      </div>

      <div v-if="showModel=='chat'" style="flex: 1;padding-top: 10px">
        <div>
          <el-table :data="WordsList" height="450" style="width: 100%" :show-header=true>
            <el-table-column prop="userA" label="Date" width="100" style="padding-left: 0px"/>
            <el-table-column prop="messageA" label="content" align="left"/>
            <el-table-column prop="messageB" label="content" align="right"/>
            <el-table-column prop="userB" label="Address" style="padding-right: 0px" width="100"/>
          </el-table>
          <el-input v-model="aMessage" placeholder="Please input" :rows="3" type="textarea"/>
          <el-button type="primary" @click="sendMessage">发送</el-button>
          <el-button type="info" @click="chatBackGlance">返回</el-button>
        </div>
      </div>


      <div v-show="doctorViewPatient">


          <!-- 中间部分  -->

          <!-- 中间部分的上部分  -->
          <div style="display: flex">
            <div>
              <!--      图片       -->

            </div>

            <!-- 中间部分的上部分的中间部分  -->
            <div style="flex: 2">
              <div style="display: flex">
                <div style="width: 200px">
                  <h3>姓名：{{patientName}}</h3>
                </div>
                <div style="width: 200px">
                  <h3>性别：{{patientGender}}</h3>
                </div>
                <div style="width: 200px">
                  <h3>地址：{{patientAddress}}</h3>
                </div>
                <div style="width: 600px">
                  <h3>联系方式：{{patientPhoneNumber}}</h3>
                </div>
              </div>
            </div>






            <!-- 中间部分的上部分的中间部分  -->

            <div style="width: 100px"></div>



          </div>
          <!-- 中间部分的上部分  -->



          <!-- 中间部分的中间部分  -->

          <div style="display: flex">
            <div style="display: flex; width: 200px">
            </div>

            <div style="flex: 2">
              <el-button type="info" @click="viewHealthInfo">查看/关闭健康上报信息</el-button>
              <el-button type="primary" @click="backGlance">返回上一页</el-button>
            </div>



          </div>

          <!-- 中间部分的中间部分  -->



          <!-- 中间部分的下部分  -->
        <div style="alignment: left">
          <h2>病历</h2>
          <el-icon @click="addMedicalRecord"><circle-plus-filled /></el-icon>
          <span @click="addMedicalRecord" style="font-weight: bold">开病历</span>
        </div>
          <div>
<!--            -->
            <el-table :data="medicalRecord" :row-class-name="tableRowClassNameB" style="width: 100%" >
              <el-table-column prop="mid" style="width: 1px" v-if=false type="mid"></el-table-column>
              <el-table-column prop="did" style="width: 1px" v-if=false type="did"></el-table-column>
              <el-table-column prop="recordtime" label="就诊时间" sortable/>
              <el-table-column prop="symptom" label="症状"/>
              <el-table-column prop="diagnose" label="诊断" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button
                      size="mini"
                      type="primary"
                      @click="showPrescription(scope.row.mid,scope.row.did,scope.row.recordtime,scope.row.symptom,scope.row.diagnose)"
                  >详情</el-button
                  >
                  <el-button
                      size="mini"
                      type="danger"
                      @click="deleteMedicalReport(scope.row.mid)"
                  >删除</el-button
                  >
                </template>
              </el-table-column>



            </el-table>



            <el-pagination
                :currentPage="currentPageB"
                :page-size="pageSizeB"
                :page-sizes="[5,10,20]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalB"
                @size-change="handleSizeChangeB"
                @current-change="handleCurrentChangeB"
            />


            <div v-show="doctorViewDailyReport">
              <el-table :data="dailyReport" :row-class-name="tableRowClassNameC" style="width: 100%" >
                <el-table-column prop="dailyreportid" style="width: 1px" v-if=false type="dailyreportid"></el-table-column>
                <el-table-column prop="error" style="width: 1px" v-if=false type="error"></el-table-column>
                <el-table-column prop="date" label="日期" sortable />
                <el-table-column prop="temperature" label="体温" />
                <el-table-column prop="highpressure" label="高压" />
                <el-table-column prop="lowpressure" label="低压" />
                <el-table-column prop="heartRate" label="脉率" />
                <el-table-column prop="covidTest" label="核酸检测结果" :formatter="formatTest"/>

              </el-table>
            </div>

            <el-dialog width="30%" v-model="MedicalRecordEdit" >
              <el-form model="MedicalRecordForm" label-width="120px">
                <el-form-item label="症状">
                  <el-input v-model="meSymptom" />
                </el-form-item>
                <el-form-item label="诊断">
                  <el-input v-model="meDiagnose" />
                </el-form-item>
              </el-form>
              <template #footer >
      <span class="dialog-footer">
        <el-button type="info" @click="cancelAddMedicalRecord">取消</el-button>
        <el-button type="primary" @click="confirmAddMedicalRecord">确定</el-button>
      </span>
              </template>
            </el-dialog>





          <!-- 中间部分的下部分  -->
        </div>
        <!-- 中间部分  -->
      </div>


      <div v-show="viewMedicalRecord">

        <div style="alignment: center"><h1>就诊病历</h1></div>

        <div style="display: flex">
          <div style="width: 160px">
            <h3>姓名：{{recordName}}</h3>
          </div>
          <div style="width: 160px">
            <h3>性别：{{recordGender}}</h3>
          </div>
          <div style="width: 160px">
            <h3>地址：{{recordAddress}}</h3>
          </div>
          <div style="width: 240px">
            <h3>主治医生：{{recordDoctor}}</h3>
          </div>
          <div style="width: 500px">
            <h3>就诊时间：{{recordTime}}</h3>
          </div>
          <div>
            <el-button type="info" @click="myFunction">{{myStatus}}</el-button>
            <el-button type="primary" @click="backView">返回上一页</el-button>
          </div>
        </div>
        <el-form model="InfoForm" label-width="90px"
                 :disabled="InfoEdit">
        <el-form-item label="病状描述">
          <el-input v-model="description" type="textarea"/>
        </el-form-item>
        <div style="height: 10px"></div>


        <el-form-item label="诊断">
          <el-input v-model="diagnosis" type="textarea"/>
        </el-form-item>
        </el-form>
        <div style="height: 1px">

        </div>

        <div style="alignment: left">
          <h2>处方</h2>
            <el-icon @click="addPrescription"><circle-plus-filled /></el-icon>
            <span @click="addPrescription" style="font-weight: bold">开处方</span>
        </div>
        <div>
          <el-table :data="prescription" style="width: 100%" >
            <el-table-column prop="id" style="width: 1px" v-if=false type="id"></el-table-column>
            <el-table-column prop="name" label="药品名" />
            <el-table-column prop="specification" label="规格" />
            <el-table-column prop="number" label="数量" />
            <el-table-column prop="way" label="用法" />
            <el-table-column prop="dosage" label="用量" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                    size="mini"
                    type="danger"
                    @click="deletePrescription(scope.row.id)"
                >删除</el-button
                >
              </template>
            </el-table-column>


          </el-table>
        </div>

        <el-dialog width="30%" v-model="PrescriptionEdit" >
          <el-form model="PrescriptionForm" label-width="120px">
            <el-form-item label="药品名" >
              <el-input v-model="preName"/>
            </el-form-item>
            <el-form-item label="规格">
              <el-input v-model="preSpecification" />
            </el-form-item>
            <el-form-item label="数量">
              <el-input v-model="preNumber" />
            </el-form-item>
            <el-form-item label="用法">
              <el-input v-model="preWay" />
            </el-form-item>
            <el-form-item label="用量">
              <el-input v-model="preDosage"/>
            </el-form-item>
          </el-form>
          <template #footer >
      <span class="dialog-footer">
        <el-button type="info" @click="cancelAddPrescription">取消</el-button>
        <el-button type="primary" @click="confirmAddPrescription">确定</el-button>
      </span>
          </template>
        </el-dialog>


      </div>




    </div>


    <div style="width: 50px"></div>
  </div>

</template>

<script>
import {CirclePlusFilled, Edit} from "@element-plus/icons-vue";
import request from "@/utils/request";
import DoctorAside from "@/components/DoctorAside";
import DoctorHeader from "@/components/DoctorHeader";
import { ref } from 'vue'



export default {

  name: "DoctorHomeView",
  components: {
    DoctorHeader,
    DoctorAside,
    CirclePlusFilled,
    Edit,

  },

  created() {
    //获取医生ID
    this.getDoctorId();
    //显示患者信息
    this.loadPatientInfo();

    // if(this.showModel == 'chat'){
    //   this.$nextTick(() => {
    //     setInterval(this.getData, 1000);
    //   });


    this.$nextTick(() => {
      setInterval(this.getData, 1000);
    });
  },


  data(){
    return{
      aMessage: ref(''),
      did: "",
      userIdForView:"",
      mid: "",
      myTime: "",
      doctorGlancePatient: true,
      doctorViewPatient: false,
      viewMedicalRecord: false,
      PrescriptionEdit:false,
      doctorViewDailyReport:false,
      MedicalRecordEdit: false,
      currentPageA:1,
      pageSizeA:10,
      totalA:0,
      currentPageB:1,
      pageSizeB:10,
      totalB:0,
      MedicalRecordForm:{},
      PrescriptionForm:{},
      patientName:"",
      patientGender:"",
      patientAddress:"",
      patientPhoneNumber:"",
      recordName:"",
      recordGender:"",
      recordAddress:"",
      recordDoctor:"",
      recordTime:"",
      description:"",
      diagnosis:"",
      meDiagnose: "",
      meSymptom: "",
      preName: "",
      preSpecification: "",
      preNumber: "",
      preWay: "",
      preDosage: "",
      InfoEdit:true,
      myStatus:"编辑",
      showModel: '',
      patientData:[

      ],
      medicalRecord:[


      ],
      dailyReport:[

      ],
      prescription: [

      ],
      dname: "",
      userid: "",
      username:"",
      WordsList:[]





    }
  },
  methods:{
    getDoctorId(){
      this.did = this.$route.params.id;
      request.get('/doctor/get',{params:{userid:this.did}}).then(res=>{
        this.dname = res.data.username;
      })
    },
    //****************//
    //doctorGlancePatient
    //****************//
    loadPatientInfo(){
      // 将数据库的患者数据总览呈现到前台
      request.get('/doctor/getAllMyUsers',{
        params:{userid:this.did}
      }).then(res=>{
        this.patientData=res.data;
        //console.log(res.data.username)
      })
    },
    showConcreteInfo(username,gender,address,phonenumber,userid){
      //在doctorGlancePatient点击查看详情

      this.patientName = username;
      if(gender===false){
        this.patientGender = "女";
      }
      else {
        this.patientGender = "男";
      }
      this.patientAddress = address;
      this.patientPhoneNumber = phonenumber;
      this.userIdForView = userid;
      //显示病历
      this.loadMedicalRecords();

      this.doctorGlancePatient = false;
      this.doctorViewPatient = true;

    },


    //****************//
    //doctorViewPatient
    //****************//
    loadMedicalRecords(){
      // 将数据库的病历数据呈现到前台
      request.get('/medicalrecord/selectRecordByUid',{
        params:{uid:this.userIdForView}
      }).then(res=>{
        this.medicalRecord=res;
      })
    },

    viewHealthInfo(){
      //查看/关闭健康上报信息
      if(this.doctorViewDailyReport === false){
        this.loadDailyReport();
        this.doctorViewDailyReport = true;

      }
      else {
        this.doctorViewDailyReport = false;
      }


    },
    loadDailyReport(){
      //将健康上报信息呈现出来
      request.get('/dailyReport/selectByUserid',{
        params:{userid:this.userIdForView}
      }).then(res=>{
        this.dailyReport=res.data;
      })
    },
    addMedicalRecord(){
      //添加一个病历
      this.MedicalRecordEdit = true;
    },
    confirmAddMedicalRecord(){
      this.MedicalRecordEdit = false;
      this.setMyTime();
      // var list={
      //   uid: this.userIdForView,
      //   did: this.did,
      //   symptom: this.meSymptom,
      //   diagnose: this.meDiagnose,
      // };
      //this.medicalRecord.push(list);

      //将更新后的数据同步到数据库
      request.post('/medicalrecord/addMedicalRecord',{
        uid: this.userIdForView,
        did: this.did,
        symptom: this.meSymptom,
        diagnose: this.meDiagnose,
      }).then(res=>{
        this.loadMedicalRecords();
      })
      //清空表单内容
      this.clearMedicalRecord();
    },
    cancelAddMedicalRecord(){
      //取消添加病历
      this.MedicalRecordEdit = false;
      this.clearMedicalRecord();
    },
    clearMedicalRecord(){
      //清空表单内容
      this.meSymptom = "";
      this.meDiagnose = "";
    },
    deleteMedicalReport(mid){
      //删除病历
      request.get('/medicalrecord/deleteMedicalrecord',{
        params: {mid: mid}
      }).then(res=>{
        this.loadMedicalRecords();
      })
    },
    showPrescription(mid,did,recordtime,symptom,diagnose){
      //在doctorViewPatient查看病历详情

      this.recordTime = recordtime;
      this.recordGender = this.patientGender;
      this.recordName = this.patientName;
      this.recordAddress = this.patientAddress;
      this.description = symptom;
      this.diagnosis = diagnose;
        request.get('/doctor/get',{
          params:{userid:did}
        }).then(res=>{
          this.recordDoctor = res.data.username;
        })
      //显示处方
      this.mid = mid;

      this.loadPrescription();

      this.doctorViewPatient = false;
      this.viewMedicalRecord = true;
    },

    //****************//
    //viewMedicalRecord
    //****************//
    loadPrescription(){
      // 将数据库的处方数据呈现到前台
      request.get('/medicalrecord/showDetail',{
        params:{mid:this.mid}
      }).then(res=>{
        this.prescription=res.data.drugs;
      })
    },
    myFunction(){
      if(this.myStatus === "编辑"){
        this.InfoEdit = false;
        this.myStatus = "确认";
      }
      else{
        this.InfoEdit = true;
        this.myStatus = "编辑";
        //将更新后的数据同步到数据库
        request.post('/medicalrecord/updateMedicalRecord',{
          mid: this.mid,
          symptom: this.description,
          diagnose: this.diagnosis
        })

      }
    },
    addPrescription(){
      //添加一个处方
      this.PrescriptionEdit = true;
    },
    confirmAddPrescription(){
      this.PrescriptionEdit = false;
      // var list={
      //   id:Object.keys(this.prescription).length + 1,
      //   name: this.preName,
      //   specification: this.preSpecification,
      //   number: this.preNumber,
      //   way: this.preWay,
      //   dosage: this.preDosage
      // };
      //this.prescription.push(list);
      //将更新后的数据同步到数据库

      request.post('/medicalrecord/addDrugs',{
        id: this.mid,
        name: this.preName,
        specification: this.preSpecification,
        number: this.preNumber,
        way: this.preWay,
        dosage: this.preDosage
      }).then(res=>{
        this.loadPrescription();
      })
      //清空表单内容
      this.clearPrescription();
    },
    cancelAddPrescription(){
      //取消添加处方
      this.PrescriptionEdit = false;
      this.clearPrescription();
    },
    clearPrescription(){
      //清空表单内容
      this.preName = "";
      this.preSpecification = "";
      this.preNumber = "";
      this.preWay = "";
      this.preDosage = "";
    },
    deletePrescription(id){
      //删除一个处方
      //this.prescription.splice(id-1,1);
      //同步到数据库
      request.get('/medicalrecord/deleteDrugs',{
        params:{did: id}
      }).then(res=>{
        this.loadPrescription();
      })
    },




    //****************//
    //message
    //****************//
    //切换到聊天界面并把聊天对象的数据进行初始化以便聊天记录查询
    startChat(row){
      this.userid = row.userid;
      this.username = row.username;
      this.doctorGlancePatient = false;
      this.showModel='chat';
      console.log(this.showModel);
    },
    //发送一条消息
    sendMessage(){
      request.get("/sendMessage",{params:{senderid:this.did,receiverid:this.userid,message:this.aMessage}});
      this.aMessage="";
    },
    //读取特定的聊天记录
    getData(){
      request.get("/getMessage",{params:{userid1:this.did,userid2:this.userid}}).then(res=>{
        if(res){
          this.WordsList=[];
          for(var i=0;i<res.length;i++){
            if(res[i].senderid==this.did){
              this.WordsList.push({userA: this.dname+':',messageA: res[i].message});
            }else {
              this.WordsList.push({userB: ':'+this.username,messageB: res[i].message});
            }
          }
        }
      })
    },



    //****************//
    //other
    //****************//
    tableRowClassNameA({row}) {
      //暂未被用到的条件
      if (row.username === "张三") {
        return "dangerousPatient";
      }
      else{
        return "normalPatient";
      }
    },
    tableRowClassNameB({row}) {
      //是否为自己接诊的患者
      if (row.did === this.did) {
        return "selfPatient";
      }
      else{
        return "otherPatient";
      }
    },
    tableRowClassNameC({row}) {
      //健康上报异常的条件
      if (row.error === 1) {
        return "dangerousPatient";
      }
      else{
        return "normalPatient";
      }
    },

    backGlance(){
      //返回患者总览
      this.doctorGlancePatient = true;
      this.doctorViewPatient = false;
    },
    backView(){
      //返回
      this.doctorViewPatient = true;
      this.viewMedicalRecord = false;
    },
    chatBackGlance(){
      //从消息页面返回
      this.showModel = '';
      this.doctorGlancePatient = true;
    },

    setMyTime(){
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth()+1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds();
      this.myTime = yy+'-'+mm+'-'+dd+' '+hh+':'+mf+':'+ss;
    },

    formatSex(row){
      if(row.gender===false){
        return "女"
      }
      else{
        return "男"
      }
    },
    // formatDoctor(row){
    //   request.get('/doctor/get',{
    //     params:{userid:row.did}
    //   }).then(res=>{
    //     return res.data.username;
    //   })
    // },
    formatTest(row){
      if(row.covidTest === false){
        return "阴"
      }
      else{
        return "阳"
      }
    }





  }


}
</script>


<style>
.el-table .dangerousPatient{
  background: #ff3700;
}
.el-table .normalPatient{
  background: #F2F6FC;
}
.el-table .selfPatient{
  background: #39c5bb;
}
.el-table .otherPatient{
  background: #F2F6FC;
}
</style>