<template>
  <!-- <div class="main-contain">
      <div class="position">
         <bread-crumb></bread-crumb>
      </div> -->
  <div class="patient-container">
    <patient-sidebar :id="patient_id" defaultActive="1-2"></patient-sidebar>
    <!-- <div class="app-container"> -->
    <div v-loading="loading">
      <div class="patient-app-container advice-container app-container">

        <div>
                    <span style="margin-left: 10px;float:right;">
                        <el-button type="primary" icon="el-icon-circle-plus-outline" size="small"
                                   @click="show_dialog = true">新增</el-button>

                        <el-button type="primary" icon="el-icon-edit-outline" size="small"
                                   @click="showEdit">修改</el-button>
                      <el-button type="primary" icon="el-icon-printer" size="small"
                                 @click="print">打印</el-button>
                        <el-button size="small" v-show="selectingRows.length > 0" type="danger"
                                   @click="deleteAction">删除</el-button>
                    </span>
          <!--<span class="filter_title">日期查询</span>-->
          <!--<el-date-picker size="small" v-model="date" type="daterange" range-separator="至" start-placeholde="开始日期" end-placeholde="结束日期" value-format="timestamp" :clearable="false" @change="requestCourseRecords()"></el-date-picker>-->
        </div>
        <!--<div></div>-->
        <div class="cell clearfix">
          <label class="title"><span class="name">日期查询</span> : </label>
          <el-date-picker v-model="start_time" prefix-icon="el-icon-date" :editable="false" style="width: 196px;"
                          type="date" placeholder="选择日期时间" align="right" format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd" @change="startTimeChange"></el-date-picker>
          <span class="">-</span>
          <el-date-picker v-model="end_time" prefix-icon="el-icon-date" :editable="false" style="width: 196px;"
                          type="date" placeholder="选择日期时间" align="right" format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd" @change="endTimeChange"></el-date-picker>
        </div>
        <div class="record">
          <el-row :gutter="15">
            <el-col :span="10">
              <el-table :header-cell-style="{
                  backgroundColor: 'rgb(245, 247, 250)',
                  color: '#606266'
                }"
                :row-style="{ color: '#303133' }" ref="record_table" :data="records"
                        border highlight-current-row @current-change="didChangeCurrentRecord"
                        @selection-change="didSelectionChange"
                        :row-class-name="tableRow"
                        @row-click="onRowClick"
              >
                <el-table-column type="selection" width="40" align="center"></el-table-column>
                <el-table-column label="病程标题" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.title}}
                  </template>
                </el-table-column>
                <el-table-column label="记录时间" align="center">
                  <template slot-scope="scope">
                    {{ recordTime(scope.row.record_time) }}
                  </template>
                </el-table-column>
                <el-table-column label="记录医生" align="center">
                  <template slot-scope="scope">
                    {{ doctorName(scope.row.recorder) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
            <el-col :span="14">
              <div class="record_content_panel">
                <div style="background-color:rgb(245, 247, 250)" class="title">病程内容</div>
                <div class="content">
                  <span v-if="current_select_record" v-html="current_select_record.content">{{current_select_record.content }}</span>
                  <span v-else></span>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      <!-- </div> -->
      <el-dialog title="新增病程记录" width="50%" top="5vh" :visible.sync="show_dialog">
        <div>
          <div class="new_record_form">
            <div class="cell clearfix">
              <label class="title"><span class="name">病程日期</span> : </label>
              <el-date-picker v-model="course_of_disease_time" prefix-icon="el-icon-date" :editable="false"
                              style="width: 200px;"
                              type="datetime" placeholder="选择日期时间" align="right" format="yyyy-MM-dd HH:mm"
                              value-format="yyyy-MM-dd HH:mm"></el-date-picker>

              <label class="title"><span class="name">日常病程</span> : </label>
              <el-select v-model="select_template" placeholder="可选择病程模板" @change="didSelectTemplate">
                <el-option v-for="(option, index) in templates" :key="index" :label="option.title"
                           :value="option.content"></el-option>
              </el-select>
            </div>

            <div class="cell clearfix" style="margin-top: 10px">
              <label class="title"><span class="name">病程标题</span> : </label>
              <el-input v-model="title" style="width: 420px"></el-input>
            </div>


            <div class="textarea_panel">
              <keep-alive>
                <editor ref="editor"
                        id="editors"
                        style="width: 600px"
                        v-bind:r_content="new_content"
                        >
                </editor>
              </keep-alive>
            </div>

            <div style="text-align: right; padding-right: 0px; padding-top: 10px; padding-bottom: 10px;">
              <el-button @click="show_dialog = false">取消</el-button>
              <el-button :disabled="$store.getters.xt_user.subscibe.state==3?true:false" type="primary"
                         @click="createAction" :loading="uploading_new_record">保存
              </el-button>
            </div>
          </div>
        </div>
      </el-dialog>


      <el-dialog title="修改病程记录" width="50%" top="5vh" :visible.sync="show_edit_dialog">
        <div>
          <div class="new_record_form">
            <div class="cell clearfix">
              <label class="title"><span class="name">病程日期</span> : </label>
              <el-date-picker v-model="edit_course_of_disease_time" prefix-icon="el-icon-date" :editable="false"
                              style="width: 200px;"
                              type="datetime"
                              placeholder="选择日期时间" align="right" format="yyyy-MM-dd HH:mm"
                              value-format="yyyy-MM-dd HH:mm"></el-date-picker>

              <label class="title"><span class="name">日常病程</span> : </label>
              <el-select v-model="select_template" placeholder="可选择病程模板" @change="didEditSelectTemplate">
                <el-option v-for="(option, index) in templates" :key="index" :label="option.title"
                           :value="option.content"></el-option>
              </el-select>
            </div>


            <div class="cell clearfix" style="margin-top: 10px">
              <label class="title"><span class="name">病程标题</span> : </label>
              <el-input v-model="edit_title" style="width: 420px"></el-input>
            </div>

            <div class="textarea_panel">
              <!--<el-input v-model="edit_new_content" type="textarea" rows="6" resize="none"></el-input>-->
              <keep-alive>
                <editor ref="edit_neditor"
                        id="edit_editor"
                        style="width: 600px"
                        v-bind:r_content="edit_new_content">
                </editor>
              </keep-alive>
            </div>

            <div style="text-align: right; padding-right: 0px; padding-top: 10px; padding-bottom: 10px;">
              <el-button @click="show_edit_dialog = false">取消</el-button>
              <el-button :disabled="$store.getters.xt_user.subscibe.state==3?true:false" type="primary"
                         @click="modifyAction" :loading="uploading_new_record">保存
              </el-button>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>

  <!-- </div> -->
</template>

<script>
  import PatientSidebar from './components/PatientSidebar'
  import Editor from '@/components/Editor'

  import {
    createCourseOfDiseaseRecord,
    deleteCourseOfDiseaseRecords,
    getCourseOfDiseaseRecords,
    modifyCourseOfDiseaseRecord,
    GetCoursePrintData
  } from '@/api/patient'
  import { parseTime } from '@/utils'
  import BreadCrumb from '@/xt_pages/components/bread-crumb'

  export default {
    name: 'CourseOfDisease',
    components: {
      PatientSidebar,
      BreadCrumb,
      Editor
    },
    data() {
      return {
        loading: false,
        title: '',
        patient_id: 0,
        date: [],
        start_time: '',
        end_time: '',
        course_of_disease_time: '',
        records: [],
        doctors: [],
        current_select_record: null,
        show_dialog: false,
        show_edit_dialog: false,
        uploading_new_record: false,
        templates: this.$store.getters.configlist.course_disease,
        select_template: '',
        new_content: '',
        edit_new_content: '',
        edit_course_of_disease_time: '',
        selectingRows: [],
        table_current_index: -1,
        edit_current_id: 0,
        edit_title: ''
      }
    },
    created() {
      this.patient_id = parseInt(this.$route.query.id)
      if (isNaN(this.patient_id) || this.patient_id <= 0) {
        this.$notify.error({
          title: '错误',
          message: '无效的id'
        })
        this.$router.push('/patients/patients')
        return
      }
      var now = new Date()
      this.date = [now.getTime() - (7 * 24 * 60 * 60 * 1000), now.getTime()]

      var nowDate = new Date()
      var nowYear = nowDate.getFullYear()
      var nowMonth = nowDate.getMonth() + 1
      var nowDay = nowDate.getDate()
      this.end_time =
        nowYear +
        '-' +
        (nowMonth < 10 ? '0' + nowMonth : nowMonth) +
        '-' +
        (nowDay < 10 ? '0' + nowDay : nowDay)
      nowDate.setMonth(nowDate.getMonth() - 1)
      nowYear = nowDate.getFullYear()
      nowMonth = nowDate.getMonth() + 1
      nowDay = nowDate.getDate()
      this.start_time =
        nowYear +
        '-' +
        (nowMonth < 10 ? '0' + nowMonth : nowMonth) +
        '-' +
        (nowDay < 10 ? '0' + nowDay : nowDay)

      this.requestCourseRecords()

    },
    methods: {
      requestCourseRecords: function() {
        this.loading = true
        getCourseOfDiseaseRecords(this.patient_id, this.start_time, this.end_time).then(rs => {
          this.loading = false
          var resp = rs.data
          if (resp.state == 1) {
            this.current_select_record = null
            this.records = resp.data.records
            this.doctors = resp.data.doctors

          } else {
            this.$message.error(resp.msg)
          }
        }).catch(error => {
          this.loading = false
          this.$message.error(error)
        })
      },

      didChangeCurrentRecord: function(record) {
        this.current_select_record = record
      },
      recordTime: function(timestamp) {
        var time = new Date(timestamp * 1000)
        return parseTime(time, '{y}-{m}-{d} {h}:{m}')
      },
      doctorName: function(doctor_id) {
        for (let index = 0; index < this.doctors.length; index++) {
          const doctor = this.doctors[index]
          if (doctor.id == doctor_id) {
            return doctor.name
          }
        }
        return ''
      },
      modifyAction: function() {

        this.edit_new_content = this.$refs.edit_neditor.content
        if (this.edit_new_content.length == 0) {
          this.$message.error('请填写病程内容')
          return
        }
        this.uploading_new_record = true
        modifyCourseOfDiseaseRecord(this.patient_id, this.edit_new_content, this.edit_course_of_disease_time, this.edit_current_id, this.edit_title).then(rs => {
          this.uploading_new_record = false
          var resp = rs.data
          if (resp.state == 1) {
            this.records[this.table_current_index].content = resp.data.record.content
            this.records[this.table_current_index].record_time = resp.data.record.record_time
            this.records[this.table_current_index].recorder = resp.data.record.recorder
            this.records[this.table_current_index].title = resp.data.record.title

            this.show_edit_dialog = false
            this.edit_new_content = ''
            this.table_current_index = -1

          } else {
            this.table_current_index = -1
            this.$message.error(resp.msg)
          }

        }).catch(error => {
          this.table_current_index = -1
          this.uploading_new_record = false
          this.$message.error(error)
        })

      },

      createAction: function() {
        this.new_content = this.$refs.editor.content
        if (this.new_content.length == 0) {
          this.$message.error('请填写病程内容')
          return
        }
        this.uploading_new_record = true
        
        createCourseOfDiseaseRecord(this.patient_id, this.new_content, this.course_of_disease_time, this.title).then(rs => {
          this.uploading_new_record = false
          var resp = rs.data
          if (resp.state == 1) {
            this.records.unshift(resp.data.record)
            // this.$refs.record_table.setCurrentRow()
            // this.$refs.record_table.setCurrentRow(this.records[0])
            // this.current_select_record = this.records[0]
            this.show_dialog = false
            this.new_content = ''
            this.title = ''

          } else {
            this.$message.error(resp.msg)
          }

        }).catch(error => {
          this.uploading_new_record = false
          this.$message.error(error)
        })
      },
      didSelectTemplate: function(templateContent) {
        this.new_content = this.new_content.length > 0 ? (this.new_content + templateContent) : templateContent

      }, didEditSelectTemplate: function(templateContent) {
        this.edit_new_content = this.edit_new_content.length > 0 ? (this.edit_new_content + templateContent) : templateContent
      },

      didSelectionChange: function(selectRows) {
        this.selectingRows = selectRows
      },
      deleteAction: function() {
        if (this.selectingRows.length == 0) {
          return
        }
        var ids = []
        for (let index = 0; index < this.selectingRows.length; index++) {
          const row = this.selectingRows[index]
          ids.push(row.id)
        }
        var ids_str = ids.join(',')
        this.loading = true
        deleteCourseOfDiseaseRecords(this.patient_id, ids_str).then(rs => {
          var resp = rs.data
          if (resp.state == 1) {
            for (let id_index = 0; id_index < ids.length; id_index++) {
              for (let record_index = 0; record_index < this.records.length; record_index++) {
                if (ids[id_index] == this.records[record_index].id) {
                  this.records.splice(record_index, 1)
                  break
                }
              }
            }
            this.selectingRows = []
            this.$message.success('已删除')

          } else {
            this.$message.error(resp.msg)
          }
          this.loading = false
        }).catch(err => {
          this.loading = false
          this.$message.error(err)
        })
      }, startTimeChange(val) {
        this.requestCourseRecords()
      }, endTimeChange(val) {
        this.requestCourseRecords()
      }, showEdit() {
        if (this.table_current_index == -1) {
          this.$message.error('请选择要修改的病程内容')
          return
        }
        this.show_edit_dialog = true
        this.edit_course_of_disease_time = this.recordTime(this.records[this.table_current_index].record_time)
        this.edit_new_content = this.records[this.table_current_index].content
        this.edit_current_id = this.records[this.table_current_index].id
        this.edit_title = this.records[this.table_current_index].title
        this.$refs.record_table.setCurrentRow(null)

      }, tableRow({ row, rowIndex }) {
        // 把每一行的索引放进row
        row.index = rowIndex
      }, onRowClick(row, event, column) {
        this.table_current_index = row.index
      },print(){
        if (this.table_current_index == -1) {
          this.$message.error('请选择要打印的病程')
          return
        }
        this.$router.push({ path: "/course/print?id="+this.records[this.table_current_index].id});
      }
    }
  }
</script>

<style rel="stylesheet/css" lang="scss" scoped>
  .container {
    margin-left: 180px;
    padding: 20px;
    background: #fff;
    min-height: calc(100vh - 173px);
    margin-bottom: 15px;

  .record {
    padding-top: 20px;
  }

  }
  .record_content_panel {
    border-width: 1px;
    border-style: solid;
    border-color: #ebeef5;
    min-height: 200px;

  .title {
    font-size: 14px;
    font-weight: 500;
    color: #909399;
    line-height: 44px;
    height: 44px;
    text-align: center;
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: #ebeef5;
  }

  .content {
    padding: 12px 15px;
    font-size: 15px;
    color: gray;
    line-height: 22px;
  }

  }

  .new_record_form {

  /*/ / padding: 10 px, 25 px;*/

  .textarea_panel {
    margin-top: 10px;
  }

  }
</style>
<style>
.el-table td,
.el-table th.is-leaf,
.el-table--border,
.el-table--group {
  border-color: #d0d3da;
}
.el-table--border::after,
.el-table--group::after,
.el-table::before {
  background-color: #d0d3da;
}
</style>
