<template>
  <div v-loading="loading">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" class="userAccount_form">
      <el-row :gutter="20">
        <el-col :md="12" class="col_item">
          <el-form-item label="工号" prop="usercode">
            <el-input v-model="ruleForm.usercode" auto-complete="off" placeholder="请输入工号"/>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="姓名" prop="username">
            <el-input v-model="ruleForm.username" auto-complete="off" placeholder="请输入姓名"/>
          </el-form-item>
        </el-col>
        <el-col v-if="!rowid" :md="12" class="col_item">
          <el-form-item label="密码" prop="passwordEnter">
            <el-input v-model="ruleForm.passwordEnter" type="password" auto-complete="off" placeholder="请输入密码"/>
          </el-form-item>
        </el-col>
        <el-col v-if="!rowid" :md="12" class="col_item">
          <el-form-item label="确认密码" prop="checkPass">
            <el-input v-model="checkPass" type="password" auto-complete="off" placeholder="请再次输入密码"/>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="分机号" prop="extensionnumber">
            <el-input v-model="ruleForm.extensionnumber" placeholder="请输入分机号"/>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="所属部门" prop="deptid">
            <el-cascader
              v-model="parentids"
              :options="departmentDropDatas"
              :props="props"
              :placeholder="departmentPlaceholder"
              clearable
              filterable
              change-on-select
              :class="{form_cascader: is_form_cascader}"
              @change="handledepartment"
              style="width: 100%">
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="团队" prop="deptteamid">
            <el-select v-model="ruleForm.deptteamid" class="form_select" filterable clearable placeholder="请选择团队">
              <el-option
                v-for="item in teamData"
                :key="item.F_Id"
                :label="item.F_Name"
                :value="item.F_Id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="职位" prop="dutyid">
            <el-select v-model="ruleForm.dutyid" class="form_select" filterable clearable placeholder="请选择职位">
              <el-option
                v-for="item in positoinData"
                :key="item.F_Id"
                :label="item.F_Name"
                :value="item.F_Id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="入职日期" prop="entrydate">
           <el-date-picker
            v-model="ruleForm.entrydate"
            type="date"
            value-format="yyyy-MM-dd"
            class="form_date"
            placeholder="请选择入职日期">
          </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="转正日期" prop="fulldate">
           <el-date-picker
            v-model="ruleForm.fulldate"
            type="date"
            value-format="yyyy-MM-dd"
            class="form_date"
            placeholder="请选择转正日期">
          </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="离职日期" prop="termdate">
           <el-date-picker
            v-model="ruleForm.termdate"
            type="date"
            value-format="yyyy-MM-dd"
            class="form_date"
            placeholder="请选择离职日期">
          </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="用户角色" prop="roleid">
            <el-select v-model="ruleForm.roleid" class="form_select" filterable clearable placeholder="请选择用户角色">
              <el-option
                v-for="item in roleOptions"
                :key="item.F_RoleId"
                :label="item.F_RoleName"
                :value="item.F_RoleId"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="坐席等级" prop="seatlevel">
            <el-input v-model="ruleForm.seatlevel" placeholder="请输入坐席等级"/>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="性别" prop="sexflag">
            <el-radio-group v-model="ruleForm.sexflag">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
              <el-radio label="未知">未知</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="电话" prop="telephone">
            <el-input v-model="ruleForm.telephone" placeholder="请输入电话"/>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="ruleForm.mobile" placeholder="请输入手机"/>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="家庭电话" prop="homephone">
            <el-input v-model="ruleForm.homephone" placeholder="请输入家庭电话"/>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="外线号码" prop="wxno">
            <el-input v-model="ruleForm.wxno" placeholder="请输入外线号码"/>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="ruleForm.remark" placeholder="备注"/>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="提醒标志" prop="remindflag">
            <el-switch v-model="ruleForm.remindflag" active-value="true" inactive-value="false" @change="changeRemindFlag"/>
          </el-form-item>
        </el-col>
        <el-col :md="12" class="col_item">
          <el-form-item label="标志" prop="seatflag">
            <el-switch v-model="ruleForm.seatflag" active-value="true" inactive-value="false" @change="changeSeatFlag"/>
          </el-form-item>
        </el-col>
        <el-col v-show="seatFlag" :md="12" class="col_item">
          <el-form-item label="坐席组" prop="seartgroupiD">
            <el-select v-model="ruleForm.seartgroupiD" class="form_select" filterable clearable placeholder="请选择坐席组">
              <el-option
                v-for="item in seatOptions"
                :key="item.F_ZXZID"
                :label="item.F_ZXZName"
                :value="item.F_ZXZID"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-show="seatFlag" :md="12" class="col_item">
          <el-form-item label="坐席组权限" prop="seatright">
            <el-radio-group v-model="ruleForm.seatright">
              <el-radio label="0">普通坐席</el-radio>
              <el-radio label="1">班长坐席</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :md="24">
          <el-form-item label="头像">
            <el-col :md="8">
              <el-button type="primary" plain @click="toggleShow">点击上传头像</el-button>
              <p class="tips">提示：预览头像见右侧(上传成功后记得保存)</p>
              <avatar-upload
                v-model="uploadAvatar.show"
                :url="uploadUrl"
                :params="uploadAvatar.params"
                :width="200"
                :height="200"
                :no-rotate="false"
                img-format="png"
                :headers = "uploadData.uploadHeader"
                @crop-success="cropSuccess"
                @crop-upload-success="cropUploadSuccess"/>
            </el-col>
            <el-col v-show="uploadAvatar.imgDataUrl" :md="8">
              <img :src="uploadAvatar.imgDataUrl" alt="头像预览图" class="avatar_img_square">
            </el-col>
            <el-col v-show="uploadAvatar.imgDataUrl" :md="8">
              <img :src="uploadAvatar.imgDataUrl" alt="头像预览图" class="avatar_img_round">
            </el-col>
          </el-form-item>
        </el-col>
        <el-col :md="24">
          <el-form-item>
            <el-button type="primary" @click="submitForm">保存</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import md5 from 'js-md5'
import avatarUpload from 'vue-image-crop-upload'
import { mapGetters } from 'vuex'
import { getRoleSelect, getDictionary, getSeatGroup, getPro } from '@/api/commonAPI'
import { getUserAccount, addUserAccount, editUserAccount, getPositionData, getTeamData } from '@/api/systemSetup/roleSetting/userManage'
import { validUsername, validName, validPassword, validateTel, validIdCard, validEmail, validExtension } from '@/utils/validate'
import { getTreeList } from '@/api/systemSetup/roleSetting/department'
import { delFiles } from '@/utils'

export default {
  name: 'AddOrEdit',
  components: {
    'avatar-upload': avatarUpload
  },
  props: {
    rowid: {
      type: String,
      default: ''
    },
    layerid: {
      type: String,
      default: ''
    }
  },
  data() {
    const validUsernameRule = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入有效的账号（4-20个字符只能是字母、下划线、数字）！'))
      } else {
        callback()
      }
    }

    const validNameRule = (rule, value, callback) => {
      if (!validName(value)) {
        callback(new Error('请输入有效的姓名（2-20位汉字和·•的组合）！'))
      } else {
        callback()
      }
    }

    const validatePass = (rule, value, callback) => {
      if (!validPassword(value)) {
        callback(new Error('请输入有效的密码（6-32个字符只能是字母、下划线、数字）！'))
      } else {
        if (this.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }

    const validatePass2 = (rule, value, callback) => {
      if (!validPassword(this.checkPass)) {
        callback(new Error('请输入有效的确认密码（6-32个字符只能是字母、下划线、数字）！'))
      } else {
        if (this.checkPass !== this.ruleForm.passwordEnter) {
          callback(new Error('两次输入密码不一致!'))
        }
        callback()
      }
    }

    const validateTelRule = (rule, value, callback) => {
      if (!validateTel(value)) {
        callback(new Error('请输入有效的手机号码!'))
      } else {
        callback()
      }
    }

    const validGroupRule = (rule, value, callback) => {
      if (this.seatFlag) {
        if (!value) {
          callback(new Error('请选择坐席组!'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    const validateExt = (rule, value, callback) => {
      if (value != "") {
        if (!validExtension(value)) {
          callback(new Error('分机号格式(4-20个字符只能是数字)！'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    return {
      uploadUrl: this.$store.getters.serverConfig.BASE_API + 'Api/Upload',
      uploadData: {
        uploadHeader: {
          Authorization: '',
        },
      },
      uploadAvatar: {
        show: false,
        params: {
          uploadtype: 'avatar'
        },
        imgDataUrl: '' // 头像剪切后生成的 datebase64格式的url
      },
      roleOptions: [], // 角色下拉数据
      parentids: [], // 部门下拉数据
      seatOptions: [], // 坐席组下拉数据
      positoinData: [], // 职位下拉数据
      teamData: [], // 团队下拉数据
      seatFlag: false, // 话务标识
      checkPass: '', // 确认密码
      departmentteamid: '', // 团队的部门id
      deptteamid: '', // 团队的部门id(详情)
      ruleForm: {
        userid: '',
        usercode: '',
        username: '',
        password: '',
        passwordEnter: '',
        extensionnumber: '', //分机号
        deptid: '', // 所属部门
        roleid: '', //角色
        dutyid: '', //职位信息
        deptteamid: '', //团队信息
        entrydate: '', //入职日期
        fulldate: '', //转正日期
        termdate: '', //离职日期
        seatlevel: '', //坐席等级
        sexflag: '男', // 性别
        remindflag: false, //提醒标志
        telephone: '', //电话
        mobile: '', // 手机号码
        homephone: '', //家庭电话
        wxno: '', //外线电话
        headimg: '', // 头像大图
        head_small_img: '', // 头像缩略图
        remark: '',
        // 话务相关
        seatflag: 'false', // 标志
        seartgroupiD: '', // 坐席组id
        seatright: '0' // 坐席组权限
      },
      rules: {
        usercode: [{
          required: true,
          trigger: 'blur',
          validator: validUsernameRule
        }],
        username: [{
          required: true,
          trigger: 'blur',
          validator: validNameRule
        }],
        passwordEnter: [{
          required: true,
          trigger: 'blur',
          validator: validatePass
        }],
        checkPass: [{
          required: true,
          trigger: 'blur',
          validator: validatePass2
        }],
        type: [{
          required: true,
          message: '请选择用户类型',
          trigger: 'change'
        }],
        roleid: [{
          required: true,
          message: '请选择用户角色',
          trigger: 'change'
        }],
        mobile: [{
          required: true,
          trigger: 'blur',
          validator: validateTelRule
        }],
        seartgroupiD: [{
          required: true,
          trigger: 'change',
          validator: validGroupRule
        }],
        extensionnumber: [{
          required: false,
          trigger: 'blur',
          validator: validateExt
        }]
      },
      loading: false,
      departmentDropDatas: [], // 下拉分类
      // 自定义菜单下拉数据的key值
      props: {
        value: 'id',
        label: 'text'
      },
      departmentPlaceholder: '请选择部门', //部门提示
      is_form_cascader: false
    }
  },
  computed: {
    ...mapGetters([
      'token',
      'avatar',
      'usercode'
    ])
  },
  created() {
    this.uploadData.uploadHeader.Authorization = this.token
    Promise.all([this.getRoleSelects(), this.getTypeDrop(),this.getPosition(), this.getSeatGroupSelects()])
      .then(() => {
        if (this.rowid) {
          this.ruleForm.userid = this.rowid
          this.is_form_cascader = true
          this.getDetail(this.rowid)
        }
      })
  },
  methods: {
    submitForm() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 添加
          if (!this.rowid) {
            this.ruleForm.password = md5(this.ruleForm.passwordEnter)
            this.ruleForm.deptid = this.parentids[this.parentids.length - 1]
            addUserAccount(this.ruleForm).then(response => {
              this.loading = false
              if (response.state.toLowerCase() === 'success') {
                this.$parent.$layer.close(this.layerid)
                this.$parent.getList() // 重新加载父级数据
                this.$message.success('恭喜你，用户信息添加成功!')
              }
            }).catch(() => {
              this.loading = false
            })
            return
          }
          // 编辑
          this.ruleForm.password = null
          editUserAccount(this.ruleForm).then(response => {
            // 更新头像
            if (this.ruleForm.usercode === this.usercode && this.ruleForm.head_small_img) {
              this.$store.dispatch('SetAvatar', this.ruleForm.head_small_img)
            }
            this.loading = false
            if (response.state.toLowerCase() === 'success') {
              this.$parent.$layer.close(this.layerid)
              this.$parent.getList() // 重新加载父级数据
              this.$message.success('恭喜你，用户信息编辑成功!')
            }
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.$message.error('请输入有效的必填项信息!')
          return false
        }
      })
    },
    resetForm() {
      this.seatFlag = false // 话务标识
      this.parentids = []
      this.checkPass = '' // 确认密码
      this.uploadAvatar.imgDataUrl = ''
      this.ruleForm.headimg = ''
      this.ruleForm.head_small_img = '' // 头像缩略图
      this.$refs.ruleForm.resetFields()
    },
    // 详情
    getDetail(rid) {
      getUserAccount(rid).then(response => {
        if (response.state.toLowerCase() === 'success') {
          const res = response.data
          // headimg: '', // 头像大图
          // head_small_img: '', // 头像缩略图

          this.ruleForm.usercode = res.F_UserCode //工号
          this.ruleForm.username = res.F_UserName //姓名
          this.ruleForm.extensionnumber = res.F_ExtensionNumber //分机号
          this.ruleForm.roleid = res.F_RoleId // 角色
          this.ruleForm.deptid = res.F_DeptId // 所属部门
          this.ruleForm.dutyid = res.F_DutyId // 职位
          this.deptteamid = res.F_DeptTeamId // 团队
          this.ruleForm.entrydate = res.F_EntryDate // 入职日期
          this.ruleForm.fulldate = res.F_FullDate // 转正日期
          this.ruleForm.termdate = res.F_TermDate // 离职日期
          this.ruleForm.seatlevel = res.F_SeatLevel //坐席等级
          this.ruleForm.sexflag = res.F_SexFlag && res.F_SexFlag.toString() //
          this.ruleForm.remindflag = res.F_RemindFlag.toString() //提醒标志
          this.ruleForm.telephone = res.F_Telephone //电话
          this.ruleForm.mobile = res.F_Mobile // 手机号码
          this.ruleForm.homephone = res.F_HomePhone // 家庭电话
          this.ruleForm.wxno = res.F_WXNo // 外线电话
          this.uploadAvatar.imgDataUrl = res.head_small_img // 头像预览图
          this.ruleForm.headimg = res.F_HeadImg // 头像大图
          // this.ruleForm.head_small_img = res.head_small_img // 头像缩略图
          this.ruleForm.remark = res.F_Remark
          this.departmentPlaceholder = res.F_Dept
          // 话务相关
          this.ruleForm.seatflag = res.F_SeatFlag.toString() // 话务标志
          this.seatFlag = res.F_SeatFlag
          this.ruleForm.seartgroupiD = res.F_SeartGroupID // 坐席组id
          this.ruleForm.seatright = res.F_SeatRight === null ? res.F_SeatRight : res.F_SeatRight.toString() // 坐席类型 默认普通坐席
        }
        if(this.ruleForm.deptid){
          this.getTeam(this.ruleForm.deptid)
          this.ruleForm.deptteamid=this.deptteamid
        }
      })
    },
    // 话务提醒标识切换
    changeRemindFlag() {
      this.remindflag = !this.remindflag
    },
    // 话务标识切换
    changeSeatFlag() {
      this.seatFlag = !this.seatFlag
    },
    // 获取角色下拉数据
    getRoleSelects() {
      return new Promise(resolve => {
        getRoleSelect().then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.roleOptions = response.data
          }
        })
        resolve()
      })
    },
    // 获取部门下拉数据
    getTypeDrop() {
      return new Promise(resolve => {
        getTreeList().then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.departmentDropDatas = response.data
          }
        })
        resolve()
      })
    },
    //获取职位数据
    getPosition(){
      getPositionData().then(response=>{
        if(response.state.toLowerCase()=='success'){
          this.positoinData=response.data
        }
      })
    },
    //部门选择信息
    handledepartment(e){
      if(e.length>0){
        this.departmentteamid=e[e.length-1]
        this.getTeam(this.departmentteamid)
        this.ruleForm.deptteamid=''
      }
    },
    //获取团队数据
    getTeam(departmentteamid){
      getTeamData(departmentteamid).then(response=>{
        if(response.state.toLowerCase()=='success'){
          this.teamData=response.data
        }
      })
    },
    // 获取坐席组下拉数据
    getSeatGroupSelects() {
      return new Promise(resolve => {
        getSeatGroup().then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.seatOptions = response.data
          }
        })
        resolve()
      })
    },
    // 头像
    toggleShow() {
      this.uploadAvatar.show = !this.uploadAvatar.show
    },
    cropSuccess(imgDataUrl, field) {
      this.uploadAvatar.imgDataUrl = imgDataUrl
    },
    cropUploadSuccess(jsonData, field) {
      if (jsonData.state.toLowerCase() === 'success') {
        this.ruleForm.headimg = jsonData.data[0].fileurl
        // this.ruleForm.head_small_img = jsonData.data[0].filesmallurl// 头像缩略图
      }
    },
    // 重置 上传文件
    resetUploads(rEl, pEl) {
      if (this.ruleForm[rEl].length > 0) {
        for (let i = this.ruleForm[rEl].length - 1; i >= 0; i--) {
          delFiles(this.ruleForm[rEl][i].filesmallurl, this.ruleForm[rEl][i].fileurl)
          this.ruleForm[rEl].splice(i, 1)
        }
      }
      this.$refs[pEl].clearFiles()	// 清空已上传的文件列表（该方法不支持在 before-upload 中调用）
    }

  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
	.userAccount_form .uploadFiles .el-upload-list--picture{
		margin-right: -1%;
	}
	.userAccount_form .el-upload-list--picture li{
		width: 24%;
		margin-right: 1%;
		float: left;
	}
	.userAccount_form{
		.form_time,
		.form_select{
			width: 100%;
		}
    .form_date{
      width: 100%;
    }
		.col_item{
			height: 51px;
		}
		.tips{
			color: #e6a23c;
		}
		.avatar_img_square{
			width: 100px;
			height: 100px;
		}
		.avatar_img_round{
			border-radius: 50%;
			width: 100px;
			height: 100px;
		}
	}
  .form_cascader {
    ::-webkit-input-placeholder { /* WebKit, Blink, Edge */
        color: #606266;
        font-size: 14px;
    }
    :-moz-placeholder { /* Mozilla Firefox 4 to 18 */
        color: #606266;
        font-size: 14px;
    }
    ::-moz-placeholder { /* Mozilla Firefox 19+ */
        color: #606266;
        font-size: 14px;
    }
    :-ms-input-placeholder { /* Internet Explorer 10-11 */
        color: #606266;
        font-size: 14px;
    }
  }
</style>
