<template>
  <div class="bind-team-drawer">
    <el-drawer
      :title="$t('pages.businessDevelopment.dialog.bindAgent')"
      :visible="true"
      :before-close="handleClose"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :modal-append-to-body="true"
      :append-to-body="true"
      custom-class="drawer-auto-layout"
    >
      <div class="bind-team">

        <div class="drawer-form">
          <el-form ref="form" :model="form" :rules="formRules" label-width="80px">
            <el-form-item prop="ownUserId" :label="$t('pages.businessDevelopment.form.agent')">
              <account-input v-model="form.ownUserId" :sys-origin="sysOrigin" :placeholder="$t('pages.businessDevelopment.placeholder.agentAccount')" />
            </el-form-item>
          </el-form>
        </div>
        <div class="drawer-footer">
          <el-button @click="handleClose()">{{ $t('pages.businessDevelopment.action.close') }}</el-button>
          <el-button type="primary" :disabled="submitLoading" :loading="submitLoading" @click="submitForm">{{ $t('pages.businessDevelopment.action.save') }}</el-button>
        </div>
      </div>
    </el-drawer>

  </div>
</template>
<script>
import { teamBindBd } from '@/api/team'
import { deepClone } from '@/utils'

export default {
  name: 'BindTeam',
  props: {
    row: {
      type: Object,
      require: false,
      default: () => {}
    }
  },
  data() {
    return {
      submitLoading: false,
      sysOrigin: '',
      form: {
        ownUserId: '',
        bdUserId: ''
      }
    }
  },
  computed: {
    formRules() {
      const commonRules = [
        { required: true, message: this.$t('pages.businessDevelopment.validation.requiredField'), trigger: 'blur' }
      ]
      return {
        ownUserId: commonRules
      }
    },
    textOptTitle() {
      return this.$t('pages.businessDevelopment.dialog.bindAgent')
    }
  },
  watch: {
    row: {
      handler(newVal) {
        const _newData = deepClone(newVal)
        this.sysOrigin = _newData.userProfile.originSys
        this.form.bdUserId = _newData.userProfile.id
      },
      immediate: true
    }
  },
  methods: {
    handleClose() {
      if (this.submitLoading) {
        this.$opsMessage.warn(this.$t('pages.businessDevelopment.message.submitting'))
        return
      }
      this.$emit('close')
    },
    submitForm() {
      const that = this
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return false
        }
        that.submitLoading = true
        teamBindBd(that.form).then(res => {
          that.submitLoading = false
          that.$opsMessage.success()
          this.$emit('success')
        }).catch(er => {
          that.submitLoading = false
        })
      })
    }
  }
}
</script>

