<template>
  <div class="collection">
    <div>
      <div style="padding: 16px">
        <el-button style="width: 180px" type="primary" size="small" @click="handleAddPatient">收藏当前患者</el-button>
      </div>
      <div style="padding:0 16px">
        <el-input v-model="remark" style="flex: 1" type="textarea" resize="none" :autosize="{minRows: 2, maxRows: 2}" clearable placeholder="请输入备注" />
      </div>
    </div>
    <div class="collection_title">个人收藏</div>
    <div class="collect_content">
      <div style="flex: 1" class="collect_context">
        <el-button v-if="!collectData.length" size="mini" @click="dialogFormVisible = true">新增节点</el-button>
        <el-tree
          v-else
          :data="collectData"
          node-key="id"
          :props="defaultProps"
          :default-expanded-keys="defaultExpandIds"
          @node-expand="handleNodeExpand"
          @node-collapse="handleNodeCollapse"
        >
          <span slot-scope="{ node, data }" :class="[curNode.id===data.id?'active':'','custom-tree-node']" @click="levelClick(data)">
            <span class="treeDefault">
              <span>{{ node.label }}</span>
            </span>
            <span>
              <el-dropdown v-if="!data.patientId" trigger="click" @command="(command)=>addNode(command,node,data)">
                <span :class="{'active':curNode.id===data.id}">
                  <i class="el-icon-plus" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="same">新增同级节点</el-dropdown-item>
                  <el-dropdown-item command="child">新增子级节点</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-dropdown trigger="click" style="margin-left: 10px" @command="(command)=>handleNode(command,node,data)">
                <span :class="{'active':curNode.id===data.id}">···</span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="rename">编辑</el-dropdown-item>
                  <el-dropdown-item command="delete">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </span>
          </span>
        </el-tree>
        <el-dialog :modal-append-to-body="false" width="30%" title="节点名称" :visible.sync="dialogFormVisible">
          <el-input ref="renameRef" v-model="editName" />
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" :disabled="disabled" @click="confirmNode()">确 定</el-button>
          </div>
        </el-dialog>
      </div>
      <div class="flex a-c" style="font-size: 16px">
        关键词搜索:<el-input v-model="keyword" style="width: 300px;padding: 16px" @change="searchPatient" />
      </div>
      <!--      搜索数据   -->
      <el-table center :data="tableData">
        <el-table-column label="姓名" prop="patientName" />
        <el-table-column label="年龄" prop="patientAge" />
        <el-table-column label="性别" prop="patientSex" />
        <el-table-column label="登记号" prop="patientId" />
        <el-table-column label="备注" prop="remark" />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <div>
              <div style="color: #ff0000;cursor: pointer" @click="deletePatient(scope.row)">删除</div>
              <div style="color: #1890ff;cursor: pointer" @click="editPatient(scope.row)">编辑</div>
              <div style="color: #1890ff;cursor: pointer" @click="goDetail(scope.row)">患者360</div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog :modal-append-to-body="false" width="30%" title="备注修改" :visible.sync="remarkDialog">
        <el-input ref="renameRef" v-model="editRemark" />
        <div slot="footer" class="dialog-footer">
          <el-button @click="remarkDialog = false">取 消</el-button>
          <el-button type="primary" @click="editPatientRemark()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    patientIdNumber: {
      type: String,
      default: ''
    },
    platform: {
      type: String,
      default: ''
    },
    patientId: {
      type: String,
      default: ''
    },
    jzNumber: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      defaultExpandIds: [],
      keyword: '',
      dialogFormVisible: false,
      remarkDialog: false,
      remark: '',
      curNode: '',
      editName: '',
      editRemark: '',
      editMessage: '新增成功',
      curPatient: {}, // 当前id下的患者
      disabled: false, // 用防止多次添加或多次重命名
      addParam: {
        id: '',
        parentId: 0
      },
      doctorId: JSON.parse(window.sessionStorage.getItem('qg-userData')).id,
      collectData: [],
      tableData: [],
      defaultProps: {
        children: 'childs',
        label: 'name'
      }
    }
  },
  watch: {
    dialogFormVisible(newValue) {
      if (newValue) {
        this.$nextTick(() => {
          this.$refs.renameRef.focus()
        })
      }
    },
    collectData(val) {
      if (!val.length) {
        this.disabled = false
        this.addParam.id = ''
        this.addParam.parentId = 0
        this.editName = ''
      }
    }
  },
  async created() {
    this.initPatient()
  },
  methods: {
    // 初始化获取或者相关信息
    initPatient() {
      this.queryPatientRemarks()
    },
    // 初始化树
    async queryPatientRemarks() {
      const { data } = await this.$http.get('/tree/findTreeIsExistPatient', {
        params: {
          doctorId: this.doctorId,
          patientId: this.patientId,
          platform: this.platform
        }
      })
      this.collectData = data.data
    },
    // 搜索患者
    searchPatient() {
      this.$http.get('/tree/findCollectPatient', {
        params: {
          doctorId: this.doctorId,
          platform: this.platform,
          queryStr: this.keyword
        }
      }).then(res => {
        this.tableData = res.data.data
      })
    },
    // 删除患者
    deletePatient(scopeRow) {
      this.$confirmFun('确定删除该患者吗？').then(() => {
        return this.$http.post('/tree/deletePatientTree', {
          id: scopeRow.id
        })
      }).then(res => {
        if (res.data.code === 0) {
          this.$message.success('删除成功！')
          this.queryCurPatient()
        } else {
          this.$message.error(res.data.msg)
        }
      }).catch(() => {})
    },
    // 编辑收藏患者
    editPatient(scopeRow) {
      this.remarkDialog = true
      this.curPatient = scopeRow
      this.editRemark = this.curPatient.remark
    },
    editPatientRemark(node) {
      const params = {
        id: this.curPatient.id,
        patientId: this.patientId,
        platform: this.platform,
        remark: this.editRemark,
        treeId: this.curNode.id,
        jzNumber: this.jzNumber
      }
      this.$http.post('/tree/addPatientTree', params).then(() => {
        this.$message.success('修改成功！')
        this.queryPatientRemarks()
        this.remarkDialog = false
      })
    },
    // 患者360跳转
    goDetail(scopeRow) {
      this.$router.push({
        path: '/360view',
        query: {
          onlyRead: true,
          isSearch: this.platform,
          patientId: scopeRow.patientId,
          jzNumber: scopeRow.jzNumber
        }
      })
    },
    levelClick(data) {
      this.curNode = data
      this.remark = data.remark || ''
      this.queryCurPatient()
    },
    queryCurPatient() {
      this.$http.get('tree/findPatientTree', {
        params: {
          platform: this.platform,
          treeId: this.curNode.id
        }
      }).then(res => {
        this.tableData = res.data.data.list
      })
    },
    // 收藏患者
    handleAddPatient() {
      let params = {}
      // 添加患者
      params = {
        patientId: this.patientId,
        platform: this.platform,
        remark: this.remark,
        treeId: this.curNode.id,
        jzNumber: this.jzNumber
      }
      this.editMessage = '收藏成功！'
      this.$http.post('/tree/addPatientTree', params).then(res => {
        if (res.data.code === 0) {
          this.$message({
            message: this.editMessage,
            type: 'success'
          })
          this.queryCurPatient()
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    // 新增节点
    addNode(command, node, data) {
      this.editMessage = '添加成功！'
      this.disabled = false
      switch (command) {
        // 新建同级节点
        case 'same':
          this.dialogFormVisible = true
          this.addParam.id = ''
          this.addParam.parentId = data.parentId
          this.editName = node.name
          break
        // 新建子级节点
        case 'child':
          this.dialogFormVisible = true
          this.addParam.id = ''
          this.addParam.parentId = data.id
          this.editName = node.name
          break
        // 初始新增
        default:
          this.addParam.id = ''
          this.addParam.parentId = 0
          this.editName = ''
          break
      }
    },
    // 确定新增节点/重命名
    async confirmNode() {
      const params = {
        createDate: this.$moment().format('YYYY-MM-DD HH:mm:ss'),
        doctorId: this.doctorId,
        flag: '1',
        name: this.editName,
        platform: this.platform,
        ...this.addParam
      }
      this.disabled = true
      await this.$http.post('/tree/addTree', params)
      this.$message({
        message: this.editMessage,
        type: 'success'
      })
      this.dialogFormVisible = false
      await this.queryPatientRemarks()
    },
    // 更多
    handleNode(command, node, data) {
      switch (command) {
        case 'rename':
          this.disabled = false
          this.editNode(node, data)
          break
        case 'delete':
          this.deleteNode(node, data)
          break
        case 'edit':
      }
    },
    // 删除树节点
    deleteNode(node, data) {
      this.curNode = ''
      // 删除患者
      if (data.patientId) {
        const param = {
          id: data.id,
          patientId: data.patientId,
          platform: this.platform,
          remark: data.remark,
          treeId: data.treeId
        }
        this.$confirmFun('你确定要删除吗？').then(() => {
          this.$http.post('/tree/deletePatientTree', param).then(() => {
            this.$message({
              message: '删除成功！',
              type: 'success'
            })
            this.queryPatientRemarks()
          })
        })
      } else {
        // 删除树节点
        const params = {
          doctorId: this.doctorId,
          flag: '1',
          name: data.label,
          platform: this.platform,
          id: data.id
        }
        this.$confirmFun('你确定要删除吗？').then(() => {
          this.$http.post('/tree/deleteTree', params).then(() => {
            this.$message({
              message: '删除成功！',
              type: 'success'
            })
            this.queryPatientRemarks()
          })
        })
      }
    },
    // 重命名
    editNode(node, data) {
      this.dialogFormVisible = true
      this.editName = node.label
      this.editMessage = '重命名成功！'
      this.addParam.id = data.id
      this.addParam.parentId = data.parentId
    },
    // 树节点展开
    handleNodeExpand() {
      if (this.defaultExpandIds.indexOf(this.curNode.id) === -1) {
        this.defaultExpandIds.push(this.curNode.id)
      }
    },
    // 树节点关闭
    handleNodeCollapse() {
      if (!this.defaultExpandIds.indexOf(this.curNode.id)) {
        const index = this.defaultExpandIds.findIndex(item => {
          return item === this.curNode.id
        })
        this.defaultExpandIds.splice(index, 1)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.flex{
  display: flex;
}
.a-c{
  align-items: center;
}
.collection {
  width: 650px;
  display: flex;
  flex-direction: column;
  .collection_title{
    font-size: 16px;
    font-weight: bold;
    padding: 10px;
  }
  .cell-cursor {
    cursor: pointer;
    color: #1e79ff;
  }
  .table-column-disable {
    color: #dddd;
  }
  ::v-deep .el-textarea__inner{
    height: 164px;
  }
}
.collect_content{
  overflow: hidden;
  overflow-y: scroll;
}
.custom-tree-node{
  width: 100%;
}
.active{
  color: #FFFFFF;
  background: #1e79ff;
}
.treeDefault{
  display: inline-block;
  min-width: 200px;
  max-width:500px;
  font-size: 16px;
  text-overflow: ellipsis;
  overflow: hidden;
  padding-right: 10px;
}
::v-deep .custom-tree-node{
  display: flex;
  align-items: center;
}
</style>
