<template>
  <el-container>
    <el-header v-if="isSearch">
      <el-form style="margin: 10px 0" :inline="true">
        <el-form-item label="分析对象名称：">
          <el-input type="text" v-model="search.hazardName"></el-input>
        </el-form-item>
        <el-form-item label="风险等级：">
          <el-select v-model="search.hazardLevel">
            <el-option label="低风险" :value="1" />
            <el-option label="一般风险" :value="2" />
            <el-option label="较大风险" :value="3" />
            <el-option label="重大风险" :value="4" />
          </el-select>
        </el-form-item>

        <el-form-item label="所属区域：">
          <el-cascader
            ref="cascaderRef"
            :props="{
              value: 'id',
              label: 'areaName',
              children: 'childList',
              checkStrictly: true
            }"
            v-model="search.areaId"
            :options="areaTreeList"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button
            style="margin-left: 10px"
            type="primary"
            icon="el-icon-search"
            @click="initList"
          >
            搜索
          </el-button>
          <el-button class="commonBtn" icon="el-icon-refresh" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-header>

    <el-main>
      <div class="headerTop">
        <div>
          <el-button type="primary" class="el-icon-plus" @click="doAdd(1)"
          v-hasPermi="['doubledefense:hazard:add']"
          >
            新增</el-button
          >
          <!-- <el-button type="primary" class="el-icon-upload2"> 导入</el-button> -->
          <!-- <el-button type="primary" class="el-icon-download"> 导出</el-button> -->
          <el-button
          type="primary"
            class="el-icon-delete"
            @click="doBatchDelete"
            v-hasPermi="['doubledefense:hazard:remove']"
          >
            删除</el-button
          >
        </div>
        <div>
          <right-toolbar  @queryTable="initList" :search="true" @update:showSearch="isSearch = !isSearch"></right-toolbar>
        </div>
      </div>

      <el-table
        :data="list"
        height="calc(100% - 200px)"
        :row-style="{ height: '0px' }"
        :header-cell-style="{ 'text-align': 'center', padding: '0px' }"
        :cell-style="{ 'text-align': 'center', padding: '2px' }"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" width="80" />
        <el-table-column label="序号" align="center" width="100">
          <template slot-scope="scope">
            <span> {{ (pageNum - 1) * pageSize + (scope.$index + 1) }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="分析对象编码"
          align="center"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.hazardName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="分析对象名称"
          align="center"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.hazardName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="风险等级"
          align="center"
          show-overflow-tooltip
          width="100"
        >
          <template slot-scope="scope">
            <span>{{ initRisk(scope.row.hazardLevel) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="所属区域"
          align="center"
          show-overflow-tooltip
          width="120"
        >
          <template slot-scope="scope">
            <span>{{ initAreaId(scope.row.areaId) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="区域负责人"
          align="center"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{
              scope.row.areaUserDTOList.map((item) => item.nickName).join()
            }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          show-overflow-tooltip
          width="120"
          v-if="$auth.hasPermi('doubledefense:hazard:edit', 'doubledefense:hazard:remove')"
          
        >

          <template #default="{ row }">
            <el-button 
              type="text" size="mini" @click="doAdd(2, row)"
              v-hasPermi="['doubledefense:hazard:edit']"
            >
              编辑
            </el-button>
            <el-button type="text" size="mini" @click="doDelete(row)"
            v-hasPermi="['doubledefense:hazard:remove']"
            >
              删除
            </el-button>
          </template>

        </el-table-column>

      </el-table>
      <pagination
        v-show="total > 0"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        @pagination="initList"
      />
    </el-main>

    <!-- 新增/编辑 的dialog -->
    <el-dialog
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      width="700px"
      :title="isEdit"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleFormRef"
        label-width="150px"
        class="demo-ruleForm"
      >
        <el-form-item label="风险分析对象名称：" prop="hazardName">
          <el-input v-model="ruleForm.hazardName" style="width: 70%"></el-input>
        </el-form-item>
        <el-form-item label="设备设施：">
          <el-select v-model="ruleForm.deviceId" style="width: 70%">
            <el-option
              :label="item.deviceName"
              :value="item.id"
              v-for="item in facilityOptions"
              :key="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="风险等级：" prop="hazardLevel">
          <el-select v-model="ruleForm.hazardLevel" style="width: 70%">
            <el-option label="低风险" :value="1" />
            <el-option label="一般风险" :value="2" />
            <el-option label="较大风险" :value="3" />
            <el-option label="重大风险" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属区域：" prop="areaId">
          <el-cascader
            ref="cascaderRef"
            :props="{
              value: 'id',
              label: 'areaName',
              children: 'childList',
              checkStrictly: true
            }"
            v-model="ruleForm.areaId"
            :options="areaTreeList"
            @change="handleChange"
            style="width: 70%"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">提 交</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import {
  hazardList,
  areaTree,
  saveHazard,
  editHazard,
  delHazard,
  deviceList
} from '@/api/risk/controlObject.js'
export default {
  name: 'RuoyiControlObject',

  data() {
    return {
      isSearch: false, //控制搜索框是否显示
      search: {
        hazardName: '',
        hazardLevel: '',
        areaId: ''
      },
      areaTreeList: [], // 所属区域列表
      loaderList: [], //区域负责人
      facilityOptions: [], //设备设施下拉菜单
      list: [],
      treeList: [],
      total: 1,
      pageNum: 1,
      pageSize: 10,

      multipleSelectionIdList: [], // 删除需要的参数

      dialogVisible: false, //新增/修改的dialog
      isEdit: '',
      ruleForm: {
        areaId: '',
        hazardLevel: '',
        hazardName: '',
        deviceId:''
      },
      rules: {
        areaId: [
          { required: true, message: '请选择所属区域', trigger: 'change' }
        ],
        hazardLevel: [
          { required: true, message: '请选择风险等级', trigger: 'change' }
        ],
        hazardName: [
          { required: true, message: '请输入风险分析对象名称', trigger: 'blur' }
        ],
        deviceId: [
          { required: true, message: '请选择设备设施', trigger: 'change' }
        ]
      }
    }
  },

  mounted() {
    this.initList() // 列表初始化
    this.initAreaTree() // 所属区域跟区域负责人的下拉内容
    this.initFacilityOption() // 设备设施的下拉菜单
  },

  methods: {
    // 列表初始化
    initList() {
      const obj = {
        hazardName: this.search.hazardName,
        hazardLevel: this.search.hazardLevel || null,
        areaId: this.search.areaId[this.search.areaId.length - 1] || null
      }
      hazardList({
        ...obj,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then((res) => {
        if (res.code === 200) {
          this.list = res.rows
          this.total = res.total
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 列表初始化
    initFacilityOption() {
      const obj = {
        deviceName: null,
        areaId: null,
        startExpirationDate: null,
        endExpirationDate: null
      }
      deviceList({
        ...obj,
        pageNum: 1,
        pageSize: 1000
      }).then((res) => {
        if (res.code === 200) {
          this.facilityOptions = res.rows
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    initRisk(val) {
      switch (val) {
        case 1:
          return '低风险'
        case 2:
          return '一般风险'
        case 3:
          return '较大风险'
        case 4:
          return '重大风险'
      }
    },
    initTree(params) {
      params.forEach((item) => {
        this.treeList.push(item)
        if (item.childList.length > 0) {
          this.initTree(item.childList)
        }
      })
    },
    initAreaId(val) {
      return this.treeList.find((item) => item.id === val).areaName
    },

    // 重置
    reset() {
      this.search.hazardName = ''
      this.search.hazardLevel = ''
      this.search.areaId = ''
      this.initList()
    },
    // 所属区域跟区域负责人的下拉内容
    async initAreaTree() {
      const res = await areaTree()
      this.areaTreeList = res
      this.initTree(this.areaTreeList)
    },
    // 层级选择器
    handleChange() {
      this.loaderList =
        this.$refs.cascaderRef.getCheckedNodes()[0].data.areaUserList
      this.search.hazardStatus = ''
    },
    // 新增
    doAdd(type, val) {
      console.log(val,999);
      if (type === 1) {
        this.isEdit = '新增'
        this.ruleForm.areaId = ''
        this.ruleForm.hazardLevel = ''
        this.ruleForm.hazardName = ''
        this.ruleForm.deviceId = ''
      } else {
        this.isEdit = '编辑'
        this.ruleForm = { ...val }
      }
      this.dialogVisible = true
    },
    // 提交
    submit() {
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (valid) {
          if (this.isEdit === '新增') {
            const obj = {
              hazardLevel: this.ruleForm.hazardLevel,
              hazardName: this.ruleForm.hazardName,
              deviceId: this.ruleForm.deviceId,
              hazardLevel: this.ruleForm.hazardLevel,
              areaId: this.ruleForm.areaId[this.ruleForm.areaId.length - 1]
            }
            const res = await saveHazard(obj)
            if (res.code !== 200) return this.$message.error(res.msg)
          } else {
            const obj = {
              level: this.ruleForm.hazardLevel,
              hazardName: this.ruleForm.hazardName,
              deviceId: this.ruleForm.deviceId,
              hazardLevel: this.ruleForm.hazardLevel,
              areaId: this.ruleForm.areaId[this.ruleForm.areaId.length - 1],
              id: this.ruleForm.id || null
            }
            const res = await editHazard(obj)
            if (res.code !== 200) return this.$message.error(res.msg)
          }

          this.initList()
          this.$message.success(`${this.isEdit}成功!`)
          this.ruleForm.areaId = ''
          this.ruleForm.hazardLevel = ''
          this.ruleForm.hazardName = ''
          this.ruleForm.deviceId = ''

          this.dialogVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 全选/反选
    handleSelectionChange(val) {
      this.multipleSelectionIdList = val.map((item) => item.id)
    },
    // 删除
    doDelete(type) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await delHazard(type.id)
          if (res.code !== 200) return this.$message.error(res.msg)
          this.initList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message.warning('已取消删除')
        })
    },
    // 批量删除
    doBatchDelete() {
      if (!this.multipleSelectionIdList.length)
        return this.$message.info('请先选择需要删除的选项')
      this.$confirm('是否删除所有选中项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await delHazard(this.multipleSelectionIdList.join())
          if (res.code !== 200) return this.$message.error(res.msg)
          this.initList()
          this.$message({
            type: 'success',
            message: '批量删除成功!'
          })
        })
        .catch(() => {
          this.$message.warning('已取消删除')
        })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
