<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 u-required">名称</span>
        <el-input
          v-model.trim="currObj.name"
          placeholder="最多30个字符"
          maxlength="30"
          clearable
        />
        <span class="c-grid-form__label u-required">配置</span>
        <schema-select
          v-model="currObj.productId"
          class="u-width"
          :schema="productSelectSchema"
          placeholder="请选择配置"
        />
        <span class="c-grid-form__label u-required">序列号</span>
        <el-input
          v-model.trim="currObj.serialNumber"
          placeholder="最多50个字符"
          maxlength="50"
          clearable
        />
        <span class="c-grid-form__label u-required">MAC</span>
        <el-input
          v-model.trim="currObj.mac"
          class="u-width--sm"
          placeholder="ff:ff:ff:ff:ff:ff"
          maxlength="17"
          clearable
        />
        <div class="c-grid-form__label u-required">开关机时间</div>
        <el-time-picker
          v-model="currObj.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="currObj.address"
          type="textarea"
          placeholder="最多100个字符"
          maxlength="100"
          :rows="2"
          show-word-limit
        />
        <span class="c-grid-form__label">坐标</span>
        <div class="l-flex--row c-grid-form__option">
          <span class="c-sibling-item">{{ currObj.longitude }},{{ currObj.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"
    />
    <mesh-dialog ref="meshDialog" />
  </schema-table>
</template>

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

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

    return {
      currObj: {},
      isSub: false,
      ratio: null,
      productSelectSchema,
      schema: {
        keepalive: true,
        list: this.getDevicesByTenant,
        transform: this.transform,
        transformData: __SUB_DEVICE__ && this.transformTableData,
        buttons: [
          { type: 'add', on: this.onAddDevice }
        ],
        filters: [
          { key: 'productId', type: 'select', placeholder: '配置', ...productSelectSchema },
          { key: 'boundFlag', type: 'select', placeholder: '使用情况', options: [
            { value: 1, label: '已使用' },
            { value: 0, label: '未使用' }
          ] },
          { key: 'serialNumber', type: 'search', placeholder: '序列号' },
          { key: 'mac', type: 'search', placeholder: 'MAC' },
          { key: 'name', type: 'search', placeholder: '设备名称' }
        ],
        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 },
          { prop: 'productName', label: '配置' },
          { prop: 'serialNumber', label: '序列号', 'min-width': 140 },
          { prop: 'mac', label: 'MAC', 'min-width': 140 },
          { 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 },
          { label: '使用情况', type: 'tag', render: ({ bound }) => bound
            ? { type: 'success', label: '已使用' }
            : { type: 'primary', label: '未使用' } },
          { type: 'invoke', render: [
            { label: '配置', render: ({ isMaster }) => isMaster, on: this.onSettingDevice },
            __SUB_DEVICE__ && { label: '添加备份', render: ({ isMaster }) => isMaster, on: this.onAddSubDevice },
            { label: '所属网点', render: ({ isMaster }) => isMaster, allow: ({ bound }) => bound, on: this.onViewMesh },
            { label: '删除', render: ({ empty }) => !empty, on: this.onDelDevice }
          ].filter(Boolean), width: __SUB_DEVICE__ ? 240 : 180 }
        ]
      }
    }
  },
  computed: {
    dialogTitle () {
      return this.isSub ? '新增备份设备' : '新增设备'
    }
  },
  methods: {
    getProducts (params) {
      return getProducts({
        tenant: this.tenant,
        ...params
      })
    },
    getDevicesByTenant (params) {
      return getDevicesByTenant(this.tenant, 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
    },
    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 () {
      if (this.isSub) {
        const { productId, openTime, closeTime, address, longitude, latitude } = this.$master
        this.currObj = {
          name: '',
          productId,
          serialNumber: '',
          mac: '',
          range: [openTime, closeTime],
          address,
          longitude,
          latitude,
          tenant: this.tenant
        }
      } else {
        this.currObj = {
          name: '',
          productId: '',
          serialNumber: '',
          mac: '',
          range: ['00:00:00', '23:59:59'],
          address: '',
          longitude: '',
          latitude: '',
          tenant: this.tenant
        }
      }
      this.$refs.editDialog.show()
    },
    onEditCoordinate () {
      const { longitude, latitude, address } = this.currObj
      this.$refs.coordinateDialog.show({
        longitude,
        latitude,
        address
      })
    },
    onChangeCoordinate ({ value: { longitude, latitude, address }, done }) {
      this.currObj.longitude = longitude
      this.currObj.latitude = latitude
      this.currObj.address = address
      done()
    },
    onSave (done) {
      if (this.check(this.currObj)) {
        const { range, ...data } = this.currObj
        if (this.isSub) {
          addSubDevice(this.$master, {
            openTime: range[0],
            closeTime: range[1],
            ...data
          }).then(() => {
            done()
            this.reloadSubDevices(this.$master)
          })
        } else {
          addDevice({
            openTime: range[0],
            closeTime: range[1],
            ...data
          }).then(() => {
            done()
            this.$refs.table.resetCondition({
              boundFlag: 0,
              name: this.currObj.name,
              productId: this.currObj.productId,
              serialNumber: this.currObj.serialNumber,
              mac: this.currObj.mac
            })
          })
        }
      }
    },
    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.range || !item.range[0] || !item.range[1]) {
        this.$message({
          type: 'warning',
          message: '请选择开关机时间'
        })
        return false
      }
      if (item.range[0] >= item.range[1]) {
        this.$message({
          type: 'warning',
          message: '开机时间必须小于关机时间'
        })
        return false
      }
      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-management-detail',
        params: {
          id: item.id
        }
      })
    },
    onDelDevice (item) {
      deleteDevice(item).then(() => {
        if (item.isMaster) {
          this.$refs.table.decrease(1)
        } else {
          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 (__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)
        }
      })
    },
    onSettingDevice ({ id }) {
      this.$router.push({
        name: 'box-settings',
        params: { id }
      })
    },
    onViewMesh ({ id }) {
      this.$refs.meshDialog.show(id)
    }
  }
}
</script>
