<template>
  <a-modal
    title='操作'
    style='top: 20px;'
    :width='800'
    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>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属地区'>
        <a-select v-decorator="['tenantId', {rules: [{ required: true, message: '请选择所属地区' }]}]"
                  @change='selectTenant'
                  :disabled='tenantEnable'>
          <a-select-option v-for='item in tenantList' :key='item.id'>{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属园区'>
        <a-select v-decorator="['parkId', {rules: [{ required: true, message: '请选择所属园区' }]}]"
                  @change='selectPark'
                  :disabled='parkEnable'>
          <a-select-option v-for='item in parkList' :key='item.id'>{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='服务名称'>
        <a-input placeholder='服务名称'
                 v-decorator="['serveName',{rules:[{required: true,  message: '请输入服务名称' }]}]" />
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='服务类型'>
        <a-select placeholder='服务类型' @change='changeServeType'
                  v-decorator="['serveType', {rules: [{required: true,  message: '请选择服务类型' }]}]">
          <a-select-option :value='1'>免费服务</a-select-option>
          <a-select-option :value='2'>增值服务</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item v-if='mdl.serveType === 2' :labelCol='labelCol' :wrapperCol='wrapperCol' label='金额描述'>
        <a-input placeholder='金额描述'
                 v-decorator="['money',{rules:[{required: true,  message: '请输入金额描述' }]}]" />
      </a-form-item>
      <a-form-item v-if='mdl.serveType === 1' :labelCol='labelCol' :wrapperCol='wrapperCol' label='服务图标'>
        <!--        <a-input placeholder="室内图片url" v-decorator="['indoorPicUrl']" />-->
        <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-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='备注'>
        <a-input placeholder='备注' v-decorator="['remake']" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import { saveRoomServe } from '@/api/admin/meeting/roomServe'
import pick from 'lodash.pick'
import storage from 'store'
import { getTenantList } from '@/api/tenant'
import { getParkList } from '@/api/admin/park'
import { getInfo } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  name: 'RoomServeModal',
  props: {},
  components: {},
  data() {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      loading: false,
      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),
      userDetail: {},
      tenantList: [], // 地区
      parkList: [], // 园区
      buildingList: [], // 楼宇
      buildingDetailList: [], // 楼层
      roomList: [], // 房间
      tenantEnable: false,
      parkEnable: false
    }
  },
  beforeCreate() {
  },
  created() {
  },
  methods: {
    // 获取用户详细信息
    getUserDetail() {
      getInfo().then(res => {
        console.log('getUserDetail', res)
        this.userDetail = res
        // 园区：5
        if (this.userDetail.roleIds && this.userDetail.roleIds.length > 0 && this.userDetail.roleIds[0] == 5) {
          //
          // 判断：是新增就查询园区
          let { id } = this.mdl
          if (!id) {
            // 选择地区 -> 查询园区
            this.selectTenant(this.userDetail.tenantId)
            // 选择园区 -> 查询楼宇
            this.selectPark(this.userDetail.parkId)
          }
          //
          // 不可编辑
          this.tenantEnable = true
          this.parkEnable = true
          // 关联地区和园区
          this.mdl.parkId = this.userDetail.parkId
          this.mdl.tenantId = this.userDetail.tenantId
          this.form.setFieldsValue({
            parkId: this.mdl.parkId,
            tenantId: this.mdl.tenantId
          })
        }
      })
    },
    // 查询地区
    getTenantData() {
      getTenantList().then(res => {
        this.tenantList = res.rows
      })
    },
    // 选择地区 -> 查询园区
    selectTenant(id) {
      console.log('selectTenant', id)
      // 清空数据
      this.mdl.parkId = null // 园区
      this.mdl.buildingId = null // 楼宇
      this.mdl.buildId = null // 楼层
      this.mdl.roomId = null // 所属房间

      this.form.setFieldsValue({
        parkId: null, // 园区

      })
      // 查询园区
      getParkList({
        tenantId: id
      }).then(res => {
        this.parkList = res.rows
      })
    },
    // 选择园区 -> 查询楼宇
    selectPark(id) {
      // 清空数据
      this.mdl.buildingId = null // 楼宇
      this.mdl.buildId = null // 楼层
      this.mdl.roomId = null // 所属房间

      this.form.setFieldsValue({
        buildingId: null, // 楼宇
        buildId: null, // 楼层
        roomId: null // 所属房间
      })
      // 查询楼宇
      this.parkId = id
    },
    changeServeType(value) {
      this.mdl.serveType = value
    },

    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) {
      this.getTenantData()
      this.mdl = Object.assign(record)
      if (this.mdl.pic) {
        this.imageUrl = process.env.VUE_APP_API_BASE_URL + this.mdl.pic
      }

      let copyMdl = JSON.parse(JSON.stringify(this.mdl))

      this.getTenantData()
      //
      if (record.id != 0) { // 编辑
        // 选择地区 -> 查询园区
        if (copyMdl.tenantId) {
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.selectTenant(copyMdl.tenantId)
        }
        // 选择园区 -> 查询楼宇
        if (copyMdl.parkId) {
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.selectPark(copyMdl.parkId)
        }
      }
      this.getUserDetail()
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'id', 'serveName', 'serveType','money', 'serveTime', 'remake', 'type', 'createBy',
          'createTime', 'updateBy', 'updateTime', 'version', 'deleteFlag','tenantId', 'parkId',))
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          this.confirmLoading = true
          saveRoomServe(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>
