<template>
  <div class="siteManage-main watchDog">
    <!-- 筛选start -->
    <div class="filter-container mb-20">
      <span class="">
        【{{ labelCom }}】站点的所有监控设备
        <a
          href="./static/伍继监控设备导入模板.xlsx"
          download
          class="downloadMb"
        >
          模板下载
        </a>
      </span>

      <!-- <el-button icon="el-icon-plus" type="success" @click="addItem()">新增</el-button > -->

      <div>
        <el-upload
          class="upload-demo"
          :action="fileUrl + '/deviceAttribute/deviceAttributeImport'"
          :on-progress="handleProgress"
          :on-success="handleUpAvatar"
          :on-error="handleError"
          multiple
          :limit="1"
          :headers="{
            accessToken: [accessToken],
          }"
          :file-list="fileList"
          style="margin-right: 10px; display: inline-block"
        >
          <el-button size="small" type="primary">导入</el-button>
        </el-upload>
        <el-button type="primary" @click="DataReportExport()">导出</el-button>
      </div>
    </div>
    <!-- 筛选end -->

    <!-- 表格start -->
    <el-table :data="tableData" border stripe :header-cell-style="headClass">
      <el-table-column prop="status" align="center" label="状态" width="50">
        <template #default="scope">
          <el-avatar
            class="status"
            :style="
              scope.row.status == 0
                ? 'background-color:red'
                : 'background-color:#04F21C'
            "
          ></el-avatar>
        </template>
      </el-table-column>
      <el-table-column
        prop="monitorDeviceName"
        label="监控设备名称"
        align="center"
        width="200px"
      ></el-table-column>
      <el-table-column
        prop="monitorDeviceCode"
        label="监控设备编号"
        align="center"
        width=""
      ></el-table-column>
      <el-table-column
        prop="loopMeterAddress"
        label="回路表计地址"
        align="center"
        width=""
      ></el-table-column>
      <el-table-column
        prop="ratedVoltage"
        label="额定电压 (kV)"
        align="center"
        width=""
      ></el-table-column>
      <el-table-column
        prop="ratedCurrent"
        label="额定电流 (A)"
        align="center"
        width=""
      ></el-table-column>
      <el-table-column
        prop="currentLoadRate"
        label="电流负载率门限"
        align="center"
        width="150"
      ></el-table-column>
      <el-table-column
        prop="qualityAnalysis"
        label="电能质量分析"
        align="center"
        width=""
      ></el-table-column>
      <el-table-column fixed="right" label="操作" width="140">
        <template #default="scope">
          <el-button
            type="text"
            size="small"
            @click.prevent="editRow(scope.row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            confirm-button-text="是"
            cancel-button-text="否"
            icon="el-icon-info"
            icon-color="red"
            title="确定删除?"
            @confirm="handleDelete(scope.row)"
            @cancel="cancelEvent"
          >
            <template #reference>
              <el-button type="text" size="small" class="delete-text">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="变量" width="100">
        <template #default>
          <el-button type="text" size="small" @click="goVariableList">
            变量列表
          </el-button>
          <!-- <el-button @click="cloneDialog(scope.row)" type="text" size="small"
            >克隆</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格end -->

    <!-- 分页start -->
    <div class="paginationBlock">
      <el-pagination
        v-model:currentPage="currentPage"
        :page-sizes="[15, 20, 25, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      ></el-pagination>
    </div>
    <!-- 分页end -->

    <!--弹框组件开始-----------------------start-->
    <dialog-component
      :dialogTitle="dialogTitle"
      :itemInfo="tableItem"
      @closeDialog="closeDialog"
      :flag="showDialog"
    ></dialog-component>
    <!--弹框组件开始-----------------------end-->

    <!--克隆组件开始-----------------------start-->
    <clone
      v-if="showDialog"
      ref="cloneDialog"
      :dialog-title="dialogTitle"
      :item-info="tableItem"
      @closeDialog="closeDialog"
    ></clone>
    <!--克隆组件end-----------------------end-->
  </div>
</template>

<script>
import { useStore } from 'vuex'
import { defineComponent, ref, reactive, onMounted, watch } from 'vue'
import * as api from '@/api/siteManage/watchDog.js'
import { ElMessage } from 'element-plus'

import DialogComponent from './dialogComponent'
import Clone from './clone'

export default defineComponent({
  components: { DialogComponent, Clone },
  props: {
    siteId: Number,
    activeName: String,
  },
  setup(props, { emit }) {
    const store = useStore()
    store
    const fileUrl = ref(window.PLATFROM_CONFIG.baseUrl)
    const fileList = ref([])
    const accessToken = ref(store.state.user.accessToken)

    const total = ref(0)
    const pageSize = ref(15)
    const currentPage = ref(1)
    const goSiteListParam = ref('')
    const platformAreaName = ref('')
    const pageShow = ref(false)

    const showDialog = ref(false)
    const tableData = ref([])

    const labelCom = ref(store.state.siteManageLabelCom)

    function goSiteList(params) {
      goSiteListParam.value = params.id
      pageShow.value = !pageShow.value
    }
    const getMsgFormSon = () => {
      pageShow.value = !pageShow.value
    }

    const tableItem = reactive([])
    const dialogTitle = ref('')

    //监控设备列表
    function deviceNewsList() {
      api
        .deviceNewsList({
          siteId: props.siteId,
          size: pageSize.value,
          current: currentPage.value,
        })
        .then((requset) => {
          if (requset.status === 'SUCCESS') {
            tableData.value = requset.data.records
            total.value = requset.data.total
          } else {
            ElMessage.error(requset.msg)
          }
        })
    }

    // 添加操作
    // const addItem = () => {
    //   tableItem.value = {
    //     platformAreaName: '',
    //     platformAreaCode: '',
    //     platformAreaAddress: '',
    //   }
    //   dialogTitle.value = '新增'
    //   showDialog.value = true
    // }

    // 编辑操作
    const editRow = (row) => {
      tableItem.value = {
        id: row.id,
        monitorDeviceCode: row.monitorDeviceCode,
        monitorDeviceName: row.monitorDeviceName,
        loopMeterAddress: row.loopMeterAddress,
        ratedVoltage: row.ratedVoltage,
        ratedCurrent: row.ratedCurrent,
        currentLoadRate: row.currentLoadRate,
        siteId: row.siteId,
        variableListId: row.variableListId,
        qualityAnalysis: row.qualityAnalysis === '是' ? true : false,
      }
      dialogTitle.value = '编辑'
      showDialog.value = true
    }

    // 关闭操作
    const closeDialog = () => {
      showDialog.value = false
      deviceNewsList()
    }

    //删除 是否删除  ---- 是
    const handleDelete = (row) => {
      api.deviceNewsDel({ id: row.id }).then((requset) => {
        if (requset.status === 'SUCCESS') {
          ElMessage.success({
            message: '删除成功',
            type: 'success',
          })
          deviceNewsList()
        } else {
          ElMessage.error(requset.msg)
        }
      })
    }

    //是否删除  ---- 否
    const cancelEvent = () => {
      console.log('cancel!')
    }

    const handleProgress = (file, fileList) => {
      file
      if (
        !(
          fileList.raw.type ===
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
          fileList.raw.type === 'application/vnd.ms-excel'
        )
      ) {
        ElMessage({
          message: '上传文件只能是 xls 和 xlsx 格式!',
          type: 'error',
        })
        return false
      } else {
        return true
      }
    }

    const handleUpAvatar = (res, file) => {
      console.log(res, file)
      fileList.value = []
      ElMessage.success({
        message: '导入成功',
        type: 'success',
      })
      deviceNewsList()
    }
    const handleError = (res) => {
      let myError = res.toString() //转字符串
      myError = myError.replace('Error: ', '') //去掉前面的
      myError = JSON.parse(myError) //转对象
      ElMessage.error({
        message: myError.msg,
        type: 'error',
      })
    }

    function goVariableList() {
      emit('func')
    }

    // 表头样式设置
    const headClass = () => {
      return 'background:#FAFAFA;'
    }
    const handleSizeChange = (val) => {
      pageSize.value = val
      deviceNewsList()
    }
    const handleCurrentChange = (val) => {
      currentPage.value = val
      deviceNewsList()
    }

    //导出
    const DataReportExport = () => {
      api
        .deviceAttributeExport({
          siteId: props.siteId,
        })
        .then((requset) => {
          if (requset.status === 'SUCCESS') {
            window.location.href = window.PLATFROM_CONFIG.fileUrl + requset.data
            ElMessage.success({
              message: '导出成功',
              type: 'success',
            })
          } else {
            ElMessage.error(requset.msg)
          }
        })
    }

    //监听变化
    watch(
      () => props.siteId,
      (newVal) => {
        console.log('newVal')
        console.log(newVal)
        labelCom.value = store.state.siteManageLabelCom
        if (props.activeName == 'second') {
          deviceNewsList()
        }
      }
    )
    watch(
      () => props.activeName,
      (newVal) => {
        if (newVal == 'second') {
          deviceNewsList()
        }
      }
    )
   

    onMounted(() => {
      if (store.state.goUrl==2) {
        deviceNewsList()
      }
    })

    return {
      tableData,
      showDialog,

      platformAreaName,
      pageShow,
      dialogTitle,

      props,
      tableItem,
      goSiteListParam,

      total,
      pageSize,
      currentPage,

      goVariableList,

      deviceNewsList,
      goSiteList,
      getMsgFormSon,
      headClass,
      // addItem,
      editRow,
      closeDialog,
      handleDelete,
      cancelEvent,

      handleSizeChange,
      handleCurrentChange,

      DataReportExport,

      fileList,
      fileUrl,
      accessToken,
      handleProgress,
      handleUpAvatar,
      handleError,

      labelCom,
    }
  },
})
</script>

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