<template>
    <div>
        <Spin size="large" fix v-if="spinShow"></Spin>
        <Row type="flex" justify="center">
            <Col span="14">
                <!--{{this.optionState === false ? '添加' : '修改'}}-->
                <Form ref="formItem" :rules="ruleValidate" label-position="right" :model="formItem" :label-width="120">
                    <FormItem v-show="hidden.login_name" label="登录名：" v-if="optionState === true">
                        <Input v-model="formItem.login_name" style="width: 70%" disabled></Input>
                    </FormItem>
                    <FormItem v-show="hidden.name" label="单位名称：" prop="name">
                        <Input v-model="formItem.name" clearable style="width: 70%"></Input>
                    </FormItem>
                    <FormItem v-show="hidden.password" label="密码：" prop="password">
                        <Input v-model="formItem.password" clearable type="password" style="width: 70%"></Input>
                        <span v-if="optionState === true" class="prompt-input">若不修改密码请留空</span>
                    </FormItem>
                    <FormItem v-show="hidden.passwordc" label="确认密码：" prop="passwordc">
                        <Input v-model="formItem.passwordc" clearable type="password" style="width: 70%"></Input>
                    </FormItem>
                    <FormItem v-show="hidden.mobile" label="手机号：" prop="mobile">
                        <Input v-model="formItem.mobile" clearable style="width: 70%"></Input>
                    </FormItem>
                    <FormItem v-show="hidden.phone" label="电话：">
                        <Input v-model="formItem.phone" clearable style="width: 70%"></Input>
                    </FormItem>
                    <FormItem v-show="hidden.email" label="邮箱：" prop="email">
                        <Input v-model="formItem.email" clearable style="width: 70%"></Input>
                    </FormItem>
                    <FormItem v-show="hidden.login_flag" label="是否可用：">
                        <i-switch v-model="formItem.login_flag" true-value="1" false-value="0" size="large">
                            <span slot="open">开启</span>
                            <span slot="close">关闭</span>
                        </i-switch>
                    </FormItem>
                    <FormItem label="用户角色：" prop="role">
                        <RadioGroup v-model="formItem.role_ids" type="button">
                            <Radio v-for="item in roleList" :key="item.id" :label="item.id" border>{{item.name}}</Radio>
                        </RadioGroup>
                        <Button class="add-role" type="text" ghost size="small" @click="addRole">前去添加角色</Button>
                    </FormItem>
                    <FormItem v-show="hidden.remarks" label="备注：">
                        <Input v-model="formItem.remarks" maxlength="255" show-word-limit type="textarea"
                               :autosize="{minRows: 2,maxRows: 5}"></Input>
                    </FormItem>
                    <FormItem>
                        <Button shape="circle" type="primary" :loading="btnLoading" @click="saveOption">保存</Button>
                        <Button shape="circle" style="margin-left: 8px" @click="cancelOption">取消</Button>
                    </FormItem>
                </Form>
            </Col>
        </Row>
    </div>
</template>

<script>
import {
  addUser,
  getById,
  setUserInfo
} from '../../../../../api/system/sys-staff-manager'
export default {
  name: 'staffOption',
  props: {
    companyId: {
      type: String,
      default: () => {
        return ''
      }
    },
    formData: {
      type: Object,
      default: () => {
        return {
          login_flag: '1'
        }
      }
    },
    roleList: {
      type: Array,
      default: () => {
        return []
      }
    },
    optionState: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    hiddenArr: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    // const validateMobile = (rule, value, callback) => {
    //   if (!value) {
    //     callback(new Error('手机号不能为空'))
    //   } else if (!/^1[3456789]\d{9}$/.test(value)) {
    //     callback(new Error('手机号格式不正确'))
    //   } else {
    //     callback()
    //   }
    // }
    const validateName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('名称不能为空'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!this.optionState) {
        if (!value) {
          callback(new Error('密码不能为空'))
        } else if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/.test(value)) {
          callback(new Error('密码格式不正确（8-16位英文与数字组成）'))
        } else {
          if (!this.formItem.passwordc) {
            // 对第二个密码框单独验证
            this.$refs.formItem.validateField('passwordc')
          }
          callback()
        }
      } else {
        if (value) {
          if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/.test(value)) {
            callback(new Error('密码格式不正确（8-16位英文与数字组成）'))
          } else {
            if (!this.formItem.passwordc) {
              // 对第二个密码框单独验证
              this.$refs.formItem.validateField('passwordc')
            }
            callback()
          }
        }
        callback()
      }
    }
    const validatePasswordc = (rule, value, callback) => {
      if (!this.optionState) {
        if (!value) {
          callback(new Error('请再次输入密码'))
        } else if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/.test(value)) {
          callback(new Error('密码格式不正确（8-16位英文与数字组成）'))
        } else if (value !== this.formItem.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      } else {
        if (this.formItem.password) {
          if (!value) {
            callback(new Error('请再次输入密码'))
          } else if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/.test(value)) {
            callback(new Error('密码格式不正确（8-16位英文与数字组成）'))
          } else if (value !== this.formItem.password) {
            callback(new Error('两次输入密码不一致'))
          } else {
            callback()
          }
        } else {
          this.formItem.passwordc = null
        }
        callback()
      }
    }
    // const validateEmail = (rule, value, callback) => {
    //   if (!value) {
    //     callback(new Error('邮箱不能为空'))
    //   } else if (!/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/.test(value)) {
    //     callback(new Error('邮箱格式不正确'))
    //   } else {
    //     callback()
    //   }
    // }
    const validateRole = (rule, value, callback) => {
      if (!this.formItem.role_ids) {
        callback(new Error('请选择一个角色，若无角色则前去添加'))
      } else {
        callback()
      }
    }
    return {
      ruleValidate: {
        // mobile: [
        //   { required: true, validator: validateMobile, trigger: 'blur' }
        // ],
        name: [
          { required: true, validator: validateName, trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validatePassword, trigger: 'blur' }
        ],
        passwordc: [
          { required: true, validator: validatePasswordc, trigger: 'blur' }
        ],
        // email: [
        //   { required: true, validator: validateEmail, trigger: 'blur' }
        // ],
        role: [
          { required: true, validator: validateRole }
        ]
      },
      btnLoading: false,
      spinShow: false,
      formItem: {},
      hidden: {
        login_name: true,
        name: true,
        password: true,
        passwordc: true,
        mobile: true,
        phone: true,
        email: true,
        login_flag: true,
        remarks: true
      }
    }
  },
  mounted () {
    this.hiddenArr.forEach(item => {
      if (this.hidden.hasOwnProperty(item)) {
        this.hidden[item] = false
      }
    })
    // console.log('处理后', this.hidden)
  },
  methods: {
    addRole () {
      this.$router.push({
        name: 'sysStaffRoleManager'
      })
    },
    saveOption () {
      this.$refs.formItem.validate((valid) => {
        if (valid) {
          // 表单额外数据添加
          let roleList = []
          roleList.push({ id: this.formItem.role_ids })
          this.formItem.rolelist = roleList
          this.formItem.user_type = '3'
          // 安全性处理
          if (this.formItem.company_id) {
            this.optionState ? this.updateUser(this.formItem) : this.addUser(this.formItem)
          } else {
            this.$Message.error('数据有误!')
          }
        } else {
          this.$Message.error('请重新核查表单项!')
        }
      })
    },
    addUser (data) {
      this.btnLoading = true
      addUser(data).then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          this.$Modal.success({
            title: data.data.Message,
            content: '用户名：' + data.data.login_name
          })
          this.$emit('staffOption')
          this.btnLoading = false
        } else {
          this.btnLoading = false
          this.error(data)
        }
      })
    },
    updateUser (data) {
      this.btnLoading = true
      setUserInfo(data).then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          this.success()
          this.$emit('staffOption')
          this.btnLoading = false
        } else {
          this.btnLoading = false
          this.error(data)
        }
      })
    },
    cancelOption () {
      this.$emit('staffOption')
    },
    getById (data) {
      this.spinShow = true
      getById(data).then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          this.formItem = data.data
          // 对已选中角色进行处理
          if (this.$common.xeUtils.isArray(this.formItem.rolelist)) {
            this.formItem.role_ids = this.formItem.rolelist[0].id
          }
          this.spinShow = false
        } else {
          this.spinShow = false
          this.error(data)
        }
      })
    },
    success () {
      this.$Message.success('操作成功')
    },
    error (data) {
      this.$Message.error({
        content: '操作失败,\n' + data.errmsg
      })
    }
  },
  watch: {
    formData () {
      this.formItem = this.$common.xeUtils.clone(this.formData)
    }
  }
}
</script>

<style scoped>
    .prompt-input {
        margin-left: 3%;
        font-size: 13px;
        color: #C5C8CE;
    }
    .add-role {
        margin-left: 10px;
        display: inline-block;
        color: #428BCA;
        font-size: 12px;
    }
</style>
