<template>
  <div>
    <a-spin :spinning="spinning" tip="Loading...">
      <a-modal
        centered
        class="userEdit-modal"
        :footer="null"
        :maskClosable="false"
        :title="titleText"
        v-model="isshow"
        @cancel="isshow=false"
        :width="800">
        <a-form-model
          id="userEdit-form"
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
        >
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-model-item label="用户名称" prop="name">
                <a-input
                  id="userEdit-name"
                  v-model.trim="form.name"
                  @change="filterEmpty"
                  :maxLength="30"
                  allowClear
                  placeholder="请输入用户名称(最多30个字符)"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="手机号码" prop="phone">
                <a-input id="userEdit-phone" v-model.trim="form.phone":maxLength="11" allowClear placeholder="请输入手机号码"/>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="20">
            <a-col :span="24">
              <a-form-model-item label="用户账号" prop="loginName" :label-col="{span: 3}" :wrapper-col="{span: 20}">
                <a-input id="userEdit-loginName" v-model.trim="form.loginName":maxLength="50" allowClear placeholder="请输入用户账号(最多50个字符)"/>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <!-- 性别 -->
            <a-col :span="12">
              <a-form-model-item label="性别" prop="sex">
                <v-select
                  ref="sex"
                  id="userEdit-sex"
                  code="SEX"
                  v-model="form.sex"
                  placeholder="请选择性别"
                  allowClear ></v-select>
              </a-form-model-item>
            </a-col>
            <!-- 状态 -->
            <a-col :span="12">
              <a-form-model-item label="状态" prop="loginFlag">
                <a-radio-group id="userEdit-flag" name="radioGroup" v-model="form.loginFlag" placeholder="请选择状态">
                  <a-radio :value="1" id="userEdit-flag1">是</a-radio>
                  <a-radio :value="0" id="userEdit-flag0">否</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item label="角色" prop="roleNames" :label-col="{span: 3}" :wrapper-col="{span: 20}">
                <a-select
                  placeholder="请选择角色"
                  id="userSyncEdit-roleNames"
                  allowClear
                  v-model="form.roleNames"
                  mode="multiple">
                  <a-select-option v-for="item in roleList" :id="item.id" :key="item.id" :value="item.id" :disabled="item.isEnable == '0' ? true : false">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item label="备注" prop="remarks" :label-col="{span: 3}" :wrapper-col="{span: 20}">
                <a-textarea id="userEdit-remarks" v-model.trim="form.remarks":maxLength="500" allowClear placeholder="请输入备注(最多500个字符)"/>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-form-model-item :label-col="{span: 0}" :wrapper-col="{span: 24}" style="text-align: center;">
            <a-button id="userEdit-save" type="primary" @click="handleSubmit()" :style="{ marginRight: '8px' }">保存</a-button>
            <a-button id="userEdit-cancel" :style="{ marginLeft: '8px' }" @click="isshow=false">取消</a-button>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </a-spin>
  </div>
</template>

<script>
import { STable, VSelect } from '@/components'
import { getRoleList, saveUserPower } from '@/api/power-user.js'
export default {
  name: 'UserModal',
  components: {
    STable, VSelect
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    nowData: { // 当前编辑数据
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data () {
    return {
      spinning: false,
      titleText: '新增用户',
      isshow: this.visible,
      roleList: [],
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 }
      },
      form: {
        name: '', // 用户名称
        phone: '', // 手机号码
        loginName: '', // 用户账号
        sex: undefined, // 性别
        loginFlag: '', // 状态
        roleNames: undefined, // 角色
        remarks: ''// 备注
      },
      rules: {
        name: [ { required: true, message: '请输入用户名称', trigger: 'blur' }, { pattern: '^[^<|>]{1,30}$', message: '请输入不含<或>的字符，最多30个字符' } ],
        phone: [ { required: true, message: '请输入手机号码', trigger: 'blur' }, { pattern: /^[1][0-9]{10}$/, message: '请输入正确的手机号码!' } ],
        loginName: [ { required: true, message: '请输入用户账号', trigger: 'blur' }, { pattern: /^[0-9A-Za-z]+$/, message: '用户账号为数字或大小写字母组成!' } ],
        sex: [ { required: true, message: '请选择性别', trigger: 'change' } ],
        loginFlag: [ { required: true, message: '请选择状态', trigger: 'change' } ],
        roleNames: [ { required: true, message: '请选择角色', trigger: 'change' } ]
      }
    }
  },
  methods: {
    // 过滤空格
    filterEmpty () {
      let str = this.form.name
      str = str.replace(/\ +/g, '')
      str = str.replace(/[ ]/g, '')
      str = str.replace(/[\r\n]/g, '')
      this.form.name = str
    },
    // 保存提交
    handleSubmit () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(_this.form))
          params.roleNames = _this.form.roleNames.join(',')
          params.id = _this.nowData && _this.nowData.id ? _this.nowData.id : null
          params.ownerOrgFlag = _this.nowData && _this.nowData.ownerOrgFlag
          _this.spinning = true
          saveUserPower(params).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$emit('refresh')
              setTimeout(function () {
                _this.isshow = false
                _this.spinning = false
              }, 300)
            } else {
              _this.spinning = false
            }
          })
        } else {
          return false
        }
      })
    },
    // 获取角色列表接口
    getRoleList () {
      getRoleList().then(res => {
        if (res.status == 200) {
          this.roleList = res.data
        } else {
          this.$message.warning(res.message)
        }
      })
    }
  },
  watch: {
    visible (newValue, oldValue) {
      this.isshow = newValue
    },
    isshow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        // 重置
        this.$refs.ruleForm.resetFields()
        this.form.name = ''
        this.form.phone = ''
        this.form.loginName = ''
        this.form.sex = undefined
        this.form.loginFlag = ''
        this.form.roleNames = undefined
        this.form.remarks = ''
        this.titleText = '新增用户'
      } else {
        this.getRoleList()
      }
    },
    nowData: {
      handler (newValue, oldValue) {
        if (this.isshow && newValue) {
          if (this.nowData.id) { //  编辑
            this.titleText = '编辑用户'
            this.form = Object.assign({}, this.nowData)
            if (this.nowData.roleIds) {
              this.form.roleNames = this.nowData.roleIds.split(',')
            }
            this.form.loginFlag = Number(this.nowData.loginFlag)
          }
        }
      },
      deep: true
    }
  }
}
</script>
