<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="siteId" placeholder="请选择换电站名称" :loading="searchLoading" loading-text="正在加载数据"
                   @change="onSearch" 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-select v-model="deviceCategory" placeholder="请选择设备类型" @change="onSearch" clearable>
          <el-option
              v-for="(item,index) in deviceCategoryList"
              :key="index+'deviceCategorySelect'"
              :label="item.name"
              :value="item.code">
          </el-option>
        </el-select>
      </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-dropdown @command="(val)=>downloadPointDetail(val,false)">
      <el-button
          style="margin-left:10px;"
          type="primary"
          plain>
        下载点位清单
      </el-button>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item v-for="(item,index) in deviceCategoryList" :key="index+'deviceCategoryList'"
                          :command="item">
          {{ item.name }}
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
    <!--    <el-dropdown @command="(val)=>uploadPointDetail(val,false)">-->
    <!--      <el-button-->
    <!--          style="margin-left:10px;"-->
    <!--          type="success"-->
    <!--          plain>-->
    <!--        上传点位清单-->
    <!--      </el-button>-->
    <!--      <el-dropdown-menu slot="dropdown">-->
    <!--        <el-dropdown-item v-for="(item,index) in deviceCategoryList" :key="index+'deviceCategoryList'"-->
    <!--                          :command="item">-->
    <!--          {{ item.name }}-->
    <!--        </el-dropdown-item>-->
    <!--      </el-dropdown-menu>-->
    <!--    </el-dropdown>-->
    <el-table
        class="common-table"
        :data="tableData"
        stripe
        max-height="600px"
        style="width: 100%;margin-top: 25px">
      <el-table-column
          prop="siteId"
          label="站点ID">
      </el-table-column>
      <el-table-column
          prop="siteName"
          label="站点名称">
      </el-table-column>
      <el-table-column
          prop="deviceId"
          label="设备ID"
      >
      </el-table-column>
      <el-table-column
          prop="deviceName"
          label="设备名称">
      </el-table-column>
      <el-table-column
          prop="categoryName"
          label="设备类别">
      </el-table-column>
      <el-table-column
          prop="deviceStatus"
          label="在线状态">
        <template slot-scope="scope">
          <span>{{ $store.state.ems.deviceStatusOptions[scope.row.deviceStatus] }}</span>
          <pcs-switch v-if="scope.row.deviceCategory === 'PCS' && ![null,'',undefined].includes(scope.row.deviceStatus)"
                      style="margin-left:5px;"
                      :data="{siteId:scope.row.siteId,deviceStatus:scope.row.deviceStatus,deviceId:scope.row.deviceId,deviceName:scope.row.deviceName}"
                      @updateSuccess="getData"/>
        </template>
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="250">
        <template slot-scope="scope">
          <el-button
              @click="pointDetail(scope.row,'point')"
              type="primary"
              size="mini">
            点位清单
          </el-button>
          <el-button
              @click="pointDetail(scope.row,'alarmPoint')"
              type="primary"
              size="mini">
            报警点位清单
          </el-button>
          <br>
          <el-button
              @click="downloadPointDetail(scope.row,true)"
              style="margin-top:10px;"
              type="primary"
              plain
              size="mini">
            下载点位清单
          </el-button>
          <el-button
              @click="uploadPointDetail(scope.row,true)"
              style="margin-top:10px;"
              type="success"
              plain
              size="mini">
            上传点位清单
          </el-button>
          <br>
          <el-button
              @click="editDevice(scope.row)"
              style="margin-top:10px;"
              type="warning"
              size="mini">
            编辑
          </el-button>
          <el-button
              type="danger"
              style="margin-top:10px;"
              @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>
    <el-dialog :visible.sync="dialogTableVisible" class="ems-dialog" title="详细信息" :close-on-click-modal="false"
               :before-close="handleClosed">
      <div class="descriptions-main" style="padding: 0">
        <el-descriptions direction="vertical" :column="2" :colon="false" border>
          <el-descriptions-item v-for="(item,index) in detailData" :key="index+'descriptions'"
                                labelClassName="descriptions-label" contentClassName="descriptions-direction" :span="1"
                                :label="item.label">{{ item.value }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
    <add-device ref="addDevice" :mode="mode" :id="editDeviceId" @update="getData" @clear="clearEditDeviceData"/>
    <point-table ref="pointTable"/>
    <point-upload ref="pointUpload" @update="getData"/>
  </div>
</template>

<script>
import {deleteService, getDeviceDetailInfo, getDeviceInfoList} from '@/api/ems/site'
import {getAllSites} from '@/api/ems/zddt'
import {formatNumber} from "@/filters/ems";
import {getAllDeviceCategory} from '@/api/ems/search'
import PointTable from './PointTable.vue'
import AddDevice from "./AddDevice.vue";
import PointUpload from "./PointUpload.vue";
import PcsSwitch from "./PcsSwitch.vue";

export default {
  name: "Sblb",
  components: {AddDevice, PointTable, PointUpload, PcsSwitch},
  data() {
    return {
      loading: false,
      searchLoading: false,
      mode: '',//新增、编辑设备
      editDeviceId: '',//编辑设备id
      siteId: '',
      siteList: [],
      deviceCategory: '',//搜索栏设备类型
      deviceCategoryList: [],//设备类别
      tableData: [],
      pageSize: 10,//分页栏当前每个数据总数
      pageNum: 1,//分页栏当前页数
      totalSize: 0,//table表格数据总数
      dialogTableVisible: false,
      detailData: [
        {label: '设备ID', value: '', attr: 'deviceId'},
        {label: '设备名称', value: '', attr: 'deviceName'},
        {label: '设备类型', value: '', attr: 'deviceType'},
        {label: '通信状态', value: '', attr: 'communicationStatus'},
        {label: 'TCP设备的IP地址', value: '', attr: 'ipAddress'},
        {label: 'TCP端口号', value: '', attr: 'ipPort'},
        {label: '串口路径', value: '', attr: 'serialPort'},
        {label: '波特率', value: '', attr: 'baudRate'},
        {label: '数据位', value: '', attr: 'dataBits'},
        {label: '停止位', value: '', attr: 'stopBits'},
        {label: '校验位', value: '', attr: 'parity'},
        {label: '设备描述', value: '', attr: 'description'},
        {label: '设备类别', value: '', attr: 'deviceCategory'},
        {label: '上级设备ID', value: '', attr: 'parentId'},
        {label: '设备唯一标识符', value: '', attr: 'deviceId'},
      ],
      detailformatAttr: {
        'deviceType': 'deviceTypeOptions',
        'communicationStatus': 'communicationStatusOptions',
      }
    }
  },
  methods: {
    // 获取设备类别
    getDeviceCategoryList() {
      getAllDeviceCategory().then(response => {
        this.deviceCategoryList = response?.data || []
      })
    },
    // 查看设备电位表格
    pointDetail(row, dataType) {
      this.$refs.pointTable.showTable(row, dataType)
    },
    // 下载点位清单
    downloadPointDetail(command, isDetail = false) {
      const siteId = isDetail ? command.siteId : this.siteId
      const deviceCategory = isDetail ? command.deviceCategory : command.code
      const categoryName = isDetail ? command.categoryName : command.name
      const deviceId = isDetail ? command.deviceId : null
      console.log('下载', command, isDetail)
      this.download('ems/pointMatch/export', {
        siteId,
        deviceCategory,
        deviceId,
      }, `点位清单_${categoryName}_${new Date().getTime()}.xlsx`)
    },
    // 上传点位清单
    uploadPointDetail(command, isDetail = false) {
      const siteId = isDetail ? command.siteId : this.siteId
      const deviceCategory = isDetail ? command.deviceCategory : command.code
      const categoryName = isDetail ? command.categoryName : command.name
      const deviceId = isDetail ? command.deviceId : ''
      console.log('上传', command, isDetail)
      this.$refs.pointUpload.showDialog({siteId, deviceCategory, categoryName, deviceId})
    },
    clearEditDeviceData() {
      this.mode = '';
      this.editDeviceId = ''
    },
    //  新增设备 展示弹窗
    addDevice() {
      this.mode = 'add';
      this.$refs.addDevice.dialogTableVisible = true
    },
    // 编辑设备
    editDevice(row) {
      this.mode = 'edit';
      this.editDeviceId = row.id
      this.$refs.addDevice.dialogTableVisible = true;
    },
    //删除设备
    deleteDevice(row) {
      this.$confirm(`确认要设备${row.deviceName}吗?`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showClose: false,
        closeOnClickModal: false,
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            deleteService(row.id).then(response => {
              response.code === 200 && done();
            }).finally(() => {
              instance.confirmButtonLoading = false;
            })
          } else {
            done();
          }
        }
      }).then(() => {
        //只有在废弃成功的情况下会走到这里
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.getData()
        //调用接口 更新表格数据
      }).catch(() => {
        //取消关机
      });
    },
    handleClosed(done) {
      this.detailData.forEach((item) => {
        item.value = ''
      })
      done()
    },
    toDetail(id) {
      this.loading = true
      getDeviceDetailInfo(id).then(response => {
        const data = response?.data || {};
        this.detailData.forEach(item => {
          if (this.detailformatAttr[item.attr]) {
            item.value = formatNumber(this.$store.state.ems[this.detailformatAttr[item.attr]][data[item.attr]]);
          } else {
            item.value = formatNumber(data[item.attr]);
          }

        })
        this.dialogTableVisible = true
      }).finally(() => {
        this.loading = false
      })

    },
    // 分页
    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.siteId = ''
      this.pageNum = 1//每次搜索从1开始搜索
      this.getData()
    },
    // 获取数据
    getData() {
      this.loading = true
      const {siteId, deviceCategory, pageNum, pageSize} = this
      getDeviceInfoList({siteId, deviceCategory, 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.siteId = this.siteList[0].siteId
      }).finally(() => {
        this.searchLoading = false
      })
    }
  },
  mounted() {
    this.loading = true
    this.siteId = ''
    this.pageNum = 1//每次搜索从1开始搜索
    this.getDeviceCategoryList()
    this.getZdList().then(() => {
      this.getData()
    })
  }
}
</script>

<style scoped lang="scss">

</style>
