<template>
  <section class="realtime-wrapper">
    <el-form id="searchForm" :model="form">
      <el-row :gutter="5" class="search-row">
        <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
          <el-form-item :label="$t('alarm.type') + ':'" label-width="90px">
            <el-select
              v-model="form.type"
              :placeholder="$t('alarm.placeSelectType')"
              style="width: 100%"
              filterable
              @change="SelectType"
            >
              <el-option
                v-for="item in TypeOptions"
                :key="item.typeId"
                :label="item.name"
                :value="item.deviceType"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
          <el-form-item :label="$t('surveillance.name') + ':'" label-width="90px">
            <el-input
              v-model="form.name"
              maxlength="30"
              :placeholder="$t('surveillance.placeholderInput')"
              class="input-box"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="10" :md="10" :lg="4" :xl="4">
          <el-button
            type="primary"
            icon="el-icon-search"
            :loading="searchLoading"
            @click="on_refresh"
          >{{ $t('surveillance.query') }}</el-button>
        </el-col>
        <el-col :xs="24" :sm="14" :md="14" :lg="4" :xl="4" style="display: flex;justify-content: end;">

          <el-button
            type="primary"
            icon="el-icon-refresh"
            :loading="SyncLoading"
            @click="handleSynchronous"
          >{{ $t('alarm.synchronous') }}</el-button>
          <!-- <el-button
          type="primary"
          icon="el-icon-plus"
          :loading="addLoading"
          @click="handleAdd"
        >新增</el-button> -->
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="headers"
            :show-file-list="false"
            :file-list="fileList"
            :on-success="handleOnSuccess"
            :on-error="handleOnError"
          />
          <!-- <el-button
            type="primary"
            :loading="exportLoading"
            icon="el-icon-upload2"
            class="reset-btn"
          >导入</el-button>
        </el-upload>

        <el-button
          type="primary"
          :loading="uploadLoading"
          class="reset-btn"
          icon="el-icon-download"
          @click="handleExport"
        >导出</el-button> -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            :loading="deleteLoading"
            @click="handleDelete"
          >{{ $t('alarm.delete') }}</el-button>

        </el-col>

      </el-row>
    </el-form>

    <div class="table-wrapper">
      <el-table
        ref="table_data"
        v-loading="load_data"
        header-align="center"
        row-key="id"
        :height="$setAutoTableHeight(46,searchHeight)"
        :data="table_data"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          :reserve-selection="true"
        />
        <el-table-column
          prop="deviceName"
          :label="$t('alarm.deviceName')"
          show-overflow-tooltip
        />
        <el-table-column prop="deviceType" :label="$t('alarm.deviceType')" />
        <el-table-column prop="colName" :label="$t('alarm.cName')" />
        <el-table-column prop="col" :label="$t('alarm.eName')" />
        <el-table-column prop="info0" :label="$t('alarm.recMessage')" />
        <el-table-column prop="info1" :label="$t('alarm.genMessage')" />
        <el-table-column :label="$t('alarm.operation')" align="center" width="200">
          <template slot-scope="scope">
            <div class="table-column-btn">
              <el-button
                type="text"
                size="mini"
                icon="el-icon-edit"
                @click="handleEdit(scope.row)"
              >{{ $t('alarm.edit') }}</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <Pagingbar>
        <div slot="page">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="pageSizes"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
      </Pagingbar>
    </div>
    <el-dialog
      :append-to-body="false"
      :visible.sync="dialogVisible"
      width="50%"
      :title="dialogTitle"
      center
      @close="onCancel"
    >
      <el-row class="top-search">
        <el-col :span="24" :offset="0">
          <el-form
            ref="formModel"
            :model="formModel"
            label-width="135px"
            label-position="right"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item
                  v-if="dialogType === 'add'"
                  :label="$t('alarm.cName')"
                  prop="colName"
                >
                  <el-input
                    v-model="formModel.colName"
                    :placeholder="$t('alarm.placeholderCName')"
                    class="input-with-select"
                    readonly
                    @focus="openTableDialog"
                  >
                    <el-button
                      slot="append"
                      icon="el-icon-search"
                      :loading="table_dialog_loading"
                      @click="openTableDialog"
                    />
                  </el-input>
                </el-form-item>
                <el-form-item v-else :label="$t('alarm.cName')" prop="colName">
                  <el-input
                    v-model="formModel.colName"
                    :placeholder="$t('alarm.placeholderCName')"
                    class="input-with-select"
                    readonly
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('alarm.eName')" prop="col">
                  <el-input
                    v-model="formModel.col"
                    readonly
                  /></el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item :label="$t('alarm.deviceTypeName')" prop="deviceType">
                  <el-input v-model="formModel.deviceType" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('alarm.type')" prop="sensType">
                  <el-input
                    v-model="sensType"
                    readonly
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label-width="195px" :label="$t('alarm.recMessage')" prop="info0">
                  <el-input
                    v-model="formModel.info0"
                    :disabled="formModel.sensType !== 1"
                    :placeholder="$t('alarm.placeholderRecMessage')"
                    maxlength="200"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label-width="195px" :label="$t('alarm.genMessage')" prop="info1">
                  <el-input
                    v-model="formModel.info1"
                    :disabled="formModel.sensType !== 1"
                    :placeholder="$t('alarm.placeholderGenMessage')"
                    maxlength="200"
                  /></el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button plain @click="onCancel"> {{ $t('alarm.cancel') }} </el-button>
        <el-button type="primary" @click="handleTosubmit"> {{ $t('alarm.sure') }} </el-button>
      </div>
    </el-dialog>

    <el-dialog
      :append-to-body="false"
      :visible.sync="tableDialog"
      width="50%"
      :title="$t('alarm.selectName')"
      center
      @close="onTableCancel"
    >
      <el-row>
        <el-col class="tableCol" :span="12" style="color: #fff">
          {{ $t('alarm.name') }}：
          <el-input
            v-model="formModel.name"
            maxlength="30"
            :placeholder="$t('alarm.placeholderCName')"
            style="width: 70%"
            @blur="blurChangeTable"
          />
        </el-col>
      </el-row>

      <el-table
        ref="dialog_table_data"
        :key="dialog_table_key"
        v-loading="dialog_load_data"
        header-align="center"
        :height="$setTableHeight(300)"
        row-key="id"
        :data="dialog_table_data"
        style="width: 100%"
        @selection-change="handleDialogSelectionChange"
      >
        <el-table-column
          :reserve-selection="true"
          type="selection"
          width="55"
        />
        <el-table-column
          prop="colName"
          :label="$t('alarm.cName')"
          show-overflow-tooltip
        />

        <el-table-column prop="col" :label="$t('alarm.eName')" />
        <el-table-column prop="deviceTypeName" :label="$t('alarm.deviceTypeName')" />
      </el-table>
      <Pagingbar>
        <div slot="page">
          <el-pagination
            :current-page="col_currentPage"
            :page-size="col_pageSize"
            :page-sizes="col_pageSizes"
            layout="total, sizes, prev, pager, next, jumper"
            :total="col_total"
            @current-change="col_handleCurrentChange"
            @size-change="col_handleSizeChange"
          />
        </div>
      </Pagingbar>
      <div slot="footer" class="dialog-footer">
        <el-button plain @click="onTableCancel"> {{ $t('alarm.cancel') }} </el-button>
        <el-button type="primary" @click="handleTableTosubmit">
          {{ $t('alarm.sure') }}
        </el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import { getToken } from '@/utils/auth'
import { pageSize, pageSizes } from '@/config'
import Pagingbar from '@/components/Pagingbar'
import { handleDownExcel } from '@/utils'

import {
  GetDeviceType,
  SyncDeviceColDefine,
  GetDeviceColDefinePage,
  UpdataDeviceColDefine,
  AddDeviceColDefine,
  DelDeviceColDefine,
  GetDeviceTypeCol
} from '@/api/alarm/alarm-definition'
export default {
  components: { Pagingbar },
  data() {
    return {
      form: {
        type: null,
        name: null
      },

      stationId: null,
      searchLoading: false,
      load_data: false,
      dialog_load_data: false,
      addLoading: false,
      exportLoading: false,
      uploadLoading: false,
      deleteLoading: false,
      table_data: [],
      dialog_table_data: [],
      TypeOptions: [],
      uploadUrl:
        process.env.VUE_APP_BASE_API + '/flow/deviceColDefine/importExcel',
      headers: {
        authorization: getToken(),
        lang: sessionStorage.getItem('language') === 'en' ? 'en_US' : 'zh_CN'
      },
      paramsData: {},
      fileList: [],
      currentPage: 1,
      col_currentPage: 1,
      // 数据总条目
      total: 0,
      col_total: 0,
      // 每页显示多少条数据
      pageSize: pageSize,
      col_pageSize: pageSize,
      col_pageSizes: pageSizes,
      pageSizes: pageSizes,
      dialogVisible: false,
      tableDialog: false,
      dialogTitle: this.$t('alarm.addAlarmDefinition'),
      dialogType: 'add',
      formModel: {
        colName: null,
        col: null,
        deviceType: null,
        deviceName: null,
        info0: null,
        info1: null
      },
      table_dialog_loading: false,
      delIdList: [],
      selectDialogData: [],
      dialog_table_key: 0,
      SyncLoading: false
    }
  },
  computed: {
    stations: function() {
      return this.$store.getters.stations || []
    },
    currentStation() {
      return this.$store.getters.currentStation || undefined
    },
    sensType() {
      if (this.formModel.sensType === 1) {
        return this.$t('alarm.yx')
      } else if (this.formModel.sensType === 2) {
        return this.$t('alarm.yc')
      } else {
        return this.$t('alarm.yk')
      }
      // return this.formModel.sensType === 1 ? '遥信' : '遥测'
    },
    searchHeight() {
      return this.$store.getters.searchHeight
    }
  },
  watch: {
    currentStation: {
      async handler(val) {
        if (val && val.id) {
          this.stationId = val.id
          this.form.type = null
          this.table_data = []
          this.form.name = ''
          this.currentPage = 1
          this.TypeOptions = []
          this.total = 0
          this.delIdList = []

          this.col_currentPage = 1
          this.GetDeviceType()
          if (this.$refs.table_data) {
            this.$nextTick(() => {
              this.$refs.table_data.clearSelection()
            })
          }
        }
      },
      deep: true,
      immediate: true
    }
  },

  created() {

  },
  methods: {

    async GetDeviceType() {
      const { data } = await GetDeviceType({ stationId: this.stationId })
      this.TypeOptions = data
      this.form.type = data[0].deviceType
      this.get_table_data()
      // this.GetDeviceTypeCol()
    },
    async GetDeviceTypeCol() {
      const params = {
        stationId: this.stationId,
        deviceType: this.form.type,
        name: this.formModel.name,
        pageNum: this.col_currentPage,
        pageSize: this.col_pageSize
      }
      this.dialog_load_data = true
      try {
        const res = await GetDeviceTypeCol(params)
        this.dialog_table_data = res.data.list
        this.col_total = res.data.totalRows
      } catch (error) {
        // console.log(error)
      } finally {
        this.dialog_load_data = false
      }
    },
    blurChangeTable() {
      // this.GetDeviceTypeCol()
    },
    // 查询
    on_refresh() {
      if (this.TypeOptions.length > 0) {
        this.currentPage = 1
        this.get_table_data()
        this.delIdList = []
        this.$refs.table_data.clearSelection()
      } else {
        return this.$message.error(this.$t('alarm.noDevice'))
      }

      // this.GetDeviceTypeCol()
    },
    async get_table_data() {
      this.load_data = true
      try {
        const res = await GetDeviceColDefinePage({
          deviceType: this.form.type,
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          name: this.form.name
        })
        this.table_data = res.data.list
        this.total = res.data.totalRows
      } catch (error) {
        // console.log(error);
      } finally {
        this.load_data = false
      }
    },
    // 编辑
    handleEdit(row) {
      this.dialogVisible = true
      this.dialogTitle = this.$t('alarm.editAlarmDefinition')
      this.dialogType = 'edit'
      this.formModel = Object.assign({}, row)
    },
    // 选择类型
    SelectType() {
      // this.GetDeviceTypeCol()
    },

    // 同步
    async handleSynchronous() {
      if (this.TypeOptions.length) {
        this.SyncLoading = true
        try {
          await SyncDeviceColDefine({
            stationId: this.stationId,
            deviceType: this.form.type
          })
          this.$notify({
            title: this.$t('alarm.tip'),
            message: this.$t('alarm.synchronousSuccess'),
            type: 'success',
            duration: 2000
          })
        } catch (error) {
        // console.log(error)
        } finally {
          this.SyncLoading = false
          this.get_table_data()
          this.delIdList = []
          this.$refs.table_data.clearSelection()
        }
      } else {
        return this.$message.error(this.$t('alarm.noDevice'))
      }
    },
    // 新增
    handleAdd() {
      this.dialogVisible = true
      this.dialogType = 'add'
      this.dialogTitle = this.$t('alarm.addAlarmDefinition')
    },
    // 选择表格数据
    handleSelectionChange(val) {
      this.delIdList = []
      val.forEach((el) => {
        this.delIdList.push(el.id)
      })
    },
    // 选取弹出框表格数据
    handleDialogSelectionChange(val) {
      this.selectDialogData = val
      if (val.length > 1) {
        this.$refs.dialog_table_data.clearSelection()
        this.$refs.dialog_table_data.toggleRowSelection(val.pop())
      }
    },
    // 删除
    handleDelete() {
      if (this.delIdList.length) {
        this.$confirm(this.$t('alarm.deleteAlarmDefinition'), this.$t('alarm.tip'), {
          confirmButtonText: this.$t('alarm.sure'),
          cancelButtonText: this.$t('alarm.cancel'),
          type: 'warning',
          showClose: false,
          center: true
        }).then(async() => {
          this.deleteLoading = true
          try {
            await DelDeviceColDefine({ idList: this.delIdList })

            this.$notify({
              title: this.$t('alarm.tip'),
              message: this.$t('alarm.deleteSuccess'),
              type: 'success',
              duration: 2000
            })
          } catch (error) {
          // console.log(error)
          } finally {
            this.delIdList = []
            this.deleteLoading = false
            this.$refs.table_data.clearSelection()
            this.get_table_data()
          }
        })
      } else {
        this.$notify({
          title: this.$t('alarm.tip'),
          message: this.$t('alarm.selectDeleteDefinition'),
          type: 'warning',
          duration: 2000
        })
      }
    },
    // 上传成功
    handleOnSuccess(file, fileList) {
      if (file.code === 200) {
        this.$notify({
          title: this.$t('alarm.importFileSuccess'),
          message: file.msg,
          type: 'success',
          duration: 2000
        })
        this.getAllCurveTemp()
      } else {
        this.$notify({
          title: this.$t('alarm.importFileError'),
          message: file.msg,
          type: 'error',
          duration: 2000
        })
      }
    },
    // 上传失败
    handleOnError(file, fileList) {
      this.$notify({
        title: this.$t('alarm.importFileError'),
        message: file.msg,
        type: 'error',
        duration: 2000
      })
    },
    // 导出
    handleExport() {
      const params = {
        title: '告警定义模板'
      }
      handleDownExcel(
        '/flow/deviceColDefine/exportTemplate',
        params,
        (callback) => {
          console.log(callback)
        }
      )
    },

    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
      this.get_table_data()
    },
    // 页码选择
    handleCurrentChange(val) {
      this.currentPage = val
      this.get_table_data()
    },
    col_handleCurrentChange(val) {
      this.col_currentPage = val
      // this.GetDeviceTypeCol()
    },
    col_handleSizeChange(val) {
      this.col_currentPage = 1
      this.col_pageSize = val
      // this.GetDeviceTypeCol()
    },

    // 关闭新增编辑框
    onCancel() {
      this.dialogVisible = false
      this.formModel = {
        colName: null,
        col: null,
        deviceType: null,
        deviceName: null,
        info0: null,
        info1: null,
        name: null
      }
      // this.$refs.dialog_table_data.clearSelection()
      this.col_currentPage = 1
    },

    // 关闭字段选择框
    onTableCancel() {
      this.tableDialog = false
    },

    // 新增确认
    async handleTosubmit() {
      const params = {
        col: this.formModel.col,
        colName: this.formModel.colName,
        deviceName: this.formModel.deviceName,
        deviceType: this.formModel.deviceType,
        id: this.formModel.id,
        info0: this.formModel.info0 ? this.formModel.info0 : '',
        info1: this.formModel.info1 ? this.formModel.info1 : ''
      }
      if (this.dialogType === 'add') {
        try {
          await AddDeviceColDefine(params)
          this.$notify({
            title: this.$t('alarm.success'),
            message: this.$t('alarm.addSuccess'),
            type: 'success',
            duration: 2000
          })
        } catch (error) {
          // console.log(error);
        } finally {
          this.dialogVisible = false
          this.get_table_data()
        }
      }
      if (this.dialogType === 'edit') {
        try {
          await UpdataDeviceColDefine(params)
          this.$notify({
            title: this.$t('alarm.success'),
            message: this.$t('alarm.editSuccess'),
            type: 'success',
            duration: 2000
          })
        } catch (error) {
          // console.log(error);
        } finally {
          this.dialogVisible = false
          this.get_table_data()
        }
      }
    },
    // 确认字段
    handleTableTosubmit() {
      this.tableDialog = false
      this.formModel = this.selectDialogData[0]
      // console.log(this.selectDialogData)
    },
    // 打开字段选择
    openTableDialog() {
      this.tableDialog = true
      // this.GetDeviceTypeCol()
    }
  }
}
</script>

<style lang="scss" scoped>
.realtime-wrapper {
  width: 100%;
  height: 100%;
  background:var(--table-bg);
  padding: 10px;
  box-shadow: inset 0px 2px 16px 0px rgba(0, 148, 255, 0.15);
  display: flex;
  flex-direction: column;
  .upload-demo {
      display: inline-block;
      margin-left: 5px;
      margin-right: 10px;
    }

  .tableCol {
    display: flex;
    align-items: center;
  }
  .table-wrapper{
    flex: 1;
    margin-top: 10px;
  }
}
</style>
