<template>
  <div >
    <ag-grid-layout
      toolbar
      :table-height="tableHeight"
      theme="ag-theme-alpine"
      :column-defs="columnDefs"
      :row-data="rowData"
      :locale-text="localeText"
      :grid-options="gridOptions"
      :default-col-def="defaultColDef"
      :animate-rows="true"
      :row-selection="rowSelection"
      :enable-cell-change-flash="true"
      @filterChanged="filterModifed"
      @sortChanged="gridSortChange"
    >
      <!--        @rowDoubleClicked="getList"-->
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-search">
          <en-table-search :placeholder="this.$t('action.keywords')" @search="handlerSearch" />
        </div>
      </div>
      <el-pagination
        v-if="pageData"
        slot="pagination"
        :current-page="pageData.page_no"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageData.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.data_total"
        @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange"
      />
    </ag-grid-layout>

    <!--    <en-table-layout-->
    <!--      toolbar-->
    <!--      pagination-->
    <!--      :table-data="tableData"-->
    <!--      :height="tableHeight"-->
    <!--      :loading="loading"-->
    <!--      @selection-change="selectFun"-->
    <!--      @sort-change="tableSort"-->
    <!--    >-->
    <!--      &lt;!&ndash;工具栏&ndash;&gt;-->
    <!--      <div slot="toolbar" class="inner-toolbar" />-->
    <!--      &lt;!&ndash;表头&ndash;&gt;-->
    <!--      <template slot="table-columns">-->
    <!--        <el-table-column prop="id" sortable="custom" :label="识别码" width="200" align="center" />-->
    <!--        <el-table-column prop="device_name" sortable="custom" :label="别名" width="200" align="center" />-->
    <!--        <el-table-column prop="device_wifi_mac" sortable="custom" :label="mac地址" width="200" align="center" />-->
    <!--        <el-table-column prop="device_eth_ip" sortable="custom" :label="IP地址" width="200" align="center" />-->
    <!--        <el-table-column prop="partid" sortable="custom" :label="科室ID" width="200" align="center" />-->
    <!--        <el-table-column :label="操作" align="center">-->
    <!--          <template slot-scope="scope">-->
    <!--            <el-button type="primary" size="mini" @click="setPartBoard(scope.row)">设定</el-button>-->
    <!--            <el-button type="primary" size="mini" @click="setBoard(scope.row)">设置</el-button>-->
    <!--            <el-button type="danger" size="mini" @click="handlerDelete(scope.row.id)">删除</el-button>-->
    <!--          </template>-->
    <!--        </el-table-column>-->
    <!--      </template>-->

    <!--      &lt;!&ndash;翻页&ndash;&gt;-->
    <!--      <el-pagination-->
    <!--        v-if="pageData"-->
    <!--        slot="pagination"-->
    <!--        :current-page="pageData.page_no"-->
    <!--        :page-sizes="[10, 20, 50, 100]"-->
    <!--        :page-size="pageData.page_size"-->
    <!--        layout="total, sizes, prev, pager, next, jumper"-->
    <!--        :total="pageData.data_total"-->
    <!--        @size-change="handlePageSizeChange"-->
    <!--        @current-change="handlePageCurrentChange"-->
    <!--      />-->
    <!--    </en-table-layout>-->

    <el-dialog :title="this.$t('board.boardSet')" :visible.sync="formshow" width="50%">
      <el-form ref="editform" v-model="boardConfig" label-width="120px">
        <fieldset>
          <legend>{{ this.$t('board.statusTime') }}</legend>
          <el-form-item :label="this.$t('board.screenFirst')">
            <el-input v-model="boardConfig.staySeconds[0]" clearable :placeholder="this.$t('board.screenFirstSet')" type="number">
              <template slot="append">{{ second }}</template>
            </el-input>

          </el-form-item>
          <el-form-item :label="this.$t('board.screenSecond')">
            <el-input v-model="boardConfig.staySeconds[1]" clearable :placeholder="this.$t('board.screenSecondSet')" type="number">
              <template slot="append">{{ second }}</template>
            </el-input>
          </el-form-item>
          <el-form-item v-for="(item,index) in boardTitles" :key="index" :label="labelStr(index)">
            <el-input v-model="boardConfig.staySeconds[index+2]" clearable :placeholder="labelStr(index)" type="number">
              <template slot="append">{{ second }}</template>
            </el-input>
          </el-form-item>
        </fieldset>
        <fieldset class="margin-top-sm">
          <legend>{{ this.$t('board.screenFixedSet') }}</legend>
          <el-form-item label-width="80">
            <el-radio-group v-model="boardConfig.stayIndex">
              <el-radio :label="0">{{ this.$t('board.noFixed') }}</el-radio>
              <el-radio :label="1">{{ this.$t('board.screenFirst') }}</el-radio>
              <el-radio :label="2">{{ this.$t('board.screenSecond') }}</el-radio>
              <el-radio v-for="(item,index) in boardTitles" :key="index" :label="(index+3)" > {{ labelStr(index) }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </fieldset>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formshow = false">{{ this.$t('action.cancel') }}</el-button>
        <el-button type="primary" @click="updateBoard()">{{ this.$t('action.yes') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { AG_GRID_LOCALE_CN } from '@/utils/AgGridVueLocaleCn'
import ButtonCellRender from '../../components/AgGridCellRender/ButtonCellRender'
import ListFilter from '@/components/AgGridCustomFilter/ListFilter'
import RadioFilter from '@/components/AgGridCustomFilter/RadioFilter'
// import { DeviceUrl } from '@/utils/domain'
import * as API_Device from '@/api/ncs_device'
import * as API_FrameGroup from '@/api/ncs_frameGroup'
import * as API_Board from '@/api/ncs_board'
const DeviceUrl = domain.DeviceUrl
export default {
  name: 'Index',
  components: { ButtonCellRender, ListFilter, RadioFilter },
  data() {
    return {
      /** 列表参数 */
      params: {
        page_size: 20,
        page_no: 1,
        fixedCondition: '(part_id=' + this.$store.getters.partId + ' OR part_id=0) AND device_type=17'
      },
      treeData: [],
      /** ag-grid参数 **/
      pageData: [],
      loading: false,
      errorId: null,
      shopVisible: false,
      columnDefs: null,
      rowData: null,
      defaultColDef: null,
      gridOptions: null,
      gridApi: null,
      columnApi: null,
      localeText: AG_GRID_LOCALE_CN,
      filterState: null,
      rowSelection: null,
      frameworkComponents: null,
      second: this.$t('action.second'),

      websock: null,
      boardObj: {},
      boardConfig: {
        staySeconds: [30, 30],
        stayIndex: 0
      },
      boardTitles: [],

      formshow: false,
      rules: {
        device_type: [
          { required: true, message: this.$t('deviceManage.deviceTypeMsg'), trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    tableHeight() {
      return this.mainAreaHeight - 130
    }
  },

  beforeMount() {
    this.gridOptions = {}
    this.columnDefs = [
      {
        headerName: '#',
        headerCheckboxSelection: true,
        headerCheckboxSelectionFilteredOnly: true,
        checkboxSelection: true,
        sortable: false, filter: false,
        width: 100,
        resizable: false,
        valueGetter: this.hashValueGetter
      },
      { headerName: 'ID', field: 'id', sortable: true, filter: 'agNumberColumnFilter', width: 130 },
      {
        headerName: this.$t('board.name'), field: 'name', sortable: true, filter: 'agTextColumnFilter', width: 150
      },
      {
        headerName: this.$t('board.ethMac'), field: 'eth_mac', sortable: true, filter: 'agTextColumnFilter', flex: 1
      },
      {
        headerName: this.$t('board.partId'), field: 'part_id', sortable: true, filter: 'agNumberColumnFilter', width: 150

      },
      {
        headerName: this.$t('action.setUp'), field: 'id',
        cellRendererFramework: 'ButtonCellRender',
        cellRendererParams: {
          onClick: this.handEdit,
          label: this.$t('board.setUpThisPart'),
          buttonType: 'primary',
          buttonSize: 'mini'
        },
        filter: false,
        pinned: 'right',
        lockPinned: true,
        width: 150,
        resizable: false,
        sortable: false
      },
      {
        headerName: this.$t('action.settings'), field: 'id',
        cellRendererFramework: 'ButtonCellRender',
        cellRendererParams: {
          onClick: this.setBoard,
          label: this.$t('board.boardSet'),
          buttonType: 'primary',
          buttonSize: 'mini'
        },
        filter: false,
        pinned: 'right',
        lockPinned: true,
        width: 150,
        resizable: false,
        sortable: false
      },
      {
        headerName: this.$t('action.delete'), field: 'shop_id',
        cellRendererFramework: 'ButtonCellRender',
        cellRendererParams: param => {
          return {
            onClick: this.deleteSingle,
            label: this.$t('action.delete'),
            buttonType: 'danger',
            buttonSize: 'mini'
          }
        },
        pinned: 'right',
        lockPinned: true,
        width: 100,
        resizable: false,
        filter: false,
        sortable: false
      }
    ]
    this.defaultColDef = {
      sortable: true,
      resizable: true,
      comparator: this.dateCustomComparator,
      filterParams: {
        debounceMs: 200,
        newRowsAction: 'keep',
        textCustomComparator: this.textCustomComparator,
        comparator: this.dateCustomComparator
      }
    }
    this.rowSelection = 'multiple'
  },
  mounted() {
    window.onresize = this.windowResize
    this.gridApi = this.gridOptions.api
    this.gridColumnApi = this.gridOptions.columnApi
    // 设置默认排序字段，应用列状态之后会触发 gridSortChange 函数，会调用getlist，后面不需要再调用this.getlist
    this.gridColumnApi.applyColumnState({
      state: [
        {
          colId: 'id',
          sort: 'asc'
        }
      ]
    })
    this.getFrameTree()
    this.getBoardTitles()
    this.initWebSocket()
  },
  methods: {
    /** 表格行选择变化记录选中行数据*/
    selectFun: function(val) {
      this.multipleSelection = val
    },
    windowResize() {
      this.$set(this, 'mainAreaHeight', Number(document.documentElement.clientHeight) - 84)
    },
    deleteSingle(row) {
      this.handlerDelete(row.id)
    },
    handlerDelete(ids) {
      this.$confirm(this.$t('action.sureDelete'), this.$t('action.waring'), {
        confirmButtonText: this.$t('action.yes'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        API_Device.remove(ids).then(
          response => {
            this.getList()
            this.$message({
              type: 'success',
              message: this.$t('action.deleted')
            })
          }
        ).catch(response => {
          this.$message({
            type: 'info',
            message: response.message
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('action.cancelDelete')
        })
      })
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.getList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.getList()
    },
    /** 加载列表数据 */
    getList() {
      this.loading = true
      const param = this.MixinClone(this.params)
      API_Device.getList(param).then(response => {
        this.loading = false
        this.rowData = [...response.data]
        this.pageData = {
          page_no: response.page_no,
          page_size: response.page_size,
          data_total: response.data_total
        }
        this.$nextTick(() => {
          const node = this.gridApi.getDisplayedRowAtIndex(0)
          if (node !== null && node !== undefined) {
            node.setSelected(true)
          }
        })
      }).catch(() => {
        this.loading = false
      })
    },
    /** 处理搜索 */
    handlerSearch(keywords) {
      this.params.query = keywords
      this.getList()
    },
    /** 处理字段排序 */
    tableSort(column) {
      if (column.order !== null) {
        this.params.sort = column.prop
        this.params.dir = column.order === 'ascending' ? 'asc' : 'desc'
      } else {
        this.params.sort = null
        this.params.dir = null
      }
      this.getList()
    },

    gridSortChange(param) {
      const columnState = param.columnApi.getColumnState()
      // 排序状态
      const sortState = columnState.filter(function(s) {
        return s.sort != null
      }).map(function(s) {
        return {
          colId: s.colId,
          sort: s.sort,
          sortIndex: s.sortIndex
        }
      }).sort(function(a, b) {
        return a.sortIndex - b.sortIndex
      })
      if (sortState.length > 0) {
        if (sortState.length === 1) {
          this.params.sort = sortState[0].colId
          this.params.dir = sortState[0].sort
        } else {
          let sortstring = ''
          sortState.forEach(function(item) {
            sortstring += item.colId + ' ' + item.sort + ','
          })
          this.params.sort = sortstring.substring(0, sortstring.length - 1)
          this.params.dir = ' '
        }
      } else {
        delete this.params.sort
        delete this.params.dir
      }

      this.getList()
      console.log(sortState)
    },

    /**
     * 获取空间结构树形数据
     * */
    getFrameTree() {
      return new Promise((resolve, reject) => {
        API_FrameGroup.getframestruct(this.$store.getters.partId, 3).then(res => {
          this.treeData = res.frameTree
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },

    setBoard(row) {
      this.boardObj = { ...row }
      this.formshow = true
      if (this.boardObj.config === null || this.boardObj.config === '') { // 没有配置看板时，设置默认值
        if (this.boardTitles.length > 0) {
          this.boardTitles.forEach((item, index) => {
            this.boardConfig.staySeconds[index + 2] = 30 // 添加默认时间
          })
        }
      } else {
        this.boardConfig = JSON.parse(this.boardObj.config)
      }
      // if (this.boardObj.device_hard_ver) this.stayIndex = Number(this.boardObj.device_hard_ver)
    },
    getBoardTitles() {
      API_Board.getBoardTitles(this.$store.getters.partId).then(res => {
        this.boardTitles = res
      })
    },

    updateBoard() {
      this.boardConfig.staySeconds=[this.boardConfig.staySeconds[0],this.boardConfig.staySeconds[1],...this.boardTitles.map((p,index)=>Number(this.boardConfig.staySeconds[index+2]))]
      if (this.boardConfig.staySeconds.length !== this.boardTitles.length + 2) {
        this.$message.success(this.$t('board.statusTimeSetMsg'))
        return false
      }
      this.boardConfig.staySeconds = this.boardConfig.staySeconds.map(p => Number(p))
      this.boardObj.config = JSON.stringify(this.boardConfig)
      API_Device.update(this.boardObj.id, this.boardObj).then(() => {
        this.$message.success(this.$t('action.settingsSuccess'))
        this.getList()
        this.formshow = false
      }).catch(response => {
        this.getList()
        this.formshow = false
      })
    },
    /**
     * 设定到科室
     * @param row
     */
    handEdit(row) {
      row.part_id = this.$store.getters.partId
      row.frame_id = this.treeData[0].id
      API_Device.update(row.id, row).then(res => {
        this.$message.success(this.$t('action.setUpSuccess'))
        this.gridApi.redrawRows()
      }).catch(response => {
        this.getList()
      })
    },

    filterModifed(param) {
      console.log(param)
      var model = param.api.getFilterModel()
      console.log('model', JSON.stringify(model))
      this.params.filter = JSON.stringify(model)
      this.getList()
    },

    initWebSocket: function() {
      var stockbase = DeviceUrl.replace('http', 'ws')
      this.websock = new WebSocket(stockbase + '/boardinfo/0/' + this.$store.getters.uuid)
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onmessage = this.websocketonmessage
      this.websock.onclose = this.websocketclose
    },
    websocketonopen: function() {
      this.$message.success(this.$t('board.webSocketSuccess'))
      console.log(this.$t('deviceManage.webSocketSuccess'))
    },
    websocketonerror: function(e) {
      console.log(this.$t('deviceManage.webSocketError'))
    },
    websocketonmessage: function(e) {
      this.getList()
    },
    websocketclose: function(e) {
      console.log('connection closed (' + e.code + ')')
    },
    labelStr(index) {
      return this.$t('board.the') + (index + 3) + this.$t('board.screen')
    },
  }
}
</script>

<style scoped>
  fieldset{
    border-style: solid;
    border-color: #DCDFE6;
    border-width: 1px;
  }
  .margin-top-sm{margin-top: 20px}
</style>
