<template>
  <a-modal
    :title="title"
    style="top: 20px;"
    :width="800"
    v-model="visible"
    :confirmLoading="confirmLoading"
    :destroyOnClose="true"
    @ok="handleSubmit"
  >
    <a-form :form="form">
      <a-form-item style="display:none">
        <a-input v-decorator="['insideSystemId']"/>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="系统名称">
        <a-input placeholder="系统名称" v-decorator="['name']"/>
      </a-form-item>
      <!--<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="域名">-->
      <!--<a-input placeholder="域名" v-decorator="['realmPlace']"/>-->
      <!--</a-form-item>-->
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="系统首页">
        <a-input placeholder="系统首页" v-decorator="['returnUrl']"/>
      </a-form-item>
      <!--<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="图标">-->
      <!--<a-input placeholder="图标" v-decorator="['icon']"/>-->
      <!--</a-form-item>-->
      <!--<a-form-item-->
      <!--:labelCol="labelCol"-->
      <!--:wrapperCol="wrapperCol"-->
      <!--label="图标"-->
      <!--&gt;-->
      <!--<a-input v-decorator="['icon',{rules: [{ required: true, message: '请选择图标' }]}]" ref="iconInput"-->
      <!--@click="iconselect()" enterButton="选择图标" placeholder="选择图标">-->
      <!--<a-icon slot="prefix" :type="icon"/>-->
      <!--<a-icon slot="suffix" type="close-circle" @click="emitEmpty"/>-->
      <!--</a-input>-->
      <!--</a-form-item>-->
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="图标">
        <!--<a-input placeholder="图标" v-decorator="['icon']"/>-->
        <a-upload
          name="file"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :headers="headers"
          :action="uploadImgUrl"
          :before-upload="beforeUpload"
          @change="handleChange"
        >
          <img v-if="imageUrl" :src="imageUrl" alt="file"/>
          <div v-else>
            <a-icon :type="loading ? 'loading' : 'plus'"/>
            <div class="ant-upload-text">
              Upload
            </div>
          </div>
        </a-upload>
      </a-form-item>

      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="请输入唯一标识">
                <a-input placeholder="请输入唯一标识" v-decorator="['joinsysCode']"/>
            </a-form-item> -->
    </a-form>
    <iconSelector-modal ref="modal" @ok="setIcon" :icon="icon"/>

  </a-modal>
</template>
<script>
import { saveInsideSystemInfo } from '@/api/backmanage/insidesystem'
import IconSelectorModal from './IconSelectorModal.vue'
// import pick from 'lodash.pick'
// import storage from 'store'
// import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getToken } from '@/utils/auth'

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

export default {
  name: 'InsideSystemInfoModal',
  props: {},
  components: {
    IconSelectorModal
  },
  data () {
    return {
        title: '',
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      mdl: {},
      form: this.$form.createForm(this),
      loading: false,
      uploadImgUrl: process.env.VUE_APP_BASE_API + '/common/upload',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      imageUrl: '',
      icon: ''
    }
  },
  beforeCreate () {
  },
  created () {
  },
  methods: {
     normFile (e) {
      console.log('Upload event:', e)
      if (Array.isArray(e)) {
        return e.file.response.fileName
      }
      return e && e.fileList
    },
    handleSuccess (res, file) {
    },
    handleChange (info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl
          this.loading = false
        })
      }
    },
    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
    },
    iconselect () {
      this.$refs.modal.show()
    },
    emitEmpty () {
      this.$refs.iconInput.focus()
      this.form.setFieldsValue({ 'icon': '' })
    },
    menuTypeChange (type) {
      this.menuType = type
    },
    setIcon (icon) {
      this.icon = icon
      this.form.setFieldsValue({ 'icon': icon })
    },
    add (value) {
      if (value) {
            this.title = value
        }
      this.visible = true
    },
    edit (record, value) {
        if (value) {
            this.title = value
        }
        this.visible = true
        this.imageUrl = record.icon
        this.$nextTick(() => {
         this.form.setFieldsValue({ 'name': record.name, 'returnUrl': record.returnUrl, 'joinsysCode': record.joinsysCode, 'insideSystemId': record.insideSystemId })
        })
         console.log('%c [ this.form ]-176', 'font-size:13px; background:pink; color:#bf2c9f;', this.form)
        console.log('%c [  ]-174', 'font-size:13px; background:pink; color:#bf2c9f;', record)
      // this.mdl = Object.assign(record)
      // this.$nextTick(() => {
      //   this.form.setFieldsValue(pick(this.mdl, 'insideSystemId', 'joinsysCode', 'icon', 'name', 'realmPlace', 'returnUrl', 'status', 'remark', 'createTime', 'createBy', 'updateTime', 'updateBy', 'version', 'delFlag'))
      // })
    },
    handleSubmit (e) {
      this.form.setFieldsValue({ 'icon': this.imageUrl })
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
            this.confirmLoading = true
            if (this.title === '新增') {
                saveInsideSystemInfo(values, this.title).then(res => {
                if (res.code === 200) {
                    this.$message.success('新增成功')
                    this.$emit('ok')
                    this.visible = false
                } else {
                    this.$message.success(res.msg)
                }
                }).catch(() => {
                    this.$message.error('系统错误，请稍后再试')
                }).finally(() => {
                    this.confirmLoading = false
                })
            } else if (this.title === '修改') {
                saveInsideSystemInfo(values, this.title).then(res => {
                    if (res.code === 200) {
                        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)
          }
        })
      }
      */
  }
}
</script>
