<template>
    <div>
        <Spin size="large" fix v-if="spinShow"></Spin>
        <Row type="flex" justify="start">
            <Col span="20" offset="3">
                <!--{{optionState == false ? '添加' : '修改'}}-->
                <Form ref="formItem" :rules="ruleValidate" label-position="right" :model="formItem" :label-width="120">
                    <FormItem label="归属公司：">
                        <Input v-model="formItem.company_name" disabled></Input>
                    </FormItem>
                    <FormItem label="登录手机号：" prop="mobile">
                        <Input v-model="formItem.mobile" clearable placeholder="手机号码"></Input>
                    </FormItem>
                    <FormItem label="登录名：" v-show="optionState == true">
                        <Input v-model="formItem.login_name" clearable placeholder="登录名"></Input>
                    </FormItem>
                    <FormItem label="工号：" v-show="optionState == true">
                        <Input v-model="formItem.no" clearable placeholder="工号"></Input>
                    </FormItem>
                    <FormItem label="姓名：" prop="name">
                        <Input v-model="formItem.name" clearable placeholder="姓名"></Input>
                    </FormItem>
                    <FormItem label="密码：" prop="password">
                        <Input v-model="formItem.password" clearable maxlength="20" type="password"
                               placeholder="密码"></Input>
                        <span v-if="optionState == true" class="prompt-input">若不修改密码请留空</span>
                    </FormItem>
                    <FormItem label="确认密码：" prop="passwordc">
                        <Input v-model="formItem.passwordc" clearable maxlength="20" type="password"
                               placeholder="确认密码"></Input>
                    </FormItem>
                    <FormItem label="邮箱：" prop="email">
                        <Input v-model="formItem.email" clearable placeholder="邮箱"></Input>
                    </FormItem>
                    <FormItem label="电话：">
                        <Input v-model="formItem.phone" clearable placeholder="电话"></Input>
                    </FormItem>
                    <FormItem 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="用户类型：">
                        <Select v-model="formItem.user_type">
                            <Option value="1">系统管理</Option>
                            <Option value="2">部门经理</Option>
                            <Option value="3">普通用户</Option>
                            <Option value="9">接口对接</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="用户角色：">
                        <CheckboxGroup v-model="currentRoleList">
                            <Checkbox v-for="(item,index) in roleList" :key="index" :label="item.name" border>
                                {{item.name}}
                            </Checkbox>
                        </CheckboxGroup>
                    </FormItem>
                    <FormItem label="备注：">
                        <Input v-model="formItem.remarks" type="textarea" maxlength="255" show-word-limit
                               :autosize="{minRows: 2,maxRows: 5}"/>
                    </FormItem>
                    <FormItem label="创建时间：" v-show="optionState == true">
                        {{formItem.create_date}}
                    </FormItem>
                    <FormItem label="最后登录：" v-show="optionState == true">
                        <div>
                            <span style="font-weight: 600; margin-right: 5px">IP: </span>
                            {{formItem.login_ip}}
                        </div>
                        <div>
                            <span style="font-weight: 600; margin-right: 5px">时间: </span>
                            {{formItem.login_date}}
                        </div>
                    </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,
  userIdGetAdminUserInfo,
  setUserInfo,
  getForUserList
} from '../../../../../api/system/system'

export default {
  name: 'userOption',
  props: {
    companyId: {
      type: String,
      default: () => {
        return ''
      }
    },
    formData: {
      type: Object,
      default: () => {
        return {
          login_flag: '1'
        }
      }
    },
    optionState: {
      type: Boolean,
      default: () => {
        return false
      }
    }
  },
  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 (!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 (value !== this.formItem.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      } else {
        if (this.formItem.password) {
          if (!value) {
            callback(new Error('请再次输入密码'))
          } 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 (currentRoleList.length <= 0) {
    //     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: {},
      currentRoleList: [],
      roleList: []
    }
  },
  mounted () {
  },
  methods: {
    saveOption () {
      this.$refs.formItem.validate((valid) => {
        if (valid) {
          // 勾选角色列表数据处理
          let arr = []
          this.currentRoleList.forEach(item => {
            this.roleList.forEach(item1 => {
              if (item === item1.name) {
                arr.push(item1)
              }
            })
          })
          this.formItem.rolelist = arr
          // 安全性处理
          this.optionState ? this.updateUserAction(this.formItem) : this.addUserAction(this.formItem)
        } else {
          this.$Message.error('请重新核查表单项!')
        }
      })
    },
    addUserAction (data) {
      // 添加状态加上company_id
      data.company_id = this.companyId
      // console.log('添加提报数据', 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('saveOption', this.currentId)
          this.btnLoading = false
        } else {
          this.btnLoading = false
          this.error(data)
        }
      })
    },
    updateUserAction (data) {
      // console.log('修改提报数据', data)
      this.btnLoading = true
      setUserInfo(data).then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          this.success()
          this.$emit('saveOption')
          this.btnLoading = false
        } else {
          this.btnLoading = false
          this.error(data)
        }
      })
    },
    cancelOption () {
      this.$emit('cancelOption')
    },
    getUserInfoAction (data) {
      this.spinShow = true
      userIdGetAdminUserInfo(data).then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          this.formItem = data.data
          // 对已选中角色进行处理
          this.currentRoleList = []
          if (this.$common.xeUtils.isArray(this.formItem.rolelist)) {
            this.formItem.rolelist.forEach(item => {
              this.currentRoleList.push(item.name)
            })
          }
          this.spinShow = false
        } else {
          this.spinShow = false
          this.error(data)
        }
      })
    },
    getForUserListAction (param) {
      getForUserList(param).then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          this.roleList = data.data
        } else {
          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)
      // console.log('当前表单', this.formItem)
    },
    companyId (val) {
      if (val) {
        const param = {
          company_id: val,
          flag: '1'
        }
        this.getForUserListAction(param)
      }
    }
  }
}
</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>
