<template>
  <div class="content-container">
    <el-row class="tool-bar">
      <el-col :span="8" class="left">
        <div class="content-title">
          {{ title }}
        </div>
      </el-col>

      <el-col :span="16" class="button-group">
        <div class="select-search right">
          <el-cascader
            v-model="conditions.rectifyGroupId"
            :options="treeData"
            :props="{ checkStrictly: true, emitPath: false }"
            style="min-width: 160px"
            filterable
            clearable
            placeholder="部门"
            @change="handleChange"
          >
            <template slot-scope="{ node, data }">
              <span>{{ data.label }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>
          <el-select v-model="conditions.rectifyAccountId" style="width:100px;margin:0 10px" filterable clearable placeholder="执行人">
            <el-option v-for="item in userList" :key="item.accountId" :value="item.accountId" :label="item.accountName" />
          </el-select>
          <el-select v-model="conditions.hdangerLevel" style="width: 80px;" filterable placeholder="级别" clearable>
            <el-option :value="0" label="较低" />
            <el-option :value="1" label="一般" />
            <el-option :value="2" label="较大" />
            <el-option :value="3" label="重大" />
          </el-select>
          <el-select v-model="conditions.hdangerType" style="width: 110px;margin:0 10px" filterable placeholder="类型" clearable>
            <el-option :value="0" label="人员巡检" />
            <el-option :value="1" label="传感器" />
          </el-select>
          <div>
            <el-select v-model="conditions.goafOrebelt" style="width: 110px;" filterable placeholder="矿带" clearable @change="changeArea(1)">
              <el-option v-for="(item,index) in goafOrebelts" :key="index" :value="item" :label="item" />
            </el-select>
            <el-select v-model="conditions.goafOrebody" style="width: 110px;margin-left:10px" filterable placeholder="矿体" clearable @change="changeArea(2)">
              <el-option v-for="(item,index) in goafOrebodys" :key="index" :value="item.goafOrebody" :label="item.goafOrebody" />
            </el-select>
            <el-select v-model="conditions.goafOreheight" style="width: 110px;margin:0 10px" filterable placeholder="中段" clearable @change="changeArea(3)">
              <el-option v-for="(item,index) in goafOreheights" :key="index" :value="item.goafOreheight" :label="item.goafOreheight" />
            </el-select>
            <el-select v-model="conditions.goafId" style="width: 150px;" filterable placeholder="采空区编号" clearable @change="changeArea(4)">
              <el-option v-for="item in goafNames" :key="item.goafId" :value="item.goafId" :label="item.goafName" />
            </el-select>
          </div>
          <el-date-picker
            v-model="conditions.startSubmitTime"
            type="date"
            placeholder="开始时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
            style="width: 180px;margin:0 10px"
          />
          <el-date-picker
            v-model="conditions.endSubmitTime"
            type="date"
            placeholder="结束时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
            style="width: 180px;margin:0 10px"
          />
          <el-input v-model="conditions.hdangerTitle" class="search-input" placeholder="请输入内容">
            <el-button slot="append" icon="el-icon-search" @click="getData()" />
          </el-input>
        </div>
      </el-col>
    </el-row>

    <el-row class="content-body">
      <el-table v-loading="listLoading" class="page-table" border :data="dataList" height="calc(100vh - 230px)">

        <el-table-column type="index" label="序号" header-align="center" align="center" width="60" />>
        <el-table-column prop="hdangerTitle" label="预警名称" header-align="left" align="left">
          <template v-slot="{row}">
            <span>{{ row.hdangerTitle }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="hdangerType" label="类型" header-align="center" align="center" min-width="120">
          <template v-slot="{row}">
            <el-tag v-if=" row.hdangerType===1" type="success" effect="plain" color="rgb(38 69 90)">传感器巡检</el-tag>
            <el-tag v-else effect="plain" color="rgb(38 69 90)">人员巡检</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hdangerLevel" label="级别" header-align="center" align="center" width="80">
          <template v-slot="{row}">
            <span><el-tag type="success" effect="plain" color="rgb(38 69 90)">{{ row.hdangerLevel | dangerLevelFilter }}</el-tag></span>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" header-align="center" align="center" width="80">
          <template v-slot="{row}">
            <span><el-tag type="warning" effect="plain" color="rgb(38 69 90)">{{ row.status | dangerStatusFilter }}</el-tag></span>
          </template>
        </el-table-column>
        <el-table-column prop="curActivityTitle" label="当前关卡" header-align="center" align="center" width="80">
          <template v-slot="{row}">
            <span><el-tag type="danger" effect="plain" color="rgb(38 69 90)">{{ row.curActivityTitle }}</el-tag></span>
          </template>
        </el-table-column>
        <el-table-column prop="curAccountName" label="当前处理人" header-align="center" align="center" width="160">
          <template v-slot="{row}">
            <span><i class="el-icon-user-solid" />{{ row.curAccountName }}( {{ row.curPositionName }} )</span>
          </template>
        </el-table-column>

        <el-table-column prop="dangerDeadline" label="整改期限" header-align="center" align="center" width="165">
          <template v-slot="{row}">
            <span><i class="el-icon-timer" />{{ row.dangerDeadline }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" header-align="center" align="center" width="180">
          <template v-slot="{row}">
            <el-button v-if="row.curAccountId===userData.userId" type="primary" size="mini" @click="handleDanger(row)">处理</el-button>
            <el-button size="mini" type="info" @click="handleDetail(row)">详情</el-button>
            <el-button v-if="row.submitAccountId===userData.userId" size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <pagination v-show="total>0" :total="total" :page.sync="conditions.page" :limit.sync="conditions.limit" @pagination="getData" />
      </div>
    </el-row>
    <submit-activity ref="submit" title="登记预警" @formSuccess="formSuccess" />
    <review-activity ref="review" title="预警评审" @formSuccess="formSuccess" />
    <rectify-activity ref="rectify" title="预警整改" @formSuccess="formSuccess" />
    <accept-activity ref="accept" title="预警验收" @formSuccess="formSuccess" />
    <danger-details ref="DangerDetails" title="预警详情" />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'

import { getGoafBaseInfo } from '@/api/goaf/info'
import { getGroupByList } from '@/api/system/groupApi'
import { getUserByPage } from '@/api/system/userApi'
import { toTree } from '@/utils/build-tree'

import { deleteDangerById, getDangerByPage } from '@/api/goaf/dangerApi'
import DangerDetails from '@/views/goaf/danger/components/Details.vue'
import { mapGetters } from 'vuex'
import SubmitActivity from './activity/Submit'
import ReviewActivity from './activity/Review'
import RectifyActivity from './activity/Rectify'
import AcceptActivity from './activity/Accept'
export default {
  name: 'DangerList',
  components: { Pagination, SubmitActivity, ReviewActivity, RectifyActivity, AcceptActivity, DangerDetails },
  filters: {
    dangerLevelFilter(val) {
      const status = ['较低', '一般', '较大', '重大']
      return status[val]
    },
    dangerStatusFilter(val) {
      const status = ['待提交', '待评审', '待整改', '待验收', '完成']
      return val === -1 ? '撤销' : status[val]
    }
  },
  props: {
    title: {
      type: [String],
      default: '预警中心'
    }
  },
  data() {
    return {
      dataList: [],
      total: 0,
      listLoading: false,
      conditions: {
        page: 1,
        limit: 10,
        status: 2,
        startSubmitTime: undefined,
        endSubmitTime: undefined,
        goafId: undefined,
        goafOrebelt: undefined,
        goafOrebody: undefined,
        goafOreheight: undefined,
        rectifyGroupId: undefined,
        rectifyAccountId: undefined,
        hdangerLevel: undefined
      },
      goafList: [],
      goafOrebelts: [],
      goafOrebodys: [],
      goafOreheights: [],
      goafNames: [],
      treeData: [],
      userList: []
    }
  },
  computed: {
    ...mapGetters([
      'userData'
    ])
  },
  created() {
    this.getData()
    getGoafBaseInfo().then((res) => {
      const goafOrebelts = res.data.map(item => item.goafOrebelt)
      this.goafOrebelts = [...new Set(goafOrebelts)]
      this.goafList = res.data
    })
    getGroupByList().then((resp) => {
      const { code, data } = resp
      if (code === 0) {
        const temp = toTree(
          data,
          {
            value: 'value',
            name: 'label',
            pValue: 'parentId'
          },
          {
            value: 'groupId',
            name: 'groupName',
            pValue: 'parentId'
          }
        )
        this.treeData = temp
      }
    })
    getUserByPage({
      page: 1,
      limit: 999999
    }).then((resp) => {
      const { data } = resp
      this.userList = data
    })
  },
  methods: {
    changeArea(type) {
      const goafs = this.deeepClone(this.goafList)
      let goafOrebodys = this.deeepClone(this.goafOrebodys)
      let goafOreheights = this.deeepClone(this.goafOreheights)
      let goafNames = this.deeepClone(this.goafNames)
      if (type === 1) {
        goafOrebodys = goafs.filter(item => item.goafOrebelt === this.conditions.goafOrebelt)
        this.goafOrebodys = goafOrebodys
        this.goafOreheights = []
        this.goafNames = []
        this.conditions.goafOrebody = ''
        this.conditions.goafOreheight = ''
        this.conditions.goafName = ''
      } else if (type === 2) {
        goafOreheights = goafs.filter(item => (item.goafOrebody === this.conditions.goafOrebody) && (item.goafOrebelt === this.conditions.goafOrebelt))
        this.goafOreheights = goafOreheights
        this.goafNames = []
        this.conditions.goafOreheight = ''
        this.conditions.goafName = ''
      } else if (type === 3) {
        goafNames = goafs.filter(item => (item.goafOreheight === this.conditions.goafOreheight) && (item.goafOrebody === this.conditions.goafOrebody) && (item.goafOrebelt === this.conditions.goafOrebelt))
        this.goafNames = goafNames
        this.conditions.goafName = ''
      } else {
        for (let i = 0; i < goafNames.length; i++) {
          if (this.conditions.goafId === goafNames[i].goafId) {
            this.conditions.goafName = goafNames[i].goafName
          }
        }
      }
      this.$forceUpdate()
    },
    handleChange(groupId) {
      getUserByPage({
        page: 1,
        limit: 999999,
        groupId
      }).then((resp) => {
        const { data } = resp
        this.userList = data
      })
    },
    // 重置查询条件
    resetConditions() {
      this.conditions.keywords = ''
      this.conditions.status = undefined
      this.conditions.submitAccountId = undefined
      this.conditions.handleAccountId = undefined
      this.conditions.curAccountId = undefined
      this.conditions.groupId = undefined
    },

    // 加载数据
    loadData(action) {
      this.conditions = { ...this.conditions, ...action }
      this.getData()
    },

    // Fetch Data
    getData() {
      this.listLoading = true
      for (const key in this.conditions) {
        if (this.conditions[key] === '' || this.conditions[key] === undefined) {
          delete this.conditions[key]
        }
      }
      getDangerByPage(this.conditions).then((resp) => {
        const { code, data, total, msg } = resp
        this.listLoading = false
        if (code === 0) {
          this.total = total
          this.dataList = data
        } else {
          this.$message.error(msg)
        }
      }).catch((error) => {
        console.log(error)
      })
    },

    // 流程处理
    handleDanger(data) {
      const { hdangerId, curActivityCode } = data
      this.$refs[curActivityCode].showModel(hdangerId, data)
    },

    // Delete Handler
    handleDelete(data) {
      const { hdangerId, hdangerTitle } = data
      this.$confirm(`此操作将删除该数据${hdangerTitle}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDangerById(hdangerId).then((resp) => {
          const { code, msg } = resp
          if (code === 0) {
            this.$message.success(msg)
            this.getData()
          } else {
            this.$message.error(msg)
          }
        }).catch((error) => {
          console.log(error)
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    },

    // Show Details
    handleDetail(data) {
      const { hdangerId } = data
      this.$refs['DangerDetails'].showView(hdangerId, JSON.parse(JSON.stringify(data)))
    },

    // Update View
    formSuccess() {
      this.getData()
      this.$emit('actionUpdate')
    },

    // Preview Photo
    previewList(photos) {
      if (Array.isArray(photos)) {
        const list = photos.map((item) => {
          return item
        })
        return list
      }
      return [photos]
    },
    deeepClone(params) {
      return JSON.parse(JSON.stringify(params))
    }
  }
}
</script>
  <style lang="scss" scoped>
  .content-container {
    margin: 10px;
    height: calc(100vh - 95px);
  }
  .select-search {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-end;
  }
  </style>

