<template>
  <el-dialog
    class="teamDialog"
    :visible.sync="visible"
    width="50%"
    :title="!dataForm.id ? '新增人员' : '修改人员'"
    @close="closeDialog"
  >
    <el-form ref="dataForm" :model="dataForm" :rules="dataRule">
      <el-form-item label="工号:" label-width="100px" prop="employeeId">
        <el-input v-model="dataForm.employeeId" placeholder="请输入工号" />
      </el-form-item>
      <el-form-item label="姓名:" label-width="100px" prop="realName">
        <el-input v-model="dataForm.realName" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="身份证:" label-width="100px" prop="userIdNumber">
        <el-input v-model="dataForm.userIdNumber" placeholder="身份证" />
      </el-form-item>
      <el-form-item v-if="!dataForm.id" label="登录密码:" label-width="100px" prop="password">
        <el-input v-model="dataForm.password" placeholder="请输入密码" @input="passwordOneChange" />
        <el-progress :percentage="passwordSafeOne" :format="progressFormatOne" :color="passwordSafeOne===33 ? '#f56c6c' : (passwordSafeOne===100 ? '#67c23a' : '')" />
        <p>密码至少8位,需涵盖大写、小写字母、数字、特殊字符</p>
      </el-form-item>
      <el-form-item label="性别:" label-width="100px" prop="gender">
        <el-radio-group v-model="dataForm.gender" size="medium">
          <el-radio-button label="0">男</el-radio-button>
          <el-radio-button label="1">女</el-radio-button>
          <el-radio-button label="2">保密</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="手机号:" label-width="100px" prop="mobile">
        <el-input v-model="dataForm.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="医生职位:" label-width="100px" prop="position">
        <el-radio-group v-model="dataForm.position" size="medium">
          <el-radio-button label="门诊医师">门诊医师</el-radio-button>
          <el-radio-button label="视光医师">视光医师</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="设置权限:" label-width="100px" prop="roleNameListValue">
        <el-cascader
          v-model="dataForm.roleNameListValue"
          :options="roleNameList"
          :props="props"
          clearable
          @change="roleCascaderChange"
        />
      </el-form-item>
      <el-form-item label="签名:" label-width="100px" prop="signImgBase" class="sign-form">
        <div v-if="dataForm.signImgBase" class="img-div">
          <img :src="dataForm.signImgBase" alt="" height="70px" @click="handlePictureCardPreview">
          <span class="icon-span" @click="deleteImgHandle">
            <i class="el-icon-delete" />
          </span>
        </div>
        <el-upload
          ref="fileupload"
          action="#"
          list-type="picture-card"
          :show-file-list="false"
          :http-request="uploadFileBaseHandle"
        >
          <i class="el-icon-plus" />
        </el-upload>
        <el-dialog :visible.sync="uploadImgDialogVisible" append-to-body width="500px">
          <el-image width="100%" :src="dataForm.signImgBase" alt="" fit="cover" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="状态:" label-width="100px" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">停用</el-radio>
          <el-radio :label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
    <cropper
      ref="cropperRef"
      :visible="cropperVisible"
      :url="uploadSignImgBase"
      :auto-crop-width="autoCropWidth"
      :auto-crop-height="autoCropHeight"
      @cancel="cropperVisible = false"
      @confirm="onConfirm"
    />
  </el-dialog>
</template>

<script>
import cropper from './cropper.vue'
import debounce from 'lodash/debounce'
import { isMobile } from '@/utils/validate'
import passwordSet from '@/mixins/passwordSet'
export default {
  components: {
    cropper
  },
  mixins: [passwordSet],
  props: {
    roleNameList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      props: {
        multiple: true,
        label: 'name',
        value: 'id',
        children: 'childrenList'
      },
      visible: false,
      isShowImg: true,
      dataForm: {
        centreId: '',
        centreName: '',
        employeeId: '',
        realName: '',
        password: '',
        userIdNumber: '',
        gender: 1,
        mobile: '',
        position: '门诊医师',
        positionIdList: [],
        positionListValue: [],
        roleIdList: [],
        roleNameListValue: [],
        signImgBase: '',
        status: 1 // 0：停用 1：正常
      },
      positionList: [
        {
          name: '医生'
        }, {
          name: '护士'
        }, {
          name: '技师'
        }, {
          name: '医辅'
        }],
      uploadSignImgBase: '',
      uploadImgDialogVisible: false,
      centerList: [],
      loginInfo: {},
      autoCropWidth: '500',
      autoCropHeight: '300',
      cropperVisible: false
    }
  },
  computed: {
    dataRule() {
      var validataMobile = (rule, value, callback) => {
        if (value && !isMobile(value)) {
          return callback(new Error(this.$t('您输入的手机号格式不正确')))
        } else if (!value) {
          return callback(new Error(this.$t('请输入手机号')))
        }
        callback()
      }
      var validataPassword = (rule, value, callback) => {
        if (value && value.length >= 8) {
          const weakReg = /^[0-9]{8,}$|^[a-zA-Z]{8,}$/
          if (weakReg.test(value)) {
            return callback(new Error('密码过于简单'))
          }
        } else {
          return callback(new Error('请输入密码'))
        }
        callback()
      }
      return {
        employeeId: [
          { required: true, message: '请输入医生工号', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入医生姓名', trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validataPassword, trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        position: [
          { required: true, message: '请选择医生职位', trigger: 'change' }
        ],
        mobile: [
          { required: true, validator: validataMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init() {
      this.visible = true
      this.$nextTick(() => {
        // 获取中心
        this.loginInfo = window.sessionStorage.getItem('qg-userData')
        this.$refs.dataForm.resetFields() // 重置表单
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    // 获取中心
    async getCentreList() {
      const { data: res } = await this.$http.get('/sys/centre/list')
      if (res.code === 0) {
        this.centerList = res.data
      }
    },
    // 获取信息
    getInfo() {
      this.$http.get(`/sys/user/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        // 权限
        const roleArr = []
        // 职位
        const postionArr = []
        res.data.roleIdList.forEach(item => {
          roleArr.push([item])
        })
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        this.dataForm.roleNameListValue = roleArr
      }).catch(() => { })
    },
    // 角色级联选择器选择
    roleCascaderChange(val) {
      this.dataForm.roleIdList = []
      val.forEach(item => {
        this.dataForm.roleIdList.push(item[0])
      })
    },
    // 上传文件转换
    uploadFileBaseHandle(data) {
      const _this = this
      const rd = new FileReader() // 创建文件读取对象
      const file = data.file
      rd.readAsDataURL(file) // 文件读取装换为base64类型
      rd.onloadend = function(e) {
        // this指向当前方法onloadend的作用域, this.result就是文件的base64， 这里可自由处理
        _this.uploadSignImgBase = this.result
        _this.cropperVisible = true
        _this.$nextTick(() => {
          _this.$refs.cropperRef.init()
        })
      }
    },
    // 裁切返回
    async onConfirm(file) {
      const _this = this
      const rd = new FileReader() // 创建文件读取对象
      rd.readAsDataURL(file) // 文件读取装换为base64类型
      rd.onloadend = function(e) {
        // this指向当前方法onloadend的作用域, this.result就是文件的base64， 这里可自由处理
        _this.dataForm.signImgBase = this.result
        _this.cropperVisible = false
      }
    },
    // 图片浏览
    handlePictureCardPreview() {
      this.uploadImgDialogVisible = true
    },
    // 删除图片
    deleteImgHandle() {
      this.dataForm.signImgBase = ''
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function() {
      this.$refs.dataForm.validate((valid) => {
        if (!valid) {
          return false
        }
        const param = { ...this.dataForm }
        param.password = this.$md5(param.password)
        this.$http[!this.dataForm.id ? 'post' : 'put']('/sys/user', param).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => { })
      })
    }, 1000, { leading: true, trailing: false }),
    // 关闭弹框
    closeDialog() {
      this.$emit('closeDialog', false)
    }
  }
}
</script>
<style lang="scss" scoped>
.teamDialog {
  .img-div {
    position:relative;
    margin-right: 20px;
  }
  .icon-span {
    display: none;
    position: absolute;
    right: 0;
    bottom: -10px;
    .el-icon-delete {
      font-size: 16px;
    }
  }
  .img-div:hover{
    .icon-span {
      cursor: pointer;
      display: inline-block;
    }

  }
}
</style>
<style lang="scss">
.teamDialog {
  .el-dialog__header {
    margin-bottom: 12px;
  }
  .el-cascader {
    display: block;
  }
  .el-dialog__body {
    padding-right: 30px;
  }
  .sign-form {
    .change-sing-fs {
      cursor: pointer;
    }
    img {
      margin-right: 10px;
    }
    .el-form-item__content {
      display: flex;
      align-items: center;
    }
  }
  .el-upload--picture-card {
    line-height: 79px;
  }
  .el-upload--picture-card,.el-upload-list--picture-card .el-upload-list__item {
    width: 70px;
    height: 70px;
  }
}
</style>
