<template>
  <Modal
    class="application"
    v-model="showModal"
    width='500px'
    @on-cancel="cancel"
  >
    <h2 class="application__h">{{$t('create_new_app')}}</h2>
     <Form v-if="showModal" ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100" >
       <FormItem class="formitem" :label="$t('app_icon')+'：'" prop="app_icon">
         <div class="flexbox">
           <img :src="formValidate.app_icon" class="app_icon" v-if="formValidate.app_icon">
        <Upload
          action="/api/platform.php?s=Platform.File.Upload"
          :data = {access_token:token}
          :on-success="handleUploadLogo"
          :max-size="2048"
          :format="['jpg','jpeg','png']"
          :show-upload-list="false"
          :on-format-error="handleFormatError"
          :on-exceeded-size="handleMaxSize"
          >
          <Button icon="ios-cloud-upload-outline">{{formValidate.app_icon?$t('reupload'):$t('upload')}}</Button>
        </Upload>
         </div>
        </FormItem>
        <FormItem class="formitem" :label="$t('app_name')+'：'" prop="appName">
            <Input v-model="formValidate.appName" :placeholder="$t('please_input_the_app_name')" style="width: 300px;" />
        </FormItem>
        <FormItem class="formitem" :label="$t('app_owner')+'：'" prop="app_owner">
            <Input v-model="formValidate.app_owner"  :placeholder="$t('please_input_the_app_owner')"  style="width: 300px" />
        </FormItem>
        <FormItem class="formitem" :label="$t('apply_reason')+'：'" prop="apply_reason">
            <Input v-model="formValidate.apply_reason" show-word-limit :rows="4" :maxlength="2000" type="textarea" :placeholder="$t('please_descript_the_reason_of_your_application')" style="width: 300px" />
        </FormItem>
    </Form>
    <div class="application__btn" slot="footer">
        <span class="tips">{{$t('your_account_has_')}}{{apply_account_left}}{{$t('_chances_left_to_create_new_apps')}}</span>
        <Button type="primary" @click="addAppFun">{{formValidate.app_key?$t('alter'):$t('apply')}}</Button>
    </div>
  </Modal>
</template>

<script>
import { AddApp, EditApp } from '@/api/application'
import { getToken } from '@/libs/util'
export default {
  props: {
    apply_account_left: {
      type: Number
    },
    edit_obj: {
      type: Object
    }
  },
  watch: {
    edit_obj (newValue) {
      if (newValue.app_key) {
        this.$set(this.formValidate, 'appName', newValue.app_name)
        this.$set(this.formValidate, 'app_key', newValue.app_key)
        this.$set(this.formValidate, 'app_owner', newValue.app_owner)
        this.$set(this.formValidate, 'app_icon', newValue.app_icon)
        this.$set(this.formValidate, 'apply_reason', newValue.apply_reason)
      }
    }
  },
  data () {
    return {
      showModal: false,
      token: getToken(),
      name: '',
      key: '',
      secret: '',
      formValidate: {
        appName: '',
        app_owner: '',
        app_icon: '',
        apply_reason: '',
        app_key: ''
      },
      ruleValidate: {
        appName: [
          { required: true, message: this.$t('please_input_the_app_name'), trigger: 'blur' }
        ],
        app_owner: [
          { required: true, message: this.$t('please_input_the_app_owner'), trigger: 'blur' }
        ],
        apply_reason: [
          { required: true, message: this.$t('please_descript_the_reason_of_your_application'), trigger: 'blur' }
        ]
        // appName: [
        //   { required: true, message: 'please_input_the_app_name', trigger: 'blur' }
        // ],
        // app_owner: [
        //   { required: true, message: 'please_input_the_app_owner', trigger: 'blur' }
        // ],
        // apply_reason: [
        //   { required: true, message: 'please_descript_the_reason_of_your_application', trigger: 'blur' }
        // ]
      }
    }
  },
  created () {
    // this.formValidate.secret = this.randomWord(false, 32)
  },
  methods: {
    resetForm () {
      this.formValidate = {
        appName: '',
        app_owner: '',
        app_icon: '',
        apply_reason: '',
        app_key: ''
      }
    },
    cancel () {
      this.showModal = false
      this.resetForm()
    },
    show () {
      this.showModal = true
    },
    handleUploadLogo (response) {
      let url = response.data.url
      this.$set(this.formValidate, 'app_icon', url)
    },
    handleFormatError (file) {
      this.$Notice.warning({
        title: this.$t('document_format_error'),
        desc: this.$t('document_format_error_content')
      })
    },
    handleMaxSize (file) {
      this.$Notice.warning({
        title: this.$t('file_too_large'),
        desc: this.$t('file_too_large_error_content')
      })
    },
    // 生成32随机key
    randomWord (randomFlag, min, max) {
      let str = ''
      let range = min
      const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
      // 随机产生
      if (randomFlag) {
        range = Math.round(Math.random() * (max - min)) + min
      }
      for (var i = 0; i < range; i++) {
        let pos = Math.round(Math.random() * (arr.length - 1))
        str += arr[pos]
      }
      return strr
    },
    addAppFun () {
      this.$refs['formValidate'].validate((val) => {
        if (!val) {
          this.$Message.error(this.$t('input_error_please_check_again'))
          return
        }
        this.$Modal.confirm({
          title: this.$t('operation_confirm'),
          content: (() => {
            return this.formValidate.app_key
              ? this.$t('Whether_to_alter_the_app')
              : this.$t('Whether_to_create_a_new_app')
          })(),
          onOk: () => {
            this.doAddNewApp()
            this.resetForm()
          }
        })
      })
    },
    doAddNewApp () {
      const formdata = new FormData()
      formdata.append('access_token', this.token)
      formdata.append('appName', this.formValidate.appName)
      formdata.append('app_owner', this.formValidate.app_owner)
      formdata.append('app_icon', this.formValidate.app_icon)
      formdata.append('apply_reason', this.formValidate.apply_reason)
      if (this.formValidate.app_key) {
        formdata.append('app_key', this.formValidate.app_key)
        EditApp(formdata).then(res => {
          if (res.data.is_updated) {
            this.$emit('updated')
            this.$Message.success(this.$t('successfully_altered'))
            this.showModal = false
          }
        })
      } else {
        AddApp(formdata).then(res => {
          if (res.data.is_add) {
            this.$emit('updated')
            this.$Message.success(this.$t('successfully_created'))
            this.showModal = false
          }
        })
      }
    }
  }
}
</script>

<style  lang="scss" scoped>
.application {
  .ivu-form-item {
    padding-left: 15px;
  }
  &__h{
    margin-bottom: 30px;
  }
  >>>.formitem .ivu-form-item .ivu-form-item-required{
    display: flex;
    flex-direction: column;
  }
  >>> .ivu-form-item-content{
    margin-left: 0;
  }
  .formitem{
    display: flex;
  }
  .ivu-form-item-label{
    width:100vh;
  }

  .flexbox {
    display: flex;
    align-items: flex-end;
    .app_icon {
      width: 100px;
      height: 100px;
      object-fit: cover;
      margin-right: 15px;
      border-radius: 3px;
      border: #e4e4e6 1px solid;
    }
  }
  .tips {
    padding: 0 16px;
    color: #888;
  }
}
/deep/.ivu-form-item-content{
  margin-left: 0!important;
}
</style>
