<template>
  <div
    class="ems-dashboard-editor-container"
    style="background-color: #ffffff"
    v-loading="loading"
  >
    <el-form :inline="true" class="select-container">
      <el-form-item label="站点选择">
        <el-select
          v-model="form.siteId"
          placeholder="请选择换电站名称"
          :loading="searchLoading"
          loading-text="正在加载数据"
          clearable
        >
          <el-option
            :label="item.siteName"
            :value="item.siteId"
            v-for="(item, index) in siteList"
            :key="index + 'zdxeSelect'"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="故障名称">
        <el-input
            v-model="form.faultName"
            clearable
            placeholder="请输入故障名称"
            style="width: 150px"
        ></el-input>
      </el-form-item>
      <el-form-item>
          <el-button type="primary" @click="onSearch" native-type="button">搜索</el-button>
          <el-button @click="onReset" native-type="button">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="addDevice" native-type="button"
      >新增设备</el-button
    >
    <el-table
      class="common-table"
      :data="tableData"
      stripe
      max-height="600px"
      style="width: 100%; margin-top: 25px"
    >
      <el-table-column prop="siteId" label="站点"  width="100"> </el-table-column>
      <el-table-column prop="faultName" label="设备保护名称" width="100"> </el-table-column>
      <el-table-column prop="faultLevel" label="故障等级" width="100">
        <template slot-scope="scope">等级{{scope.row.faultLevel}}</template>
      </el-table-column>
      <el-table-column prop="isAlert" label="是否告警" width="100">
        <template slot-scope="scope">{{scope.row.isAlert === 1 ? '是' : '否'}}</template>
      </el-table-column>
      <el-table-column prop="description" label="处理方案描述" width="200" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="protectionSettings" label="保护前提" show-overflow-tooltip width="400">
        <template slot-scope="scope">
          <div v-html="handleProtectionSettings(scope.row.protectionSettings)"></div>
        </template>
      </el-table-column>
      <el-table-column prop="faultDelaySeconds" label="保护前提延时(s)" width="120">
      </el-table-column>
      <el-table-column prop="protectionPlan" label="保护方案" show-overflow-tooltip width="200">
        <template slot-scope="scope">
          <div v-html="handleProtectionPlan(scope.row.protectionPlan)"></div>
        </template>
      </el-table-column>
      <el-table-column prop="releaseDelaySeconds" label="保护方案延时(s)" width="120">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150">
        <template slot-scope="scope">
          <el-button @click="editDevice(scope.row)" type="warning" size="mini">
            编辑
          </el-button>
          <el-button type="danger" @click="deleteDevice(scope.row)" size="mini">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-show="tableData.length > 0"
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalSize"
      style="margin-top: 15px; text-align: center"
    >
    </el-pagination>
    <add-device
      ref="addDevice"
      @update="getData"
    />
  </div>
</template>

<script>
import {
  protectPlanList,
  deleteProtectPlan,
} from "@/api/ems/site";
import { getAllSites } from "@/api/ems/zddt";
import AddDevice from "./AddDevice.vue";
export default {
  name: "SBBH",
  components: { AddDevice },
  data() {
    return {
      form:{
        siteId:'',
        faultName:''
      },
      loading: false,
      searchLoading: false,
      siteList: [],
      tableData: [],
      pageSize: 10, //分页栏当前每个数据总数
      pageNum: 1, //分页栏当前页数
      totalSize: 0, //table表格数据总数
      dialogTableVisible: false,
    };
  },
  methods: {
    handleProtectionSettings(data){
      if(!data || !JSON.parse(data)) return
      const arr = JSON.parse(data),
      str= arr.map((item,index)=>{
        const {categoryName='',deviceId='',point='',faultOperator='',faultValue='',releaseOperator='',releaseValue='',relationNext=''} = item
        return `<div>${index+1}、 <span>${categoryName ? categoryName + '-' : ''}${deviceId ? deviceId + '-' : ''}${ point || ''}</span> <span>故障:${faultOperator || ''}${ faultValue || ''}</span> <span>释放:${releaseOperator || ''}${releaseValue || ''}</span> ${arr[index+1] ? '<span>关系:'+(relationNext || '')+'</span>' : ''}</div>`
      })
      return str.join('')
    },
    handleProtectionPlan(data){
      if(!data || !JSON.parse(data)) return
      const arr = JSON.parse(data),
          str= arr.map((item,index)=>{
            const {categoryName='',deviceId='',point='',value=''} = item
            return `<div>${index+1}、 <span>${categoryName ? categoryName + '-' : ''}${deviceId ? deviceId + '-' : ''}${ point || ''}</span> <span>故障:=${ value || ''}</span> </div>`
          })
      return str.join('')
    },
    //  新增设备 展示弹窗
    addDevice() {
      this.$refs.addDevice.open()
    },
    // 编辑设备
    editDevice(row) {
      this.$refs.addDevice.open(row.id,row.siteId)
    },
    //删除设备
    deleteDevice(row) {
      console.log('删除')
      this.$confirm(`确认要设备保护${row.faultName}吗?`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showClose: false,
        closeOnClickModal: false,
        type: "warning",
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            deleteProtectPlan(row.id)
              .then((response) => {
                response.code === 200 && done();
              })
              .finally(() => {
                instance.confirmButtonLoading = false;
              });
          } else {
            done();
          }
        },
      })
        .then(() => {
          //只有在废弃成功的情况下会走到这里
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getData();
          //调用接口 更新表格数据
        })
        .catch(() => {
          //取消关机
        });
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.$nextTick(() => {
        this.getData();
      });
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.$nextTick(() => {
        this.getData();
      });
    },
    // 搜索
    onSearch() {
      this.pageNum = 1; //每次搜索从1开始搜索
      this.getData();
    },
    // 重置
    onReset() {
      this.form={
        siteId: "",
        faultName: "",
      }
      this.pageNum = 1; //每次搜索从1开始搜索
      this.getData();
    },
    // 获取数据
    getData() {
      this.loading = true;
      const { pageNum, pageSize } = this,{siteId,faultName=''}=this.form;
      protectPlanList({ siteId, faultName,pageNum, pageSize })
        .then((response) => {
          this.tableData = response?.rows || [];
          this.totalSize = response?.total || 0;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //获取站点列表
    getZdList() {
      this.searchLoading = true;
      return getAllSites()
        .then((response) => {
          this.siteList = response?.data || [];
          if (this.siteList.length > 0) this.form.siteId = this.siteList[0].siteId;
        })
        .finally(() => {
          this.searchLoading = false;
        });
    },
  },
  mounted() {
    this.loading = true;
    this.form = {
      siteId: "",
      faultName: "",
    };
    this.pageNum = 1; //每次搜索从1开始搜索
    this.getZdList().then(() => {
      this.getData();
    });
  },
};
</script>

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