<template>
	<div class="portalDetailWapper">
		<div class="portalDetailTitle">
			<span class="title">{{fromCenter ? '账户基本信息修改' : $route.meta.title}}</span>
			<div class="detailOperations">
				<a-button @click='handleReturn'>返回</a-button>
				<a-button type="primary" @click='handleAdd' html-type="submit">保存</a-button>
			</div>
		</div>
		<div class="portalDetailContentWapper">
			<a-form class="protalForm portalDetailContentBody" :form="searchForm">
				<div class="layoutMargin layoutPadding detailsPartSection">
					<a-row class="formItemLine">
						<a-col span="8">
							<a-form-item class="formItem" label="姓名" v-bind="colSpe">
								<a-input placeholder="请输入" v-decorator="['name',{
                  validateTrigger: 'blur', rules: [ { required: true, message : '请输入姓名' } ]
                }]" />
							</a-form-item>
						</a-col>
            <a-col span="8">
							<a-form-item class="formItem" label="手机" v-bind="colSpe">
								<a-input placeholder="请输入手机号" :disabled="fromCenter" v-decorator="['phone',{
                  validateTrigger: 'blur', rules: [ { required : true, validator: this.validatePhone } ]
                }]" />
							</a-form-item>
						</a-col>
            <a-col span="8">
							<a-form-item class="formItem" label="邮箱" v-bind="colSpe">
								<a-input placeholder="请输入" v-decorator="['mail',{
                  validateTrigger: 'blur'
                }]" />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row class="formItemLine">
            <a-col span="8">
							<a-form-item label="机构类型" v-bind="colSpe">
								<a-select placeholder="请选择" allowClear mode="multip" @select="changeType" v-decorator="['orgType', {
                  validateTrigger: 'change', rules: [ { required: true, message: '请选择机构类型！' } ]
                }]">
									<a-select-option value="2">房办</a-select-option>
                  <a-select-option value="4">区级</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
            <a-col span="8" v-if="show">
							<a-form-item label="机构名称" v-bind="colSpe" >
								<a-select placeholder="请选择" allowClear mode="multi" v-decorator="['DorgId', {
                  validateTrigger: 'change', rules: [ { required: true, message: '请选择机构名称！' } ]
                }]">
									<a-select-option v-for="(item,index) in orgnazation" :key="index" :value="item.id+'#'+item.hoName">{{item.hoName}}</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
					</a-row>
					<a-row class="formItemLine">
          	<a-col span="8" >
							<a-form-item label="角色名称" v-bind="colSpe">
								<a-select placeholder="请选择" @change="roleChange" allowClear mode="multiple"  show-search v-decorator="['notes']
                ">
									<a-select-option v-for="(item,index) in roleList" :key="index" :value="item.roleName+'#'+item.id">{{item.roleName}}</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
          </a-row>
					<div class="layoutMargin detailsPartLine">
						<a-tree class="portalRoleTree" checkable disabled :treeData="treeData" v-model="checkedKeys" />
					</div>
				</div>
			</a-form>
		</div>
	</div>
</template>

<script>

export default {
  beforeCreate() {
    this.searchForm = this.$form.createForm(this)
  },
  data() {
    return {
      show: true,
      exclusionRoleIds: [ '999999', ],
      userRoldIDsOrg: [],
      orgnazation: [],
      detail: [],
      colSpe: {
        labelCol: {
          span: 6
        },
        wrapperCol: {
          span: 15
        }
      },
      checkedKeys: [],
      treeData: [],
      administrativeRegions: [],
      roleList: [],
      roles: [],
      // 是否从个人中心-账户信息跳转过来的
      fromCenter: true,
    }
  },
  created(){
    // 从个人中心-账户信息跳过来的不能修改手机号
    this.fromCenter = !!this.$route.query.id
  },
  
  mounted() {
    this.getRoleLists()
    
    this.$ajax.get({
      url: this.$api.GET_HOS_LIST,
      params: {
        pageSize: 1000,
        sectType_in: 1
      }
    }).then(res => {
      if (res.code == '200') {
        this.orgnazation = res.data.content
      }
    })
    //如果路由有id则为修改数据-- 去获取对应数据渲染
   
    this.getTree()
    
  },
  methods: {
    // 查询权限树
    getTree() {
      this.$ajax.get({
        url: this.$api.GET_ALL_ROLE + '?isTree=true'
      }).then(res => {
        const data = res.data.content
        data.forEach((item, index) => {
          this.treeData.push(this.getTreeData(item, index))
        })
      })
    },
    // 整理权限树
    getTreeData(item, index) {
      const childrenNode = {
        title: item.permName,
        key: item.id,
        value: item.id
      }
      if (item.childList && item.childList.length) {
        childrenNode.children = []
        item.childList.forEach((subItem, subIndex) => {
          const subkey = subItem.id
          childrenNode.children.push(this.getTreeData(subItem, subkey))
        })
      }
      return childrenNode
    },
    handleReturn() {
      this.$router.back()
    },
    //添加账户
    handleAdd() {
      
      this.searchForm.validateFields((err, values) => {
        values={...values, status: 1, roleIds: ''} // 直接启用账户

        if (values.phone1 ) {
          values.phone+=','+ values.phone1 +','
        }
        if (values.phone2) {
          values.phone+= values.phone2
        }
        values.DorgId = ''
        values.orgId = this.searchForm.getFieldValue('DorgId')?this.searchForm.getFieldValue('DorgId').split('#')[0]:''
        values.orgName = this.searchForm.getFieldValue('DorgId')?this.searchForm.getFieldValue('DorgId').split('#')[1]:''
        values.notes.forEach((item, index) => {
          let key = item.split('#')[1]
          if (index == 0) {
            values.roleIds += key
            return
          }
          values.roleIds += ','+ key
        })
        values.roleNames = ''
        values.notes.forEach((ele, index) => {

          if (index == 0) {
            values.roleNames += ele.split('#')[0]
          }else{
            values.roleNames += ','+ ele.split('#')[0]
          }
        })
        if (!err) {
          if (!this.$route.query.id) {
            this.$ajax.post({
              url: this.$api.POST_ADD_USER,
              params: {...values, type: this.$route.query.personType}
            }).then(res => {
              if (res.code == '200') {
                this.$message.success('新增成功！')
                this.$router.push({
                  name: 'people'
                })
              }
            })
          } else {
            this.$ajax.put({
              url: this.$api.GET_USER_DETAIL.replace('{id}', this.$route.query.id),
              params: {...values, id: this.$route.query.id}
            }).then(res => {
              if (res.code == '200') {
                this.$message.success('修改成功！')
                this.$router.push({
                  name: 'people'
                })
              }
            })
          }
        } else {
          this.$com.getFormValidErrTips(this, err)
        }
      })
    },
    //获取当前登录账号可操作的角色列表   供多选框选择
    getRoleLists() {
      const curUserRoles = this.$store.state.userInfos.roleIds
      const sparams = {
        pageNo: 1,
        pageSize: 10000,
      }
      if (!this.$store.state.userInfos.isAllPerm ) {
        if(!!curUserRoles){
          sparams.id_in = curUserRoles
        }
      }
      this.$ajax.get({
        url: this.$api.GET_ROLE_LIST,
        params: sparams
      }).then(res => {
        this.roleList = this.$com.confirm(res, 'data.content', []) // 得到当前账号可支配全部角色  供多选框选择
        if (this.$route.query.id) {
          this.getDetail()
        }
        
      })
    },
    // 角色切换
    roleChange(item) {
      this.roles = item
      this.checkedKeys = []

      if (item.length != 0) {
        const params = item.map((it) => {
          return it.split('#')[1]
        })
        
        this.$ajax.get({
          url: this.$api.ROLE_DETAIL.replace('{id}', params.join(','))
        }).then(res => {
          if (res.code === '200') { 
            const data = res.data.content
            for(let i=0;i<data.length;i++){
              this.checkedKeys.push(data[i].id)
            }
          } else {
            this.$message.error(res.msg)
          }
        })
      }
    },
    changeType(val){
      if(val == 4){
        this.show = false
      }else{
        this.show = true
      }
    },
    //获取id 对应的账户信息
    getDetail() {
      this.$ajax.get({
        url: this.$api.GET_USER_DETAIL.replace('{id}', this.$route.query.id)
      }).then(res => {
        this.detail = res.data.content

        let {
          mail,
          name,
          username,
          dept,
          phone,
          phone1,
          phone2,
          orgId,
          addr,
          zipCode, 
          orgName,
          orgType,
          roleIds
        } = this.detail
        if(res.code === '200'){
          const data = res.data.content
          this.$nextTick(() => {
            this.searchForm.setFieldsValue({
              DorgId: data.orgId+'#'+data.orgName
            })
          })
        }
        if (phone.indexOf(',') != -1 ) {
          phone.split(',').forEach((ele, index) => {
            if (index == 0) {
              phone = ele
            } else if (index == 1) {
              phone1 = ele
            }else if (index == 2) {
              phone2 = ele
            }
          })
        }
        // 整理当前用户详情中的角色ID数据，去除重复
        const userRoldIdsOrg = this.detail.roleIds != null ? this.detail.roleIds.split(',') : []
      
        const userRoleIDs = []
        for(let i=0;i<userRoldIdsOrg.length;i++){
          if(!this.$com.oneOf(userRoldIdsOrg[i], userRoleIDs) && !this.$com.oneOf(userRoldIdsOrg[i], this.exclusionRoleIds)){
            userRoleIDs.push(userRoldIdsOrg[i])
          }
        }
        // 整理当前用户详情中的角色名称数据，去除重复
        const userRoldNamesOrg = this.detail.roleNames != null ? this.detail.roleNames.split(',') : []
        const userRoleNames = []
        for(let i=0;i<userRoldNamesOrg.length;i++){
          if(userRoleNames.indexOf(userRoldNamesOrg[i]) == -1){
            userRoleNames.push(userRoldNamesOrg[i])
          }
        }
        // 组装需要展示在用户信息表单“角色名称”项的初始数据
        userRoleIDs.forEach((ele, index) => {
          // userRoleIDs[index] = {
          //   'key': ele,
          //   'label': userRoleNames[index]
          // }
          userRoleIDs[index] = userRoleNames[index]+'#'+ele
        })
        let _this = this
        this.userRoldIDsOrg = []
        userRoldIdsOrg.forEach((ele, index) => {
          this.userRoldIDsOrg.push(
            // {
            //   'key': ele,
            //   'label': userRoldNamesOrg[index]
            // }
            userRoldNamesOrg[index]+'#'+ele
          )
        })
        const setDatas = {
          mail,
          name,
          dept,
          phone,
          phone1,
          phone2,
          addr,
          zipCode,
          username,
          orgType
          // DorgId
        }
        this.show = orgType=='2'
        setDatas.notes = userRoleIDs
        this.roles = userRoleIDs
        this.roleChange(this.userRoldIDsOrg)
        this.$nextTick(() => {
          this.searchForm.setFieldsValue(setDatas)
        })
      })
      
    },
    
    validateUserName(rule, value, callback){
      
      if(this.fromCenter){
        callback()
      }else{
        if (!value) {
          callback('必填(6-8位数字字母)！')
        }else{ 
          const filter = /^[A-Za-z0-9]{6,8}$/ 
          if(!filter.test(value)){
            callback('用户名为6-8位数字字母！')
          }else {
            this.$ajax.get({
              url: this.$api.GET_USERNAME_EXIST,
              PublicApiSign: this.sign,
              params: {
                username: value,
              }
            }).then(res => {
              if (res.code == '200') { 
                if(!res.data){
                  callback()
                }else{ 
                  callback('用户名已存在！')
                }
              } else{
                callback(res.msg)
              }
            }) 
          }
        }
      }
    },
    validatePhone(rule, value, callback){
      if (!value) {
        callback('必填！')
      }else {
        const filter = /^1[3-9][0-9]{9}$/
        if(!filter.test(value)){
          callback('请输入正确手机号！')
        }else {
          if(value==this.searchForm.getFieldValue('phone1')){
            callback('手机号不能重复')
          }else if(value==this.searchForm.getFieldValue('phone2')){
            callback('手机号不能重复')
          }else{
            if (this.fromCenter&&this.detail.phone&&this.detail.phone.indexOf(value) != -1) {
              callback()
            }else{
              this.$ajax.get({
                url: this.$api.GET_CHECK_PHONE_EXIST + '?phone=' + value+'&userType=0'
              }).then(res => {
                if (!res.data.content) {
                  callback()
                } else {
                  callback('已存在该账号！')
                }
              })
            }
          }
        }
      }
    },
    validatePhoneBY(rule, value, callback){
      if (!value) {
        callback()
      }else {
        const filter = /^1[3-9][0-9]{9}$/
        if(!filter.test(value)){
          callback('请输入正确手机号！')
        }else {
          if(this.searchForm.getFieldValue('phone1')==this.searchForm.getFieldValue('phone')){
            callback('手机号不能重复')
          }else if(this.searchForm.getFieldValue('phone1')==this.searchForm.getFieldValue('phone2')){
            callback('手机号不能重复')
          } else{
            if(this.fromCenter&&this.detail.phone&&this.detail.phone.indexOf(value)!=-1){
              callback()
            }else{
              this.$ajax.get({
                url: this.$api.GET_CHECK_PHONE_EXIST + '?phone=' + value
              }).then(res => {
                if (!res.data) {
                  callback()
                } else {
                  callback('已存在该账号！')
                }
              })
            }
          }

        }
      }
    },
    validatePhoneBY2(rule, value, callback){
      if (!value) {
        callback()
      }else {
        const filter = /^1[3-9][0-9]{9}$/
        if(!filter.test(value)){
          callback('请输入正确手机号！')
        }else {
          if(this.searchForm.getFieldValue('phone2')==this.searchForm.getFieldValue('phone')){
            callback('手机号不能重复')
          }else if(this.searchForm.getFieldValue('phone2')==this.searchForm.getFieldValue('phone1')){
            callback('手机号不能重复')
          } else{
            if(this.fromCenter&&this.detail.phone&&this.detail.phone.indexOf(value)!=-1){
              callback()
            }else{
              this.$ajax.get({
                url: this.$api.GET_CHECK_PHONE_EXIST + '?phone=' + value
              }).then(res => {
                if (!res.data) {
                  callback()
                } else {
                  callback('已存在该账号！')
                }
              })
            }
          }

        }
      }
    },
  }
}
</script>

<style scoped>
	.position {
		margin-left: 5px;
		color: #1890ff;
		cursor: pointer;
		display: inline;
	}
</style>
<style>

</style>
