<template>
  <a-modal  :width="1000"
            height="auto"
            :visible="editVisible" @cancel="handleCancelClick"
            cancelText="取消" okText="提交" @ok="handleSubmit">
    <a-form-model
        class="a-form-model"
        ref="ruleForm"
        :model="itemEditData"
        :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="itemEditData.userName"
              @blur="
                   () => {
                     $refs.userName.onFieldBlur();
                   }"
          />
        </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="itemEditData.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="itemEditData.authRoleId" :defaultValue="itemEditData.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="itemEditData.departmentId"
              :defaultValue="itemEditData.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="itemEditData.lockStatus" :defaultValue="itemEditData.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="itemEditData.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="itemEditData.password"
              @blur="
                   () => {
                     $refs.realName.onFieldBlur();
                   }"
          />
        </a-form-model-item>
      </div>
    </a-form-model>
  </a-modal>
</template>
<script>
import {mapState, mapMutations} from 'vuex'
import baseUtils from '@/utils/baseUtils'
import moment from 'moment'
moment.locale('en')
const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 18 }
}
export default {
  name: 'ItemEdit',
  components:{
    baseUtils:baseUtils,
    moment:moment
  },
  props: {
    editVisible: {
      default: false
    },
    itemEditData: {
      required: true,
      default: {

      }
    },
  },
  data () {
    return {
      sketchList:[], //用户简略信息集合
      corpRegionOption:[], //地区
      submitUrl:'api/v1/authUser/updateItem', //提交URL
      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',
          },
        ],
      },
      labelCol: {
        span: 5,
      },
      wrapperCol: {
        span: 15,
      },
      formItemLayout,
      departmentTreeData: [],
      roleDataList: [],
      departmentId: '', //用户绑定的部门ID
      departmentIdList:[], //如果是多部门的话采用此选项
      authUserId: '',
      sex: '',
      status: '',
      loading: false
    }
  },
  computed: {
    ...mapState({
      currentUser: state => state.account.user
    })
  },
  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))
    },
    ...mapMutations({
      setUser: 'account/setUser'
    }),
    handleAuthRoleChange(value){
      this.itemEditData.authRoleId = value
    },
    onSetupTimeOK(value){
      console.log('onOk: ', value);
    },
    moment, //时间处理
    handleFullscreen(){ //处理全屏播放

    },
    handleCancel() {
      this.previewVisible = false;
    },
    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) {
          let userName = this.itemEditData
          if(this.sketchList.length>0){
            this.itemEditData.sketchList = this.sketchList
          }
          this.loading = true
          //从表单里面拿到值
          this.$putBodyRequest(this.submitUrl, {
            ...this.itemEditData
          }).then(() => {
            this.loading = false
            this.resetForm()
            this.clearAll();
            this.reset()
            this.$emit('success')
            if (userName === this.currentUser.userName) {
              this.$get(`api/v1/authUser/${userName}`).then((r) => {
                this.setUser(r.data)
              })
            }
          }).catch(() => {
            this.$message.error('更新出现错误')
            this.loading = false
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  },

  //监测editVisible值的变动
  watch: {
    editVisible () {
      if (this.editVisible) {
        console.log(JSON.stringify(this.itemEditData))
        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(JSON.stringify(data))
            if(!baseUtils.isNull(data.children) && data.children.length > 0 ){
              this.departmentTreeData = data.children
            }
          }
        })
        this.itemEditData.password = ''
      }
    }
  }
}
</script>
<style lang="less" scoped>
@import "~@/utils/utils.less";
</style>

