<template>
  <div class="content-main common-scroll">
    <div class="content-body">
      <Row :gutter="8" style="width:100%;height:100%">
        <i-col span="5" style="height:100%">
          <div class="station-tree">
            <div class="station-tree-body">
              <div class="station-tree-top">
                <Input suffix="ios-search" placeholder="请输入关键字查询" clearable search v-model="currentStation" class="common-search"  @on-search="iconChange" @on-clear="clearChange"/>
              </div>
              <div class="station-tree-center">
                <div class="station-tree-left common-scroll" v-show="showTree">
                  <tree-list :defaultData="stationData" :currentStaData="currentStaData" :clickAllNode="true" secondCalssName="icon-shebei1" thirdCalssName="icon-shebei" v-if="stationData && stationData.length>0" @treeChange="treeChange" ref="tree"></tree-list>
                </div>
                <div class="station-tree-left-notree" v-show="!showTree">
                  关键字输入错误！
                </div>
              </div>
            </div>
          </div>
        </i-col>
        <i-col span="19" style="height:100%">
          <div class="right-main">
            <div class="manage-main-top">
              <Button icon="ios-add" class="common-add-btn" @click="addClick">新增关联</Button>
            </div>
            <div class="manage-main-center">
              <Table :columns="columns" :data="tableData" class="common-table" no-data-text="" :row-class-name="rowClassName" :loading="loading">
                <template slot="loading">
                    <Loading-animation></Loading-animation>
                </template>
                <template slot-scope="{ row }" slot="action">
                  <Tooltip content="解绑" placement="top">
                      <i class="iconfont icon-guanlian" style="cursor:pointer;color:#E92E2E;fontSize:20px;marginRight:6px" @click="boundClick(row)"></i>
                  </Tooltip>
                </template>
              </Table>
            </div>
            <Page :total="tableTotal" :current="tableParams.pageNum" :page-size="tableParams.pageSize" @on-change="changePage" @on-page-size-change="sizeChange" show-elevator class="common-page"/>
          </div>
        </i-col>
      </Row>
    </div>
     <Modal
      v-model="showModal"
      :title="title"
      width="25"
      ref="modalGrag"
      draggable
      reset-drag-position
      :mask-closable="false"
      @on-visible-change="modalChange"
      class-name="common-modal">
      <Form class="common-form" ref="formOption" :model="formOption" :rules="ruleValidate" :label-width="120">
				<FormItem label="应用名称：" prop="applicationId">
           <Select v-model="formOption.applicationId" placeholder="应用名称">
              <Option v-for="item in appNameList" :value="(item.id)" :key="item.value">{{ item.appName }}</Option>
          </Select>
				</FormItem>
				<FormItem label="设备类型：" prop="equipmentTypeId">
           <Select v-model="formOption.equipmentTypeId" placeholder="设备类型">
              <Option v-for="item in equipTypeData" :value="(item.id)" :key="item.id">{{ item.name }}</Option>
          </Select>
        </FormItem>
			</Form>
      <div slot="footer">
          <Button @click="modalCancel">取消</Button>
          <Button type="primary" @click="modalOk('formOption')">确定</Button>
        </div>
    </Modal>
    <Modal
      v-model="modalStatus"
      title="确认解绑"
      width="25"
      ref="modalGrag"
      draggable
      reset-drag-position
      :mask-closable="false"
      class-name="common-modal">
      <Icon type="ios-information-circle" class="modal-icon"  style="color:#E92E2E"></Icon>
      <span class="modal-text">删除的同时将解绑所有运营数据，且数据不可恢复。请慎重操作。</span>
      <div slot="footer">
          <Button @click="commonCancel">取消</Button>
          <Button type="primary" @click="commonOk">确定</Button>
        </div>
    </Modal>
</div>
</template>
<script>
import _ from 'lodash'
export default {
  name: "ApplicationEquip",
  components:{
  },
  data() {
    return {
      currentStation: '',
      currentStaData: [], // 当前搜索框搜索的站台数组对象，传给子组件，用来判断单选站台名当前选中状态
      showTree: true,// 是否显示树形组件
		  stationData: [],
      tableTotal: 0,
      tableParams: {
        applicationId:'',
        equipmentTypeId: '',
        keywords: '',
        pageNum: 1,
        pageSize: 10
      },
      loading: true,
      tableData: [],
      columns: [
          {
            title: '应用名称',
            key: 'appName',
            align: 'center'
          },
          {
            title: '设备类型',
            key: 'equipmentName',
            align: 'center'
          },
          {
            title: '接入设备数量',
            key: 'equipmentNum',
            align: 'center'
          },
          {
            title: '操作',
            align: 'center',
            slot: 'action',
          }
      ],
      rowObj: {},
      formOption: {applicationId: '',equipmentTypeId:''},
      ruleValidate: {
        applicationId: [{
          required: true,
          type: 'number',
          message: '请选择应用名称',
          trigger: 'change'
        }],
        equipmentTypeId: [{
          required: true,
          type: 'number',
          message: '请选择设备类型',
          trigger: 'change'
        }],
      }, 
    equipTypeData: [],
    showModal: false,
    title: '新增关联',
    modalStatus: false,
    appNameObj: {
        level: '',
        lineId: '',
        stationId: '',
        equipmentCheck: '',
        instrumentCheck: '',
        pageNum: 1,
        pageSize: 9999
      },
      appNameList: []
    };
  },
  mounted() {
    this.getMetroLevel()
  },
  methods: {
    // 获取树形数据
    getMetroLevel () {
     this.$get('metroapi/application/appEquipmentTypeTree').then(res => {
      if (res.httpCode == 1) {
        this.stationData = res.data
			}
		 })
    },
    // 递归函数 每层数组的第一个对象里的属性expand 全展开(true)
    getTree(arr) {
      return arr.map((v,index) => {
        if (index==0) {
          v.expand = true
        }
        if (v.children) v.children = this.getTree(v.children);
        return v;
      });
    },
    iconChange: _.throttle(function() {
      this.currentStaData = []
      this.treeName = []
      this.$nextTick(()=> {
        this.getTableData()
      })
      if(this.currentStation != ''){
        this.showTree = false
        document.querySelector(".common-scroll").scrollTo(0, 0); // 滚动条回到顶部
      } else {
        document.querySelector(".common-scroll").scrollTo(0, 0); // 滚动条回到顶部
        this.showTree = true
        this.stationData = this.getTree(this.stationData)
        return 
      }
      this.getSelectedItem()
		}, 500),
    clearChange () {
      this.getSelectedItem()
      this.$nextTick(()=> {
        this.getTableData()
      })
    },
    getSelectedItem  () {
      this.stationData.forEach((item, index,itemArr) => {
        item.expand = false;
        item.disabled = false; 
        item.selected = false;
        if (item.title == this.currentStation) {
            item.selected = true;
            item.disabled = true; // disabled 是否禁止选中 
            item.expand = true;
            this.currentStaData.push(item)
            this.showTree = true
        }
        if (this.currentStation == '' && index == 0) {
          item.expand = true
        }
        item.children.forEach((val, i,valArr) => {
          val.expand = false; //expand 是否展开直子节点 
          val.disabled = false; // disabled 是否禁止选中
          val.selected = false;
          if (val.title == this.currentStation) {
            val.selected = true;
            val.disabled = true; // disabled 是否禁止选中 
            val.expand = true;
            item.expand = true;
            this.currentStaData.push(val)
            this.showTree = true
          }
          if (this.currentStation == '' && i==0) {
            val.expand = true
          }
          val.children.forEach ((lastVal,lastIndex) => {
            lastVal.selected = false; //expand 是否展开直子节点 
            lastVal.disabled = false; 
            lastVal.expand = false;
            if (lastVal.title == this.currentStation) {
              lastVal.selected = true;
              lastVal.disabled = true; // disabled 是否禁止选中 
              lastVal.expand = true;
              val.expand = true
              item.expand = true
              this.currentStaData.push(lastVal)
              this.showTree = true
            } 
          })
        });
      });
    },
    treeChange(val,arr,level) {
      this.currentStation = val
      this.$nextTick(()=> {
        this.getTableData(arr,level)
      })
		},
    rowClassName(row, index) {
      if (index % 2 == 0) {
        return "ivu-table-stripe-even";
      } else {
        return "ivu-table-stripe-odd";
      }
    },
    // 分页
    changePage (val) {
      this.tableParams.pageNum = val
      this.getTableData()
    },
    //跳转
    sizeChange (val) {
      this.tableParams.pageSize = val
      this.getTableData()
    },
    getTableData (arr,level) {
      if (level) {
        this.tableParams.keywords = ''
        if (level == 2) {
          this.tableParams.applicationId = arr[arr.length-1]
          this.tableParams.equipmentTypeId = ''
        } else if (level == 3) {
          this.tableParams.applicationId = arr[arr.length-2]
          this.tableParams.equipmentTypeId = arr[arr.length-1]
        } else {
          this.tableParams.applicationId = ''
          this.tableParams.applicationId = ''
        }
      } else {
        this.tableParams.applicationId = ''
        this.tableParams.equipmentTypeId = ''
        if (this.currentStation == '合肥轨道交通' || this.currentStation == '') {
          this.tableParams.keywords = ''
        } else {
          this.tableParams.keywords = this.currentStation
        }
      }
      this.loading = true
      this.$get('metroapi/application/equipmentTypeInfo', this.tableParams).then(res=>{
        this.loading = false
          if ( res.httpCode == 1 ){
            this.tableData = res.data.data
            this.tableTotal = res.data.count
            if (res.data.data.length==0 && this.tableParams.pageNum>1) {
              this.tableParams.pageNum--
              return this.getTableData()
            }
          } else {
            this.tableData = []
            this.tableTotal = 0
          }
        })
    },
    getType  () {
      // 获取设备类型
      this.$get('metroapi/equipment/queryEquipmentType', {name:''}).then(res=>{
        if (res.httpCode == 1 ){
          this.equipTypeData = res.data
        } else {
          this.equipTypeData = []
        }
      })
      // 获取应用名称
      this.$get('metroapi/application/info/list', this.appNameObj).then(res=>{
          if (res.httpCode == 1 ){
            this.appNameList = res.data.data
          } else {
            this.appNameList = []
          }
        })
    },
    addClick () {
      this.showModal = true
    },
    boundClick (row) {
      this.rowObj = row
      this.modalStatus = true
    },
    modalChange (modalStatus) {
     if (!modalStatus) {
      this.$refs.formOption.resetFields();
     }
    },
    modalOk (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$post('metroapi/application/addEquipmentType', this.formOption).then(res=>{
            if (res.httpCode == 1 ){
              this.showModal = false
              this.$Message.info(res.msg)
              this.getTableData()
              this.getMetroLevel()
            } else {
              this.$Message.info(res.msg)
            }
          })
        } else {
          this.showModal = true
        }
      })
    },
    modalCancel () {
      this.showModal = false
    },
    commonOk () {
      this.$post('metroapi/application/deleteEquipmentType',{appEquipmentTypeId:this.rowObj.appEquipmentTypeId}).then(res=>{
        if (res.httpCode == 1 ){
          this.modalStatus = false
          this.getTableData()
          this.getMetroLevel()
          this.$Message.info(res.msg)
        } else {
          this.$Message.info(res.msg)
        }
      })
    },
    commonCancel () {
      this.modalStatus = false
    },
  }
};
</script>
<style scoped lang="stylus">
.content-main {
  width: 100%;
  height: calc(100% - 50px);
  overflow: auto;
}
.common-search {
  width: 100%;
}
>>> .common-search .ivu-input {
  background-color: #06214D;
  border: 1px solid #2355A6;
  border-radius: 15px;
  color: #fff;
  height: 32px;
}
>>> .common-search .ivu-input:focus {
    border-color: #0185ea;
}
.content-body {
  width: 100%;
  height: 100%;
  background: #06214D;
}
.station-tree {
  height: 100%;
  padding: 10px;
}
.station-tree-body {
  border: 1px solid #204384;
  height: 100%;
  padding: 10px;
}
.station-tree-center {
  height: calc(100% - 32px);
  padding-top: 10px;
  // display: flex;
}
.station-tree-left {
  height: 100%;
  overflow: hidden;
  overflow-y: auto;
}
.station-tree-left-notree {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  fon-size: 14px;
}
.right-main {
  height: 100%;
  padding: 10px 0;
  position: relative;
  // padding: 16px;
}
.manage-main-top {
  padding: 12px 0;
  display: flex;
  justify-content: flex-end;
}
.manage-main-center {
  width: 100%;
  height: calc(100% - 100px);
}
.common-table {
  max-height: 100%;
}
>>> .common-table .ivu-table th {
  height: 54px;
 }
 >>> .common-table .ivu-table td {
  height: 54px;
 }
>>> .ivu-spin-fix {
  top: 54px;
  height: calc(100vh - 350px);
}
>>> .ivu-table-tip {
  background: url('../../../assets/images/noData.png') no-repeat center;
  height: calc(100vh - 350px);
}
.common-page {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
  position: absolute;
  bottom: 0;
  right: 0;
}
</style>