<template>
  <div>
    <a-modal
      centered
      class="userEdit-modal"
      :footer="null"
      :maskClosable="false"
      :title="titleText"
      v-model="isshow"
      @cancel="isshow=false"
      :width="800">
      <a-spin :spinning="spinning" tip="Loading...">
        <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="24">
            <a-col :span="12">
              <a-form-model-item label="用户账号" prop="loginName">
                <a-input id="userEdit-loginName" v-model.trim="form.loginName":maxLength="50" allowClear placeholder="请输入用户账号(最多50个字符)"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="12" v-if="!(nowData&&nowData.id)">
              <a-form-model-item label="用户密码" prop="password">
                <a-input
                  id="userEdit-password"
                  type="password"
                  v-model.trim="form.password"
                  :maxLength="16"
                  allowClear
                  placeholder="请输入用户密码(最多16个字符)"/>
              </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-loginFlag" name="radioGroup" v-model="form.loginFlag" placeholder="请选择状态">
                  <a-radio :value="1" id="userEdit-loginFlag1">是</a-radio>
                  <a-radio :value="0" id="userEdit-loginFlag0">否</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
                  show-search
                  :filter-option="filterOption"
                  placeholder="请选择角色"
                  id="userSyncEdit-roleNames"
                  allowClear
                  v-model="form.roleNames"
                  mode="multiple">
                  <a-select-option v-for="item in roleList" :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-cancel" :style="{ marginRight: '10px' }" @click="isshow=false">取消</a-button>
            <a-button id="userEdit-save" type="primary" @click="handleSubmit()">保存</a-button>
          </a-form-model-item>
        </a-form-model>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable, VSelect } from '@/components'
// 接口
import { getRoleList, saveUserPower } from '@/api/power-user.js'
export default {
  name: 'UserModal',
  mixins: [commonMixin],
  components: { STable, VSelect },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    nowData: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data () {
    return {
      titleText: '新增用户', // 弹出标题
      spinning: false,
      isshow: this.visible, // 打开关闭弹窗
      roleList: [], // 角色列表数据
      // form表单label布局
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 }
      },
      // 提交参数
      form: {
        name: '', // 用户名称
        phone: '', // 手机号码
        loginName: '', // 用户账号
        password: '', // 用户密码
        sex: undefined, // 性别
        loginFlag: '', // 状态
        roleNames: [], // 角色
        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: '用户账号为数字或大小写字母组成!' } ],
        password: [ { required: true, message: '请输入用户密码', trigger: 'blur' }, { pattern: /^[0-9A-Za-z]{6,16}$/, message: '用户密码为6到16位数字或大小写字母组成!' } ],
        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(',')
          if (_this.nowData && _this.nowData.id) {
            params.id = _this.nowData.id
          } else {
            delete params.id
          }
          _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 {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 获取角色列表接口
    getRoleList () {
      getRoleList().then(res => {
        if (res.status == 200) {
          this.roleList = res.data
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    }
  },
  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 = []
        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)
            this.form.roleNames = this.nowData.roleIds.split(',')
            if (!this.nowData.roleIds) {
              this.nowData.roleIds = ''
              this.form.roleNames = []
            }
            this.form.loginFlag = Number(this.nowData.loginFlag)
          }
        }
      },
      deep: true
    }
  }
}
</script>
