<template lang='pug'>
  el-container(style="padding:0px;height:77.6vh;")
    el-aside( width="330px;", style="z-index:1000;box-shadow: 2px 0 8px 0 rgba(0, 0, 0, 0.2);background: #f4f4f4;" )
      el-card.treeCard(:body-style="{ padding: '0px'}" style="border: 0; box-shadow: 0 0 !important;")
        div(slot="header")
          span.title-bold( style="padding-right:150px;margin-left:10px;z-index:1001;" ) 线路资源树
        el-tree.dic_tree( :data="data", :highlight-current="true", :props="defaultProps", :default-expand-all="true", @node-click="handleNodeClick" )
          div(slot-scope="{ node, data }")
            .dic_tree_header(v-if="data.children && data.children.length > 0")
              .tree_house
                img(src="../../../../assets/images/zpoint.png")
              span {{ data.name }}
            span(v-else)
              .tree_point
                img(src="../../../../assets/images/road-icon.png")
              span.tree_label &nbsp; {{ node.label }}
    el-container
      el-header( style="height:42px;line-height:42px;background: #f4f4f4;z-index:1001;border: 1px solid rgba(195, 195, 195, 1);" )
        span.title-bold.title-left-color 站点接管管理
        el-popover( placement="bottom" width="150")
                el-button( slot="reference" size='mini' type="primary" icon="el-icon-s-tools" style='float:right;transform:translateY(6px)')  筛选
                el-checkbox-group( v-model="checkList")
                    el-col( :span="24")
                        el-checkbox( v-for="(item,index) in tableHeader" :label="item" :key="index" )
                          span {{item.label}}
        el-button( type="primary" style='float:right;margin-top: 6px;margin-right:20px;' size="mini" @click="applyListHandle()" ) 申请接管记录
      el-main.box_main
        el-card()
          drag-table( :data="dataList" :header="checkList" :isToLine='false' :option="tableOption"  @getDataList="getDataList" v-loading="dataListLoading"  :operationNum="4"  :isShowOperate="true")
            //- -- 插槽
            el-table-column(slot="fixed"  fixed  prop=""  label="序号"  width='80' header-align="center" align="center")
                template( slot-scope="scope")
                  span   {{scope.$index+(pageIndex - 1) * pageSize + 1}}

            template( slot='type' slot-scope="scope")
                span(v-if="scope.row.type == '1'") 正线站点
                span(v-if="scope.row.type == '2'") 换乘站点
            template( slot='isMaster' slot-scope="scope")
                span(v-if="scope.row.isMaster == 1") 主站
                span(v-if="scope.row.isMaster == 2") 从站

            template( slot='runStatus' slot-scope="scope")
                span(v-if="scope.row.runStatus == 1") 正常运行
                span(v-if="scope.row.runStatus == 2") 线路接管
                span(v-if="scope.row.runStatus == 3") 路网接管

            //- 操作项
            template( slot-scope="scope"  )
                el-button( type="text", size="mini", index="1-1", v-if="isAuth('sys:takeover:apply') && scope.row.isMaster == 1 && scope.row.runStatus == 1 && scope.row.takeoverStatus != 1" @click="addApply(scope.row)" ) 申请接管
                el-button( type="text", size="mini", index="1-2", v-if="isAuth('sys:takeover:abandon') && scope.row.isMaster == 1 && scope.row.runStatus != 1 && scope.row.takeoverStatus == 2" @click="abandonTakeoverHandle(scope.row)" ) 放弃接管
                span(v-if="scope.row.takeoverStatus == 1") 待审批
      el-footer.box_footer
        el-pagination( @size-change="sizeChangeHandle", background, @current-change="currentChangeHandle", :current-page="pageIndex", :page-sizes="[10, 20, 50, 100]", :page-size="pageSize", :total="totalPage", layout="total, sizes, prev, pager, next, jumper" )
    el-dialog(title="申请接管站点" :visible.sync="dialogVisible" width="30%" :append-to-body='true' :before-close="handleClose")
      el-form(ref="applyInfo" :model="applyInfo" label-width="80px")
        el-form-item(label="申请理由" prop="reason" :rules="[ { required: true, message: '请输入申请理由', trigger: 'blur' }, { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' } ]")
          el-input(type="textarea" :rows="3" placeholder="请输入申请理由" v-model="applyInfo.reason")
      span(slot="footer")
        el-button(@click="cancel") 取 消
        el-button(type="primary" @click="applyTakeoverHandle(applyInfo)") 确 定
    apply-list( v-if="applyListVisible" ref="applyList"  @refreshdatalist="getDataList")
</template>

<script>
import applyList from './apply-list'
import dragTable from '../../../components/tab'

export default {
  components: {
    applyList,
    dragTable
  },
  data() {
    return {
      applyInfo: {},
      dialogVisible: false,
      checkList: [], //筛选数据
        tableHeader: [
        { label: '所属线路名称', prop: 'lineName' },
        { label: '车站名称', prop: 'stationName' },
        { label: '车站编码', prop: 'code' },
        { label: '站点类型', prop: 'type', slot: true },
        { label: '主站/从站', prop: 'isMaster', slot: true },
        { label: '站点简称', prop: 'shortName' },
        { label: '状态', prop: 'runStatus', slot: true }

      ],
      tableOption: {
        border: false, //是否边框
        maxHeight: 500//高度
      },
      word: '', //查询
      dataList: [], //列表
      dataListLoading: false,
      pageIndex: 1,
      pageSize: 50,
      totalPage: 0,
      applyListVisible: false,
      ruleForm: {},
      visible: false,
      lineId: '', //选中的线路id
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      typeList: [
        { id: 1, name: '正线站点' },
        { id: 2, name: '换乘站点' }
      ],
      bean: ''
    }
  },
  watch: {
    totalPage() { //注意这个函数的名字必须和你监听data中的属性的名字一样,这样才能当你data中的属性发生变化时,触发这个函数
      let pages = Math.ceil(this.totalPage / this.pageSize)//新数据总页数
      //总页数小于当前页数则重新加载列表数据
      if (pages < this.pageIndex) {
          this.pageIndex = pages || 1
          this.getDataList()//获取表格数据的方法
      }
    },
    message(message) {
      if (message) {
        console.log('message', message)
        this.getDataList()
        this.$store.dispatch('d2admin/takeover/set', false)
      }
    }
  },
  created() {
    this.bean = JSON.parse(localStorage.getItem('sysSystem'))
    this.initTree()
    this.checkList = [...this.tableHeader]
  },
  computed: {
    message() {
      return this.$store.state.d2admin.takeover.message
    }
  },
  methods: {
    //排序
    sortChange(column) {
      if (column.order === 'descending') {
        this.order = 'desc'
      } else {
        this.order = 'asc'
      }
      if (column.column.columnKey) {
        this.sort = column.column.columnKey
      } else {
        this.sort = column.prop
      }
      this.getDataList()
    },
    //线路树节点点击事件
    handleNodeClick(data) {
      this.lineId = data.id
      this.pageIndex = 1
      this.getDataList()
    },
    //生成申请
    addApply(row) {
      // 查询是否可以接管
      // console.log(row)
      this.$http({
          url: this.$http.adornUrl('/sysStationTakeover/takingOver'),
          method: 'post',
          data: {
            byx2: row.byx2,
            stationId: row.id
          }
      }).then(data => {
        if (data && data.code === 0) {
          this.applyInfo = row
          this.dialogVisible = true
        }
      })
    },
    //申请接管
    applyTakeoverHandle(row) {
      this.$refs.applyInfo.validate((valid) => {
        if (valid) {
          let sysSystem = JSON.parse(localStorage.getItem('sysSystem'))
          let applyType = sysSystem.type - 1
          if (applyType < 1) this.$message.error('接管失败')
          let applyUserName = ''
          if (sysSystem.type === '2') {
            applyUserName = '线路管理员'
          } else if (sysSystem.type === '3') {
            applyUserName = '路网管理员'
          }
          this.$http({
              url: this.$http.adornUrl('/sysStationTakeover/applyTakeover'),
              method: 'post',
              data: {
                applyType: applyType, //申请接管类型(1线路中心,2路网中心)
                takeoverOrgName: sysSystem.name,
                // applyUserName: this.$store.state.d2admin.user.info.userName,
                applyUserName: applyUserName,
                applyUserId: localStorage.getItem('userId'),
                stationId: row.id,
                stationName: row.stationName,
                lineId: row.lineId,
                lineName: row.lineName,
                takeoverType: 1, //接管类型(1主动接管,2被动接管)
                byx2: row.byx2, //被接管服务器ip
                byx3: sysSystem.byx2 || 'localhost', //接管服务器ip(本地服务器ip)
                status: 1,
                reason: row.reason,
                type: sysSystem.type
              }
          }).then(data => {
            if (data && data.code === 0) {
              this.$message.success('操作成功')
              this.handleClose()
              this.getDataList()
            }
          })
        }
      })
    },
    //查看详情
    abandonTakeoverHandle(row) {
      this.$confirm(`您确定要放弃接管${row.stationName}站点安防平台管理系统的控制权吗?`, '放弃接管站点', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/sysStationTakeover/abandonTakeover'),
          method: 'post',
          data: {
            stationId: row.id,
            id: row.takeoverId,
            status: 5, //审批状态(1待审批,2审批通过,3审批不通过,4中断,5放弃接管)
            lineName: row.lineName,
            byx2: row.byx2, //接管站点ip
            type: JSON.parse(localStorage.getItem('sysSystem')).type
          }
        }).then(data => {
          if (data && data.code === 0) {
            this.$message({ message: '操作成功', type: 'success', duration: 1500 })
            this.getDataList()
            let takeoverList = JSON.parse(sessionStorage.getItem('takeoverList') || '[]')
            let list = takeoverList.filter(item => {
              return item !== row.id
            })
            sessionStorage.setItem('takeoverList', JSON.stringify(list))
          }
        })
      })
    },
    applyListHandle() {
      this.applyListVisible = true
      this.$nextTick(() => {
        this.$refs.applyList.init(this.lineId)
      })
    },
    initTree() {
      let data = {}
      if (this.bean) {
          //站点\线路
          if (this.bean.type === '1' || this.bean.type === '2') {
              data.id = this.bean.lineId
          }
      }
      this.$http({
        url: this.$http.adornUrl('/liLine/getTreeList'),
        method: 'post',
        data: data
      }).then((data) => {
        if (data && data.code === 0) {
          this.data = data.tree
          if (!this.lineId) {
            this.lineId = this.data[0].children[0].id
          }
          this.getDataList()
        }
      })
    },
    getDataList(sort, order) {
      let data = {
          page: this.pageIndex,
          rows: this.pageSize,
          sort: sort,
          order: order
        }
      if (this.bean) {
          //站点
          if (this.bean.type === '1') {
              data.id = this.bean.code
          }
          //线路
          if (this.bean.type === '2') {
              data.lineId = this.bean.lineId
          }
          //路网
          if (this.bean.type === '3') {
              data.lineId = this.lineId
          }
      }
      this.$http({
        url: this.$http.adornUrl('/liStation/listTakeover'),
        method: 'post',
        data: data
      }).then((data) => {
        // console.log('data:', data)
        if (data && data.code === 0) {
          this.dataList = data.page.rows
          this.totalPage = data.page.total
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    closeForm() {
      console.log('取消')
      this.visible = false
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    //关闭页面
    handleClose() {
      this.applyInfo = {}
      this.$refs.applyInfo.resetFields()
      this.dialogVisible = false
    },
    //取消
    cancel() {
      this.$confirm('确认取消?', '申请接管站点', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.handleClose()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消退出'
          })
        })
    }
  }
}
</script>
<style lang='scss' scoped>
.tree_warp {
  overflow: auto;
  height: 100%;
  box-sizing: border-box;
  background: #f4f4f4;
}

.infopage {
  margin: 24px;
  padding: 24px;
  height: 750px;
  background-color: rgba(7, 58, 116, 0.596);
}

.tree_house {
  width: 12px;
  height: 18px;
  display: inline-block;

  img {
    width: 20px;
    height: 20px;
    vertical-align: middle;
    // transform: translateY(-8px);
    transform: translateX(-40px);
  }
}

.tree_point {
  width: 12px;
  height: 18px;
  display: inline-block;

  img {
    width: 12px;
    height: 18px;
    vertical-align: middle;
    transform: translateY(-2px);
  }
}

.dic_tree {
  background: #f4f4f4;
  width: 330px;
}

.dic_tree_header {
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: rgba(54, 54, 54, 1);
  text-indent: 25px;
}

.dic_tree /deep/ .el-tree-node__expand-icon.expanded {
  display: none;
}

.dic_tree /deep/ .el-tree-node__content > .el-tree-node__expand-icon {
  display: none;
}

.dic_tree /deep/ .el-tree-node__expand-icon.is-leaf {
  display: none;
}

.dic_tree
  /deep/
  .el-tree-node
  > .el-tree-node__children
  .el-tree-node__content {
  width: 280px;
  height: 30px;
  line-height: 30px;
  border-radius: 15px 0 0 15px;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: rgba(0, 0, 0, 1);
  background: white;
  margin-top: 10px;
  margin-left: 30px;
  box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.05);
}

.el-tree--highlight-current
  /deep/
  .el-tree-node.is-current
  > .el-tree-node__content {
  background-color: #35aff8;
  color: white;
}
</style>