<template>
    <div>
<!--        <el-button class="elbut" type="primary" icon="el-icon-check" @click="clickbindMonitor">新增策略</el-button>-->
      <el-button v-if="showButton" class="elbut" type="primary" icon="el-icon-check" @click="addDeptStrategy">新增策略</el-button>
        <el-row :gutter="20">
            <el-col :span="9" class="col1">
                <el-input
                    placeholder="输入关键字进行过滤"
                    style="width: 240px"
                    class="mb10"
                    v-model="filterText"
                    clearable
                ></el-input>
                <el-tree
                    :style="`height: ${vh}px; overflow-y: auto`"
                    class="filter-tree"
                    :data="data"
                    :props="defaultProps"
                    default-expand-all
                    highlight-current
                    :expand-on-click-node="false"
                    :filter-node-method="filterNode"
                    ref="tree"
                >
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <span @click="click1(node)">{{ node.label }}</span>
                        <div v-if="data.level==2">
                            <span>
                                <el-button
                                    type="text"
                                    icon="el-icon-document"
                                    :style="`color:${color}`"
                                    @click="tactics(data.id, 0)"
                                >
                                    自动策略
                                </el-button>
                                <el-button
                                    type="text"
                                    icon="el-icon-document"
                                    :style="`color:${color};margin-left: 15px`"
                                    @click="tactics(data.id, 1)"
                                >
                                    手动策略
                                </el-button>
                                <el-button
                                    type="text"
                                    icon="el-icon-document"
                                    :style="`color:${color};margin-left: 15px`"
                                    @click="tactics(data.id, 2)"
                                >
                                    排除策略
                                </el-button>
                            </span>
                        </div>
                    </span>
                </el-tree>
            </el-col>
            <el-col :span="15">
                <vxe-table
                    border
                    stripe
                    style="width: 100%; margin-top: 45px"
                    ref="xTable"
                    size="mini"
                    highlight-current-row
                    row-id="id"
                    v-loading="loading1"
                    :height="vh + 'px'"
                    :data="tableData1"
                    :radio-config="{ highlight: true }"
                    header-cell-class-name="table_header"
                >
<!--                    <vxe-column type="radio" align="center" width="60"></vxe-column>-->
                    <vxe-column field="name" align="center" title="策略名称"></vxe-column>
                    <vxe-column field="type" width="150" align="center" title="策略类型">
                      <template v-slot="row">
                        <span>{{row.row.type===0 ? '预警单':'告警单' }}</span>
                      </template>
                    </vxe-column>
                    <vxe-column field="grade" width="150" align="center" title="策略等级">
                      <template v-slot="row">
                        <span>{{row.row.grade===0 ? '自动策略':row.row.grade === 1?'手动策略':'排他策略' }}</span>
                      </template>
                    </vxe-column>

                  <vxe-column field="grade" width="150" align="center" title="状态">
                    <template slot-scope="scope">
                      <el-switch
                          :width="60"
                          v-model.number="scope.row.state"
                          active-color="#13ce66"
                          inactive-color="#ff4949"
                          :active-value="1"
                          :inactive-value="2"
                          @change="stateChange($event, scope.row.id)"
                      ></el-switch>
                    </template>
                  </vxe-column>

                    <vxe-column title="操作" align="center">
                        <template #default="{ row }">
                            <el-button type="primary" size="mini" @click="lookOver(row)" icon="el-icon-view">
                                查看
                            </el-button>
                          <el-button type="primary" size="mini" @click="lookOver(row)" icon="el-icon-view">
                            修改
                          </el-button>
                          <el-button type="primary" size="mini" @click="delStrategy(row.id)" icon="el-icon-view">
                            删除
                          </el-button>
                        </template>
                    </vxe-column>
                </vxe-table>
            </el-col>
<!--            <el-col :span="8">
                <el-input
                    placeholder="输入关键字进行过滤"
                    style="width: 240px; margin-top: 45px"
                    class="mb10"
                    v-model="filterText1"
                    clearable
                ></el-input>
                <el-tree
                    :data="tableData"
                    show-checkbox
                    v-loading="loading"
                    default-expand-all
                    highlight-current
                    node-key="id"
                    ref="trees"
                    :filter-node-method="filterNode1"
                    :style="`height: ${vh - 45}px; overflow-y: auto; `"
                    :tree-config="{ children: 'children' }"
                    :props="defaultProps"
                ></el-tree>
            </el-col>-->
        </el-row>
        <!-- 绑定 -->
        <binding v-if="binding" :id="bindingID"  :operateType="operateType" :deptId="formInline.deptId" :grade="formInline.grade" :type="typeKey" @close="reClose" />
    </div>
</template>
<script>
import { existMonitorDeptTree } from '@/api/admin/dept'
import {
  getMonitor,
  bindMonitor,
  getStrategyList,
  echoMonitor,
  delStrategy,
  updateStrategyState
} from '@/api/Processsupervision/tactics.js'
import binding from './binding.vue'
export default {
    components: { binding },
    props: {
        typeKey: {
            type: [String, Number]
        }
    },
    data() {
        return {
            vh: null,
            data: [],
            deptId: JSON.parse(window.sessionStorage.getItem('Info')).deptId,
            filterText: '',
            filterText1: '',
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            loading: false,
            loading1: false,
            binding: false,
            multipleSelection: [],
            color: JSON.parse(window.localStorage.echartsColor).WordColor,
            tableData: [],
            tableData1: [],

            showButton:false,

            id: '',
            bindingID: '',
            formInline: {
                alarmId: [],
                grade: null,
                deptId: '',
                monitorId: [],
                type: ''
            },


           operateType:0, //0.新增操作 1.查看操作
        }
    },
    created() {},
    mounted() {
        this.formInline.type = this.typeKey
        this.setHeight()
        window.addEventListener('resize', this.setHeight)
        this.queryData()
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.setHeight)
    },
    methods: {
        setHeight() {
            this.vh = window.sessionStorage.getItem('appheight') - 177
        },
        //获取部门树
        queryData() {
          existMonitorDeptTree().then(res => {
                this.data = res.data
            })
        },
        // 树点击按钮
        async tactics(deptId, grade) {
            this.showButton = true
            this.loading = true
            this.loading1 = true
            this.formInline.deptId = deptId
            this.formInline.grade = grade
            await getMonitor({
                orgId: deptId
            }).then(res => {
                this.tableData = res.data
                this.loading = false
            })
            await getStrategyList({
                grade: grade,
                type: this.typeKey,
                deptId:this.formInline.deptId
            }).then(res => {
                this.tableData1 = res.data
                this.loading1 = false
            })
            await echoMonitor({
                deptId: deptId,
                type: this.typeKey,
                grade: grade
            }).then(res => {
                this.$refs.trees.setCheckedKeys(res.data.children)
                if (res.data.id != null) {
                    this.tableData1.forEach(item => {
                        if (item.id == res.data.id) {
                            this.$refs.xTable.setRadioRow(item)
                        }
                    })
                }
            })
        },
        // 保存
        clickbindMonitor() {
            this.multipleSelection = this.$refs.trees.getCheckedNodes()
            this.formInline.alarmId = [this.$refs.xTable.getRadioRecord().id]

            if (this.formInline.deptId == '') {
                this.$message({
                    message: '请选择单位!',
                    type: 'warning'
                })
            } else if (this.formInline.alarmId.length == 0) {
                this.$message({
                    message: '请选择策略!',
                    type: 'warning'
                })
            } else if (this.multipleSelection.length == 0) {
                this.$message({
                    message: '请选择监测点!',
                    type: 'warning'
                })
            } else {
                ;(this.formInline.monitorId = []),
                    this.multipleSelection.forEach(item => {
                        if (item.leven == 3) {
                            this.formInline.monitorId.push(item.id)
                        }
                    })

                bindMonitor(this.formInline).then(res => {
                    if (res.code == 'A0000') {
                        this.$message({
                            message: '保存成功!',
                            type: 'success'
                        })
                    }
                })
            }
        },
        click1(e){
            console.log("🚀 ~ click1 ~ e:", e)

        },
        filterNode(value, data, node) {
            if (!value) {
                return true
            }
            let _array = [] //这里使用数组存储 只是为了存储值。
            this.getReturnNode(node, _array, value)
            let result = false
            _array.forEach(item => {
                result = result || item
            })

            return result
        },
        filterNode1(value, data, node) {
            if (!value) {
                return true
            }
            let _array = [] //这里使用数组存储 只是为了存储值。
            this.getReturnNode(node, _array, value)
            let result = false
            _array.forEach(item => {
                result = result || item
            })
            return result
        },
        getReturnNode(node, _array, value) {
            let isPass = node.data && node.data.name && node.data.name.indexOf(value) !== -1
            isPass ? _array.push(isPass) : ''
            this.index++
            if (!isPass && node.name != 1 && node.parent) {
                this.getReturnNode(node.parent, _array, value)
            }
        },
        selectChangeEvent({ records }) {
            this.multipleSelection = records
        },

        // // 单选点击事件
        // radioChangeEvent1({ row }) {

        //   this.formInline.alarmId = [row.id];
        // },
        // 查看
        lookOver(row) {
            this.bindingID = row.id
            this.binding = true
            this.operateType = 1
        },

      //新增单位策略
      addDeptStrategy(){
        this.binding = true
        this.bindingID = ''
        this.operateType = 0
      },

      // 删除(id)
      delStrategy(id) {
        this.$confirm('确认是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delStrategy({
            ids: id
          }).then(res => {
            if (res.code == 'A0000') {
              this.$message({
                message: '删除成功!',
                type: 'success'
              })
              this.tactics(this.formInline.deptId,this.formInline.grade)
            }
          })
        })
      },

      // 修改表格状态
      stateChange(e, id) {
        updateStrategyState({ id: id, state: e }).then(res => {
          if (res.code == 'A0000') {
            this.$message({
              message: '告警单修改状态,成功!',
              type: 'success'
            })
          }
          this.tactics(this.formInline.deptId,this.formInline.grade)
        })
      },

      reClose(){
        this.binding = false;
        this.tactics(this.formInline.deptId,this.formInline.grade)
      }

    },

    computed: {},

    watch: {
        filterText(val) {
            this.$refs.tree.filter(val)
        },
        filterText1(val) {
            this.$refs.trees.filter(val)
        }
    }
}
</script>
<style lang="less" scoped>
@import url('../../../../styles/comStyle.less');
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
.tab .cell {
    text-align: left;
}
.elbut {
    position: absolute;
    z-index: 999;
    right: 10px;
}
</style>
