<template>
  <div class="collection">
    <div class="collection_title">个人收藏</div>
    <div style="flex: 1">
      <el-button v-if="!collectData.length" size="mini" @click="dialogFormVisible = true">新增节点</el-button>
      <el-tree
        v-else
        :data="collectData"
        node-key="id"
        default-expand-all
        :props="defaultProps"
        :expand-on-click-node="false"
      >
        <span slot-scope="{ node, data }" class="custom-tree-node" @click="levelClick(data)">
          <span style="display: inline-block;min-width: 100px">
            <span>{{ node.label }}</span>
          </span>
          <span>
            <el-dropdown trigger="click" @command="(command)=>addNode(command,node,data)">
              <span>
                <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>···</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>
      <div style="display:flex;text-align: center;padding: 16px">
        <span>备注：</span>
        <el-input v-model="remark" style="flex: 1" type="textarea" resize="none" clearable placeholder="请输入备注" />
      </div>
      <div style="text-align: right;padding:0 16px 16px">
        <el-button style="width: 180px" type="primary" size="small" @click="handleAddPatient">收藏当前患者</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import dialogjs from '@/mixins/dialog'
import infoDetail from './infoDetail'

export default {
  components: {
    infoDetail
  },
  mixins: [dialogjs],
  props: {
    patientIdNumber: {
      type: String,
      default: ''
    },
    platform: {
      type: String,
      default: ''
    },
    patientId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogFormVisible: false,
      remark: '',
      curNode: '',
      editName: '',
      editMessage: '',
      disabled: false, // 用防止多次添加或多次重命名
      addParam: {
        id: '',
        parentId: 0
      },
      doctorId: JSON.parse(window.localStorage.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.findTree()
    },
    // 获取当前或者最新备注
    async queryPatientRemarks() {
      const { data } = await this.$http.get('/tree/findTreeIsExistPatient', {
        params: {
          doctorId: this.doctorId,
          patientId: this.patientId,
          platform: this.platform
        }
      })
      // this.tableData =
      this.collectData = this.handlePatientList(data.data)
    },
    handlePatientList(arr) {
      arr.forEach(item => {
        if (!item.childs) {
          item.childs = []
        }
        if (item.hisManagePatientEntity) {
          this.$set(item.hisManagePatientEntity, 'name', item.hisManagePatientEntity.remark)
          item.childs.push(item.hisManagePatientEntity)
        }
        if (item.childs && item.childs.length) {
          this.handlePatientList((item.childs))
        }
      })
      return arr
    },
    // 查询树结构
    async findTree() {
      const { data } = await this.$http.get(`/tree/findTree`, {
        params: {
          doctorId: JSON.parse(window.localStorage.getItem('qg-userData')).id,
          platform: this.platform
        }
      })
      this.collectData = data.data
      await this.queryPatientRemarks()
    },
    // 或者详情目录结构包含或者备注信息
    // async patientTrees() {
    //   const { data } = await this.$http.get('/tree/findTreeIsExistPatient', {
    //     params: {
    //       doctorId: this.doctorId,
    //       patientId: this.patientId,
    //       platform: this.platform
    //     }
    //   })
    //   console.log('详情目录', data)
    // },
    levelClick(data) {
      this.curNode = data
    },
    searchRemark(data) {
      // this.treeId = data.id
      // this.remark = data.hisManagePatientEntity ? data.hisManagePatientEntity.remark : ''
      // this.remarkId = data.hisManagePatientEntity ? data.hisManagePatientEntity.id : ''
    },
    handleAddPatient() {
      const params = {
        createDate: this.$moment().format('YYYY-MM-DD HH:mm:ss'),
        patientId: this.patientId,
        platform: this.platform,
        remark: this.remark,
        treeId: this.curNode.id
      }
      this.$http.post('/tree/addPatientTree', params).then(() => {
        this.editMessage = '收藏成功！'
        this.$message({
          message: this.editMessage,
          type: 'success'
        })
        this.findTree()
      })
    },
    // 新增节点
    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
      if (this.curNode.patientId) {
        this.curNode.name = this.editName
        await this.$http.post('/tree/addPatientTree', { ...this.curNode })
      } else {
        await this.$http.post('/tree/addTree', params)
      }
      this.dialogFormVisible = false
      await this.findTree()
    },
    // 更多
    handleNode(command, node, data) {
      if (command === 'delete') {
        this.deleteNode(node, data)
      } else {
        this.disabled = false
        this.editNode(node, data)
      }
    },
    // 删除树节点
    deleteNode(node, data) {
      if (this.curNode.patientId) {
        this.$confirmFun('你确定要删除吗？').then(() => {
          this.$http.post('/tree/deletePatientTree', { ...this.curNode }).then(() => {
            this.$message({
              message: '删除成功！',
              type: 'success'
            })
            this.findTree()
          })
        })
      } 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.findTree()
          })
        })
      }
    },
    // 重命名
    editNode(node, data) {
      this.dialogFormVisible = true
      this.editName = node.label
      this.editMessage = '重命名成功！'
      this.addParam.id = data.id
      this.addParam.parentId = data.parentId
    }
  }
}
</script>

<style lang="scss" scoped>
.collection {
  width: 600px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .collection_title{
    font-size: 16px;
    font-weight: bold;
    padding: 18px;
  }
  .cell-cursor {
    cursor: pointer;
    color: #1e79ff;
  }
  .table-column-disable {
    color: #dddd;
  }
  ::v-deep .el-textarea__inner{
    height: 164px;
  }
}
</style>
