<template>
  <div class="siteManage-main variableList">
    <!-- 筛选start -->
    <div class="filter-container mb-20">
      <div class="left">
        <div>
          <span class="" style="margin-right: 30px">
            【{{ store.state.siteManageLabelCom }}】 站点的所有变量

          </span>
          <el-button icon="Plus" type="success" @click="addItem()"
            :disabled="store.state.authorities.indexOf('新增') == -1">
            新增
          </el-button>
          <el-button icon="Refresh" type="primary">
            同步配置到采集器
          </el-button>
          <a href="./static/伍继变量列表导入模板.xlsx" download class="downloadMb">模板下载</a>
        </div>

        <div style="display: flex; margin-top: 15px">
          <el-radio-group v-model="select" @change="(val) => { select = val, query() }"
            :disabled="store.state.authorities.indexOf('查询') == -1">
            <el-radio-button label="day" :value="1">模拟量</el-radio-button>
            <el-radio-button label="month" :value="2">状态量</el-radio-button>
            <el-radio-button label="year" :value="3">参数量</el-radio-button>
          </el-radio-group>

          <el-input v-model="variableName" placeholder="搜索变量名称" style="width: 200px; margin:0 20px"
            :disabled="store.state.authorities.indexOf('查询') == -1"></el-input>

          <el-button type="primary" icon="Search" class="search-button" @click="query()"
            :disabled="store.state.authorities.indexOf('查询') == -1" style="margin: auto 0;">
            搜索
          </el-button>
        </div>
      </div>

      <el-upload class="upload-demo" :action="fileUrl + 'deviceAnalogVariableList/variableListImport'"
        :on-progress="handleProgress" :on-success="handleUpAvatar" :on-error="handleError" multiple :limit="1" :headers="{
          accessToken: [accessToken],
        }" :file-list="fileList" style="margin: 0 10px 0 auto; display: inline-block"
        :disabled="store.state.authorities.indexOf('导入') == -1">
        <el-button type="primary" :disabled="store.state.authorities.indexOf('导入') == -1">导入</el-button>
      </el-upload>

      <el-button type="primary" @click="DataReportExport()"
        :disabled="store.state.authorities.indexOf('导出') == -1">导出</el-button>
    </div>
    <!-- 筛选end -->

    <!-- 表格start -->
    <el-table :data="tableData" border stripe :default-sort="{ prop: 'date', order: 'descending' }">
      <el-table-column type="index" label="序号" width="80px" sortable></el-table-column>
      <el-table-column prop="variableName" label="变量名" width="150px" sortable></el-table-column>
      <el-table-column prop="variableCoding" label="变量编号" width="150px" sortable></el-table-column>
      <el-table-column prop="monitorDeviceName" label="监控设备" width="150px"></el-table-column>
      <el-table-column prop="deviceName" label="通信设备" width=""></el-table-column>
      <el-table-column prop="dataAddress" label="数据地址" width=""></el-table-column>
      <el-table-column prop="dataType" label="数据类型" width=""></el-table-column>
      <el-table-column prop="coefficient" label="系数" width=""></el-table-column>
      <el-table-column prop="saveCycle" label="存盘周期" width=""></el-table-column>
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="scope">
          <el-button type="primary" size="small" @click.prevent="editRow(scope.row)"
            :disabled="store.state.authorities.indexOf('修改') == -1" link>
            修改
          </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="danger" size="small" :disabled="store.state.authorities.indexOf('删除') == -1" link>
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </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 ref="dialogComponentRef" :siteId="props.siteId" @handleSelect="query()"></dialog-component>
    <!--弹框组件开始-----------------------end-->
  </div>
</template>

<script setup>
/*----------------------------------依赖引入-----------------------------------*/
import { useStore } from 'vuex'
import { ElMessage, ElNotification } from 'element-plus'
import { ref, onMounted, watch, getCurrentInstance, reactive, toRefs, nextTick } from 'vue'
/*----------------------------------接口引入-----------------------------------*/
import * as api from '@/api/siteManage/variableList'
/*----------------------------------组件引入-----------------------------------*/
import DialogComponent from './dialogComponent'
/*----------------------------------store引入-----------------------------------*/
/*----------------------------------公共方法引入-----------------------------------*/
/*----------------------------------公共变量-----------------------------------*/
const store = useStore()
const props = defineProps({
  siteId: Number,
  activeName: String,
}) //数据双向绑定
const emit = defineEmits([]);
const { proxy } = getCurrentInstance();
/*----------------------------------变量声明-----------------------------------*/
const fileUrl = ref(window.PLATFROM_CONFIG.baseUrl)
const fileList = ref([])
const accessToken = ref(store.state.user.accessToken)
const state = reactive({
  tableData: [],
  currentPage: 1,
  pageSize: 10,
  total: 0,
  variableName: ""
})
const { tableData, currentPage, pageSize, total, variableName } = toRefs(state)
const select = ref(1)


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) => {
  fileList.value = []
  ElMessage.success({
    message: '导入成功',
    type: 'success',
  })
  query()
}
const handleError = (res) => {
  let myError = res.toString() //转字符串
  myError = myError.replace('Error: ', '') //去掉前面的
  myError = JSON.parse(myError) //转对象
  ElMessage.error({
    message: myError.msg,
    type: 'error',
  })
}

//是否删除  ---- 否
const cancelEvent = () => {
  console.log('cancel!')
}
//查询变量列表
function query() {
  api
    .variableList({
      size: pageSize.value,
      current: currentPage.value,
      dataArea: select.value,
      siteId: props.siteId,
      variableName: variableName.value,
    })
    .then((requset) => {
      if (requset.status === 'SUCCESS') {
        tableData.value = requset.data.records
        total.value = requset.data.total
      } else {
        ElMessage.error(requset.msg)
      }
    })
}

function Select(value) {
  select.value = value
  query()
}

// 添加操作
function addItem() {
  proxy.$refs['dialogComponentRef'].openDialog({
    dialogTitle: '新增',
    tableItem: {
      deviceCode: "",
      monitoringEquipment: '',
      communicationEquipment: '',
      // dataArea:'1'
    }
  })
}

// 编辑操作
function editRow(row) {
  proxy.$refs['dialogComponentRef'].openDialog({
    dialogTitle: '编辑',
    tableItem: {
      deviceCode: row.deviceCode,
      variableName: row.variableName,
      monitorDeviceName: row.monitorDeviceName,
      variableCoding: row.variableCoding,
      monitoringEquipment: row.monitoringEquipment,
      communicationEquipment: row.communicationEquipment,
      dataAddress: row.dataAddress,
      dataType: row.dataType,
      coefficient: row.coefficient,
      saveCycle: row.saveCycle,
      dataArea: row.dataArea.toString(),
      id: row.id
    }
  })

}

//删除操作
function handleDelete(row) {
  api.variableListDel({ id: row.id }).then((requset) => {
    if (requset.status === 'SUCCESS') {
      ElMessage.success({
        message: '删除成功',
        type: 'success',
      })
      query()
    } else {
      ElMessage.error(requset.msg)
    }
  })
}

//导出
function DataReportExport() {
  api
    .variableListExport({
      dataArea: select.value,
      siteId: props.siteId,
      variableName: variableName.value,

    })
    .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)
      }
    })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  query()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  query()
}

watch(
  () => props.activeName,
  (newVal) => {
    if (newVal == 'third' && props.siteId) {
      query()
    }
  }
)

onMounted(() => {
  if (store.state.goUrl == 3) {
    query()
  }
})
</script>

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