<template>
  <div>
    <el-form ref="detailForm" :status-icon="!editMode" :model="detailData" :rules="rules" @submit.native.prevent>
      <el-row :gutter="15">
        <el-col :span="12">
          <h5 class="form-field-title">个人信息</h5>
          <div class="column-wrapper">
            <el-form-item label="工号" prop="company_id" :label-width="formLabelWidth">
              <el-input v-model="detailData.company_id" ref="inputCompanyId"
                        auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="name" :label-width="formLabelWidth">
              <el-input v-model="detailData.name" ref="inputName" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="tel" :label-width="formLabelWidth">
              <el-input v-model="detailData.tel" ref="inputTel" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" :label-width="formLabelWidth">
              <el-input type="password" v-model="detailData.password" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="password_check"
                          :label-width="formLabelWidth">
              <el-input type="password" v-model="detailData.password_check"
                        auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="mail_address" :label-width="formLabelWidth">
              <el-input v-model="detailData.mail_address" ref="inputMailAddress"
                        auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="用户状态" prop="status" :label-width="formLabelWidth">
              <el-select
                v-model="detailData.status">
                <el-option
                  v-for="item in employeeStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="性别" prop="sex" :label-width="formLabelWidth">
              <el-select
                v-model="detailData.sex">
                <el-option
                  v-for="item in sexOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="入职日期" prop="accedence_time" :label-width="formLabelWidth">
              <el-date-picker
                v-model="detailData.accedence_time"
                type="date"
                value-format="timestamp"
                placeholder="选择日期"
                :picker-options="assistantOptions">
              </el-date-picker>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="12">
          <h5 class="form-field-title">组织架构</h5>
          <div class="column-wrapper">
            <el-form-item label="所属部门" prop="dept_id" :label-width="formLabelWidth">
              <el-cascader
                v-model="detailData.dept_id"
                clearable
                :options="deptTree"
                change-on-select>
              </el-cascader>
            </el-form-item>
            <el-form-item label="上级" prop="superior_id" :label-width="formLabelWidth">
              <el-select
                clearable
                filterable
                v-model="detailData.superior_id">
                <el-option
                  v-for="item in employeeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <div class="button-bar-fw" style="margin-top:20px;">
      <el-button type="primary" round @click="submitForm('detailForm')">保存</el-button>
      <el-button round @click="discardBack">取消</el-button>
    </div>
  </div>
</template>
<script>
  export default {
    data() {
      let validateCompanyId = (rule, value, callback) => {
        let validValue = value ? value.replace(/\s/g, "").replace(/&nbsp;/ig, "") : value
        if (!validValue) {
          return callback(new Error('请填写工号'))
        }
        let illegalChar = /[\uFF00-\uFFFF]/
        if (illegalChar.test(value)) {
          return callback(new Error('有效工号中不能使用全角字符，请重新填写'))
        } else {
          callback()
        }
      }
      let validateName = (rule, value, callback) => {
        let validValue = value ? value.replace(/\s/g, "").replace(/&nbsp;/ig, "") : value
        if (!validValue) {
          return callback(new Error('请填写姓名'))
        } else {
          callback()
        }
      }
      let validateTel = (rule, value, callback) => {
        let validValue = value ? value.replace(/\s/g, "").replace(/&nbsp;/ig, "") : value
        if (!validValue) {
          return callback(new Error('请填写手机号码'))
        }
        let pattern = /^1\d{10}$/
        if (pattern.test(value)) {
          callback()
        } else {
          return callback(new Error('无效的手机号，请重新输入'))
        }
      }
      let validatePassword = (rule, value, callback) => {
        if (!this.editMode) {
          if (!value) {
            return callback(new Error('请填写密码'))
          }
          if (value.length < 5) {
            return callback(new Error('密码长度应至少在5位或以上'))
          }
        } else {
          if (value && value.length < 5) {
            return callback(new Error('密码长度应至少在5位或以上'))
          }
        }
        callback()
      }
      let validatePasswordCheck = (rule, value, callback) => {
        if (!this.editMode || this.detailData.password) {
          if (!value) {
            return callback(new Error('请再次填写密码确认'))
          }
          if (value.length < 5) {
            return callback(new Error('密码长度应至少在5位或以上'))
          }
          if (value != this.detailData.password) {
            return callback(new Error('两次输入的密码不一致，请核对后再输入'))
          }
        }
        callback()
      }
      let validateMailAddress = (rule, value, callback) => {
        if (!value) {
          return callback()
        }
        let pattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
        if (!pattern.test(String(value).toLowerCase())) {
          return callback(new Error('不是合法的邮箱地址，请重新输入'))
        }
        callback()
      }
      let isEditMode = this.$route.params.targetId > 0 ? true : false
      return {
        profile: this.$store.getters.user_info,
        editMode: isEditMode,
        formLabelWidth: '105px',
        detailData: {
          id: '',
          company_id: '',
          name: '',
          tel: '',
          status: 1,
          sex: 0,
          mail_address: '',
          accedence_time: '',
          superior_id: '',
          dept_id: []
        },
        employeeStatus: [
          {
            value: 1,
            label: '正常'
          },
          {
            value: 2,
            label: '请假'
          },
          {
            value: 0,
            label: '离职'
          },
          {
            value: -1,
            label: '禁用'
          }
        ],
        sexOptions: [
          {
            value: 0,
            label: '男'
          },
          {
            value: 1,
            label: '女'
          }
        ],
        deptTree: [],
        employeeList: [],
        assistantOptions: {
          disabledDate(time) {
            let date = new Date()
            var lastDayOfThisMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0)
            return time.getTime() > lastDayOfThisMonth
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          }, {
            text: '本周一',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24 * (1 - date.getDay()))
              picker.$emit('pick', date)
            }
          }]
        },
        rules: {
          company_id: [
            {validator: validateCompanyId, trigger: 'blur'}
          ],
          name: [
            {validator: validateName, trigger: 'blur'}
          ],
          tel: [
            {validator: validateTel, trigger: 'blur'}
          ],
          password: [
            {validator: validatePassword, trigger: 'blur'}
          ],
          password_check: [
            {validator: validatePasswordCheck, trigger: 'blur'}
          ],
          mail_address: [
            {validator: validateMailAddress, trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      //获取基本数据
      loadBaseData: function () {
        let params = {
          site_id: this.profile.site_id,
          get_employee_list: 1
        }
        var self = this
        this.$http('get','/integral.php/ajax_request_common/get_org_base',params).then(function (response) {
          if (response.status == 200) {
            let jsonData = response.data
            try {
              self.deptTree = jsonData.tree
              self.employeeList = jsonData.employee_list
              self.$emit('update-page-title', " - " + (self.detailData.name ? self.detailData.name : "新建"))
            } catch (err) {
              console.log(err)
            }
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      //获取用户数据
      loadEmployeeDetail: function (employeeId) {
        let params = {
          id: employeeId
        }
        var self = this
        this.$http('get','/integral.php/ajax_request_common/get_employee_info',params).then(function (response) {
          if (response.status == 200) {
            let jsonData = response.data
            try {
              self.detailData = self.processDetailData(jsonData)
            } catch (err) {
              console.log(err)
            }
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      discardBack: function () {
        if (window.history.length < 2) {
          this.$router.replace({
            name: "employee_table"
          })
        } else {
          this.$router.go(-1)
        }
      },
      submitForm: function (formName) {
        var form = this.$refs[formName]
        var self = this
        form.validate((valid) => {
          if (valid) {
            if (form) {
              self.sendSaveRequest()
            }
          } else {
            //console.log('验证未通过');
            return false
          }
        })
      },
      sendSaveRequest: function () {
        var formData = {}
        var dataObj = this.detailData
        for (let item in dataObj) {
          if (item == 'password_check') {
            continue
          } else if (item == 'accedence_time') {
            if (!dataObj[item]) {
              continue
            }
            formData[item] = parseInt(dataObj[item] / 1000)
          } else if (item == 'dept_id') {
            var length = dataObj[item].length
            formData[item] = length == 0 ? 0 : dataObj[item][length - 1]
          } else {
            if (!dataObj[item]) {
              continue
            }
            formData[item] = dataObj[item]
          }
        }
        formData['site_id'] = this.profile.site_id
        let url = '/integral.php/ajax_request_common/'
        url += this.editMode ? 'update_employee' : 'add_employee'
        var self = this
        this.$http('post',url,formData,'','',
          {transformRequest: [(data) => {
            let paramArray = new Array()
            for (let it in data) {
              paramArray.push(encodeURIComponent(it) + '=' + encodeURIComponent(data[it]))
            }
            return paramArray.join("&")
          }]},
          // headers: {
          //   'Content-Type': 'application/x-www-form-urlencoded'
          // }
        ).then(function (response) {
          var message = ""
          var status = 0
          if (response.status == 200) {
            var data = response.data
            status = isNaN(data.status) ? 0 : parseInt(data.status)
            let actionName = self.editMode ? "修改员工信息" : "新增员工"
            switch (status) {
              case 1:
                message = actionName + "成功"
                break
              case -1:
                message = "表单参数错误"
                break
              case -2:
                message = data.info ? data.info : actionName + "失败"
                self.$refs[data.target_field].focus()
                self.$refs[data.target_field].$parent.clearValidate()
                break;
              default:
                message = data.info ? data.info : actionName + "失败"
            }
          } else {
            message = "服务器出现问题"
          }
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          })
          if (status == 1) {
            self.$refs["detailForm"].resetFields()
            if (self.editMode) {
              self.$router.go(-1)
            } else {
              self.$router.replace({
                name: "employee_table"
              })
            }
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      processDetailData: function (object) {
        //所属部门转换成插件需要的数组格式
        let pathStr = object.dept_id.toString()
        object.dept_id = pathStr.split(",").map(Number)
        //时间戳转换
        object.accedence_time *= 1000
        object.superior_id = !isNaN(object.superior_id) && object.superior_id > 0 ? parseInt(object.superior_id) : ''
        return object
      }
    },
    created() {
      this.loadBaseData()
      if (this.$route.params.targetId > 0) {
        this.loadEmployeeDetail(this.$route.params.targetId)
      }
    }
  }
</script>
