<template>
  <div>
    <a-modal
      class="modalBox"
      :title="titleText"
      v-model="isshow"
      @cancle="cancel"
      width="35%"
      :footer="null">
      <a-form :form="form" @submit="handleSubmit">
        <a-row :gutter="24">
          <a-col :span="12">
            <!-- 用户名称 -->
            <a-form-item label="员工姓名" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
              <a-input
                placeholder="请输入员工姓名30个字以内"
                :maxLength="30"
                id="userModal-name"
                v-decorator="['formData.name', {
                  initialValue: formData.name,
                  rules: [{ required: true, message: '请输入员工姓名30个字以内!' },{pattern:'^[^<|>]{1,30}$',message:'请输入不含<或>的字符，最多30个字符'}] }]"
                allowClear />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <!-- 手机号码 -->
            <a-form-item label="手机号码" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
              <a-input
                placeholder="请输入手机号码"
                :maxLength="11"
                id="userModal-phone"
                v-decorator="['formData.phone', {
                  initialValue: formData.phone,
                  rules: [{ required: true, message: '请输入手机号码!' },{pattern:/^[1][0-9]{10}$/, message: '请输入正确的手机号码!'}] }]"
                allowClear />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <!-- 性别 -->
          <a-col :span="12">
            <a-form-item label="性别" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
              <v-select
                code="SEX"
                id="userModal-sex"
                placeholder="请选择性别"
                v-decorator="[
                  'formData.sex',
                  {
                    initialValue: formData.sex,
                    rules: [{ required: true, message: '请选择性别!' }] },
                ]"
                allowClear></v-select>

            </a-form-item>
          </a-col>
          <!-- 角色 -->
          <a-col :span="12">
            <a-form-item label="角色" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
              <a-select
                id="userModal-roleNames"
                v-decorator="[
                  'formData.roleNames',
                  {
                    initialValue: formData.roleNames,
                    rules: [{ required: true, message: '请选择角色!' }] },
                ]"
                style="width: 100%"
                placeholder="请选择角色"
                mode="multiple">
                <a-select-option v-for="item in roleList" :key="item.id" :disabled="item.isEnable == '0' ? true : false">{{ item.name }}</a-select-option>
              </a-select>

            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item class="form-label" label="所属机构" prop="orgCode" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
              <a-tree-select
                id="userModal-orgCode"
                allowClear
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="treeData"
                placeholder="请选择所属机构"
                treeNodeFilterProp="title"
                @change="treeChange"
                v-decorator="[
                  'formData.orgCode',
                  {
                    initialValue: formData.orgCode,
                    rules: [{ required: true, message: '请选择所属机构!' }] },
                ]">
              </a-tree-select>
            </a-form-item>
          </a-col>
          <!-- 状态 -->
          <a-col :span="12">
            <a-form-item label="状态" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
              <a-radio-group
                id="userModal-loginFlag"
                name="radioGroup"
                v-decorator="[
                  'formData.loginFlag',
                  {
                    initialValue: formData.loginFlag,
                    rules: [{ required: true, message: '请选择状态!' }] },
                ]">
                <a-radio :value="1" >是</a-radio>
                <a-radio :value="0" >否</a-radio>
              </a-radio-group>

            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item :wrapper-col="{ span: 12, offset: 5 }" style="text-align: center;">
          <a-button type="primary" @click="handleSubmit()" id="userModal-handleSubmit">
            保存
          </a-button>
          <a-button :style="{ marginLeft: '50px' }" @click="handleCancel()" id="userModal-handleCancel">
            取消
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import {
  STable,
  VSelect,
  Tree
} from '@/components'
import {
  saveUserPower
} from '@/api/supervision-user.js'
import {
  getAllRole
} from '@/api/supervision-role.js'
import {
  findOrgTree
} from '@/api/atorg.js'
export default {
  name: 'UserModal',
  components: {
    STable,
    VSelect,
    Tree
  },
  props: {
    // 弹窗是否显示
    visible: {
      type: Boolean,
      default: false
    },
    // 编辑督导的数据
    data: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data () {
    return {
      titleText: '添加用户',
      isshow: this.visible,
      formLayout: 'horizontal',
      form: this.$form.createForm(this, {
        name: 'miniForm'
      }),
      roleList: [], // 角色
      parentCodePaths: '', // 组织机构父路径
      formData: {
        orgCode: null, // 组织机构
        name: '', // 员工姓名
        loginFlag: '', // 状态
        phone: '', // 手机号码
        sex: '', // 性别
        roleNames: undefined // 角色
      },
      treeData: []

    }
  },
  methods: {
    cancel (e) {
      this.clear()
      this.$emit('close')
    },
    // 获取组织机构树的数据
    getOrgData () {
      findOrgTree().then(res => {
        if (res.status == 200) {
          this.treeData = this.recursionFun(res.data)
        } else {
          this.treeData = []
        }
      })
    },
    //  组织归属  change
    treeChange (value, label, extra) {
      this.parentCodePaths = extra.triggerNode.$options.propsData.dataRef.parentCodePaths
    },
    //  递归函数
    recursionFun (data) {
      if (data) {
        data.map(item => {
          if (item.children && item.children.length == 0) {
            item.key = item.id ? 'org' + item.id : ''
            item.value = item.id ? item.id : ''
            item.title = item.name ? item.name : ''
          } else {
            item.key = item.id ? 'org' + item.id : ''
            item.value = item.id ? item.id : ''
            item.title = item.name ? item.name : ''
            this.recursionFun(item.children)
          }
        })
      }
      return data
    },
    // 保存提交
    handleSubmit () {
      const _this = this
      this.form.validateFields((err, values) => {
        if (!err) {
          values.formData.roleNames = values.formData.roleNames.join(',')
          const formData = JSON.parse(JSON.stringify(values.formData))
          formData.org = {
            id: formData.orgCode
          }
          delete formData.orgCode
          saveUserPower(Object.assign({
            id: this.data.id ? this.data.id : ''
          }, formData)).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$emit('refresh')
              setTimeout(function () {
                _this.cancel()
              }, 300)
            } else {
              _this.$message.error(res.message)
            }
          })
        }
      })
    },
    // 取消
    handleCancel () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确定取消吗?',
        okText: '确定',
        cancelText: '取消',
        onOk () {
          _this.clear()
          _this.cancel()
        }
      })
    },
    clear () {
      this.form.resetFields()
      delete this.formData.id
      this.formData.orgCode = null // 所属机构
      this.formData.name = '' // 员工姓名
      this.formData.loginFlag = '' // 状态
      this.formData.phone = '' // 手机号码
      this.formData.sex = '' // 性别
      this.formData.roleNames = undefined // 角色
    },
    // 获取角色列表接口
    getRoleData () {
      getAllRole().then(res => {
        if (res.status == 200) {
          this.roleList = res.data
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 编辑赋值
    pageInitData () {
      const _this = this
      this.titleText = '编辑用户'
      this.formData.orgCode = this.data.org.id // 组织机构
      this.formData.name = this.data.name // 员工姓名
      this.formData.loginFlag = Number(this.data.loginFlag) // 状态
      this.formData.phone = this.data.phone // 手机号码
      this.formData.sex = this.data.sex // 性别
      let roleNames = this.data.roleNames
      if (roleNames) {
        roleNames = roleNames.split(',')
        setTimeout(() => {
          const arr = []
          roleNames.map(item => {
            console.log(item)
            const row = _this.roleList.find(a => a.name == item)
            if (row) {
              arr.push(row.id)
            }
          })
          this.formData.roleNames = arr
        }, 500)
      } else {
        this.formData.roleNames = []
      }
    }
  },
  beforeCreate () {
    this.form = this.$form.createForm(this, {
      name: 'miniForm'
    })
  },
  watch: {
    visible (newValue, oldValue) {
      this.isshow = newValue
    },
    isshow (newValue, oldValue) {
      if (newValue) {
        this.getOrgData() // 打开弹窗获取组织机构数据
        this.getRoleData() // 打开弹窗获取角色列表数据
        if (this.data.id) { // 编辑
          this.pageInitData()
        } else {
          this.titleText = '添加用户'
        }
      } else {
        this.cancel()
      }
    }
  }
}
</script>

<style scoped>
	.ant-modal-footer {
		display: none;
	}
</style>
