<template>
  <div>
    <el-container :style="{height: asideHeight+'px'}">
      <el-aside width="280px" style="border-color: rgb(238, 241, 246)">
        <div class="el-row--flex">
          <el-input
            v-model="filterText"
            :placeholder="this.$t('frameManage.keywordsFilter')"
            clearable
          />
          <el-button
            type="text"
            size="mini"
            style="margin-left: 10px;color: #67C23A"
            @click="quickCreateFrame"
          >{{ this.$t('frameManage.quickCreate') }}</el-button>

        </div>
        <el-tree
          ref="frameTree"
          :data="treeData"
          :show-checkbox="false"
          node-key="id"
          :default-expand-all="true"
          :auto-expand-parent="true"
          :expand-on-click-node="false"
          :highlight-current="true"
          :current-node-key="selectedNodeId"
          draggable
          :accordion="true"
          :filter-node-method="filterNode"
          @node-drag-start="nodeDragStart"
          @node-drop="nodeDrop"
          @node-click="nodeClick"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <!--            <span><svg-icon :icon-class="data.type===4?'sickroom':data.type===5?'bed':'area'" />{{ data.full_name }}</span>-->
            <span><svg-icon :style="data.customer_id ? 'color: #0a901c' : ''" :icon-class="data.type===4?'sickroom':data.type===5?'bed':'area'" />{{ data.full_name }}</span>
            <span>
              <el-button
                v-if="data.type!==5"
                type="text"
                size="mini"
                icon="el-icon-plus"
                @click.stop="() => append(data)"
              />
              <el-button
                type="text"
                :disabled="data.type===1 || data.type===3"
                size="mini"
                icon="el-icon-edit"
                @click.stop="() => edit(data)"
              />
              <el-button
                type="text"
                :disabled="data.type===1"
                size="mini"
                icon="el-icon-delete"
                @click.stop="() => remove(data)"
              />
            </span>
          </span>
        </el-tree>
      </el-aside>
      <el-main>
        <el-tabs v-model="activeName" style="margin:0px;" type="border-card">
          <el-tab-pane :label="this.$t('frameManage.memberList')" name="frameInfo">
            <keep-alive>
              <customer-manager v-if="uiVersion===2" :frame="selectedNode" @saved="handleCustomerChange" />
              <patient-manager v-if="uiVersion===1" :frame="selectedNode" @saved="handleCustomerChange" />
            </keep-alive>
          </el-tab-pane>
          <el-tab-pane :label="this.$t('frameManage.deviceList')" name="deviceList">
            <keep-alive>
              <device-manager :frame="selectedNode" />
            </keep-alive>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>

    <!---添加空间结构弹窗 -->
    <el-dialog :title="frameEditTitle" :visible.sync="frameDialogVisible" width="500px">
      <el-form ref="editForm" :model="frameInfo" :rules="rules" label-width="130px">
        <el-row>
          <el-col :span="24">
            <!--医院结构名称-->
            <el-form-item :label="this.$t('action.name')" prop="name">
              <el-input v-model="frameInfo.name" :maxlength="20" @change="frameChange">
                <template slot="append">{{ frameInfo.type === 4? this.$t('frameManage.room') : this.$t('frameManage.bed') }}</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <!--医院结构别名-->
            <el-form-item :label="this.$t('action.alias')" prop="alias">
              <el-input v-model="frameInfo.alias" :maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <!--医院结构别名-->
            <el-form-item :label="this.$t('action.fullName')" prop="full_name">
              <el-input v-model="frameInfo.full_name" :maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row hidden>
          <el-col :span="12">
            <el-form-item :label="this.$t('action.type')">
              <el-radio v-model="frameInfo.type" :label="1">{{ this.$t('frameManage.room') }}</el-radio>
              <el-radio v-model="frameInfo.type" :label="2">{{ this.$t('frameManage.bed') }}</el-radio>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" class="save" @click="handleFrameSubmit('editForm')">{{ this.$t('action.yes') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!---添加空间结构弹窗 -->

    <!---快速创建结构弹窗 -->
    <el-dialog :title="this.$t('frameManage.quickCreateFrame')" :visible.sync="frameQuickCreateVisible" width="600px">
      <el-form ref="createFrameForm" :model="createFrameModel" :rules="createFrameRules" label-width="200px">
        <el-row>
          <el-col :span="24">
            <!--开始房间号-->
            <el-form-item :label="this.$t('frameManage.startRoom')" prop="start_no">
              <el-input-number v-model="createFrameModel.room_start_no" :min="1" @change="roomStartChange" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <!--结束房间号-->
            <el-form-item :label="this.$t('frameManage.endRoom')" prop="end_no">
              <el-input-number v-model="createFrameModel.room_end_no" :min="createFrameModel.room_start_no" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <!--每房床位数-->
            <el-form-item :label="this.$t('frameManage.bedQuantity')" prop="beds_per_room">
              <el-input-number v-model="createFrameModel.beds_per_room" :min="1" :max="20" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="18">
            <!--每房床位数-->
            <el-form-item :label="this.$t('frameManage.showRoomDigit')" prop="room_num_bits">
              <el-input-number v-model="createFrameModel.room_num_bits" :min="1" :max="4" @change="(val)=>{bitNumChange(val,'room')}" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div class="el-form-item__label">
              {{ this.$t('frameManage.example') }}：{{ room_num_demo }}
            </div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="18">
            <!--每房床位数-->
            <el-form-item :label="this.$t('frameManage.showBedDigit')" prop="bed_num_bits">
              <el-input-number v-model="createFrameModel.bed_num_bits" :min="1" :max="4" @change="(val)=>{bitNumChange(val,'bed')}" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div class="el-form-item__label">
              {{ this.$t('frameManage.example') }}：{{ bed_num_demo }}
            </div>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" class="save" @click="quickCreateSubmit()">{{ this.$t('action.yes') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!---快速创建结构弹窗 -->

  </div>
</template>

<script>
import * as HospitalFrame_API from '@/api/ncs_hospitalFrame'
import * as API_FrameGroup from '@/api/ncs_frameGroup'
import CustomerManager from '../customer/components/customerManager'
import DeviceManager from '../ncs-device/components/deviceManager'
import PatientManager from '../customer/components/patientManager'
// import { uiVersion } from '@/utils/domain'
import { FRAME_TYPE } from '@/utils/enum/FrameTypeEnum'
const uiVersion = domain.uiVersion
export default {
  name: 'FrameTreeView',
  components: { PatientManager, DeviceManager, CustomerManager },
  data() {
    return {
      treeData: [],
      treeDataClone: [],
      /** 当前选中的树节点 */
      selectedNodeId: 0,
      selectedNode: {},
      filterText: '',
      activeName: 'frameInfo',
      /** 上级机构数组 **/
      parents: [],
      /** frame 编辑弹窗 **/
      frameEditTitle: this.$t('action.add'),
      frameDialogVisible: false,
      frameInfo: {},
      rules: {
        name: [
          this.MixinRequired(this.$t('frameManage.inputFrameName')),
          { min: 2, max: 10, message: this.$t('frameManage.inputLong'), trigger: 'blur' }
        ],
        alias: [
          { min: 2, max: 10, message: this.$t('frameManage.inputLong'), trigger: 'blur' }
        ],
        full_name: [
          this.MixinRequired(this.$t('frameManage.inputFrameFullName')),
          { min: 2, max: 10, message: this.$t('frameManage.inputLong'), trigger: 'blur' }
        ]
      },
      /** 快速创建空间结构弹窗 **/
      frameQuickCreateVisible: false,
      createFrameModel: {
        room_start_no: 1,
        room_end_no: 2,
        beds_per_room: 4,
        room_num_bits: 2,
        bed_num_bits: 2
      },
      bed_num_demo: '01',
      room_num_demo: '01',
      createFrameRules: {

      },
      uiVersion: uiVersion
    }
  },
  computed: {
    asideHeight() {
      return this.mainAreaHeight
    }
  },
  watch: {
    selectedNodeId(newval, old) {
      console.log('watch', newval)
      this.selectedNode = this.findNodeById(this.treeData, newval)
    },
    filterText(val) {
      this.$refs.frameTree.filter(val)
    }
  },
  mounted() {
    this.getFrameTree().then(() => {
      this.selectedNodeId = this.treeData[0].id
      this.$refs.frameTree.setCurrentKey(this.selectedNodeId)
    }).catch(err => {
      this.$message.error(err.message)
    })
  },
  methods: {
    /**
     * 获取空间结构树形数据
     * */
    getFrameTree() {
      return new Promise((resolve, reject) => {
        API_FrameGroup.getAllFrameTreeByType(FRAME_TYPE.HOSPITAL).then(res => {
          this.treeData = res.frameTree
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },

    append(data) {
      if (data.type === FRAME_TYPE.HOSPITAL) {
        this.formmodel = {}
        this.formmodel.parent_id = data.hospital_id
        this.formmodel.frame_parent_id = data.id
        this.formmodel.full_name = data.name
        console.log('this.formmodel.parent_id=', this.formmodel.parent_id)
        this.formshow = true
      } else {
        if (data.type === FRAME_TYPE.ROOM) {
          this.frameEditTitle = '【' + data.full_name + '】' + this.$t('frameManage.addBed')
        } else {
          this.frameEditTitle = '【' + data.full_name + '】' + this.$t('frameManage.addRoom')
        }
        this.frameInfo = {
          hospital_id: data.hospital_id,
          parent_id: data.id,
          type: data.type === FRAME_TYPE.ROOM ? FRAME_TYPE.BED : FRAME_TYPE.ROOM,
          parent_name: data.name,
          name: '',
          alias: ''
        }
        this.frameDialogVisible = true
        console.log('append', data)
      }
    },
    edit(data, e) {
      if (data.type === FRAME_TYPE.PART || data.type === FRAME_TYPE.HOSPITAL) {
        this.$message.info(this.$t('action.notDevelopedYet') + '')
        return
      }
      const parentNode = this.findNodeById(this.treeData, data.parent_id)
      this.frameInfo = {
        ...data,
        parent_name: parentNode === null ? '' : parentNode.name
      }
      this.frameEditTitle = this.$t('frameManage.editFrame')
      this.frameDialogVisible = true
    },
    remove(data) {
      let warning = ''
      if (data.type === FRAME_TYPE.ROOM) {
        warning = this.$t('frameManage.sureDelete') + '【' + data.full_name + '】' + this.$t('frameManage.allBad')
      } else {
        warning = this.$t('frameManage.sureDeleteBed') + '【' + data.full_name + '】?'
      }
      this.$confirm(warning, this.$t('action.waring' + ''), {
        confirmButtonText: this.$t('action.yes'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        HospitalFrame_API.deleteHospitalFrame(data.id).then(response => {
          this.$message({
            type: 'success',
            message: this.$t('action.deleted')
          })
          this.getFrameTree().then(() => {
            // 判断选中节点是否被删除，如果被删除需要重新选择根节点
            const selectNode = this.findNodeById(this.treeData, this.selectedNodeId)
            if (selectNode === null) {
              this.selectedNodeId = this.treeData[0].id
            }
            this.$refs.frameTree.setCurrentKey(this.selectedNodeId)
          })
        }).catch(response => {
          this.$message({
            type: 'info',
            message: response.message
          })
        })
      }).catch(() => {

      })
    },

    handleFrameSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const params = this.MixinClone(this.frameInfo)
          if (params.id) {
            HospitalFrame_API.updateHospitalFrame(params.id, params).then(response => {
              this.$message.success(this.$t('action.editSuccess') + '')
              this.frameDialogVisible = false
              this.getFrameTree().then(() => {
                this.selectedNodeId = response.id
                this.$refs.frameTree.setCurrentKey(this.selectedNodeId)
              })
            })
          } else {
            if (!params.part_id) {
              params.part_id = this.$store.getters.partId
            }

            HospitalFrame_API.addHospitalFrame(params).then(response => {
              this.$message.success(this.$t('action.addSuccess') + '')
              this.frameDialogVisible = false
              this.getFrameTree()
            })
          }
        } else {
          this.$message.error(this.$t('action.fromError'))
          return false
        }
      })
    },
    /** 开始拖拽之前保存treeData数据，拖拽完成后判定能否拖拽到目标节点，不允许拖拽把初始数据覆盖拖拽后的数据，否则拖拽成功
     * @param node
     * @param event
     */
    nodeDragStart(node, event) {
      this.treeDataClone = this.MixinClone(this.treeData)
    },
    /** 拖拽结束 **/
    nodeDrop(node, target, position, event) {
      var success = true
      const nparent = this.findNodeById(this.treeDataClone, node.data.parent_id)
      const tparent = this.findNodeById(this.treeDataClone, target.data.parent_id)
      if (position === 'inner') { // 进入了某个节点之中,不能将某一节点拖入同级节点，也不能跨级拖动
        if (Number(node.data.type) <= Number(target.data.type) || Number(node.data.type) - Number(target.data.type) > 1) {
          this.treeData = this.treeDataClone
          success = false
        }
      } else {
        // 查找Target和node的parent 判定target的parent类型与node的parent类型是否一致
        if (nparent === null || tparent === null || nparent.type !== tparent.type) {
          this.treeData = this.treeDataClone
          success = false
        }
      }
      if (success) { // 拖拽完成,更新node和target排序
        HospitalFrame_API.sort(node.data.id, target.data.id, position).then(res => {
          this.selectedNodeId = node.data.id
          this.getFrameTree().then(() => {
            this.$refs.frameTree.setCurrentKey(this.selectedNodeId)
            console.log('sid', this.selectedNodeId)
          })
        })
      }
    },
    /** 树形结构中查找指定Id节点 */
    findNodeById(data, id) {
      let node = null
      if (data.length > 0) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].id === id) {
            node = data[i]
            break
          }
          if (data[i].children && data[i].children.length > 0) {
            const subresult = this.findNodeById(data[i].children, id)
            if (subresult !== null) {
              node = subresult
              break
            }
          }
        }
      }
      return node
    },
    /** 节点过滤方法 **/
    filterNode(value, data) {
      if (!value) return true
      return data.full_name.indexOf(value) !== -1
    },
    /** 点击树形节点  **/
    nodeClick(data, node, leaf) {
      this.$set(this, 'selectedNodeId', data.id)
    },
    /** 快速创建空间结构弹窗 **/
    quickCreateFrame() {
      this.frameQuickCreateVisible = true
    },

    quickCreateSubmit(formname) {
      const params = this.createFrameModel
      params.part_frame_id = this.treeData[0].id
      HospitalFrame_API.quickCreate(params).then(res => {
        this.$message.success(this.$t('action.createSuccess') + '')
        this.frameQuickCreateVisible = false
        this.getFrameTree().then(() => {
          this.$refs.frameTree.setCurrentKey(this.selectedNodeId)
        })
      }).catch(err => {
        this.$message.error(err.message)
      })
    },

    /** 显示位数变化 **/
    bitNumChange(val, frame_type) {
      const s = Array(val).join(0) + 1
      if (frame_type === 'room') {
        this.room_num_demo = s
      } else {
        this.bed_num_demo = s
      }
    },
    /** 起始位数变化 结束位置要根据起始位置的大小来变化 */
    roomStartChange(val) {
      console.log(val)
      if (val > this.createFrameModel.room_end_no) {
        this.createFrameModel.room_end_no = val
      }
    },
    /**
     * 名称输入变化
     * @param val
     */
    frameChange(val) {
      console.log('s', this.frameInfo)
      if (!this.frameInfo.full_name) {
        if (this.frameInfo.type === FRAME_TYPE.ROOM) {
          this.$set(this.frameInfo, 'full_name', val + this.$t('frameManage.room'))
          // this.frameInfo.full_name = val
        } else {
          this.$set(this.frameInfo, 'full_name', this.frameInfo.parent_name + '-' + val + this.$t('frameManage.bed'))
          // this.frameInfo.full_name =
        }
      }
    },
    handleCustomerChange() {
      this.getFrameTree()
    }
  }
}
</script>

<style scoped>
.el-aside{
  margin: 8px;
  padding: 8px;
  border-width: 1px;
  border-style: solid;
  background: #fff;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.el-tree{margin-top: 8px}
.el-main{
  margin: 8px;
  padding: 0;
}
</style>
