<template>
  <div class="foreBox">
    <div class="btnBox">
      <el-button v-print="'#foreCheck'" size="small">打印</el-button>
      <el-button type="primary" size="small" @click="saveFore('2', '前段检查')">保存</el-button>
      <el-button type="primary" size="small">保存为模板</el-button>
      <div size="small" style="display:inline-block;margin-left:10px;text-align:center;width: 32px;height: 32px;background-color: #1e79ff;border-radius: 4px;vertical-align: bottom" @click="addForeData">
        <img :src="require('@/assets/img/data.png')" alt="" style="width: 17px;height: 16px;margin-top: 3px">
      </div>
    </div>
    <div class="moveIcon">
      <p @click="moveAll(1)"><i class="el-icon-back" /></p>
      <p style="margin-top: 5px" @click="moveAll(2)"><i class="el-icon-back" style="transform: rotateY(180deg)" /></p>
    </div>
    <div style="display: flex;margin-top: 32px">
      <div style="width: 200px;padding-right: 8px">
        <p style="font-weight: bold;margin-bottom: 12px;text-align: left">描述项模板</p>
        <el-tree
          ref="tree"
          :data="treeTemplate"
          :props="treeProps"
          :render-content="renderContent"
          :default-expand-all="true"
          :expand-on-click-node="false"
          @node-click="nodeClick"
        />
      </div>
      <el-table
        id="foreCheck"
        :data="tableData"
        style="margin: 8px 8px 0 0"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          align="center"
          label="OD"
        >
          <template slot-scope="scope">
            <div>
              <span v-if="scope.row.sort === 1">
                <treeSelect v-model="scope.row.od" :options="scope.row.data" :props="treeProps" :multiple="true" :filterable="true" :check-strictly="true" :default-expand-all="true" @add="addTree(scope.row, $event)" @remove="removeTree" />
              </span>
              <span v-if="!scope.row.sort">{{ scope.row.name }}</span>
              <span v-if="scope.row.sort === 2">
                <span style="margin-right: 16px">结膜：充血</span><treeSelect v-model="scope.row.od" :props="treeProps" style="display: inline-block;width: 60%" :options="scope.row.data" :multiple="true" :filterable="true" :check-strictly="true" :default-expand-all="true" @add="addTree(scope.row, $event)" />
              </span>
              <span v-if="scope.row.sort === 3">
                <span style="margin-right: 16px">结膜：分泌物</span><treeSelect v-model="scope.row.od" :props="treeProps" style="display: inline-block;width: 60%" :options="scope.row.data" :multiple="true" :filterable="true" :check-strictly="true" :default-expand-all="true" @add="addTree(scope.row, $event)" />
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          class="move"
          align="center"
          width="120"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.sort">
              <p @click="moveHandle(scope.$index,1, scope.row.os)"><i class="el-icon-back" /></p>
              <p style="margin-top: 5px" @click="moveHandle(scope.$index,2, scope.row.od)"><i class="el-icon-back" style="transform: rotateY(180deg)" /></p>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="OS"
          width="300"
        >
          <template slot-scope="scope">
            <div>
              <span v-if="scope.row.sort === 1">
                <treeSelect v-model="scope.row.os" :options="scope.row.data" :props="treeProps" :multiple="true" :filterable="true" :check-strictly="true" :default-expand-all="true" @add="addTree(scope.row, $event)" />
              </span>
              <span v-if="!scope.row.sort">{{ scope.row.name }}</span>
              <span v-if="scope.row.sort === 2">
                <span style="margin-right: 16px">结膜：充血</span><treeSelect v-model="scope.row.os" :props="treeProps" style="display: inline-block;width: 60%" :options="scope.row.data" :multiple="true" :filterable="true" :check-strictly="true" :default-expand-all="true" @add="addTree(scope.row, $event)" />
              </span>
              <span v-if="scope.row.sort === 3">
                <span style="margin-right: 16px">结膜：分泌物</span><treeSelect v-model="scope.row.os" :props="treeProps" style="display: inline-block;width: 60%" :options="scope.row.data" :multiple="true" :filterable="true" :check-strictly="true" :default-expand-all="true" @add="addTree(scope.row, $event)" />
              </span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="新增子级" :visible.sync="dialogFormVisible">
      <el-form :model="form" style="margin-top: 16px">
        <el-form-item label="名称：" label-width="120px">
          <el-input v-model="form.name" auto-complete="off" style="width: 300px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveTree">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import eventBus from '@/page-subspecialty/utils/eventBus'
import treeSelect from '@/components/360View/itemSelect'
import axios from 'axios'
import Cookies from 'js-cookie'
const Base64 = require('js-base64').Base64
export default {
  components: {
    treeSelect
  },
  mixins: [],
  props: {
    patientIdNumber: {
      type: String,
      default: ''
    },
    patientId: {
      type: String,
      default: ''
    }
  },
  inject: ['refresh'],
  data() {
    return {
      userData: {},
      treeTemplate: [],
      treeProps: {
        value: 'id',
        label: 'name',
        children: 'child'
      },
      type: '',
      doctorId: '',
      deleteId: '',
      parentId: 0,
      collectId: '',
      form: {
        name: ''
      },
      multipleSelection: [],
      dialogFormVisible: false,
      data: [
        {
          value: 1,
          label: '一级 1',
          children: [{
            value: 4,
            label: '二级 1-1',
            children: [{
              value: 9,
              label: '三级 1-1-1'
            }, {
              value: 10,
              label: '三级 1-1-2'
            }]
          }]
        }, {
          value: 2,
          label: '一级 2',
          children: [{
            value: 5,
            label: '二级 2-1'
          }, {
            value: 6,
            label: '二级 2-2'
          }]
        }, {
          value: 3,
          label: '一级 3',
          children: [{
            value: 7,
            label: '二级 3-1'
          }, {
            value: 8,
            label: '二级 3-2'
          }]
        }],
      tableData: [
        {
          name: '眼睑'
        }, {
          name: '眼睑',
          sort: 1,
          type: 'anion',
          od: '',
          os: ''
        }, {
          name: '结膜'
        }, {
          name: '结膜',
          sort: 2,
          type: 'jimmy',
          od: '',
          os: ''
        }, {
          name: '结膜',
          sort: 3,
          type: 'jimmy',
          od: '',
          os: ''
        }, {
          name: '泪器'
        }, {
          name: '泪器',
          sort: 1,
          type: 'liq',
          od: '',
          os: ''
        }, {
          name: '角膜'
        }, {
          name: '角膜',
          sort: 1,
          type: 'Giacomo',
          od: '',
          os: ''
        }, {
          name: '前房'
        }, {
          name: '前房',
          sort: 1,
          type: 'Jianfeng',
          od: '',
          os: ''
        }, {
          name: '虹膜'
        }, {
          name: '虹膜',
          sort: 1,
          type: 'mongo',
          od: '',
          os: ''
        }, {
          name: '瞳孔'
        }, {
          name: '瞳孔',
          sort: 1,
          type: 'tonguing',
          od: '',
          os: ''
        }, {
          name: '晶状体'
        }, {
          name: '晶状体',
          sort: 1,
          type: 'jingling',
          od: '',
          os: ''
        }, {
          name: '睫状体'
        }, {
          name: '睫状体',
          sort: 1,
          type: 'jingles',
          od: '',
          os: ''
        }, {
          name: '眼位'
        }, {
          name: '眼位',
          sort: 1,
          type: 'yawn',
          od: '',
          os: ''
        }, {
          name: '眼眶'
        }, {
          name: '眼眶',
          sort: 1,
          type: 'yanking',
          od: '',
          os: ''
        }, {
          name: '眼球运动'
        }, {
          name: '眼球运动',
          sort: 1,
          type: 'yang',
          od: '',
          os: ''
        }],
      treeList: []
    }
  },
  created() {
  },
  mounted() {
    this.userData = JSON.parse(window.localStorage.getItem('qg-userData'))
    this.doctorId = this.userData.id
    this.getforeList('2').then(() => {
      console.log(123)
      // this.queryOptions()
    })
    this.queryTemplate()
  },
  methods: {
    async getforeList(flag) {
      const { data: res } = await this.$http.get('/case/getCase', {
        params: {
          patientId: this.patientId,
          platform: 1,
          flag: flag
        }
      })
      if (res.code === 0) {
        this.tableData = res.data ? JSON.parse(res.data.jsonText) : []
        this.collectId = res.data ? res.data.id : ''
      } else {
        this.$message.error(res.msg)
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(this.multipleSelection)
    },
    // 添加数据集
    addForeData() {
      console.log(this.$parent)
      eventBus.$emit('sendData', this.multipleSelection)
    },
    // 获取下拉选择项
    queryOptions() {
      this.treeList = []
      this.tableData.forEach(item => {
        if (item.type) {
          const p = this.queryTree(item.type)
          this.treeList.push(p)
        }
      })
      Promise.all(this.treeList).then((result) => {
        if (result.length) {
          result.forEach(item => {
            item.forEach(row => {
              this.tableData.forEach(e => {
                if (e.type === row.type) {
                  e.data = [row]
                }
              })
            })
          })
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 全部移动
    moveAll(type) {
      if (type === 1) {
        this.tableData.forEach(item => {
          if (item.sort) {
            item.od = item.os
          }
        })
      } else {
        this.tableData.forEach(item => {
          if (item.sort) {
            item.os = item.od
          }
        })
      }
    },
    // 移动
    moveHandle(index, type, row) {
      console.log(index, type, row)
      if (type === 1) {
        this.tableData[index].od = row
      } else {
        this.tableData[index].os = row
      }
    },
    // 保存前段检查
    async saveFore(flag, name) {
      const params = {
        flag: flag,
        jsonText: JSON.stringify(this.tableData),
        name: name,
        patientId: this.patientId,
        platform: 1
      }
      let url = ''
      if (this.collectId) {
        url = '/case/update'
        params.id = this.collectId
      } else {
        url = '/case/save'
      }
      const { data: res } = await this.$http.post(url, params)
      if (res.code === 0) {
        this.$message.success('保存成功')
        await this.getforeList('2')
      } else {
        this.$message.error(res.msg)
      }
    },
    // 新增树
    addTree(item, event) {
      this.type = event.type
      this.parentId = event.id
      this.dialogFormVisible = true
    },
    removeTree(item) {
      console.log(item)
      this.type = item.type
      this.deleteId = item.id
      this.remove()
    },
    queryTree(type) {
      // 47.110.224.240:8036
      // 192.168.4.24:8036
      console.log(11)
      return new Promise((resolve, reject) => {
        axios.defaults.headers.common['token'] = Cookies.get('xa-token') || ''
        axios.get('http://47.110.224.240:8036/xiangan-crf/treetag/findTree', {
          params: {
            doctorId: this.doctorId,
            type: type,
            platform: 1
          }
        }).then(res => {
          if (res.data.code === 0) {
            const data = res.data
            resolve(data.data)
          }
        })
          .catch(error => {
            reject(error)
          })
        // const { data: res } = this.$http.get('/treetag/findTree', {
        //   params: {
        //     doctorId: this.doctorId,
        //     type: type,
        //     platform: 1
        //   }
        // })
        // console.log(res)
        // resolve(res.data)
        // if (res.code === 0) {
        //   resolve(res.data)
        // } else {
        //   reject(res.msg)
        //   this.$message.error(res.msg)
        // }
      })
    },
    // 新增保存树
    async handleSaveTree() {
      const params = {
        doctorId: this.doctorId,
        name: this.form.name,
        flag: 1,
        type: this.type,
        parentId: this.parentId,
        platform: 1
      }
      const { data: res } = await this.$http.post('/treetag/addTree', params)
      if (res.code === 0) {
        this.dialogFormVisible = false
        this.updataList()
        this.$message.success('保存成功')
      } else {
        this.$message.error(res.msg)
      }
    },
    // 刷新下拉树
    updataList() {
      this.queryTree(this.type).then((res) => {
        this.tableData.forEach(item => {
          if (item.type === this.type) {
            const sort = item.sort
            item.sort = ''
            this.$nextTick(() => {
              item.sort = sort
            })
            item.data = res
          }
        })
        console.log(this.tableData)
      })
    },
    renderContent(h, { node, data, store }) {
      return (
        <span style='flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;'>
          <span>
            <span>{node.label}</span>
          </span>
          <span>
            <el-button icon='el-icon-plus' style='font-size: 12px;color: black' type='text' on-click={ () => this.append(data) }>
            </el-button>
            <el-button icon='el-icon-delete' style='font-size: 12px;color: black' type='text' on-click={ () => this.remove(node, data) }>
            </el-button>
          </span>
        </span>)
    },
    // 点击节点
    nodeClick(node) {
    },
    append(data) {
      // const newChild = { value: value++, label: 'testtest', children: [] }
      // if (!data.children) {
      //   this.$set(data, 'children', [])
      // }
      // data.children.push(newChild)
    },
    remove(node, data) {
      this.$confirm('确定删除该节点?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleRemove()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      // const parent = node.parent
      // const children = parent.data.children || parent.data
      // const index = children.findIndex(d => d.id === data.id)
      // children.splice(index, 1)
    },
    async handleRemove() {
      const params = {
        id: this.deleteId
      }
      const { data: res } = await this.$http.post('/treetag/deleteTree', params)
      if (res.code === 0) {
        this.$message.success('删除成功')
        this.updataList()
      } else {
        this.$message.error(res.msg)
      }
    },
    async queryTemplate() {
      const { data: res } = await this.$http.get('/treetemplate/findTree', {
        params: {
          platform: 1,
          doctorId: this.doctorId
        }
      })
      if (res.code === 0) {
        this.treeTemplate = res.data
      } else {
        this.$message.error(res.msg)
      }
    },
    async queryTreeTemplate() {
      const { data: res } = await this.$http.get('/treetemplate/findTreeCase', {
        params: {
          nodeId: this.nodeId,
          doctorId: this.doctorId
        }
      })
      if (res.code === 0) {
        this.treeTemplate = res.data
      } else {
        this.$message.error(res.msg)
      }
    },
    // 共三个参数，依次为：传递给 data 属性的数组中该节点所对应的对象、节点对应的 Node、节点组件本身
    handleMoveCopyNodeClick(data) {
      this.currentNodeKey = data.id
    }
  }
}
</script>
<style lang="scss" scoped>
.foreBox{
  width: 100%;
  height: 100%;
  //padding: 16px;
  box-sizing: border-box;
  overflow-y: auto;
  position: relative;
  .btnBox{
    position: fixed;
    right: 84px;
    text-align: right;
    margin-right: 16px;
    background-color: white;
    z-index: 999;
  }
  .moveIcon{
    position: absolute;
    left: calc(50% + 120px);
    top: 40px;
    z-index: 9;
  }
}
</style>
<style lang="scss">
.foreBox{
  .el-form-item__content{
    text-align: left;
  }
}
</style>
