<template>
  <div class="application">
    <div class="application__h">
      <h2 class="application__h--p">{{$t('app_modify')}}</h2>
    </div>
     <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="150" class="application__form">
        <FormItem class="formitem" :label="$t('app_modify')+'：'" 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" disabled :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" />
            <Button class="formitem__btn" type="primary" @click="getRandomWord">{{$t('randomly_generate')}}</Button>
        </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="this.$t('edit_app_icon')"
            v-model="modal"
            width="50%"
            :closable="true">
              <cropper
              ref="info"
              :crop-button-text="this.$t('confirm')"
              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" 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-if="apiLimit === '1'" :label="$t('api_request_times')+'：'" prop="limit">
          <Input clearable v-model="formValidate.limit" :placeholder="$t('api_request_times')" style="width: 300px" />
          <p>{{$t('app_limit_tips')}}</p>
        </FormItem>
        <FormItem class="formitem" :label="$t('verification')+'：'">
            <Select clearable v-model="formValidate.audit" style="width:300px">
              <Option v-for="item in auditArr" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
        </FormItem>
        <FormItem class="formitem" :label="$t('apply_reason')+'：'">
          <Input clearable v-model="formValidate.apply_reason" :placeholder="$t('apply_reason')" 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" />
          <div class="formitem__info">
            <p class="formitem__info-p">{{$t('cur_developer')}}：{{ devname }}</p>
            <router-link :to="{name:'userList'}" target="_blank">
              <p>{{$t('view_other_developers')}}</p>
            </router-link>
          </div>
        </FormItem>
        <FormItem class="formitem" :label="$t('allow_ips')+'：'">
          <Input clearable v-model="formValidate.allow_ips" :placeholder="$t('allow_ips')" style="width: 300px" />
          <p>{{$t('allow_ips_tips')}}</p>
        </FormItem>
    <div class="application__btn">
        <Button type="primary" @click="updateAppFun">{{$t('save')}}</Button>
    </div>
    </Form>
  </div>
</template>

<script>
import Cropper from '@/components/cropper'
import { Upload } from '@/api/user'
import { GetAppInfo, EditApp, GetAppSecret } from '@/api/application'
import { getToken } from '@/libs/util'
export default {
  components: {
    Cropper
  },
  data () {
    return {
      modal: false,
      queryName: '',
      queryId: '',
      devname: '',
      headImgUrl: '',
      token: getToken(),
      formValidate: {
        name: '',
        secret: '',
        key: '',
        limit: '100',
        allow_ips: '',
        audit: 0, // 默认状态
        apply_reason: '',
        app_uid: 0
      },
      auditArr: [
        {
          value: 0,
          label: this.$t('to_be_reviewed')
        },
        {
          value: 1,
          label: this.$t('passed')
        },
        {
          value: 2,
          label: this.$t('not_passed')
        }
      ],
      apiLimit: '0',
      allow_ips: '',
      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 }
        ],
        limit: [
          { required: true, message: this.$t('api_limit_input_warning'), trigger: 'blur' },
          { message: this.$t('input_integer_warning'), pattern: /^\+?[0-9]*$/ }
        ]
      }
    }
  },
  created () {
    this.getSingleApp()
  },
  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
    },
    changeLimit (data) {
      this.apiLimit = data
    },
    /* changeAudit (data) {
      console.log(data, '----')
    }, */
    getSingleApp () {
      this.queryName = this.$route.query.name
      this.queryId = this.$route.query.id
      this.GetAppSecretFun()
      const formdata = new FormData()
      formdata.append('access_token', this.token)
      formdata.append('id', this.queryId)
      GetAppInfo(formdata).then(res => {
        if (res.ret === 200) {
          this.devname = res.data.info.uidName
          this.formValidate.key = res.data.info.app_key
          this.formValidate.name = res.data.info.app_name
          this.formValidate.app_uid = res.data.info.uid
          this.formValidate.audit = res.data.info.verify_status
          this.formValidate.apply_reason = res.data.info.apply_reason
          this.formValidate.allow_ips = res.data.info.allow_ips
          this.headImgUrl = res.data.info.app_icon
          if (res.data.info.app_limit === 0) {
            this.apiLimit = '0'
          } else {
            this.apiLimit = '1'
            this.formValidate.limit = res.data.info.app_limit + ''
          }
        } else {
          this.$Message.error(res.msg)
        }
      })
    },
    GetAppSecretFun () {
      this.queryId = this.$route.query.id
      const formdata = new FormData()
      formdata.append('access_token', this.token)
      formdata.append('id', this.queryId)
      GetAppSecret(formdata).then(res => {
        this.formValidate.secret = res.data.app_secret
      })
    },
    getRandomWord () {
      this.formValidate.secret = this.randomWord(false, 32)
    },
    // 生成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
      // this.formValidate.secret = str
    },
    updateAppFun () {
      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('modify_app_secret_tips'),
          onOk: () => {
            this.doAddNewApp()
          }
        })
      })
    },
    doAddNewApp () {
      this.queryId = this.$route.query.id
      const formdata = new FormData()
      formdata.append('access_token', this.token)
      formdata.append('app_name', this.formValidate.name)
      formdata.append('uid', this.formValidate.app_uid)
      formdata.append('app_secret', this.formValidate.secret)
      formdata.append('verify_status', this.formValidate.audit)
      if (this.headImgUrl) {
        formdata.append('app_icon', this.headImgUrl)
      }
      if (this.formValidate.apply_reason) {
        formdata.append('apply_reason', this.formValidate.apply_reason)
      }
      if (this.apiLimit !== '0') {
        formdata.append('app_limit', this.formValidate.limit)
      } else {
        formdata.append('app_limit', 0)
      }
      formdata.append('id', this.queryId)
      formdata.append('allow_ips', this.formValidate.allow_ips)
      EditApp(formdata).then(res => {
        if (res.data.is_update) {
          this.$Message.success(this.$t('successfully_altered'))
          this.$router.push({ name: 'applicationList' })
        } else {
          this.$Message.error(this.$t('nothing_altered'))
        }
      })
    }
  }
}
</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: 30px;
    &--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__btn{
  margin-left: 20px;
}
.formitem__info{
  display: flex;
  &-p{
    margin-right:5px;
  }
}
.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>
