<template>
  <div class="application">
    <div class="application__h">
      <p class="application__h--p">{{$t('create_new_app')}}</p>
    </div>
     <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="150" class="application__form">
        <FormItem class="formitem" :label="$t('app_name')+'：'" prop="name">
            <Input clearable v-model="formValidate.name" :placeholder="$t('please_input_the_app_name')"   style="width: 300px;" />
        </FormItem>
        <FormItem class="formitem" :label="$t('app_key')+'：'" prop="key">
            <Input clearable v-model="formValidate.key" :placeholder="$t('app_key_input_tips')" style="width: 300px" />
        </FormItem>
        <FormItem class="formitem" :label="$t('app_secret')+'：'" prop="secret">
            <Input clearable v-model="formValidate.secret" :placeholder="$t('app_secret')" style="width: 300px" />
        </FormItem>
        <FormItem class="formitem" :label="$t('app_icon')+'：'">
          <!-- <Button class="application__h--right--btn" type="primary" @click="modal = true">选择头像</Button> -->
          <div class="formitem__icon" @click="modal = true">
            <Icon v-if="!headImgUrl" style="font-size:50px;color:#b8b7b7" type="ios-add" />
            <img v-else style="height: 100%;" :src="headImgUrl" alt="">
          </div>
          <Modal
            :title="$t('edit_app_icon')"
            v-model="modal"
            width="50%"
            :closable="true">
              <cropper
              ref="info"
              :crop-button-text="$t('submit')"
              v-if="modal"
              @transmitInfo="handleCroped"
            ></cropper>
            <div slot="footer">
              <!-- <Button type="text" size="large" @click="modalCanel">取消</Button> -->
            </div>
          </Modal>
        </FormItem>
        <FormItem class="formitem" :label="$t('whether_to_limit_api_request')+'：'">
            <Select v-model="apiLimit" clearable style="width:300px" @on-change="changeLimit">
              <Option v-for="item in limitList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
        </FormItem>
        <!-- <FormItem class="formitem" v-show="apiLimit === '1'" label="请求次数：" prop="limit"> -->
        <FormItem class="formitem" v-if="apiLimit === '1'" :label="$t('api_request_times')+'：'" prop="limit">
          <Input clearable v-model="formValidate.limit" :placeholder="$t('api_request_times')"  style="width: 300px" />
        </FormItem>
        <FormItem class="formitem" :label="$t('account_id')+'：'">
          <Input clearable v-model="formValidate.app_uid" :placeholder="$t('account_id')"  style="width: 300px" />
          <router-link :to="{name:'userList'}" target="_blank">
            <p>{{$t('view_account_id')}}</p>
          </router-link>
        </FormItem>
        <div class="application__btn">
            <Button type="primary" @click="addAppFun">{{$t('submit')}}</Button>
        </div>
    </Form>
  </div>
</template>

<script>
// import AssetsLibs from '@/components/assets-libs/assets-libs.vue'
import { Upload } from '@/api/user'
import Cropper from '@/components/cropper'
import { AddApp } from '@/api/application'
import { getToken } from '@/libs/util'
export default {
  components: {
    Cropper
  },
  data () {
    return {
      // imgUrl: [],
      modal: false,
      token: getToken(),
      name: '',
      key: '',
      secret: '',
      headImgUrl: '',
      formValidate: {
        app_icon: '',
        name: '',
        key: '',
        secret: '',
        limit: '100000',
        app_uid: ''
      },
      apiLimit: '0',
      limitList: [
        {
          value: '0',
          label: this.$t('unlimited')
        },
        {
          value: '1',
          label: this.$t('limited')
        }
      ],
      ruleValidate: {
        name: [
          { required: true, message: this.$t('please_input_the_app_name'), trigger: 'blur' }
        ],
        key: [
          { required: true, message: this.$t('app_key_input_warning'), trigger: 'blur' },
          { message: this.$t('app_key_input_error'), pattern: '^[A-Za-z0-9]+$' }
        ],
        secret: [
          { required: true, message: this.$t('app_secret_input_warning'), trigger: 'blur' }
        ],
        limit: [
          { required: true, message: this.$t('api_limit_input_warning'), trigger: 'blur' },
          { message: this.$t('input_integer_warning'), pattern: /^\+?[0-9]*$/ }
        ]
      }
    }
  },
  created () {
    this.formValidate.key = this.randomWord(false, 12)
    this.formValidate.secret = this.randomWord(false, 32)
  },
  methods: {
    handleCroped (fileData) {
      const formdata = new FormData()
      formdata.append('access_token', this.token)
      formdata.append('file', fileData.updataFile)
      // formdata.append('file_name', fileData.name)
      Upload(formdata).then((res) => {
        if (res.ret === 200) {
          this.modal = false
          this.headImgUrl = res.data.url
        } else {
          this.modal = false
          this.$Message.warning(this.$t('file_too_large_error_content'))
        }
      })
    },
    modalCanel () {
      this.modal = false
    },
    // 生成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 str
    },
    addAppFun () {
      this.$refs['formValidate'].validate((val) => {
        if (!val) {
          this.$Message.error(this.$t('wrong_form_and_fill_again'))
          return
        }
        this.$Modal.confirm({
          title: this.$t('operation_confirm'),
          content: this.$t('whether_create_new_app'),
          onOk: () => {
            this.doAddNewApp()
          }
        })
      })
    },
    doAddNewApp () {
      const formdata = new FormData()
      formdata.append('access_token', this.token)
      formdata.append('appName', this.formValidate.name)
      formdata.append('app_key', this.formValidate.key)
      formdata.append('app_secret', this.formValidate.secret)
      if (!this.formValidate.app_uid) {
        formdata.append('app_uid', 0)
      } else {
        formdata.append('app_uid', this.formValidate.app_uid)
      }
      if (this.headImgUrl) {
        formdata.append('app_icon', this.headImgUrl)
      }
      if (this.apiLimit !== '0') {
        formdata.append('app_limit', this.formValidate.limit)
      } else {
        formdata.append('app_limit', 0)
      }
      AddApp(formdata).then(res => {
        if (res.data.is_add) {
          this.$Message.success(this.$t('add_successfully'))
          this.$router.push({ name: 'applicationList' })
        } else {
          this.$Message.error(this.$t('app_key_existed'))
        }
      })
    },
    changeLimit (data) {
      this.apiLimit = data
    }
  }
}
</script>

<style  lang="scss" scoped>
.application {
  &__h{
    height:72px;
    background:rgba(255,255,255,1);
    box-shadow:0px 0px 30px 0px rgba(0,0,0,0.05);
    border-radius:10px;
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    &--p{
      font-size:16px;
      font-family:PingFangSC-Medium,PingFang SC;
      font-weight:500;
      margin-left: 30px;
      color:rgba(35,35,42,1);
    }
  }
  &__form{
    display: flex;
    text-align: left;
    flex-direction: column;
    box-shadow:0px 0px 30px 0px rgba(0,0,0,0.05);
    border-radius:10px;
    background: #fff;
    padding-top: 20px;
    &--box{
      display: flex;
      margin-top: 30px;
    }
  }
  &__btn{
    margin: 20px 150px;
  }
  >>>.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;
  }
}
/deep/.ivu-form-item-content{
  margin-left: 0!important;
}
.formitem__icon{
  width: 300px;
  height:50px;
  padding: 4px 7px;
  border-radius: 4px;
  border: 1px solid #dcdee2;
  display: flex;
  justify-content: center;
  align-items: center;
}
/deep/.ivu-form-item-content{
  margin-left: 0!important;
}
/deep/ .ivu-modal{
  top: 50px;
}
/deep/ .cropper-wrapper{
  max-height: 80%;
  .cropper-box{
    width: 80%;
    height: 300px;
    .img-box{
        width: inherit;
        height: inherit;
        img{
          width: inherit;
          height: inherit;
        }
        .cropper-container .cropper-bg{
        height: 300px;
        }
    }
  }
}
</style>
