<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"
      :debounce-vertical-scrollbar="true"
      :default-col-def="defaultColDef"
      :animate-rows="true"
      :row-selection="rowSelection"
      :framework-components="frameworkComponents"
      @filterChanged="filterModifed"
      @sortChanged="gridSortChange"
    >
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-search">
          <en-table-search :placeholder="this.$t('action.keywords')" @search="handlerSearch" />
        </div>
        <div class="toolbar-btns">
          <el-button v-if="part_view" type="primary" size="mini" @click="handleAdd">{{ this.$t('deviceManage.deviceAdd') }}</el-button>
          <el-button v-if="part_view" type="danger" size="mini" @click="batchDelete">{{ this.$t('action.deleteList') }}</el-button>
          <el-button v-if="!part_view" type="primary" size="mini" @click="deviceServerChange">{{ this.$t('deviceManage.deviceServerChange') }}</el-button>
        </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>

    <!-- 设备编辑弹窗 -->
    <el-dialog :title="deviceEditTitle" :visible.sync="deviceDialogVisible" :width="this.$i18n.locale === 'zh' ? '60%' : '70%'">
      <el-form ref="deviceEditForm" :rules="deviceRules" :label-width="this.$i18n.locale === 'zh' ? '120px' : '165px'" :model="deviceModel">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.deviceType')" prop="device_type">
              <el-select v-model="deviceModel.device_type" :placeholder="this.$t('deviceManage.choiceDeviceType')" :disabled="deviceTypeDisabled" clearable @change="deviceTypeChange">
<!--                <el-option v-for="(item,index) in deviceTypeTransfer" :key="index" :label="item.key" :value="item.value" />-->
                <el-option v-for="(item, index) in Object.keys(deviceTypeEnum)" :key="index" :label="deviceTypeEnum[item]" :value="parseInt(item)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.deviceName')" prop="name">
              <el-input v-model="deviceModel.name" clearable :maxlength="20" :placeholder="this.$t('deviceManage.inputDeviceName')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.code')" prop="code">
              <el-input v-model="deviceModel.code" clearable :placeholder="this.$t('deviceManage.inputCode')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.model')" prop="model">
              <el-input v-model="deviceModel.model" clearable :placeholder="this.$t('deviceManage.inputModel')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.ethMac')" prop="eth_mac">
              <el-input v-model="deviceModel.eth_mac" clearable :placeholder="this.$t('deviceManage.inputEthMac')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.ethIp')" prop="eth_ip">
              <el-input v-model="deviceModel.eth_ip" clearable :placeholder="this.$t('deviceManage.inputEthIp')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.wifiMac')" prop="wifi_mac">
              <el-input v-model="deviceModel.wifi_mac" clearable :placeholder="this.$t('deviceManage.inputWifiMac')" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.wifiIp')" prop="wifi_ip">
              <el-input v-model="deviceModel.wifi_ip" clearable :placeholder="this.$t('deviceManage.inputWifiIp')" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.softVer')" prop="soft_ver">
              <el-input v-model="deviceModel.soft_ver" clearable :placeholder="this.$t('deviceManage.inputSoftVer')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.hardVer')" prop="hard_ver">
              <el-input v-model="deviceModel.hard_ver" clearable :placeholder="this.$t('deviceManage.inputHardVer')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.wifiHostname')">
              <el-input v-model="deviceModel.wifi_hostname" :readonly="true" clearable :placeholder="this.$t('deviceManage.inputWifiHostname')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.wifiPassword')">
              <el-input v-model="deviceModel.wifi_password" :readonly="true" clearable :placeholder="this.$t('deviceManage.inputPassword')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.frameName')" prop="frame_id">
              <el-select v-model="deviceModel.frame_id" filterable clearable :disabled="frameSelectabled" :placeholder="this.$t('deviceManage.choiceFrameName')">
                <el-option v-for="(item,index) in typeFrames" :key="index" :label="item.full_name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.phoneNumber')">
              <el-input v-model="deviceModel.phone_number" clearable :placeholder="this.$t('deviceManage.inputPhoneNumber')" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.priority')">
              <el-input-number v-model="deviceModel.priority" controls-position="right" :min="1" :max="99" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.backupId')">
              <el-input v-model="deviceModel.backup_id" clearable placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.deviceStatus')">
              <el-checkbox v-model="deviceModel.status" :true-label="1" :false-label="0">{{ this.$t('deviceManage.choiceDeviceStatus') }}</el-checkbox>
              <!--              <el-radio v-model="formmodel.status" :label="1">启用</el-radio>-->
              <!--              <el-radio v-model="formmodel.status" :label="0">不启用</el-radio>-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="hasRoleId">
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.roleName')" prop="role_id">
              <el-select v-model="deviceModel.role_id" :placeholder="this.$t('deviceManage.roleName')" clearable>
                <el-option v-for="item in rolesOptions" :key="item.role_id" :label="item.role_name" :value="item.role_id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="hasAudioId">
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.transAudio')" prop="trans_audio_id">
              <el-select v-model="deviceModel.trans_audio_id" :placeholder="this.$t('deviceManage.transAudio')" clearable>
                <el-option v-for="item in audioOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.transRs485')" prop="trans_rs485_id">
              <el-select v-model="deviceModel.trans_rs485_id" :placeholder="this.$t('deviceManage.transRs485')" clearable>
                <el-option v-for="item in rs485Options" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="hasAudioId">
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.re485SipId')" prop="sip_id">
              <el-input v-model="deviceModel.sip_id" clearable :placeholder="this.$t('deviceManage.inputRe485SipId')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isVitalSigns">
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.signType')" prop="sign_type">
              <el-select v-model="deviceModel.sign_type" :placeholder="this.$t('deviceManage.choiceSignType')" clearable>
                <el-option v-for="(item, index) in Object.keys(vitalSignsDeviceEnum)" :key="index" :label="vitalSignsDeviceEnum[item]" :value="parseInt(item)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="hasSosDeviceSettings">
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.sosDeviceSettingType')" prop="type">
              <el-select v-model="sosDeviceSetting.type" :placeholder="this.$t('deviceManage.sosDeviceSettingType')" clearable>
<!--                <el-option v-for="item in sosDeviceSettingsTypeOptions" :key="item.value" :label="item.label" :value="item.value" /><el-option v-for="(item, index) in Object.keys(sosDeviceSettingEnum)" :key="index" :label="sosDeviceSettingEnum[item]" :value="parseInt(item)" />-->
                <el-option v-for="(item, index) in Object.keys(sosDeviceSettingEnum)" :key="index" :label="sosDeviceSettingEnum[item]" :value="parseInt(item)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="sosDeviceSetting.type === 2">
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.sosDeviceSettingTime')" prop="setting_time">
              <el-input-number v-model="sosDeviceSetting.setting_time" controls-position="right" :min="0" :max="60" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.sosDeviceSettingUnit')" prop="unit">
              <el-radio-group v-model="sosDeviceSetting.unit" size="mini" prop="unit">
                <el-radio :label="this.$t('action.time')">{{ this.$t('action.time') }}</el-radio>
                <el-radio :label="this.$t('action.minute')">{{ this.$t('action.minute') }}</el-radio>
                <el-radio :label="this.$t('action.second')">{{ this.$t('action.second') }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isLedDevice">
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.ledResolutionRatio')" prop="led_resolution_ratio">
              <el-input v-model="deviceModel.led_resolution_ratio" clearable :placeholder="this.$t('deviceManage.ledResolutionRatio')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.ledVoice')" prop="led_voice">
              <el-checkbox v-model="deviceModel.led_voice" :true-label="1" :false-label="0">
                {{ this.$t('deviceManage.ledVoiceStatus') }}</el-checkbox>
<!--              <el-radio-group v-model="deviceModel.led_voice" size="mini" prop="led_voice">-->
<!--                <el-radio :label=1>开启语音</el-radio>-->
<!--                <el-radio :label=0>关闭语音</el-radio>-->
<!--              </el-radio-group>-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isLedDevice">
          <el-col :span="12">
            <el-form-item :label="this.$t('deviceManage.ledFontSize')" prop="led_font_size">
              <el-input-number v-model="deviceModel.led_font_size" controls-position="right" :min="0" :max="60" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlerFormSubmit('deviceEditForm')">{{ this.$t('action.yes') }}</el-button>
      </div>
    </el-dialog>
    <!-- 设备编辑弹窗 -->

    <el-dialog :title="this.$t('deviceManage.deviceServerChange')" :visible.sync="serverAddressDialogVisible" width="30%">
      <el-form ref="deviceServerChange" :rules="serverAddressRules" label-width="120px" :model="serverAddress">
        <el-row>
          <el-form-item :label="this.$t('deviceManage.serverIp')" >
            <el-input v-model="serverAddress.server_ip" clearable :maxlength="20" :placeholder="this.$t('deviceManage.inputServerIp')" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item :label="this.$t('deviceManage.serverPort')">
            <el-input v-model="serverAddress.server_port" clearable :maxlength="20" :placeholder="this.$t('deviceManage.inputServerPort')" />
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateDevicesServerIp()">{{ this.$t('action.yes') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { AG_GRID_LOCALE_CN } from '@/utils/AgGridVueLocaleCn'
import { unix2Date } from '@/utils/Foundation'
import ButtonCellRender from '@/components/AgGridCellRender/ButtonCellRender'
import ListFilter from '@/components/AgGridCustomFilter/ListFilter'
import RadioFilter from '@/components/AgGridCustomFilter/RadioFilter'
import * as API_Device from '@/api/ncs_device'
import * as API_Frame from '@/api/ncs_hospitalFrame'
import * as API_SosDeviceSetting from '@/api/ncs_sos_device_settings'
import * as clerk_API from '@/api/ncs_clerk'
import { FRAME_TYPE } from '@/utils/enum/FrameTypeEnum'
import { DEVICE_TYPE } from '@/utils/enum/DeviceTypeEnum'
import { SOS_DEVICE_SETTING_TYPE } from "@/utils/enum/SosDeviceSettingTypeEnum";
import { VITAL_SIGNS_DEVICE_TYPE } from "@/utils/enum/VitalSignsDeviceEnum";
import * as shop_API from "@/api/ncs_shop";
const DeviceUrl = domain.DeviceUrl
export default {
  name: 'DeviceManager',
  components: { ButtonCellRender, ListFilter, RadioFilter },
  props: {
    frame: {
      type: Object,
      default: () => {}
    },
    part_view: { // 是否为科室视图
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      /** ag-grid参数 **/
      pageData: {}, // 翻页数据
      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,
      /** 列表参数 */
      params: {
        page_size: 20,
        page_no: 1,
        fixedCondition: this.part_view ? ('part_id=' + this.$store.getters.partId) : '1=1'
      },
      /** device 弹窗 **/
      deviceDialogVisible: false,
      deviceEditTitle: this.$t('deviceManage.deviceAdd'),
      deviceModel: {},
      deviceTypeDisabled: false,
      deviceRules: {
        name: [
          this.MixinRequired(this.$t('deviceManage.inputDeviceName'))
        ],
        device_type: [
          { required: true, message: this.$t('deviceManage.choiceDeviceType'), trigger: 'blur' }
        ],
        code: [
          { required: true, message: this.$t('deviceManage.inputCode'), trigger: 'blur' }
        ],
        model: [
          { required: true, message: this.$t('deviceManage.inputModel'), trigger: 'blur' }
        ],
        eth_mac: [
          { required: true, message: this.$t('deviceManage.inputEthMac'), trigger: 'blur' },
          // { pattern: /^([0-9A-Fa-f]{2}:?){6}/gi, message: '请输入正确的MAC地址', trigger: 'blur' }
          { pattern: null, message: this.$t('deviceManage.inputTrueEthMac'), trigger: 'blur' }
        ],
        frame_id: [
          { required: Object.keys(this.frame).length === 0, message: this.$t('deviceManage.choiceFrameName'), trigger: 'blur' } // 没有传入frame 属性，必须选择安装位置
        ],
        phone_number: [
          { required: true, message: this.$t('deviceManage.phoneNumber'), trigger: 'blur' }
        ],
        role_id: [
          { required: true, message: this.$t('deviceManage.choiceRoleName'), trigger: 'blur' }
        ],
        trans_audio_id: [
          { required: true, message: this.$t('deviceManage.choiceTransAudio'), trigger: 'blur' }
        ],
        sign_type: [
          { required: true, message: this.$t('deviceManage.choiceSignType'), trigger: 'blur' }
        ],
        // trans_rs485_id: [
        //   { required: true, message: '请选择485转换盒', trigger: 'blur' }
        // ],
        // sip_id: [
        //   { required: true, message: '请输入485地址', trigger: 'blur' }
        // ]
        // type: [
        //   { required: true, message: '报警设备模式', trigger: 'blur' }
        // ],
        // sosDeviceSetting: [
        //   { required: true, message: '报警时间', trigger: 'blur' }
        // ],
        // unit: [
        //   { required: true, message: '报警时间单位', trigger: 'blur' }
        // ],
        led_resolution_ratio: [
          { required: true, message: this.$t('deviceManage.ledResolutionRatio'), trigger: 'blur' }
        ],
        // led_voice: [
        //   { required: true, message: this.$t('deviceManage.ledVoice'), trigger: 'blur' }
        // ],
        led_font_size: [
          { required: true, message: this.$t('deviceManage.ledFontSize'), trigger: 'blur' }
        ],
      },
      partFrames: [],
      typeFrames: [],
      /** 设备类型转换数组 **/
      deviceTypeTransfer: [
        { key: this.$t('deviceType.NURSE_HOST'), value: 1 },
        { key: this.$t('deviceType.DOCTOR_HOST'), value: 2 },
        { key: this.$t('deviceType.DOOR_DEVICE'), value: 3 },
        { key: this.$t('deviceType.DIGIT_BED_DEVICE'), value: 4 },
        { key: this.$t('deviceType.LCD_SCREEN'), value: 5 },
        { key: this.$t('deviceType.LED_SCREEN'), value: 6 },
        { key: this.$t('deviceType.NURSE_WATCH'), value: 7 },
        // { key: '护工腕表', value: 8 },
        { key: this.$t('deviceType.USER_WATCH'), value: 9 },
        { key: this.$t('deviceType.CELL_PHONE'), value: 10 },
        { key: this.$t('deviceType.TRANSFER_DEVICE'), value: 11 },
        { key: this.$t('deviceType.SIMULATE_BED_DEVICE'), value: 12 },
        { key: this.$t('deviceType.SIMULATE_EMERGENCY_BUTTON'), value: 13 },
        { key: this.$t('deviceType.SIMULATE_DOOR_LIGHT'), value: 14 },
        { key: this.$t('deviceType.REMOTE_CONTROL'), value: 15 },
        { key: this.$t('deviceType.BEACON'), value: 16 },
        { key: this.$t('deviceType.INFORMATION_BOARD'), value: 17 },
        { key: this.$t('deviceType.ENTRANCE_GUARD'), value: 18 },
        { key: this.$t('deviceType.VISITATION'), value: 19 },
        { key: this.$t('deviceType.RS485_TRANSFER'), value: 20 },
        { key: this.$t('deviceType.EMERGENCY_BUTTON'), value: 21 },
        { key: this.$t('deviceType.RS485_DOOR'), value: 22 },
        { key: this.$t('deviceType.ALARM_BODY_INDUCTIVE'), value: 23 },
        { key: this.$t('deviceType.ALARM_WATER_OVERFLOW'), value: 24 },
        { key: this.$t('deviceType.ALARM_HOUSEHOLD_GAS'), value: 25 },
        { key: this.$t('deviceType.ALARM_HOUSEHOLD_SMOKE'), value: 26 },
        { key: this.$t('deviceType.ALARM_BUTTON_SOS'), value: 27 },
        { key: this.$t('deviceType.VITAL_SIGNS_DEVICE'), value: 28 },
        { key: this.$t('deviceType.ALARM_RESTRAINT_BAND'), value: 29 },
        { key: this.$t('deviceType.DOOR_LOCK'), value: 30 },
        { key: this.$t('deviceType.EMERGENCY_GATEWAY'), value: 31 },
        { key: this.$t('deviceType.ALARM_433BUTTON'), value: 32 },
        { key: this.$t('deviceType.OTHER_HOST'), value: 33 },
          { key: this.$t('deviceType.BREASTPLATE'), value: 34 },
          { key: this.$t('deviceType.OWON_X5_GATEWAY'), value: 35 },
          { key: this.$t('deviceType.FALL_DETECTION_RADAR'), value: 36 },

      ],
      deviceTypeEnum: DEVICE_TYPE.getValueList(),
      deviceStatusTransfer: [
        { key: this.$t('deviceManage.statusTure'), value: 1, color: 'green' },
        { key: this.$t('deviceManage.statusFalse'), value: 0, color: 'red' }
      ],
      rolesOptions: [],
      hasRoleId: false,
      audioOptions: [],
      rs485Options: [],
      hasAudioId: false,
      isVitalSigns: false,
      hasSosDeviceSettings: false,
      sosDeviceSetting: {},
      sosDeviceSettingsTypeOptions: [
        {
          value: 0,
          label: '不开启'
        }, {
          value: 1,
          label: '疫情防控模式'
        }, {
          value: 2,
          label: '关爱老人模式'
        }
      ],
      sosDeviceSettingEnum: SOS_DEVICE_SETTING_TYPE.getValueList(),
      vitalSignsDeviceEnum: VITAL_SIGNS_DEVICE_TYPE.getValueList(),
      isLedDevice: false,
      websock: null,
      onlineDevice: [],
      // 请求当前科室的数据
      shop: {},
      serverAddress: {
        server_ip: '172.28.100.100',
        server_port: '8006'
      },
      serverAddressDialogVisible: false,
      serverAddressRules: {
        serverIp: [
          this.MixinRequired(this.$t('deviceManage.inputServerIp'))
        ],
        serverPort: [
          this.MixinRequired(this.$t('deviceManage.inputServerPort'))
        ]
      }
    }
  },
  computed: {
    tableHeight() {
      return Object.keys(this.frame).length === 0 ? this.mainAreaHeight - 130 : this.mainAreaHeight - 174
    },
    frameSelectabled() { return Object.keys(this.frame).length > 0 }
  },
  watch: {
    frame(val, oldvalue) {
      console.log('watch', val)
      this.params.fixedCondition = Object.keys(this.frame).length === 0 ? 'part_id=' + this.$store.getters.partId :
          (this.frame.part_id ?  'part_id=' + this.frame.part_id + ' and frame_id =' + this.frame.id :
              'part_id=' + this.frame.hospital_id + ' and frame_id =' + this.frame.id)

      this.getList()
    }
  },
  beforeMount() {
    this.gridOptions = {
    }
    this.columnDefs = [
      {
        headerName: '#',
        headerCheckboxSelection: true,
        headerCheckboxSelectionFilteredOnly: true,
        checkboxSelection: true,
        sortable: false, filter: false,
        width: 80,
        resizable: false,
        valueGetter: this.hashValueGetter
      },
      { headerName: 'ID', field: 'id', sortable: true, filter: 'agNumberColumnFilter', width: 100 },
      { headerName: this.$t('deviceManage.deviceType'), field: 'device_type', sortable: true,
        filterFramework: 'ListFilter', width: 160,
        filterParams: {
          listData: this.deviceTypeTransfer
        },
        valueGetter: this.deviceTypeGetter
      },
      // lockPosition 锁定位置，会在第一列
      // lockPinned = true 不能拖动然后固定
      // resizeable 单元个大小是否可以调整
      { headerName: this.$t('deviceManage.deviceName'), field: 'name', sortable: true, filter: 'agTextColumnFilter' },
      { headerName: this.$t('deviceManage.status'), field: 'status', sortable: true,
        filterFramework: 'RadioFilter',
        filterParams: {
          listData: this.deviceStatusTransfer
        },
        cellRenderer: this.deviceStatusFormatter
      },
      { headerName: this.$t('deviceManage.connect'), field: 'online_state', sortable: false, filter: 'agTextColumnFilter',

        filterParams: {
          textCustomComparator: (filter, value, filterText) => {
            if (filterText) {
              const filterTextLowerCase = filterText.toLowerCase()
              const valueLowerCase = value.toString().toLowerCase()
              switch (filter) {
                case 'contains':
                  return valueLowerCase.indexOf(filterTextLowerCase) >= 0
                case 'notContains':
                  return valueLowerCase.indexOf(filterTextLowerCase) === -1
                case 'equals':
                  return valueLowerCase === filterTextLowerCase
                case 'notEqual':
                  return valueLowerCase !== filterTextLowerCase
                case 'startsWith':
                  return valueLowerCase.indexOf(filterTextLowerCase) === 0
                case 'endsWith':
                  var index = valueLowerCase.lastIndexOf(filterTextLowerCase)
                  return index >= 0 && index === (valueLowerCase.length - filterTextLowerCase.length)
                default:
                  // should never happen
                  console.warn('invalid filter type ' + filter)
                  return false
              }
            }
          }
        },
        cellRenderer: this.onlineStateFormatter
      },
      { headerName: this.$t('deviceManage.frameFullName'), field: 'full_name', sortable: true, filter: 'agTextColumnFilter' },
      { headerName: this.$t('deviceManage.phoneNumber'), field: 'phone_number', sortable: true, filter: 'agTextColumnFilter' },
      { headerName: this.$t('deviceManage.ethMac'), field: 'eth_mac', sortable: true, filter: 'agTextColumnFilter' },
      { headerName: this.$t('deviceManage.ethIp'), field: 'eth_ip', sortable: true, filter: 'agTextColumnFilter' },
      { headerName: this.$t('deviceManage.ethIpPort'), field: 'eth_ip_port', sortable: true, filter: 'agNumberColumnFilter' },
      { headerName: this.$t('deviceManage.model'), field: 'model', sortable: true, filter: 'agTextColumnFilter' },
      { headerName: this.$t('deviceManage.code'), field: 'code', sortable: true, filter: 'agTextColumnFilter' },
      { headerName: this.$t('deviceManage.softVer'), field: 'soft_ver', sortable: true, filter: 'agTextColumnFilter' },
      { headerName: this.$t('deviceManage.hardVer'), field: 'hard_ver', sortable: true, filter: 'agTextColumnFilter' },
      { headerName: this.$t('deviceManage.wifiMac'), field: 'wifi_mac', sortable: true, filter: 'agTextColumnFilter' },
      { headerName: this.$t('deviceManage.wifiIp'), field: 'wifi_ip', sortable: true, filter: 'agTextColumnFilter' },
      { headerName: this.$t('deviceManage.sipId'), field: 'sip_id', sortable: true, filter: 'agTextColumnFilter' },
      { headerName: this.$t('deviceManage.updateTime'), field: 'update_time', sortable: true, filter: 'agDateColumnFilter', valueFormatter: this.unixDateFormatter, filterParams: {
        comparator: (filterLocalDateAtMidnight, cellValue) => { // 所有数据都由服务器端过滤，此处只需返回0 即可
          const celldate = unixToDate(cellValue, 'yyyy-MM-dd 00:00:00')
          return (new Date(celldate).getTime() / 1000) - (filterLocalDateAtMidnight.getTime() / 1000)
        }
      }},
      { headerName: this.$t('action.edit'), field: 'id',
        cellRendererFramework: 'ButtonCellRender',
        cellRendererParams: {
          onClick: this.handleEdit,
          label: this.$t('action.edit'),
          buttonType: 'primary',
          buttonSize: 'mini'
        },
        filter: false,
        pinned: 'right',
        lockPinned: true,
        width: 90,
        resizable: false,
        sortable: false },
      { headerName: this.$t('action.delete'), field: 'id',
        cellRendererFramework: 'ButtonCellRender',
        cellRendererParams: param => {
          return {
            onClick: this.deleteSingle,
            label: this.$t('action.delete'),
            buttonType: 'danger',
            buttonSize: 'mini',
            disabled: param.data['member_name'] === 'superadmin'
          }
        },
        pinned: 'right',
        lockPinned: true,
        width: 90,
        resizable: false,
        filter: false,
        sortable: false }
    ]
    this.defaultColDef = {
      // filter: 'agTextColumnFilter',
      sortable: true,
      resizable: true,
      enableValue: true,
      filter: true,
      // comparator: this.dateCustomComparator,
      filterParams: {
        debounceMs: 500,
        newRowsAction: 'keep',
        textCustomComparator: this.textCustomComparator
      }
    }
    this.rowSelection = 'multiple'
  },
  mounted() {
    window.onresize = this.windowResize
    this.gridApi = this.gridOptions.api
    this.gridColumnApi = this.gridOptions.columnApi
    this.gridColumnApi.applyColumnState({
      state: [
        {
          colId: 'id',
          sort: 'desc'
        }
      ]
    })
    this.getShop(this.$store.getters.partId)
    this.initWebSocket()
  },
  methods: {
    windowResize() {
      this.$set(this, 'mainAreaHeight', Number(document.documentElement.clientHeight) - 84)
    },
    /** 加载列表数据 */
    getList() {
      const param = this.MixinClone(this.params)
      this.gridApi.showLoadingOverlay()
      API_Device.getList(param).then(response => {
        const deviceData = [...response.data]
        deviceData.forEach(item => {
          if (this.onlineDevice.length > 0) {
            if (this.isCannotBeOnline(item.device_type)) {
              if (item.eth_mac) {
                const mac = this.onlineDevice.filter(p => p.toLowerCase() === item.eth_mac.toLowerCase())[0]
                // console.log('在线设备1', mac)
                if (mac !== undefined && mac !== null) {
                  item['online_state'] = this.$t('deviceManage.connectTrue')
                } else {
                  item['online_state'] = this.$t('deviceManage.connectFalse')
                }
              }
            } else {
              item['online_state'] = '/'
            }
          } else {
            if (this.isCannotBeOnline(item.device_type)) {
              item['online_state'] = this.$t('deviceManage.connectFalse')
            } else {
              item['online_state'] = '/'
            }
          }
        })
        this.rowData = deviceData
        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)
          }
        })
      })
      this.typeFrames = this.partFrames
    },
    getTypeFrame(partId) {
      if (this.shop.shop_type === "0" && this.shop.parent_id === -1) {
        API_Frame.getAllFrames(partId).then(res => {
          this.partFrames = [...res]
        })
      } else {
        API_Frame.getFramesPartId(partId).then(res => {
          this.partFrames = [...res]
        })
      }
    },
    /** 将partFrames做分割 */
    getFramesByType(frame_type) {
      if (this.partFrames != null) {
        if (frame_type === FRAME_TYPE.HOSPITAL || frame_type === FRAME_TYPE.PART) {
          this.typeFrames = this.partFrames.filter(item => item.type === FRAME_TYPE.HOSPITAL || item.type === FRAME_TYPE.PART)
        } else {
          this.typeFrames = this.partFrames.filter(item => item.type === frame_type)
        }
      }
    },

    /**
     * 过滤状态发生变化，发送到服务器检索数据
     */
    filterModifed(param) {
      var model = param.api.getFilterModel()
      // 连接状态不经过服务器过滤
      delete model.online_state
      this.params.filter = JSON.stringify(model)
      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()
    },
    /** 处理搜索 */
    handlerSearch(keywords) {
      this.params.query = keywords
      this.getList()
    },
    /** 获取设备类型文字显示,从deviceTypeTransfer 中找出value值对应的key显示出来 */
    deviceTypeGetter(params) {
      const gridVal = params.data.device_type
      // return this.deviceTypeTransfer.filter(p => p.value === gridVal).map(p => p.key)
      return DEVICE_TYPE.getDescFromValue(gridVal)
    },
    /** 格式化时间函数 */
    unixDateFormatter(param) {
      if (!param.value) return ''
      return unix2Date(param.value * 1000)
    },
    /** 设备状态格式化 **/
    deviceStatusFormatter(params) {
      if (params.value === null || params.value === undefined) return ''
      const item = this.deviceStatusTransfer.filter(p => p.value === params.value)[0]
      if (item) {
        return '<span style="color:' + item.color + ';">' + item.key + '</span>'
      } else {
        return ''
      }
    },
    /** 设备连接状态格式化 **/
    onlineStateFormatter(params) {
      if (params.value === this.$t('deviceManage.connectTrue')) {
        // return '<span style="color:green;">在线</span>'
        return '<span style="color:green;">' + this.$t('deviceManage.connectTrue') + '</span>'
      } else if (params.value === this.$t('deviceManage.connectFalse')) {
        // return '<span style="color:gray;">离线</span>'
        return '<span style="color:gray;">' + this.$t('deviceManage.connectFalse') + '</span>'
      } else {
        return '<span style="color:gray;"> / </span>'
      }
    },
    /** 删除设备 **/
    deleteSingle(row) {
      this.handlerDelete(row.id)
    },
    /** 删除设备 **/
    handlerDelete(id) {
      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(id).then(
          response => {
            this.getList()
          }
        ).catch(response => {
          this.$message({
            type: 'info',
            message: response.message
          })
        })
        if (this.hasSosDeviceSettings) {
          API_SosDeviceSetting.deleteByDeviceId(id).then(() => {
            this.hasSosDeviceSettings = false
            this.getList()
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('action.cancelDelete')
        })
      })
    },
    /** 设备类型选中变化  **/
    deviceTypeChange(val) {
      this.deviceTypeChangeToFrameTypeChange(val)
      if (val === DEVICE_TYPE.SIMULATE_BED_DEVICE || // 只能直接在后面加设备，会判断错误，必须重新用val = 设备
          val === DEVICE_TYPE.RS485_DOOR ||
          val === DEVICE_TYPE.SIMULATE_EMERGENCY_BUTTON ||
          val === DEVICE_TYPE.SIMULATE_DOOR_LIGHT ||
          val === DEVICE_TYPE.EMERGENCY_BUTTON) { // 模拟设备不需要mac地址
        this.deviceRules.eth_mac[0].required = false
        this.deviceRules.eth_mac[1].pattern = null
      } else if (val === DEVICE_TYPE.REMOTE_CONTROL) {
        this.deviceRules.eth_mac[1].pattern = null
        this.deviceRules.eth_mac[0].required = true
      } else if (val === DEVICE_TYPE.DIGIT_BED_DEVICE) {
        this.deviceRules.eth_mac[1].pattern = null
        this.deviceRules.eth_mac[0].required = true
      } else {
        // this.deviceRules.eth_mac[1].pattern = /^([0-9A-Fa-f]{2}:?){6}/gi
        this.deviceRules.eth_mac[1].pattern = null
        this.deviceRules.eth_mac[0].required = true
      }
      this.hasRoleId = val === DEVICE_TYPE.NURSE_WATCH
      this.hasAudioId = val === DEVICE_TYPE.SIMULATE_BED_DEVICE ||
                        val === DEVICE_TYPE.RS485_DOOR ||
                        val === DEVICE_TYPE.SIMULATE_EMERGENCY_BUTTON ||
                        val === DEVICE_TYPE.SIMULATE_DOOR_LIGHT
      this.isVitalSigns = val === DEVICE_TYPE.VITAL_SIGNS_DEVICE
      this.hasSosDeviceSettings = val === DEVICE_TYPE.ALARM_BODY_INDUCTIVE ||
          val === DEVICE_TYPE.DOOR_LOCK ||
          val === DEVICE_TYPE.ALARM_RESTRAINT_BAND
      this.isLedDevice = val === DEVICE_TYPE.LED_SCREEN
    },
    /** 设备类型选中对应的空间结构  **/
    deviceTypeChangeToFrameTypeChange(val) {
      if (val === DEVICE_TYPE.NURSE_HOST ||
          val === DEVICE_TYPE.OTHER_HOST ||
          val === DEVICE_TYPE.NURSE_HOST ||
          val === DEVICE_TYPE.DOCTOR_HOST ||
          val === DEVICE_TYPE.LED_SCREEN ||
          val === DEVICE_TYPE.LCD_SCREEN ||
          val === DEVICE_TYPE.NURSE_WATCH ||
          val === DEVICE_TYPE.WORKER_WATCH ||
          val === DEVICE_TYPE.TRANSFER_DEVICE ||
          val === DEVICE_TYPE.INFORMATION_BOARD ||
          val === DEVICE_TYPE.RS485_TRANSFER) {
        this.getFramesByType(FRAME_TYPE.PART)
      } else if (val === DEVICE_TYPE.DOOR_DEVICE ||
          val === DEVICE_TYPE.SIMULATE_EMERGENCY_BUTTON ||
          val === DEVICE_TYPE.RS485_DOOR ||
          val === DEVICE_TYPE.SIMULATE_DOOR_LIGHT ||
          val === DEVICE_TYPE.BEACON) {
        this.getFramesByType(FRAME_TYPE.ROOM)
      } else if (val === DEVICE_TYPE.DIGIT_BED_DEVICE ||
          val === DEVICE_TYPE.SIMULATE_BED_DEVICE ||
          val === DEVICE_TYPE.REMOTE_CONTROL ||
          val === DEVICE_TYPE.CELL_PHONE ||
          val === DEVICE_TYPE.ALARM_433BUTTON
      ) {
        this.getFramesByType(FRAME_TYPE.BED)
      } else {
        this.getTypeFrame(this.$store.getters.partId)
        this.typeFrames = this.partFrames
      }
    },
    /** 添加设备事件 **/
    handleAdd() {
      this.deviceModel = {
        soft_ver: 'SV1.0',
        hard_ver: 'HV1.0',
        priority: 1,
        code: 'C' + parseInt(Math.random() * 100000),
        model: 'M' + parseInt(Math.random() * 100000),
        status: 1
      }
      this.sosDeviceSetting = {
        type: 0,
        unit: '小时',
        setting_time: 0,
      }
      if (Object.keys(this.frame).length > 0) {
        this.$set(this.deviceModel, 'frame_id', this.frame.id)
      }
      delete this.deviceModel.id
      this.hasRoleId = false
      this.getRoles({ page_size: 200, page_no: 1, fixedCondition: ' shop_id = -1', sort: ' role_id', dir: 'desc' })
      this.hasAudioId = false
      this.isVitalSigns = false
      this.hasSosDeviceSettings = false
      this.isLedDevice = false
      this.getDevices(this.$store.getters.partId)
      this.deviceEditTitle = this.$t('deviceManage.deviceAdd')
      this.deviceDialogVisible = true
      this.deviceTypeDisabled = false // 新增设备可以选择设备类型
      this.typeFrames = this.partFrames
    },
    /** 修改设备  **/
    handleEdit(params) {
      this.getRoles({ page_size: 200, page_no: 1, fixedCondition: ' shop_id = -1', sort: ' role_id', dir: 'desc' })
      this.getDevices(params.part_id)
      this.deviceTypeChangeToFrameTypeChange(params.device_type)
      this.hasRoleId = params.device_type === DEVICE_TYPE.NURSE_WATCH
      this.hasAudioId = params.device_type === DEVICE_TYPE.SIMULATE_BED_DEVICE ||
                        params.device_type === DEVICE_TYPE.RS485_DOOR ||
                        params.device_type === DEVICE_TYPE.SIMULATE_EMERGENCY_BUTTON ||
                        params.device_type === DEVICE_TYPE.SIMULATE_DOOR_LIGHT
      this.isVitalSigns = params.device_type === DEVICE_TYPE.VITAL_SIGNS_DEVICE

      if (params.device_type === DEVICE_TYPE.ALARM_BODY_INDUCTIVE ||
          params.device_type === DEVICE_TYPE.DOOR_LOCK ||
          params.device_type === DEVICE_TYPE.ALARM_RESTRAINT_BAND) {
        this.hasSosDeviceSettings = true
        this.getSosDeviceSetting(params.id)
      } else {
        this.hasSosDeviceSettings = false
      }

      this.isLedDevice = params.device_type === DEVICE_TYPE.LED_SCREEN
      this.deviceModel = {
        ...params
      }
      this.deviceEditTitle = this.$t('deviceManage.deviceEdit')
      this.deviceDialogVisible = true
      this.deviceTypeDisabled = true // 修改设备时，不能改变设备类型
    },
    /** 新增 提交表单 */
    handlerFormSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const _this = this;
          if (this.frame.type != null) {
            this.deviceModel.part_id = this.frame.type === FRAME_TYPE.HOSPITAL ? this.frame.hospital_id : this.frame.part_id
          } else {
            this.deviceModel.part_id = this.$store.getters.partId
          }
          console.log('this.deviceModel', this.deviceModel)
          /** 新增 */
          if (!this.deviceModel.id) {
             API_Device.add(this.deviceModel).then(r => {
               this.$message.success(this.$t('action.saveSuccess'))
               _this.device = r
               this.sosDeviceSetting.device_id = _this.device.id
               this.sosDeviceSetting.part_id = _this.device.part_id

               if (this.hasSosDeviceSettings) {
                 API_SosDeviceSetting.add(this.sosDeviceSetting).then(() => {
                   this.$message.success(this.$t('action.saveSuccess'))
                   this.hasSosDeviceSettings = false
                 })
               }

               this.deviceDialogVisible = false
               this.getList()
            })
          } else {
            /** 修改 */
            API_Device.update(this.deviceModel.id, this.deviceModel).then(() => {
              this.$message.success(this.$t('action.editSuccess'))

              if (this.hasSosDeviceSettings) {
                this.sosDeviceSetting.device_id = this.deviceModel.id
                this.sosDeviceSetting.part_id = this.deviceModel.part_id
                API_SosDeviceSetting.updateByDeviceId(this.deviceModel.id, this.sosDeviceSetting).then(() => {
                  this.$message.success(this.$t('action.saveSuccess'))
                  this.hasSosDeviceSettings = false
                })
              }

              this.deviceDialogVisible = false
              this.getList()
            })
          }
        }
      })
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.getList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.getList()
    },
    getRoles(param) {
      // 获取角色
      clerk_API.getRoles(param).then(response => {
        this.rolesOptions = response.data
      })
    },
    getDevices(partId) {
      // 获取设备列表
      API_Device.getDeviceByType(partId, DEVICE_TYPE.TRANSFER_DEVICE).then(response => {
        this.audioOptions = response
      })
      API_Device.getDeviceByType(partId, DEVICE_TYPE.RS485_TRANSFER).then(response => {
        this.rs485Options = response
      })
    },
    getSosDeviceSetting(deviceId) {
      API_SosDeviceSetting.getSosDeviceSetting(deviceId).then(r => {
        this.sosDeviceSetting = r;
      })
    },
    getShop(shopId) {
      shop_API.getShop(shopId).then(res => {
        this.shop = res;
        this.getTypeFrame(shopId)
      })
    },

    initWebSocket: function() {
      var stockbase = DeviceUrl.replace('http', 'ws')
      this.websock = new WebSocket(stockbase + '/deviceonline/' + 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() {
      console.log(this.$t('deviceManage.webSocketSuccess'))
    },
    websocketonerror: function(e) {
      console.log(this.$t('deviceManage.webSocketError'))
    },
    websocketonmessage: function(e) {
      this.onlineDevice = JSON.parse(e.data)
      if (this.rowData !== null) {
        for (let i = 0; i < this.rowData.length; i++) {
          if (this.isCannotBeOnline(this.rowData[i].device_type)) {
            if (this.rowData[i].eth_mac) {
              const mac = this.onlineDevice.filter(p => p.toLowerCase() === this.rowData[i].eth_mac.toLowerCase())[0]
              this.rowData[i]['online_state'] = (mac !== undefined && mac !== null) ? this.$t('deviceManage.connectTrue') : this.$t('deviceManage.connectFalse')
            }
          } else {
            this.rowData[i]['online_state'] = '/'
          }
        }
       //只刷新在线状态列数据
          var params = {
              columns: ['online_state']
          }
          this.gridApi.refreshCells(params);

      }
    },
    websocketclose: function(e) {
      console.log('connection closed (' + e.code + ')')
    },
    batchDelete() {
      const rows = this.gridApi.getSelectedRows()
      if (rows.length === 0) {
        this.$message({ type: 'info', message: this.$t('action.pleaseChoiceDelete') })
        return
      }
      const ids = []
      rows.forEach(function(item) {
        ids.push(item.id)
      })
      this.handlerDelete(ids.join(','))
    },
    deviceServerChange() {
      this.serverAddressDialogVisible = true
    },
    updateDevicesServerIp() {
      API_Device.updateDevicesServerIp(this.serverAddress).then(r =>  {
        this.$message.success(this.$t('action.settingsSuccess'))
        this.serverAddressDialogVisible = false
      })
    },
    /**
     * 判断设备是否为模拟分机这种，无法在线是设备
     */
    isCannotBeOnline(val){
      return val === DEVICE_TYPE.NURSE_HOST ||
          val === DEVICE_TYPE.OTHER_HOST ||
          val === DEVICE_TYPE.NURSE_HOST ||
          val === DEVICE_TYPE.DOCTOR_HOST ||
          val === DEVICE_TYPE.NURSE_WATCH ||
          val === DEVICE_TYPE.WORKER_WATCH ||
          val === DEVICE_TYPE.TRANSFER_DEVICE ||
          val === DEVICE_TYPE.DOOR_DEVICE ||
          val === DEVICE_TYPE.DIGIT_BED_DEVICE ||
          val === DEVICE_TYPE.CELL_PHONE;
    }
  }
}
</script>

<style scoped>

</style>
