<template>
  <a-modal :visible="addFormvisible" :title="formTitle" @ok="handleOk()" @cancel="handleCancel()" width="800px">
    <a-form v-bind="formLayout" :form="form">
      <a-row>
        <a-col :span="12">
          <a-form-item label="登录账号:">
            <a-input
              placeholder="请输入登录账号"
              v-decorator="[
                'loginName',
                {
                  initialValue: (detail && detail.loginName) || undefined,
                  rules: [{ required: true, message: '请输入登录账号' }],
                },
              ]"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <!-- <a-form-item label="组织">
            <a-tree-select
              placeholder="请选择组织"
              v-decorator="[
                'orgId',
                {
                  initialValue: (detail && detail.orgId) || undefined,
                  rules: [{ required: true, message: '请选择组织' }],
                },
              ]"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="orgOptions"
              :replaceFields="replaceFields"
              tree-default-expand-all
            />
          </a-form-item> -->
          <a-form-item label="岗位">
            <a-select
              allow-clear
              option-filter-prop="label"
              mode="multiple"
              v-decorator="[
                'postIds',
                {
                  initialValue: (detail && detail.postIds) || undefined,
                },
              ]"
              placeholder="请选择"
            >
              <a-select-option v-for="(d, index) in postOptions" :key="index" :value="d.postId" :label="d.postName">
                {{ d.postName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-item label="手机号">
            <a-input
              placeholder="请输入手机号"
              v-decorator="[
                'mobilePhone',
                {
                  initialValue: (detail && detail.mobilePhone) || undefined,
                  rules: [{ required: true, message: '请输入手机号' }, { validator: handleConfirmPhoe }],
                },
              ]"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="邮箱">
            <a-input
              placeholder="请输入邮箱"
              v-decorator="[
                'email',
                {
                  initialValue: (detail && detail.email) || undefined,
                },
              ]"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-item label="用户姓名">
            <a-input
              placeholder="请输入用户姓名"
              v-decorator="[
                'userName',
                {
                  initialValue: (detail && detail.userName) || undefined,
                  rules: [{ required: true, message: '请输入用户姓名' }],
                },
              ]"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="密码" v-if="id == undefined">
            <a-input-password
              placeholder="请输入密码"
              v-decorator="[
                'password',
                {
                  initialValue: (detail && detail.password) || undefined,
                  rules: [{ required: true, message: '请输入密码' }],
                },
              ]"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <!-- <a-col :span="12">
          <a-form-item label="性别">
            <a-radio-group
              v-decorator="[
                'sex',
                {
                  initialValue: (detail && detail.sex) || undefined,
                },
              ]"
              button-style="solid"
            >
              <a-radio-button v-for="(d, index) in sexOptions" :key="index" :value="d.dictValue">{{
                d.dictLabel
              }}</a-radio-button>
            </a-radio-group>
          </a-form-item>
        </a-col> -->
        <a-col :span="12">
          <a-form-item label="状态">
            <a-radio-group
              v-decorator="[
                'status',
                {
                  initialValue: (detail && detail.status) || '0',
                  rules: [{ required: true, message: '请选择状态' }],
                },
              ]"
              button-style="solid"
            >
              <a-radio-button v-for="(d, index) in statusOptions" :key="index" :value="d.dictValue">{{
                d.dictLabel
              }}</a-radio-button>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
      <!-- <a-row> -->
      <!-- <a-col :span="12">
          <a-form-item label="所属公司">
            <a-select
              v-decorator="[
                'subCompanyCode',
                {
                  initialValue: (detail && detail.subCompanyCode) || undefined,
                },
              ]"
              placeholder="请选择所属公司"
            >
              <a-select-option v-for="item in subCompnayCods" :key="item.dictValue" :value="item.dictValue"
                >{{ item.dictLabel }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col> -->
      <!-- </a-row> -->
      <a-row>
        <a-col :span="12">
          <a-form-item
            required
            :label="index == 0 ? '组织:' : ' '"
            :colon="false"
            v-for="(item, index) in orgRolesArr"
            :key="index"
            :help="(item.orgId && item.roleIds) || !submitOk ? '' : '请选择组织和角色'"
          >
            <div style="display: flex">
              <a-tree-select
                placeholder="请选择组织"
                v-model="item.orgId"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="orgOptions"
                :replaceFields="replaceFields"
                @change="changeSelectOrg(item.orgId, index)"
                tree-default-expand-all
              />
              <a-select
                allow-clear
                v-model="item.roleIds"
                :disabled="item.orgId ? false : true"
                option-filter-prop="label"
                mode="multiple"
                placeholder="请选择角色"
              >
                <a-select-option
                  v-for="(d, index) in roleOptions[item.orgId]"
                  :key="index"
                  :value="d.roleId"
                  :label="d.roleName"
                >
                  {{ d.roleName }}
                </a-select-option>
              </a-select>
              <a-icon
                type="plus-circle"
                style="font-size: 30px; margin-right: 15px"
                @click.prevent="addorgRolesArr(index)"
                v-if="index == 0"
              />
              <a-icon
                type="minus-circle"
                style="font-size: 30px"
                @click.prevent="deleteorgRolesArr(index)"
                v-if="index != 0"
              />
            </div>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-item label="备注">
            <a-textarea
              v-decorator="[
                'remark',
                {
                  initialValue: (detail && detail.remark) || undefined,
                },
              ]"
              placeholder="请填写备注"
              allow-clear
              style="width: 662px"
              allowClear
              :autosize="{ minRows: 4 }"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script>
import formMixin from '@/utils/form-mixin'
import { getUser, addUser, updateUser, orgRole } from '@/api/system/user'
import { getConfigKey } from '@/api/system/config'
// import { listData } from '@/api/system/dict/data'
import md5 from 'md5'

export default {
  name: 'CreateForm',
  mixins: [formMixin],
  props: {
    orgOptions: {
      type: Array,
      required: true,
    },
    statusOptions: {
      type: Array,
      required: true,
    },
    sexOptions: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      addFormvisible: false,
      detail: undefined,
      formTitle: '',
      replaceFields: { children: 'children', title: 'label', key: 'value', value: 'value' },
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: {},
      subCompnayCods: [],
      // 默认密码
      initPassword: undefined,
      id: undefined,
      orgId: undefined,
      orgRolesArr: [
        {
          orgId: undefined,
          roleIds: undefined,
        },
      ],
      helpM: '',
      isChecked: false,
      submitOk: false,
    }
  },
  created() {
    getConfigKey('sys.user.initPassword').then((response) => {
      this.initPassword = response.msg
    })
    this.getOrgList()
  },
  watch: {
    roleOptions(val) {
      this.roleOptions = val
    },
  },
  methods: {
    //修改组织触发的方法
    changeSelectOrg(val, key) {
      this.orgRolesArr[key].roleIds = undefined
      this.orgRole(val)
    },
    //根据组织获取用户
    orgRole(id) {
      orgRole(id).then((res) => {
        this.roleOptions[id] = res.result
        this.$forceUpdate()
      })
    },
    addorgRolesArr() {
      this.orgRolesArr.push({
        orgId: undefined,
        roleIds: undefined,
      })
    },
    deleteorgRolesArr(index) {
      this.orgRolesArr.splice(index, 1)
    },
    getOrgList() {
      this.getDicts('SUB_COMPANY_COD').then((res) => {
        this.subCompnayCods = res.result
      })
    },
    handleConfirmPhoe(rule, value, callback) {
      const reg = /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/
      if (value == '' || value == undefined || value == null) {
        callback()
      } else {
        if (!reg.test(value) && value != '') {
          callback(new Error('请输入正确的手机号码'))
        } else {
          callback()
        }
      }
    },
    handleConfirmEmail(rule, value, callback) {
      const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (value == '' || value == undefined || value == null) {
        callback()
      } else {
        if (!reg.test(value) && value != '') {
          callback(new Error('请输入正确的邮箱地址'))
        } else {
          callback()
        }
      }
    },
    handleAdd() {
      this.submitOk = false
      this.detail = undefined
      this.id = undefined
      this.formTitle = '新增用户'
      this.$emit('select-tree')
      getUser()
        .then((response) => {
          this.postOptions = response.result.posts
          // this.roleOptions = response.result.roles
        })
        .finally(() => {
          this.addFormvisible = true
        })
    },
    /** 修改按钮操作 */
    handleUpdate(row, ids) {
      this.submitOk = false
      this.detail = undefined
      this.formTitle = '修改用户'
      this.$emit('select-tree')
      const userId = row ? row.userId : ids
      this.id = userId
      getUser(userId)
        .then((response) => {
          this.detail = response.result.user
          if (this.detail.orgs.length>0) {
            this.orgRolesArr = this.detail.orgs.map((item) => {
              this.orgRole(item.orgId)
              const roles = []
              item.roles.map((val) => {
                roles.push(val.roleId)
              })
              return { orgId: item.orgId, roleIds: roles }
            })
          } else {
            this.orgRolesArr = [
              {
                orgId: undefined,
                roleIds: undefined,
              },
            ]
          }
          this.orgId = response.result.user.orgId
          this.postOptions = response.result.posts
          this.orgRole(this.orgId)
          // this.roleOptions = response.result.roles
          this.detail.postIds = response.result.postIds
          this.detail.roleIds = response.result.roleIds
        })
        .finally(() => {
          this.addFormvisible = true
        })
    },
    checkOrgRolesArr() {
      this.isChecked = false
      this.orgRolesArr.map((item) => {
        if (!item.orgId || !item.roleIds) {
          this.isChecked = false
        } else this.isChecked = true
      })
    },
    handleOk() {
      const _this = this
      const roleIds = []
      this.submitOk = true
      this.checkOrgRolesArr()
      this.form.validateFields((errors, values) => {
        if (!errors && this.isChecked) {
          _this.orgRolesArr.map((item) => {
            item.roleIds.map((val) => {
              roleIds.push(val)
            })
          })
          const org = _this.orgRolesArr[0].orgId
          const parameters = {
            source: 'I',
            roleIds: roleIds,
            userId: _this.detail ? _this.detail.userId : undefined,
            orgId: org,
            userName: values.userName ? values.userName : _this.detail.userName,
            loginName: values.loginName,
            password: values.password ? md5(values.password) : _this.detail.password,
            mobilePhone: values.mobilePhone,
            // subCompanyCode: values.subCompnayCode,
            email: values.email,
            // sex: values.sex,
            status: values.status,
            remark: values.remark,
            postIds: values.postIds,
          }
          const requestActivity = _this.detail ? updateUser : addUser
          requestActivity(parameters).then((response) => {
            _this.$message.success(_this.detail ? '修改成功' : '添加成功', 3)
            _this.handleCancel()
            _this.$emit('ok')
          })
        }
      })
    },
    handleCancel() {
      this.addFormvisible = false
      this.submitOk = false
      this.isChecked = []
      this.orgRolesArr = [
        {
          orgId: undefined,
          roleIds: undefined,
        },
      ]
      this.id = undefined
      this.$nextTick(() => {
        this.detail = undefined
        this.formTitle = undefined
        this.form.resetFields()
      })
    },
  },
}
</script>
<style scoped>
::v-deep .ant-select {
  min-width: 200px;
  margin-right: 15px;
}
::v-deep .ant-form-explain {
  color: red !important;
}
</style>
