<template>
  <div class="layout-no-cols">
    <el-toolbar>
      <el-button @click="$router.back()" type="primary" size="medium" round class="shadow-primary"><i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <el-button type="button" class="el-button el-button--default save" priv="Platform.User.Add||Platform.User.Edit" v-loading="confirmLoading" @click="confirm"><span><i class="fa fa-save"></i>保存</span></el-button>
    </el-toolbar>
    <div>
      <div class="detail-panel">
        <div class="panel-header">
          <div class="title">{{userId === 'new' ? '添加用户' : '编辑用户'}}</div>
        </div>
        <el-form :model="tmpUser" :rules="userRules" ref="userForm" label-width="120px" label-suffix="：" class="system-user-form" v-loading="formDataLoading">
          <el-form-item label="用户名" prop="userName">
            <el-input type="text" v-model="tmpUser.userName" auto-complete="off" :disabled="userId!='new'"></el-input>
          </el-form-item>
          <el-form-item label="真实姓名" prop="realName">
            <el-input type="text" v-model="tmpUser.realName"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="userId=='new'">
            <el-input type="password" v-model="tmpUser.password" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="repeatPassword" v-if="userId=='new'">
            <el-input type="password" v-model="tmpUser.repeatPassword" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="所属机构" prop="branchInnerCode">
            <tree-select :value.sync="tmpUser.branchInnerCode" :disabled="tmpUser.userName=='admin'&& userId!='new'" :items="branches" :style="{'display':'inline-block','width':'auto'}" :itemsOptions="treeItemsOptions" placeholder="请选择所属机构">
            </tree-select>
          </el-form-item>
          <el-form-item prop="email" label="邮箱">
            <el-input v-model="tmpUser.email"></el-input>
          </el-form-item>
          <el-form-item label="联系电话"  prop="tel">
            <el-input v-model="tmpUser.tel" placeholder="联系电话"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="tmpUser.mobile" placeholder="手机号码"></el-input>
          </el-form-item>
          <el-form-item label="所属角色" prop="roleIds">
            <el-select v-model="tmpUser.roleIds" multiple collapse-tags placeholder="请选择所属角色" style="width:350px;">
              <el-option v-for="role in roles" :key="role.roleCode" :label="role.name" :value="role.roleCode">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-switch v-model="tmpUser.status" active-value="Y" nactive-value="N"></el-switch>
          </el-form-item>
        </el-form>
      </div>
      <el-tabs class="tabs-wrap" v-model="currentTab" v-if="userId!='new'">
        <el-tab-pane :label="type.name" :name="type.code"  v-for="type in permissionTypes" :key="type.code">
          <div>
            <component v-if="currentTab==type.code" :is="type.code"  :id="userId" :type="privType"></component>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script>
import TreeSelect from '@src/components/TreeSelect.vue'
import MenuPermission from './MenuPermission.vue'
import SitePermission from './SitePermission.vue'
import APIPermission from './APIPermission.vue'
import CatalogPermission from './CatalogPermission.vue'
import DocPermission from './DocPermission.vue'
import ModulesPermission from './ModulesPermission.vue'
import BlockPermission from './BlockPermission.vue'
import util from '@src/common/util.js'
export default {
  components: {
    'tree-select': TreeSelect,
    menuPermission: MenuPermission,
    sitePermission: SitePermission,
    apiPermission: APIPermission,
    catalogPermission: CatalogPermission,
    modulesPermission: ModulesPermission,
    docPermission: DocPermission,
    blockPermission: BlockPermission
  },
  props: {
    userId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      confirmLoading: false,
      formDataLoading: false,
      branches: [],
      roles: [],
      permissionTypes: [],
      tmpUser: {},
      userRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (/^[_\w]{4,16}$/.test(value) === false) {
                callback(new Error('请输入4-16位的英文字母、数字或者下划线'))
              } else {
                callback()
              }
            },
            trigger: 'blur',
            required: true
          }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }, { min: 5, max: 18, message: '必须是5-18位的字符', trigger: 'blur' }],
        repeatPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.tmpUser.password) {
                callback(new Error('两次输入密码不一致!'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        email: [
          {
            validator: (rule, value, callback) => {
              if (
                value &&
                  /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value) ===
                    false
              ) {
                callback(new Error('请输入正确的邮箱'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        tel: [
          {
            validator: (rule, value, callback) => {
              if (value && (/^[0-9]*$/.test(value) === false || value.length > 12)) {
                callback(new Error('请填入正确的电话号码'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            validator: (rule, value, callback) => {
              if (
                value &&
                  /^13[0-9]{9}$|14[0-9]{9}|15[0-9]{9}$|18[0-9]{9}$|17[0-9]{9}$/.test(
                    value
                  ) === false
              ) {
                callback(new Error('请输入正确的手机号'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        branchInnerCode: [
          {
            required: true,
            message: '请选择所属机构',
            trigger: 'blur, change'
          }
        ]
      },
      treeItemsOptions: {
        children: 'children',
        label: 'name',
        key: 'branchInnerCode'
      },
      currentTab: 'menuPermission',
      privType: 'U'
    }
  },
  mounted() {
    this.loadBranches()
    this.loadRoles()
    this.beforeTurnToPage()
  },
  watch: {
    userId(val) {
      this.beforeTurnToPage()
    }
  },
  methods: {
    async loadBranchPermissionTypes() {
      let res = await axios.get(`/ui/permissions/id/none/type/none/types`)
      this.permissionTypes = res.data.data
    },
    async loadRoles() {
      let res = await axios.get('/ui/roles')
      this.roles = res.data.data
    },
    async loadBranches() {
      let res = await axios.get('/ui/branches')
      this.branches = res.data.data
    },
    async beforeTurnToPage() {
      if (this.userId !== 'new') {
        await this.loadBranchPermissionTypes()
      }
      this.tmpUser = {
        userName: '',
        realName: '',
        password: '',
        repeatPassword: '',
        status: 'Y',
        branchInnerCode: '',
        roleIds: [],
        lastModifyPassTime: '',
        email: '',
        tel: '',
        mobile: '',
        remark: ''
      }
      if (this.userId !== 'new') {
        await this.initFormData()
      }
    },
    async initFormData() {
      this.formDataLoading = true
      let res
      try {
        res = await axios.get(`/ui/users/${this.userId}`)
      } catch (e) {
        this.formDataLoading = false
        return
      }
      this.formDataLoading = false
      this.tmpUser = Object.assign({ roleIds: [] }, res.data.data)
      this.tmpUser.roleIds = this.tmpUser.roles.map(val => {
        return val.roleCode
      })
      this.tmpUser.addTime = util.formatDate(this.tmpUser.addTime, 'yyyy-MM-dd HH:mm:ss')
      this.currentTab = 'menuPermission'
    },
    async confirm() {
      this.confirmLoading = true
      try {
        await util.validateForm(this.$refs['userForm'])
        this.tmpUser.roleCode = this.tmpUser.roleIds.join(',')
        let res = ''
        if (this.userId === 'new') {
          res = await axios.post('/ui/users', this.tmpUser)
        } else {
          res = await axios.put(`/ui/users/${this.userId}`, this.tmpUser)
        }
        this.confirmLoading = false
        if (res.data.status === 1 && this.userId === 'new' && res.data.userName) {
          this.$router.replace({path: `/platform/user/${res.data.userName}`})
        }
        util.showResponseMessage(res.data)
      } catch (e) {
        this.confirmLoading = false
        util.showErrorMessageBox(e)
      }
    }
  }
}
</script>
<style>
.system-user-form {
  margin-top: 20px;
}
.system-user-form .el-form-item .el-input {
  width: 350px;
}
.system-user-form .el-form-item .el-select .el-input,
.system-user-form .el-form-item .select-wrap .el-input {
  width: auto;
}
</style>
