<template>
  <ai-list class="addressBook">
    <template slot="title">
      <ai-title title="人员设备" isShowArea isShowBottomBorder v-model="search.areaId" :instance="instance" @change="search.current = 1, getList()"></ai-title>
    </template>
    <template slot="content">
      <ai-search-bar class="search-bar" bottomBorder>
        <template #left>
          <ai-select
            v-model="search.abnormalStatus"
            @change="search.current = 1, getList()"
            placeholder="异常状态"
            :selectList="dict.getDict('intelligentGuardianshipAbnormalStatus')">
          </ai-select>
          <ai-select
            v-model="search.onlineStatus"
            @change="search.current = 1, getList()"
            placeholder="在线状态"
            :selectList="onlineStatusList">
          </ai-select>
        </template>
        <template slot="right">
          <el-input
            v-model="search.name"
            size="small"
            @keyup.enter.native="search.current = 1, getList()"
            placeholder="请输入成员姓名、设备号、监护人"
            clearable
            @clear="search.current = 1, search.name = '', getList()"
            suffix-icon="iconfont iconSearch">
          </el-input>
        </template>
      </ai-search-bar>
      <ai-search-bar class="search-bar" style="margin-top: 12px;">
        <template #left>
          <el-button size="small" type="primary" icon="iconfont iconAdd" @click="toAdd('')">添加</el-button>
        </template>
      </ai-search-bar>
      <ai-table
        :tableData="tableData"
        :col-configs="colConfigs"
        :total="total"
        v-loading="loading"
        style="margin-top: 6px;"
        :current.sync="search.current"
        @handleSelectionChange="handleSelectionChange"
        :size.sync="search.size"
        @getList="getList">
        <el-table-column slot="options" width="240px" fixed="right" label="操作" align="center">
          <template slot-scope="{ row }">
            <div class="table-options">
              <el-button type="text" @click="toAdd(row.id)">编辑</el-button>
              <el-button type="text" @click="$router.push({name: '监护地图', query: {id: row.id, lat: row.lat, lng: row.lng}})">地图查看</el-button>
              <el-button type="text" @click="toMonitor(row.id)">监测数据</el-button>
              <el-button type="text" @click="remove(row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
        <div slot="paginationBtns" class="table__btns">
          <span style="margin-right: 8px;" @click="removeAll">批量删除</span>
        </div>
      </ai-table>
    </template>
  </ai-list>
</template>

<script>
  import { mapState } from 'vuex'
  export default {
    name: 'List',

    props: {
      instance: Function,
      dict: Object
    },

    data() {
      return {
        search: {
          current: 1,
          size: 10,
          name: '',
          areaId: '',
          abnormalStatus: '',
          onlineStatus: ''
        },
        abnormalStatusList: [{
          dictName: '正常',
          dictValue: '0'
        }, {
          dictName: '异常',
          dictValue: '1'
        }],
        onlineStatusList: [{
          dictName: '离线',
          dictValue: '0'
        }, {
          dictName: '在线',
          dictValue: '1'
        }],
        ids: [],
        loading: false,
        total: 0,
        tableData: []
      }
    },

    computed: {
      ...mapState(['user']),
      colConfigs () {
        return [
          { type: 'selection', label: ''},
          { prop: 'name', label: '姓名' },
          { prop: 'mid', label: '设备号', width: 140 },
          {
            prop: 'departmentNames',
            label: '年龄',
            align: 'center',
            render: (h, { row }) => {
              return h('span', {}, this.getIdInfo(row.idNumber, 3))
            }
          },
          { prop: 'sex', align: 'center', label: '性别', formart: v => v === '1' ? '男' : '女' },
          { prop: 'phone', align: 'center', label: '联系方式', width: 120 },
          { prop: 'guardianCount', align: 'center', label: '监护人数' },
          { prop: 'areaName', align: 'center', label: '所属地区' },
          { prop: 'electricQuantity', align: 'center', label: '电量', formart: v => v ? `${v}%` : '-' },
          { prop: 'createTime', align: 'center', width: 150, label: '最后更新时间' },
          { prop: 'temperature', align: 'center', label: '体温' },
          {
            prop: 'abnormalStatus',
            align: 'center',
            label: '是否异常',
            render: (h, { row }) => {
              return h('span', {
                style: {
                  color: this.getStatusColor(row.abnormalStatus)
                }
              }, this.getStatus(row.abnormalStatus))
            }
          },
          {
            prop: 'onlineStatus',
            align: 'center',
            label: '在线状态',
            render: (h, { row }) => {
              return h('span', {
                style: {
                  color: row.onlineStatus === '1' ? '#2EA222' : '#F46'
                }
              }, row.onlineStatus === '1' ? '在线' : '离线')
            }
          }
        ]
      }
    },

    mounted() {
      this.search.areaId = this.user.info.areaId

      this.dict.load(['intelligentGuardianshipAbnormalStatus']).then(() => {
        this.getList()
      })
    },

    methods: {
      handleSelectionChange (e) {
        this.ids = e.map(v => v.id).join(',')
      },

      getStatusColor (status) {
        if (!status && status !== '0') return ''

        return {
          '0': '#2EA222',
          '1': '#F46',
          '2': '#D326C7'
        }[status]
      },

      getStatus (status) {
        if (!status && status !== '0') return '-'

        return {
          '0': '正常',
          '1': '异常',
          '2': '求助'
        }[status]
      },

      getList () {
        this.loading = true
        this.instance.post(`/app/appintelligentguardianshipdevice/list`, null, {
          params: {
            ...this.search
          }
        }).then(res => {
          if (res.code == 0) {
            this.tableData = res.data.records
            this.total = res.data.total

            this.$nextTick(() => {
              this.loading = false
            })
          } else {
            this.loading = false
          }
        }).catch(() => {
          this.loading = false
        })
      },

      getIdInfo (UUserCard, num) {
        if (num == 1) {
          var birth = UUserCard.substring(6, 10) + '-' + UUserCard.substring(10, 12) + '-' + UUserCard.substring(12, 14)
          return birth
        }
        if (num == 2) {
          if (parseInt(UUserCard.substr(16, 1)) % 2 == 1) {
            return '1'
          } else {
            return '0'
          }
        }

        if (num == 3) {
          var myDate = new Date()
          var month = myDate.getMonth() + 1
          var day = myDate.getDate()
          var age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;
          if (UUserCard.substring(10, 12) < month || UUserCard.substring(10, 12) == month && UUserCard.substring(12, 14) <= day) {
            age ++
          }

          return age
        }
      },

      removeAll () {
        if (!this.ids) return

        this.remove(this.ids)
      },

      remove (id) {
        this.$confirm('确定删除该数据？').then(() => {
          this.instance.post(`/app/appintelligentguardianshipdevice/delete?ids=${id}`).then(res => {
            if (res.code == 0) {
              this.$message.success('删除成功！')
              this.getList()
            }
          })
        })
      },

      toMonitor (id) {
        this.$emit('change', {
          type: 'Monitor',
          params: {
            id: id || ''
          }
        })
      },

      toAdd(id) {
        this.$emit('change', {
          type: 'Add',
          params: {
            id: id || ''
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>
