<template>
  <page-layout :title="isEdit ? '编辑用户' : '新建用户'">
    <a-card>
      <a-col
        :xs="{span: 24}"
        :sm="{span: 20}"
        :xl="{span: 16}">
        <a-form
          :form="form"
          @submit="handleSubmit">
          <a-divider v-if="isEdit">基本信息</a-divider>
          <a-form-item
            v-if="isEdit"
            label="ID"
            v-bind="layout">
            {{id}}
          </a-form-item>
          <a-form-item
            v-if="isEdit"
            label="加入日期"
            v-bind="layout">
            {{account.date_joined}}
          </a-form-item>
          <a-form-item
            v-if="isEdit"
            label="上次登录时间"
            v-bind="layout">
            {{account.last_login || '无'}}
          </a-form-item>
          <a-divider v-if="isEdit">修改信息</a-divider>
          <a-form-item
            label="用户名"
            v-bind="layout">
            <a-input
              type="text"
              v-decorator="[
                'username',
                {
                  rules: [
                    {required: true, message: '请输入用户名'},
                    {validator: usernameValidator, message: '用户名重复'}
                  ],
                  validateTrigger: 'blur',
                  initialValue: isEdit ? account.username : ''
                 }
              ]">
            </a-input>
          </a-form-item>
          <a-form-item
            label="密码"
            v-bind="layout">
            <a-tooltip v-if="isEdit" title="不修改留空即可" placement="right">
              <a-input
                type="password"
                v-decorator="[
                'password',
                {
                  rules: [
                    {required: !isEdit, message: '请输入密码'},
                    {min: 8, message: '密码长度在8个字符以上'},
                    {validator: notAllNumberValidator, message: '密码不能全为数字'},
                  ],
                  validateTrigger: 'blur'
                 }
              ]">
              </a-input>
            </a-tooltip>
            <a-input
              v-else
              type="password"
              v-decorator="[
                'password',
                {
                  rules: [
                    {required: !isEdit, message: '请输入密码'},
                    {min: 8, message: '密码长度在8个字符以上'},
                    {validator: notAllNumberValidator, message: '密码不能全为数字'},
                  ],
                  validateTrigger: 'blur'
                 }
              ]">
            </a-input>
          </a-form-item>
          <a-form-item
            label="确认密码"
            v-bind="layout">
            <a-input
              type="password"
              v-decorator="[
                'password_retry',
                {
                  rules: [
                    {required: !isEdit, message: '请再次输入密码'},
                    {min: 8, message: '密码长度在8个字符以上'},
                    {validator: samePasswordValidator, message: '密码不能全为数字'},
                  ],
                  validateTrigger: 'blur'
                 }
              ]">
            </a-input>
          </a-form-item>
          <a-form-item
            label="角色"
            v-bind="layout">
            <a-tooltip title="只有管理员才能够进入Booking Admin" placement="right">
              <a-select
                v-decorator="[
                  'role',
                  {
                    rules: [
                      {required: true, message: '请选择角色'},
                    ],
                    validateTrigger: 'blur',
                    initialValue: isEdit ? account.role : ''
                  }
                ]">
                <a-select-option v-for="item in roleList" :value="item.id">{{item.name}}</a-select-option>
              </a-select>
            </a-tooltip>
          </a-form-item>
          <a-form-item
            label="职员"
            v-bind="layout">
            <a-tooltip title="标识是否能够进入Admin" placement="right">
              <a-radio-group
                v-decorator="[
                  'is_staff',
                  {
                    rules: [
                      {required: true, message: '请选择'},
                    ],
                    validateTrigger: 'blur',
                    initialValue: isEdit ? account.is_staff : false
                  }
                ]">
                <a-radio :value="true">是</a-radio>
                <a-radio :value="false">否</a-radio>
              </a-radio-group>
            </a-tooltip>
          </a-form-item>
          <a-form-item
            label="超级管理员"
            v-bind="layout">
            <a-tooltip title="标识是否拥有全部权限" placement="right">
              <a-radio-group
                v-decorator="[
                  'is_superuser',
                  {
                    rules: [
                      {required: true, message: '请选择'},
                    ],
                    validateTrigger: 'blur',
                    initialValue: isEdit ? account.is_superuser : false
                  }
                ]">
                <a-radio :value="true">是</a-radio>
                <a-radio :value="false">否</a-radio>
              </a-radio-group>
            </a-tooltip>
          </a-form-item>
          <a-form-item
            label="状态"
            v-bind="layout">
            <a-tooltip title="标识是否被禁用或删除" placement="right">
              <a-radio-group
                v-decorator="[
                  'is_active',
                  {
                    rules: [
                      {required: true, message: '请选择'},
                    ],
                    validateTrigger: 'blur',
                    initialValue: isEdit ? account.is_active : true
                  }
                ]">
                <a-radio :value="true">有效</a-radio>
                <a-radio :value="false">无效</a-radio>
              </a-radio-group>
            </a-tooltip>
          </a-form-item>
          <a-form-item
            label="邮箱"
            v-bind="layout">
            <a-input
              type="email"
              v-decorator="[
                'email',
                {
                  rules: [
                    {pattern: /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/, message: '请输入正确的邮箱格式'}
                  ],
                  validateTrigger: 'blur',
                  initialValue: isEdit ? account.email : ''
                }
              ]">
            </a-input>
          </a-form-item>
          <a-form-item
            label="积分"
            v-bind="layout">
            <a-input
              type="number"
              addonAfter="分"
              v-decorator="[
                'point',
                {
                  rules: [
                    {pattern: /^[1-9]\d*$/, message: '请输入大于1的正整数'}
                  ],
                  validateTrigger: 'blur',
                  initialValue: isEdit ? account.point : 20
                }
              ]">
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-button
              type="primary"
              html-type="submit"
              style="float: right; margin: 0 0 0 4px;">
              保存
            </a-button>
            <a-popconfirm title="是否要删除？" @confirm="handleDelete" v-if="isEdit && account.id !== $store.getters.userid">
              <a-button type="danger" style="float: right; margin: 0 4px;">
                删除
              </a-button>
            </a-popconfirm>
            <a-popconfirm title="是否要取消？" @confirm="$router.go(-1)">
              <a-button style="float: right; margin: 0 4px;">
                取消
              </a-button>
            </a-popconfirm>

          </a-form-item>
        </a-form>
      </a-col>
    </a-card>
  </page-layout>
</template>

<script>
  import PageLayout from '../../components/page/PageLayout'
  import api from '../../api/account'

  export default {
    name: 'AccountDetail',
    components: {
      PageLayout
    },
    props: {
      id: String,
    },
    data () {
      return {
        layout: {
          'label-col': { span: 6 },
          'wrapper-col': { span: 18 }
        },
        form: this.$form.createForm(this),
        roleList: [],
        account: {}
      }
    },
    mounted () {
      api.getRoleList()
        .then(data => {
          this.roleList = data
          if (this.isEdit) this.getData()
        })
    },
    methods: {
      getData () {
        api.getUser(this.id)
          .then(data => {
            this.account = data
          })
      },
      handleSubmit (e) {
        e.preventDefault()
        this.form.validateFields((error, data) => {
          if (!error) {
            if (this.isEdit) {
              api.updateUser(this.account.id, data)
                .then(data => {
                  this.$notification.success({
                    message: '成功',
                    description: `更新用户${this.account.id}成功`,
                    key: 'SUCCESS'
                  })
                  this.$router.push({ name: 'account' })
                })
            } else {
              api.createUser(data)
                .then(data => {
                  this.$notification.success({
                    message: '成功',
                    description: `新建用户${this.account.id}成功`,
                    key: 'SUCCESS'
                  })
                  this.$router.push({ name: 'account' })
                })
            }
          }
        })
      },
      handleDelete () {
        api.deleteUser(this.id)
          .then(data => {
            this.$notification.success({
              message: '成功',
              description: `删除用户${this.account.id}成功`,
              key: 'SUCCESS'
            })
            this.$router.push({ name: 'account' })
          })
      },
      usernameValidator (rule, value, callback) {
        if ((value && !this.isEdit) || (value && this.isEdit && (value !== this.account.username))) {
          api.checkUsername(value)
            .then(data => {
              if (data) {
                callback('username is duplicated')
                return false
              } else {
                callback()
                return true
              }
            })
        } else {
          callback()
          return true
        }
      },
      notAllNumberValidator (rule, value, callback) {
        if (/^[0-9]+.?[0-9]*$/.test(value)) {
          callback('password cant be all numbers')
          return false
        }
        callback()
        return true
      },
      samePasswordValidator (rule, value, callback) {
        if (value && (value !== this.form.getFieldValue('password'))) {
          callback('two passwords are different')
          return false
        }
        callback()
        return true
      }
    },
    computed: {
      isEdit () {
        return this.$route.path.split('/').pop() === 'edit'
      }
    }
  }
</script>

<style scoped lang="less">

</style>