<template>
  <wrapper
    fill
    margin
    padding
    background
    horizontal
  >
    <department-tree
      class="c-sibling-item c-sidebar u-width--md"
      @change="onGroupChanged"
    />
    <table-dialog
      ref="attentionList"
      title="关注列表"
      :schema="attentionSchema"
    />
    <schema-table
      ref="table"
      class="c-sibling-item far"
      row-key="id"
      :schema="schema"
    />
    <confirm-dialog
      ref="editDialog"
      title="编辑"
      @confirm="onSave"
    >
      <div class="c-grid-form u-align-self--center">
        <span class="c-grid-form__label u-required">名称</span>
        <el-input
          v-model.trim="info.name"
          placeholder="最多30个字符"
          maxlength="30"
          clearable
        />
        <div class="c-grid-form__label u-required">开关机时间</div>
        <el-time-picker
          v-model="info.range"
          class="u-width u-pointer"
          is-range
          value-format="HH:mm:ss"
          :clearable="false"
        />
        <span class="c-grid-form__label u-required">地址</span>
        <el-input
          v-model.trim="info.address"
          type="textarea"
          placeholder="最多100个字符"
          maxlength="100"
          :rows="4"
          resize="none"
          show-word-limit
        />
        <span class="c-grid-form__label">坐标</span>
        <div class="l-flex--row c-grid-form__option">
          <span class="c-sibling-item">{{ info.longitude }},{{ info.latitude }}</span>
          <i
            class="c-sibling-item el-icon-edit u-color--blue has-active"
            @click="onEditCoordinate"
          />
        </div>
      </div>
    </confirm-dialog>
    <coordinate-dialog
      ref="coordinateDialog"
      @confirm="onChangeCoordinate"
    />
  </wrapper>
</template>

<script>
import {
  validLongitude,
  validLatitude
} from '@/utils/validate'
import {
  getDevicesByQuery,
  getSubDevices,
  activateDevice,
  deactivateDevice,
  updateDevice,
  addDeviceAttention,
  cancelDeviceAttention,
  getDeviceAttentionList
} from '@/api/device'

export default {
  name: 'DeviceManagement',
  data () {
    return {
      attentionSchema: {
        nonPagination: true,
        list: getDeviceAttentionList,
        cols: [
          { type: 'refresh', render: (data, h) => h(
            'i',
            {
              staticClass: `${data.ifAttention === 1 ? 'el-icon-star-on u-font-size--xl' : 'el-icon-star-off u-font-size--lg'} u-color--warning`,
              on: {
                click: () => {
                  data.ifAttention === 1 ? this.cancelDeviceAttention(data) : this.addDeviceAttention(data)
                }
              }
            }
          ) },
          { prop: 'name', label: '设备名称' }
        ]
      },
      schema: {
        keepalive: true,
        list: this.getDevicesByQuery,
        transform: this.transform,
        transformData: __SUB_DEVICE__ && this.transformTableData,
        // listeners: {
        //   'row-click': this.onRowClick
        // },
        filters: [
          { key: 'name', type: 'search', placeholder: '设备名称' }
        ],
        buttons: [
          { label: '关注列表', on: this.onShowAttentionList }
        ],
        cols: [
          // { type: 'refresh', render: __SUB_DEVICE__
          //   ? (data, h) => data.isMaster
          //     ? h('i', {
          //       staticClass: `o-expand-icon u-pointer ${data.loading ? 'el-icon-loading' : 'el-icon-arrow-right'}`,
          //       class: { expand: data.expand }
          //     })
          //     : null
          //   : null },
          // __SUB_DEVICE__
          //   ? { label: '设备名称', render: (data, h) => data.empty ? h('span', { staticClass: 'u-color--info' }, '暂无备份设备') : data.name, 'min-width': 120 }
          //   : { prop: 'name', label: '设备名称', 'min-width': 120 },
          { type: 'refresh', render: (data, h) => h(
            'i',
            {
              staticClass: `${data.ifAttention === 1 ? 'el-icon-star-on u-font-size--xl' : 'el-icon-star-off u-font-size--lg'} u-color--warning`,
              on: {
                click: () => {
                  data.ifAttention === 1 ? this.cancelDeviceAttention(data) : this.addDeviceAttention(data)
                }
              }
            }
          ) },
          { prop: 'name', 'min-width': 120 },
          { prop: 'serialNumber', label: '序列号' },
          { prop: 'mac', label: 'MAC' },
          { label: '运行时间', render: ({ empty, openTime, closeTime }) => empty
            ? ''
            : openTime && closeTime
              ? `${openTime} - ${closeTime}`
              : '-' },
          { label: '坐标', type: 'tag', render: ({ empty, longitude, latitude }) => empty
            ? null
            : longitude && latitude
              ? {
                type: 'success',
                label: '已设置'
              }
              : {
                type: 'warning',
                label: '未设置'
              } },
          { type: 'tag', render: ({ empty, activate, onlineStatus }) => empty
            ? null
            : activate
              ? onlineStatus === 0
                ? { type: 'primary', label: '待接入' }
                : onlineStatus === 1
                  ? { type: 'success', label: '在线' }
                  : { type: 'danger', label: '离线' }
              : { type: 'warning', label: '未激活' },
            on: this.onTagClick },
          { type: 'invoke', render: [
            { label: '编辑', render ({ empty }) { return !empty }, on: this.onEditDevice },
            { label: '详情', render ({ empty }) { return !empty }, on: this.onViewDevice },
            { label: '配置', render ({ isMaster }) { return isMaster }, on: this.onSettingDevice }
          ], width: 160 }
        ]
      },
      info: {}
    }
  },
  methods: {
    onGroupChanged (group) {
      this.$group = group
      this.$refs.table?.pageTo(1)
    },
    getDevicesByQuery (params) {
      if (!this.$group) {
        return Promise.resolve({ data: [] })
      }
      return getDevicesByQuery({
        org: this.$group.path,
        isAttentionFlag: 1,
        attentionValue: 2,
        ...params
      })
    },
    transform (data) {
      return {
        ...data,
        loaded: false,
        loading: false,
        expand: false,
        subs: [],
        isMaster: true
      }
    },
    transformTableData (data) {
      const arr = []
      data.forEach(item => {
        arr.push(item)
        if (item.loaded && item.expand) {
          arr.push(...item.subs)
        }
      })
      return arr
    },
    onViewDevice (item) {
      this.$router.push({
        name: 'device-management-detail',
        params: {
          id: item.id
        }
      })
    },
    reloadSubDevices (item) {
      item.loaded = false
      item.children = []
      this.getSubDevices(item)
    },
    getSubDevices (item, pageSize = 999) {
      item.loading = true
      getSubDevices({
        id: item.id,
        pageNum: 1,
        pageSize
      }).then(({ data, totalCount }) => {
        if (totalCount > pageSize) {
          this.getSubDevices(item, totalCount)
        } else {
          item.loading = false
          item.loaded = true
          item.expand = true
          if (data.length === 0) {
            item.subs = [{ id: `${Math.random()}`, empty: true }]
          } else {
            item.subs = data.map(device => {
              return {
                ...device,
                isMaster: false,
                empty: false,
                parent: item
              }
            })
          }
        }
      }, () => {
        item.loading = false
      })
    },
    onRowClick (data) {
      if (__SUB_DEVICE__ && data.isMaster) {
        if (data.loaded) {
          data.expand = !data.expand
        } else if (!data.loading) {
          this.getSubDevices(data)
        }
      }
    },
    onTagClick (data) {
      (data.activate ? deactivateDevice : activateDevice)(data).then(() => {
        if (data.isMaster) {
          this.$refs.table.pageTo()
        } else {
          this.reloadSubDevices(data.parent)
        }
      })
    },
    onEditDevice (device) {
      const { id, name, openTime, closeTime, address, longitude, latitude } = device
      this.$device = device
      this.info = { id, name, range: [openTime || '', closeTime || ''], address, longitude, latitude }
      this.$refs.editDialog.show()
    },
    onEditCoordinate () {
      const { longitude, latitude, address } = this.info
      this.$refs.coordinateDialog.show({
        longitude,
        latitude,
        address
      })
    },
    onChangeCoordinate ({ value: { longitude, latitude, address }, done }) {
      this.info.longitude = longitude
      this.info.latitude = latitude
      this.info.address = address
      done()
    },
    onSave (done) {
      const { id, name, range, longitude, address, latitude } = this.info
      if (!name) {
        this.$message({
          type: 'warning',
          message: '名称不能为空'
        })
        return
      }
      if (!range || !range[0] || !range[1]) {
        this.$message({
          type: 'warning',
          message: '请选择开关机时间'
        })
        return
      }
      if (range[0] >= range[1]) {
        this.$message({
          type: 'warning',
          message: '开机时间必须小于关机时间'
        })
        return
      }
      if (!address) {
        this.$message({
          type: 'warning',
          message: '地址不能为空'
        })
        return
      }
      if (longitude && !validLongitude(longitude)) {
        this.$message({
          type: 'warning',
          message: '经度格式错误，-180 ~ +180'
        })
        return
      }
      if (latitude && !validLatitude(latitude)) {
        this.$message({
          type: 'warning',
          message: '纬度格式错误，-90 ~ +90'
        })
        return
      }
      const info = { id, name, openTime: range[0], closeTime: range[1], address, longitude, latitude }
      if (Object.keys(info).every(key => info[key] === this.$device[key])) {
        done()
        return
      }
      updateDevice(info).then(() => {
        done()
        Object.assign(this.$device, info)
      })
    },
    onSettingDevice ({ id }) {
      this.$router.push({
        name: 'device-management-settings',
        params: { id }
      })
    },
    addDeviceAttention (row) {
      addDeviceAttention(row.id).then(() => {
        row.ifAttention = 1
      })
    },
    cancelDeviceAttention (row) {
      cancelDeviceAttention(row.id).then(() => {
        row.ifAttention = 0
      })
    },
    cancelDeviceAttentionByDialog (row) {
      cancelDeviceAttention(row.id).then(() => {
        this.$refs.table.pageTo()
      })
    },
    onShowAttentionList () {
      this.$refs.attentionList.show()
    }
  }
}
</script>
