<template>
  <a-modal  :width="1000"
            height="auto"
            :visible="addVisible" @cancel="handleCancelClick"
            cancelText="取消" okText="提交" @ok="handleSubmit">
    <a-form-model
        class="a-form-model"
        ref="ruleForm"
        :model="itemAddData"
        :rules="validateRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        @validate="validate">
      <div class="a-form-model-item-view">
        <a-form-model-item has-feedback class="a-form-model-item" ref="userName" label="用户名" prop="userName">
          <a-input
              placeholder="请输入用户名"
              v-model="itemAddData.userName"
              @blur="handleUserNameBlur"
          />
        </a-form-model-item>
        <a-form-model-item has-feedback class="a-form-model-item" ref="phoneNumber" label="手机号" prop="phoneNumber">
          <a-input
              placeholder="请输入手机号"
              v-model="itemAddData.phoneNumber"
              @blur="
                   () => {
                     $refs.phoneNumber.onFieldBlur();
                   }"
          />
        </a-form-model-item>
      </div>
      <div class="a-form-model-item-view">
        <a-form-model-item has-feedback class="a-form-model-item" ref="authRoleId" label="角色" prop="authRoleId">
          <!--mode="multiple"-->
          <!--:allowClear="true"-->
          <a-select
              style="width: 100%"
              @change="handleAuthRoleChange"
              v-model="itemAddData.authRoleId"
              :defaultValue="itemAddData.authRoleId"
              placeholder="请选择角色">
            <a-select-option v-for="r in roleDataList" :key="r.authRoleId">{{r.roleName}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item has-feedback class="a-form-model-item" ref="departmentId" label="部门" prop="departmentId">
          <a-tree-select
              :allowClear="true"
              :dropdownStyle="{ maxHeight: '500px', overflow: 'auto' }"
              :treeData="departmentTreeData"
              v-model="itemAddData.departmentId"
              :defaultValue="itemAddData.departmentId"
              placeholder="请选择部门"
              @change="onDepartmentChange">
          </a-tree-select>
        </a-form-model-item>
      </div>
      <div class="a-form-model-item-view">
        <a-form-model-item has-feedback class="a-form-model-item" ref="lockStatus" label="锁定状态" prop="lockStatus">
          <a-radio-group v-model="itemAddData.lockStatus" :defaultValue="itemAddData.lockStatus" >
            <a-radio :value="1">锁定</a-radio>
            <a-radio :value="2">有效</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item has-feedback class="a-form-model-item" ref="realName" label="真实姓名" prop="realName">
          <a-input
              placeholder="请输入真实姓名"
              v-model="itemAddData.realName"
              @blur="
                   () => {
                     $refs.realName.onFieldBlur();
                   }"
          />
        </a-form-model-item>
      </div>
      <div class="a-form-model-item-view">
        <a-form-model-item has-feedback class="a-form-model-item" ref="password" label="登陆密码" prop="password">
          <a-input
              type="password"
              placeholder="请输入密码"
              v-model="itemAddData.password"
              @blur="
                   () => {
                     $refs.realName.onFieldBlur();
                   }"
          />
        </a-form-model-item>
      </div>
    </a-form-model>
  </a-modal>
</template>
<script>
import baseUtils from '@/utils/baseUtils'
import moment from 'moment'
const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 18 }
}
export default {
  name: 'ItemAdd',
  components:{
    baseUtils,
    moment:moment
  },
  props: {
    addVisible: {
      default: false
    }
  },
  data () {
    return {
      sketchList:[], //用户简略信息集合
      corpRegionOption:[], //地区
      submitUrl:'api/v1/authUser/addAuthUser', //提交URL
      itemAddData: { //数据新增
        userName: '',
        phoneNumber:''
      },
      timeFormat:'YYYY-MM-DD', //时间格式
      //校验规则
      validateRules: {
        userName: [
          { required: true,  message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 100, message: '用户名全称长度为1-100', trigger: 'blur' },
        ],
        realName: [
          { required: true,  message: '请输入真实姓名', trigger: 'blur' },
          { min: 1, max: 10, message: '真实姓名全称长度为1-10', trigger: 'blur' },
        ],
        phoneNumber: [
          { required: true,  message: '请输入手机号', trigger: 'blur' },
          { min: 1, max: 11, message: '手机号全称长度为1-11', trigger: 'blur' },
          { pattern: '^0?(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8}$', message: '请输入格式正确的手机号',trigger: 'blur'},
        ],
        authRoleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
        departmentId: [{ required: true, message: '请选择部门', trigger: 'change' }],
        sketchOtherId: [{ required: true, message: '请选择地区', trigger: 'change' }],
        lockStatus:{ required: true, message: '请选择锁定状态', trigger: 'change' },
        authUserId: [
          { required: true, message: '请选择关联人员', trigger: 'change' }
        ],
        type: [
          {
            type: 'array',
            required: true,
            message: 'Please select at least one activity type',
            trigger: 'change',
          },
        ],
      },
      loading: false,
      roleDataList: [],
      departmentTreeData: [],
      labelCol: {
        span: 5,
      },
      wrapperCol: {
        span: 15,
      },
      formItemLayout,
      defaultPassword: '123456',
      form: this.$form.createForm(this),
      validateStatus: '',
      help: ''
    }
  },
  methods: {
    handleRegionChange(value){
      this.sketchList.splice(0,this.sketchList.length)
      let item = {
        sketchOtherId:value,
        sketchOtherType:'REGION'
      }
      this.sketchList.push(item)

      console.log('this.sketchList : '+JSON.stringify(this.sketchList))
    },
    handleAuthRoleChange(value){
      this.itemAddData.authRoleId = value
    },
    validate(successStatus,object){
      console.log(successStatus)
      console.log(object)
    },
    resetForm() { //重置表单
      this.$refs.ruleForm.resetFields();
    },
    handleCancelClick(){
      this.reset();
      this.clearAll();
      this.$emit("close")
    },
    reset () {
      this.loading = false
      this.$refs.ruleForm.resetFields();
    },
    onClose () {
      this.loading = false;
      this.clearAll();
      this.$emit('close')
    },
    clearAll(){
      console.log('clearAll')
      this.departmentTreeData.splice(0,this.departmentTreeData.length);
      this.roleDataList.splice(0,this.roleDataList.length);
    },
    onDepartmentChange (value) {
      console.log(JSON.stringify(value))
      this.departmentId = value
    },
    handleSubmit () { //处理提交
      let that = this
      that.$refs.ruleForm.validate(valid => {
        if (valid) {
          if(this.sketchList.length>0){
            this.itemAddData.sketchList = this.sketchList
          }
          this.loading = true
          //从表单里面拿到值
          this.$postBodyRequest(this.submitUrl, {
            ...this.itemAddData
          }).then((res) => {
            let data = res.data
            console.log(JSON.stringify(data))
            if(data && data.code == 200){
              this.loading = false
              this.resetForm()
              this.clearAll();
              this.$emit('success')
            }
          }).catch((err) => {
            this.$message.error('新增出现错误')
            this.loading = false
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleUserNameBlur () {
      let userName = this.itemAddData.userName.trim()
      if (userName.length) {
        if (userName.length > 100) {
          this.validateStatus = 'error'
          this.help = '用户名不能超过100个字符'
        } else if (userName.length < 2) {
          this.validateStatus = 'error'
          this.help = '用户名不能少于2个字符'
        } else {
          this.validateStatus = 'validating'
          this.$get(`api/v1/authUser/checkUserName?userName=`+userName).then((r) => {
            if (r.data) {
              this.validateStatus = 'success'
              this.help = ''
            } else {
              this.validateStatus = 'error'
              this.help = '抱歉，该用户名已存在'
            }
          })
        }
      } else {
        this.validateStatus = 'error'
        this.help = '用户名不能为空'
      }
    }
  },
  watch: {
    addVisible () {
      if (this.addVisible) {
        this.$postBodyRequest('api/v1/authRole/queryAuthRoleByPage',{
          needAll:true,
          optionalStatus: '01' //是否可选 01 是 02 否 只查询可选的角色
        }).then((r) => {
          this.roleDataList = r.data.data.rows
        })
        this.$get('api/v1/authDepartment/queryAllDepartmentTree').then((r) => {
          let data = r.data.data
          if(data){
            console.log('data : '+JSON.stringify(data))
            if(!baseUtils.isNull(data.children) && data.children.length > 0 ){
              this.departmentTreeData = data.children
            }
          }
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
/*使用~@引入*/
@import "~@/utils/utils.less";
</style>
