<template>
  <a-modal
    title='操作'
    style='top: 20px;'
    :width='1000'
    v-model='visible'
    :confirmLoading='confirmLoading'
    @ok='handleSubmit'
  >
    <a-form :form='form'>
      <a-form-item style='display:none'>
        <a-input v-decorator="['id']" />
      </a-form-item>
      <a-form-item style='display:none'>
        <a-input v-decorator="['version']" />
      </a-form-item>
      <div style='display: flex;margin-bottom: 20px'>
        <span style='width: 20px;display: block;font-size: 25px;color: #1890ff;font-weight: bold;'>|</span>
        <span style='display: block;margin-top: 11px;font-size: 15px'>新增设备</span>
      </div>
      <a-row>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='设备编号'>
            <a-input placeholder='设备编号' v-decorator="['equipmentNum', {rules: [{required: true, message: '请输入设备编号'}]}]" />
          </a-form-item>
        </a-col>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='设备名称'>
            <a-input placeholder='设备名称' v-decorator="['equipmentName',{rules: [{required: true, message: '请输入设备名称'}]}]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='设备类型'>
            <a-select v-decorator="['type',{rules: [{ required: true, message: '请选择设备类型'}]}]" placeholder='请选择设备类型'>
              <a-select-option value='0'>
                门禁
              </a-select-option>
              <a-select-option value='1'>
                开门控制器
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='设备ip'>
            <a-input placeholder='设备ip' v-decorator="['ip',{rules: [{required: true, message: '请输入设备ip'}]}]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属楼层'>
            <a-select v-decorator="['buildId',{rules: [{ required: true, message: '请选择所属楼层' }]}]" placeholder='所属楼层'
                      @change='getRoomList'>
              <a-select-option v-for='item in floorList' :key='item.id' :value='item.id' >
                {{ item.floorName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='存放地点'>
            <a-select v-decorator="['roomId',{rules: [{ required: true, message: '选择存放地点' }]}]" placeholder='所属房间'
            >
              <a-select-option v-for='item in roomList' :key='item.id' :value='item.id' >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='设备状态'>
            <a-select v-decorator="['status',{rules: [{ required: true, message: '请选择设备状态'}]}]" placeholder='请选择设备状态'>
              <a-select-option value='0'>
                开启
              </a-select-option>
              <a-select-option value='1'>
                损坏
              </a-select-option>
              <a-select-option value='2'>
                离线
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='设备图片'>
            <!--        <a-input placeholder="设备图片" v-decorator="['pic',{rules: [{required: true, message: '请输入设备图片'}]}]"/>-->
            <a-upload
              v-decorator="['pic']"
              list-type='picture-card'
              class='avatar-uploader'
              :show-upload-list='false'
              :action='uploadUrl'
              :headers='headers'
              :before-upload='beforeUpload'
              @change='handleChange'
            >
              <img v-if='imageUrl' :src='imageUrl' style='width: 102px; height: 102px' />
              <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class='ant-upload-text'> 上传</div>
              </div>
            </a-upload>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <div style='display: flex;margin-bottom: 20px'>
      <span style='width: 20px;display: block;font-size: 25px;color: #1890ff;font-weight: bold;'>|</span>
      <span style='display: block;margin-top: 11px;font-size: 15px'>开门记录</span>
    </div>
    <a-table :columns='columns'
             size='default'
             ref='table'
             style='width: 800px;margin-left: 20px'
             :data-source='loadData'
             >
      <a slot='name' slot-scope='text'>{{ text }}</a>

    </a-table>

  </a-modal>
</template>
<script>
import { saveEquipment, get,recordByDeviceId } from '@/api/admin/meeting/equipment'
import pick from 'lodash.pick'
import { getFloorList, getRoomListByFloorId } from '@/api/admin/meeting/roomContent'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  name: 'EquipmentModal',
  props: {},
  components: {},
  data() {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      loadData:[],
      loading: false,
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      uploadUrl: process.env.VUE_APP_API_BASE_URL + '/api/dfs/upload',
      imageUrl: '',
      headers: {
        Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN)
      },
      confirmLoading: false,
      mdl: {},
      form: this.$form.createForm(this),
      floorList: [],
      roomList: [],
      columns: [
        {
          title: '开门时间',
          dataIndex: 'createTime'
        },
        {
          title: '开门方式',
          dataIndex: 'type',
        },
        {
          title: '开门人',
          dataIndex: 'userName'
        },
      ],
    }
  },
  beforeCreate() {
  },
  created() {
    this.getFloorList()
  },
  methods: {
    getFloorList() {
      getFloorList().then((res) => {
        this.floorList = res.data
      })
    },
    getRoomList(value) {
      let param = {
        'buildingDetailId': value
      }
      getRoomListByFloorId(param).then((res) => {
        this.roomList = res.data
      })
    },

    //开门记录

    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 < 500
      if (!isLt2M) {
        this.$message.error('图片必须小于 500kb!')
      }
      return isJpgOrPng && isLt2M
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        const { form: { setFieldsValue } } = this
        const result = info.file.response
        // 设置值
        this.$nextTick(() => {
          setFieldsValue({
            // 设置相对路径
            pic: result.fileName
          })
        })
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl
          this.loading = false
        })
      }
    },
    add() {
      this.form.resetFields()
      this.edit({ id: 0 })
    },
    edit(record) {


      if (record.id != 0){
        get(record.id).then((res) => {
          this.form.setFieldsValue({
            ip: res.ip,
            status: res.status.toString(),
            type: res.type.toString(),
            buildId: res.buildId,
            roomId: res.roomName,
          })
        })
        recordByDeviceId(record.id).then(res =>{
          this.loadData =res.data
        })

      }


      this.mdl = Object.assign(record)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'id', 'type', 'equipmentName', 'status', 'createDate', 'equipmentNum', 'pic', 'deleteFlag', 'createBy', 'createTime', 'updateBy', 'updateTime'))
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          this.confirmLoading = true
          saveEquipment(values).then(res => {
            if (res.code === 0) {
              this.$message.success('保存成功')
              this.$emit('ok')
              this.visible = false
            } else {
              this.$message.error(res.msg)
            }
          }).catch(() => {
            this.$message.error('系统错误，请稍后再试')
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}

function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
</script>
