<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 :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: '请选择所属园区' }]}]"
                  :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="['buildingName', {rules: [{ required: true, message: '请输入楼宇名称' }]}]" />
      </a-form-item>
      <a-form-item
        :labelCol='labelCol'
        :wrapperCol='wrapperCol'
        label='备注'
      >
        <a-textarea :rows='5' placeholder='...' v-decorator="['remark']" />
      </a-form-item>

    </a-form>
  </a-modal>
</template>
<script>
import { saveBuilding } from '@/api/admin/building'
import pick from 'lodash.pick'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getInfo } from '@/api/login'
import { getTenantList } from '@/api/tenant'
import { getParkList } from '@/api/admin/park'


export default {
  name: 'BuildingModal',
  props: {},
  components: {},
  data() {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      roleAll: [],
      mdl: {},
      uploadUrl: process.env.VUE_APP_API_BASE_URL + '/api/dfs/upload',
      headers: {
        token: storage.get(ACCESS_TOKEN)
      },
      tenantList: [],
      parkList: [],
      form: this.$form.createForm(this),
      userDetail: {},
      tenantEnable: false,
      parkEnable: false
    }
  },
  beforeCreate() {
  },
  created() {
    this.getUserDetail()
  },
  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) {
          // 不可编辑
          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.form.setFieldsValue({
        parkId: null
      })
      // 查询园区
      getParkList({
        tenantId: id
      }).then(res => {
        this.parkList = res.rows
      })
    },
    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 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      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
        console.log('result', result)
        // 设置值
        this.$nextTick(() => {
          setFieldsValue({
            buildingPic: 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()
    },
    edit(record) {
      this.mdl = Object.assign(this.mdl, record)
      let copyMdl = JSON.parse(JSON.stringify(this.mdl))
      this.visible = true
      if (this.mdl.buildingPic) {
        this.imageUrl = process.env.VUE_APP_API_BASE_URL + this.mdl.buildingPic
      }
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'id', 'buildingName', 'buildingPic', 'remark', 'parkId', 'tenantId'))
      })
      // 查询地区
      this.getTenantData()
      // 选择地区 -> 查询园区
      if (this.mdl.tenantId) {
        this.selectTenant(this.mdl.tenantId)
      }
      this.mdl = copyMdl
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          this.confirmLoading = true
          saveBuilding(values).then(res => {
            if (res.code === 0) {
              this.$message.success('保存成功')
              this.$emit('ok')
              this.visible = false
            } else {
              this.$message.success(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>
