<template>
    <d2-container>
        <div v-if="isExpend" class="d2-fl d2-tree-view">
            <el-tree
                    ref="tree"
                    highlight-current
                    :data="treeData"
                    default-expand-all
                    :props="defaultProps"
                    @node-click="handleNodeClick"
            >
        <span class="icon-tree" slot-scope="{ node, data }">
          <div v-if="data.alias == 'top'">
          	<i class="fa fa-university"></i>
          	<span>&nbsp;{{node.label}}</span>
          </div>
          <div v-if="data.alias == 'campus'">
          	<i class="fa fa-building"></i>
          	<span>&nbsp;{{node.label}}</span>
          </div>
             <div v-if="data.alias == 'building'">
          	<i class="fa fa-university"></i>
          	<span>&nbsp;{{node.label}}</span>
          </div>
            	<div v-if="data.alias == 'room'">
				 		 				<i class="fa fa-users"></i>
				 		 				<span>&nbsp;{{node.label}}</span>
				 		 			</div>
            <!--<div v-if="data.alias == 'user'">-->
            <!--<i class="fa fa-users"></i>-->
            <!--<span>&nbsp;{{node.label}}</span>-->
            <!--</div>-->
        </span>
            </el-tree>
        </div>
        <div
                @click="isExpend = !isExpend"
                :class="[{'angle-view':isExpend},{'angle-view-none':!isExpend}]"
        >
            <i :class="['fa', {'fa-angle-left':isExpend},{'fa-angle-right':!isExpend}]"></i>
        </div>
        <div @click="isExpend = !isExpend" :class="[{'angle-view':isExpend},{'angle-view-none':!isExpend}]">
            <i :class="['fa', {'fa-angle-left':isExpend},{'fa-angle-right':!isExpend}]"></i>
        </div>
        <div :class="[{'d2-fl':isExpend},{'d2-table-view':isExpend},{'d2-table-view-full':!isExpend}]" style="overflow: hidden">
            <div class="d2-table-view-header">
                <el-form size="small" :inline="true" :model="filter" @keyup.enter.native="handleList" class="demo-form-inline" labelPosition="right">
                    <el-form-item label="房间号">
                        <el-input v-model.trim="filter.roomNo" placeholder="房间号" clearable/>
                    </el-form-item>
                    <el-form-item label="所属楼栋">
                        <el-input v-model.trim="filter.towerNm" placeholder="所属楼栋" clearable/>
                    </el-form-item>
                    <el-form-item label="房间类型">
                        <custom-select :value="filter.roomTyp" v-model="filter.roomTyp" typeName="房间类型" style="width: 100%"></custom-select>
                    </el-form-item>
                    <el-form-item label="所在楼层">
                            <el-input v-model.trim="filter.floor" placeholder="所在楼层" clearable />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleList('1')">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="d2-table-view-content">
                <div class="d2-table-view-handle">
                    <el-button @click="operVisible = !operVisible" size="small" icon="el-icon-plus">新增</el-button>
                    <label slot="headerButton" for="upload-input_1">
                        <span   class="import-button">批量导入</span>
                    </label>
                    <el-button  size="small" @click="onMutilDelClick">批量删除</el-button>
                </div>
                <d2-crud
                        title="房间管理"
                        ref="d2Crud"
                        :options="tableOptions"
                        :loading="loading"
                        :columns="columns"
                        :data="data"
                        :rowHandle="rowHandle"
                        @edit="handleRowEdit"
                        @delete="handleRowRemove"
                        selection-row
                        @selection-change="handleSelectionChange"
                >
                </d2-crud>
            </div>
            <div class="d2-table-view-footer">
                <el-pagination
                        @current-change="handleCurrentChange"
                        @size-change="handleSizeChange"
                        :current-page.sync="currentPage"
                        :page-size="tableOptions.pageList[0]"
                        :page-sizes="tableOptions.pageList"
                        layout="total,sizes, prev, pager, next,jumper"
                        :total="pagination.total">
                </el-pagination>
            </div>
        </div>
        <el-dialog
                :title="diaLogName"
                :visible.sync="operVisible"
                @close="clearForm"
                width="40%"
                :close-on-click-modal="false"
        >
            <el-form ref="form" :model="form" label-width="80px" labelPosition="right" :rules="rules">
                <el-row :gutter="15">
                    <el-col :span="20">
                        <el-form-item label="房间号" prop="roomNo">
                            <el-input v-model.trim="form.roomNo" maxlenth="10"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="房间名" prop="roomNm">
                            <el-input v-model.trim="form.roomNm" maxlenth="15"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="所属楼栋" prop="towerId"> <!--belongsId所属校区id  belongs所属校区  -->
                            <el-select v-model="form.towerId" placeholder="请选择" style="width: 100%">
                                <el-option
                                        v-for="item in towerOptions"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="所在楼层" prop="floor">
                            <el-input v-model.trim="form.floor" type="number" maxlenth="3"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="入住性别" prop="sex">
                            <el-select v-model="form.sex" placeholder="请选择" style="width: 100%">
                                <el-option
                                        label="男"
                                        value="男">
                                </el-option>
                                <el-option
                                        label="女"
                                        value="女">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="房间类型" prop="roomTyp">
                            <custom-select :value="form.roomTyp" v-model="form.roomTyp" typeName="房间类型" style="width: 100%"></custom-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="床位数" prop="beds">
                            <el-input v-model.trim="form.beds" maxlenth="2" type="number" min="1"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="备注" prop="rmk">
                            <el-input type="textarea" maxlength="50" v-model.trim="form.rmk"/>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <zl-button :loading="staLoading" @click="operInstance(2)">保存</zl-button>
      </span>
        </el-dialog>
        <input id="upload-input_1" style="display: none" type="file"
               multiple
               ref="upload_1"
               name="file"
               @change="upload_1($event)">
        <input id="upload-input" style="display: none" type="file"
               multiple
               ref="upload"
               name="file"
               accept = "image/*"
               @change="upload($event)">
    </d2-container>
</template>

<script>
  import { Loading } from 'element-ui';
  import { tableOptions } from '../../../assets/options'
  import {RoomTreeNodeAll,getRoomMessageList,getTowerOptions,saveOrUpdataRoom,roomById,deleteRoomMess} from '@/api/dormitory/manageRoom'
  export default {
    name: 'system-merchant',
    data () {
      let checkCardId = (rule, value, callback) => {
        if(!value){
          return callback(new Error('不能为空'))
        }
        let reg = /^[0-9a-zA-Z]+$/
        if (!reg.test(value)) {
          return callback(new Error('请输入数字或英文组成的编号'))
        } else {
          callback ()
        }
      }
      return {
        ids:[],
        idss:"",
        towerOptions:[],
        staLoading:false,
        diaLogName:'新增房间信息',
        operVisible:false,
        time:'',
        falg:true,
        leaveOverId:[],
        selection:[],
        disabled:false,
        isExpend:true,
        currentPage:1,
        tableOptions,
        loading: false,
        filter: {
          treeNodeId:"",
          alias:"",
          roomNo:"",
          towerNm:"",
          roomTyp:"",
          floor:"",
          pageSize: 10,
          pageNum: 1
        },
        form:{
          rmk:"",
          id:"",
          roomNo:"",
          roomNm:'',
          towerId:"",
          floor:'',
          sex:"",
          roomTyp:"",
          beds:""
        },
        pagination: {
          total: 0
        },
        columns: [
          {
            title: '房间号',
            key: 'roomNo',
            minWidth: '120'
          },
          {
            title: '房间名',
            key: 'roomNm',
            minWidth: '120',
            showOverflowTooltip: true
          },
          {
            title: '所属楼栋',
            key: 'towerNm',
            minWidth: '120',
            // formatter (row, column, cellValue, index) {
            //   if (cellValue === '1') {
            //     return '人脸识别'
            //   } else if (cellValue === '2') {
            //     return '卡识别'
            //   }else if (cellValue === '3') {
            //     return '人脸+卡识别'
            //   }
            // }
          },
          {
            title: '所在楼层',
            key: 'floor',
            minWidth: '120'
          },
          {
            title: '入住性别',
            key: 'sex',
            minWidth: '90',
          },
          {
            title: '房间类型',
            key: 'roomTyp',
            minWidth: '120'
          },
          {
            title: '床位',
            key: 'beds',
            minWidth: '120'
          },
          {
            title: '备注',
            key: 'rmk',
            minWidth: '180'
          }
        ],
        rowHandle: {
          columnHeader: '操作',
          minWidth: '180',
          align: 'center',
          custom: [
            {
              text: '编辑',
              type: 'primary',
              size: 'small',
              emit: 'edit'
            },
            {
              text: '删除',
              type: 'danger',
              size: 'small',
              emit: 'delete'
            }
          ]
        },
        currentParentId:'',
        treeData:[],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        data: [],
        rules:{
          roomNo:[{validator:checkCardId,required: true, trigger: 'blur'}],
          roomNm:[{required: true, message: '请输入房间名', trigger: 'blur'}],
          towerId:[{required: true, message: '请选择所属楼栋', trigger: 'blur'}],
          floor:[{required: true, message: '请输入所在楼层', trigger: 'blur'}],
          sex:[{required: true, message: '请选择性别', trigger: 'blur'}],
          roomTyp:[{required: true, message: '请选择房间类型', trigger: 'blur'}],
          beds:[{required: true, message: '请输入床位数', trigger: 'blur'}],
      }
      }
    },
    methods: {
      operInstance() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if(parseInt(this.form.beds)<=0){
              this.$message({
                message:'床位数请输入1-20的数字',
                type: 'warning'
              })
              return
            }else if(parseInt(this.form.beds)>20){
              this.$message({
                message:'床位数请输入1-20的数字',
                type: 'warning'
              })
              return
            }
            this.loading = true
            saveOrUpdataRoom(this.form).then(res => {
              this.loading=false
              this.$message({
                message:'操作成功',
                type: 'success'
              })
              this.operVisible=false
              this.handleTreeNode()
            }).catch(err => {
              this.loading=false
            })

          }
        })
      },
      // upload_1 (e) {
      //   //this.files= []
      //   let files = e.target.files
      //   let formData = new FormData()
      //   for (let k in files) {
      //     if (files.hasOwnProperty(k)) {
      //       formData.append('file', files[k])
      //     }
      //   }
      //   let loadingInstance_2=Loading.service({ fullscreen: true,text:'导入中...',background:"rgba(0, 0, 0, 0.8)" })
      //   uploadImagess(formData).then(res => {
      //     this.$message({
      //       message: '导入成功',
      //       type: 'success'
      //     })
      //     this.$nextTick(() => {
      //       loadingInstance_2.close();
      //     });
      //     this.handleList()
      //   }).catch(err=>{
      //     this.$nextTick(() => {
      //       loadingInstance_2.close();
      //     });
      //   })
      //
      //   this.$refs.upload_1.value = null
      // },
      handleNodeClick(data) {
        if(data.alias !=='top'){
          this.falg = true
          this.filter.treeNodeId = data.id
          this.filter.alias=data.alias
        }else{
          this.falg = false
          this.filter.treeNodeId = ''
          this.filter.alias='top'
        }
        this.handleList()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleTreeNode () {
        RoomTreeNodeAll({}).then(res => {
          this.treeData = JSON.parse(res.msgDat)
          // this.form.orgId = this.treeData[0].id
        })
        this.handleList()
      },

      handleList (val) {
        if(val){this.filter.pageNum=1
          this.currentPage = 1}
        this.loading = true
        getRoomMessageList(this.filter).then(res => {
          this.loading = false
          this.data = res.list.list
          this.pagination.total = res.list.total
        }).catch(err => {
          this.loading = false
        })
      },

      handleCurrentChange (val) {
        this.filter.pageNum = val
        this.handleList()
      },

      handleSizeChange (val) {
        this.filter.pageNum = 1
        this.filter.pageSize = val
        this.handleList()
      },
      handleRowEdit ({index, row}) {
        this.diaLogName = '编辑房间信息'
        roomById({id:row.id}).then(res => {
          this.form = res.roomManageVO
          this.operVisible = true
        })

      },
      onMutilDelClick(){
        if(!this.multipleSelection.length){
          this.$message({
            message: '请选择记录',
            type: 'warning'
          })
        }else{
          this.$confirm(`确认删除当前房间信息?`, '确认操作', {
            confirmButtonText: '确定',
            cancelButtonText: '放弃',
            type: 'warning'
          }).then(() => {
            this.ids=[]
            this.multipleSelection.forEach((item,index)=>{
              this.ids.push(item.id)
            })
            this.idss=this.ids.join(",")
            deleteRoomMess({
              id:this.idss
            }).then(res=>{
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.handleTreeNode ()
            })
          })
        }
      },
      handleRowRemove ({index, row}) {
        this.$confirm(`确认删除当前房间信息`, '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '放弃',
          type: 'warning'
        }).then(() => {
          deleteRoomMess({
            id:row.id
          }).then(res=>{
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.handleTreeNode ()
          })
        })
      },
      clearForm () {
        if (this.$refs['form']!==undefined) {
          this.$refs['form'].resetFields()
        }
        this.form= {}
      },
    },
    mounted () {
      getTowerOptions().then(res=>{
        this.towerOptions=JSON.parse(res.msgDat)
      })
      this.tableOptions = this.$calcTableHeight(tableOptions,90)
      this.filter.pageSize = this.tableOptions.pageList[0]
      this.handleTreeNode()
    }
  }
</script>