<template>
  <schema-table
    ref="table"
    row-key="id"
    :schema="schema"
    @row-click="onRowClick"
  >
    <confirm-dialog
      ref="editDialog"
      :title="dialogTitle"
      @confirm="onSave"
    >
      <div class="c-grid-form u-align-self--center">
        <span class="c-grid-form__label required">名称：</span>
        <el-input
          v-model.trim="currObj.name"
          placeholder="最多50个字符"
          maxlength="50"
          clearable
        />
        <span class="c-grid-form__label required">产品：</span>
        <schema-select
          v-model="currObj.productId"
          placeholder="请选择产品"
          :schema="productSelectSchema"
          :disabled="isSub"
        />
        <span class="c-grid-form__label required">序列号：</span>
        <el-input
          v-model.trim="currObj.serialNumber"
          placeholder="最多50个字符"
          maxlength="50"
          clearable
        />
        <span class="c-grid-form__label required">MAC：</span>
        <el-input
          v-model.trim="currObj.mac"
          placeholder="ff:ff:ff:ff:ff:ff"
          maxlength="17"
          clearable
        />
        <span class="c-grid-form__label required">地址：</span>
        <el-input
          v-model.trim="currObj.address"
          placeholder="最多100个字符"
          maxlength="100"
          clearable
        />
        <span class="c-grid-form__label">经度：</span>
        <div class="l-flex--row c-grid-form__option">
          <el-input
            v-model.trim="currObj.longitude"
            class="l-flex__fill c-sibling-item"
            placeholder="-180 ~ +180"
            maxlength="13"
            clearable
          />
          <span class="c-sibling-item far c-grid-form__label">纬度：</span>
          <el-input
            v-model.trim="currObj.latitude"
            class="l-flex__fill c-sibling-item"
            placeholder="-90 ~ +90"
            maxlength="12"
            clearable
          />
        </div>
        <span />
        <a
          class="o-link grid"
          href="http://api.map.baidu.com/lbsapi/getpoint/index.html"
          target="_blank"
        />
      </div>
    </confirm-dialog>
  </schema-table>
</template>

<script>
import {
  getDevicesByAdmin,
  addDevice,
  deleteDevice,
  getSubDevices,
  addSubDevice,
  activateDevice,
  deactivateDevice,
  getProducts
} from '@/api/device'
import {
  validMAC,
  validLongitude,
  validLatitude
} from '@/utils/validate'

export default {
  name: 'Device',
  props: {
    group: {
      type: Object,
      required: true
    }
  },
  data () {
    const productSelectSchema = {
      remote: getProducts,
      condition: { tenant: this.group.path },
      pagination: true,
      value: 'id',
      label: 'name'
    }

    return {
      currObj: {},
      isSub: false,
      ratio: null,
      productSelectSchema,
      schema: {
        condition: { productId: void 0, name: '', tenant: this.group.path },
        list: getDevicesByAdmin,
        transform: this.transform,
        transformData: this.transformTableData,
        buttons: [
          { type: 'add', on: this.onAddDevice }
        ],
        filters: [
          { key: 'productId', type: 'select', placeholder: '全部产品', ...productSelectSchema },
          { key: 'name', type: 'search', placeholder: '设备名称' }
        ],
        cols: [
          { type: 'refresh', render (data, h) {
            return data.isMaster
              ? h('i', {
                staticClass: `o-expand-icon u-pointer ${data.loading ? 'el-icon-loading' : 'el-icon-arrow-right'}`,
                class: { expand: data.expand }
              })
              : null
          } },
          { label: '设备名称', 'min-width': 120, render (data, h) {
            return data.empty ? h('span', { staticClass: 'u-color--info' }, '暂无备份设备') : data.name
          } },
          { prop: 'productName', label: '产品' },
          { prop: 'serialNumber', label: '序列号', 'min-width': 100 },
          { prop: 'mac', label: 'MAC', 'min-width': 100 },
          { type: 'tag', 'width': 100, render ({ empty, activate, onlineStatus }) {
            return empty
              ? null
              : {
                type: activate
                  ? activate === 1
                    ? void 0
                    : onlineStatus === 1
                      ? 'success'
                      : 'danger'
                  : 'warning',
                label: activate
                  ? activate === 1
                    ? '已激活'
                    : onlineStatus === 1
                      ? '在线'
                      : '离线'
                  : '未激活'
              }
          }, on: this.onTagClick },
          { type: 'invoke', width: 180, render: [
            { label: '查看', render ({ empty }) { return !empty }, on: this.onViewDevice },
            { label: '添加备份', render ({ isMaster }) { return isMaster }, on: this.onAddSubDevice },
            { label: '删除', render ({ empty }) { return !empty }, on: this.onDelDevice }
          ] }
        ]
      }
    }
  },
  computed: {
    dialogTitle () {
      return this.isSub ? '新增备份设备' : '新增设备'
    }
  },
  methods: {
    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
    },
    onAddDevice () {
      this.isSub = false
      this.$master = null
      this.productSelectSchema.option = null
      this.onAdd()
    },
    onAddSubDevice (item) {
      this.isSub = true
      this.$master = item
      this.productSelectSchema.option = { value: item.productId, label: item.productName }
      this.onAdd()
    },
    onAdd () {
      this.currObj = {
        name: '',
        productId: this.$master?.productId,
        serialNumber: '',
        mac: '',
        longitude: '',
        latitude: '',
        address: '',
        tenant: this.group.path
      }
      this.$refs.editDialog.show()
    },
    onSave (done) {
      if (this.check(this.currObj)) {
        if (this.isSub) {
          addSubDevice(this.$master, this.currObj).then(() => {
            done()
            this.reloadSubDevices(this.$master)
          })
        } else {
          addDevice(this.currObj).then(() => {
            done()
            this.$refs.table.resetCondition({ name: this.currObj.name, productId: this.currObj.productId })
          })
        }
      }
    },
    check (item) {
      if (!item.name) {
        this.$message({
          type: 'warning',
          message: '名称不能为空'
        })
        return false
      }
      if (!item.productId) {
        this.$message({
          type: 'warning',
          message: '请选择产品'
        })
        return false
      }
      if (!item.serialNumber) {
        this.$message({
          type: 'warning',
          message: '序列号不能为空'
        })
        return false
      }
      if (!item.mac) {
        this.$message({
          type: 'warning',
          message: 'MAC不能为空'
        })
        return false
      }
      if (!validMAC(item.mac)) {
        this.$message({
          type: 'warning',
          message: 'MAC格式不正确，例 ff:ff:ff:ff:ff:ff'
        })
        return false
      }
      item.mac = item.mac.toLowerCase()
      if (!item.address) {
        this.$message({
          type: 'warning',
          message: '地址不能为空'
        })
        return false
      }
      if (item.longitude && !validLongitude(item.longitude)) {
        this.$message({
          type: 'warning',
          message: '经度格式错误，-180 ~ +180'
        })
        return false
      }
      if (item.latitude && !validLatitude(item.latitude)) {
        this.$message({
          type: 'warning',
          message: '纬度格式错误，-90 ~ +90'
        })
        return false
      }
      return true
    },
    onViewDevice (item) {
      this.$router.push({
        name: 'device-detail',
        params: {
          id: item.id
        }
      })
    },
    onDelDevice (item) {
      if (item.isMaster) {
        deleteDevice(item).then(() => {
          this.$refs.table.decrease(1)
        })
      } else {
        deleteDevice(item).then(() => {
          this.reloadSubDevices(item.parent)
        })
      }
    },
    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 (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)
        }
      })
    }
  }
}
</script>
