<template>
  <div style="padding:0 20px 0 20px">
    <el-form
      ref="detailForm"
      :status-icon="!editMode"
      :model="detailData"
      :rules="rules"
      @submit.native.prevent
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="员工信息" name="first">
          <div style="height: 30px;"></div>
          <el-row>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <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>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple-light">
                <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>
              </div>
            </el-col>
            <el-col :span="12">
              <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-col>
            <el-col :span="12">
              <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-col>
            <el-col :span="12">
              <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-col>
            <el-col :span="12">
              <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-col>
            <el-col :span="12">
              <el-form-item label="所属部门" prop="dept_id" :label-width="formLabelWidth">
                <el-cascader
                  v-model="detailData.dept_id"
                  style="width:100%;"
                  clearable
                  :options="deptTree"
                  change-on-select
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入职日期" prop="accedence_time" :label-width="formLabelWidth">
                <el-date-picker
                  style="width:100%;"
                  v-model="detailData.accedence_time"
                  type="date"
                  value-format="timestamp"
                  placeholder="选择日期"
                  :picker-options="assistantOptions"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="上级" prop="superior_id" :label-width="formLabelWidth">
                <el-select placeholder="请选择,可搜索" 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>
            </el-col>
            <el-col :span="8">
              <!-- <div style="height: 30px;"></div> -->
              <el-form-item
                label="用户状态"
                prop="status"
                :label-width="formLabelWidth"
                style="width:255px;"
              >
                <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-col>
            <el-col :span="8">
              <el-form-item
                label="性别"
                prop="sex"
                :label-width="formLabelWidth"
                style="width:250px;"
              >
                <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-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="固定积分" name="sec">
          <div style="height: 30px;"></div>

          <el-form-item v-for="(val,index) in fixed_rule" :key="index" :label="val.name" label-width="100px">
            <el-checkbox-group v-model="val.checked">
              <el-checkbox v-for="i in val.item" :label="i.id" :key="i.id">{{i.content}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>

      <div style=" text-align: center;">
        <el-button type="primary" :loading="loading" plain @click="submitForm('detailForm')">保存</el-button>
        <el-button plain @click="discardBack">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import qs from "qs";
export default {
  data() {
    const validateCompanyId = (rule, value, callback) => {
      let validValue = value
        ? value.replace(/\s/g, "").replace(/&nbsp;/gi, "")
        : value;
      if (!validValue) {
        return callback(new Error("请填写工号"));
      }
      let illegalChar = /[\uFF00-\uFFFF]/;
      if (illegalChar.test(value)) {
        return callback(new Error("有效工号中不能使用全角字符，请重新填写"));
      } else {
        callback();
      }
    };
    const validateName = (rule, value, callback) => {
      let validValue = value
        ? value.replace(/\s/g, "").replace(/&nbsp;/gi, "")
        : value;
      if (!validValue) {
        return callback(new Error("请填写姓名"));
      } else {
        callback();
      }
    };
    const validateTel = (rule, value, callback) => {
      let validValue = value
        ? value.replace(/\s/g, "").replace(/&nbsp;/gi, "")
        : value;
      if (!validValue) {
        return callback(new Error("请填写手机号码"));
      }
      let pattern = /^1\d{10}$/;
      if (pattern.test(value)) {
        callback();
      } else {
        return callback(new Error("无效的手机号，请重新输入"));
      }
    };
    const 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();
    };
    const validatePasswordCheck = (rule, value, callback) => {
      if (!this.editMode || this.detailData.password) {
        if (!value) {
          console.log(value);
          return callback(new Error("请再次填写密码确认"));
        }
        if (value.length < 5) {
          return callback(new Error("密码长度应至少在5位或以上"));
        }
        if (value != this.detailData.password) {
          return callback(new Error("两次输入的密码不一致，请核对后再输入"));
        }
      }
      callback();
    };
    const 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 {
      loading:false,
      activeName: "first",
      editMode: false,
      profile: this.$store.getters.user_info,
      dialogTableVisible: false,
      dialogCreateCategoryVisible: false,
      formLabelWidth: "105px",
      fixed_rule: [],
      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);
        });
    },
    get_fixed_rule(employeeId) {
      let params = {
        employee_id: employeeId
      };
      var self = this;
      this.$http('get',"/integral.php/ajax_request_common/get_fixed_rule",params)
        .then(function(response) {
          if (response.status == 200) {
            let jsonData = response.data;
            try {
              for (let i in jsonData.data) {
                jsonData.data[i]["value"] = [];
                for (let j in jsonData.data[i].item) {
                  if (jsonData.data[i].item[j].checked == 1) {
                    jsonData.data[i]["value"].push(jsonData.data[i].item[j].id);
                  }
                }
              }
              self.fixed_rule = jsonData.data;
            } catch (err) {
              console.log(err);
            }
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    //获取用户数据
    loadEmployeeDetail: function(employeeId) {
      this.get_fixed_rule(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() {
      this.$parent.$parent.dialogTableVisible = false;
    },
    formrset: function() {
      this.$refs["detailForm"].resetFields();
    },
    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() {
      this.loading = true
      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]) {
            if(item == 'sex' || item == 'status'){
              formData[item] = dataObj[item];
            }
            continue;
          }
          formData[item] = dataObj[item];
        }
      }
      formData["site_id"] = this.profile.site_id;

      for (let i in this.fixed_rule) {
        for (let j in this.fixed_rule[i].item) {
          if (
            this.fixed_rule[i].checked.indexOf(this.fixed_rule[i].item[j].id) >=
            0
          ) {
            this.fixed_rule[i].item[j]["checked"] = 1;
          } else {
            this.fixed_rule[i].item[j]["checked"] = 0;
          }
        }
      }
      formData["fixed_rule"] = this.fixed_rule;
      if(!formData.superior_id){
        formData["superior_id"] = 0
      }
      let url = "/integral.php/ajax_request_common/";
      url += this.editMode ? "update_employee" : "add_employee";
      var self = this;
      this.$http("post",url,qs.stringify(formData),
        // headers: {
        //   "Content-Type": "application/x-www-form-urlencoded"
        // }
      )
        .then(function(response) {
          self.loading = false
          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();
            self.$parent.$parent.dialogTableVisible = false;
            self.$parent.$parent.loadEmployeeList();
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    clearForm() {
      this.detailData = {
        company_id: "",
        name: "",
        tel: "",
        status: 1,
        sex: 0,
        password: "",
        password_check: "",
        mail_address: "",
        accedence_time: "",
        superior_id: "",
        dept_id: []
      };

      this.$refs["detailForm"].clearValidate();
    },
    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>
<style>
.bmxx .el-dialog__body {
  padding: 30px 100px 20px 10px !important;
}
</style>
