<template>
  <div style="padding:0 20px 0 20px">
    <el-form ref="detailForm" :status-icon="!editMode" :model="detailData" :rules="rules" @submit.native.prevent v-loading="show_loading">
      <el-form-item label="员工标识" prop="id" :label-width="formLabelWidth" style="position: relative;" v-if="dialogTableVisibleNone">
        <el-input v-model="detailData.id" :disabled="true" :placeholder="detailData.id"
        auto-complete="off"></el-input>
        <!-- <i class="el-icon-edit-outline" @click="handleCopy(detailData.id,$event)" style="position:absolute;top:7px;right:7px;font-size:22px;color: #b6bfd2;cursor:pointer;"></i> -->
        <span style="position:absolute;top:1px;right:7px;font-size:12px;color:#61aeff;cursor:pointer;" @click="handleCopy(detailData.id,$event)">点击复制</span>
      </el-form-item>
      <el-form-item label="姓名" prop="name" :label-width="formLabelWidth">
        <el-input v-model="detailData.name" :disabled="detailData.status != 1 && managerId != 0" placeholder="请输入姓名"
          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" :disabled="detailData.status != 1 && managerId != 0" placeholder="请输入手机" ref="inputTel"
          auto-complete="off"></el-input>
      </el-form-item>

      <el-form-item label="工号" prop="company_id" :label-width="formLabelWidth">
        <el-input placeholder="请输入工号" v-model="detailData.company_id" ref="inputCompanyId" auto-complete="off"
          :disabled="detailData.status == 2 && managerId != 0"></el-input>
        </el-col>
        </el-row>
      </el-form-item>


      <el-form-item label="部门" prop="dept_id" :label-width="formLabelWidth">
        <el-input auto-complete="off" v-model="name" :disabled="detailData.status == 2 && managerId != 0" placeholder="请选择上级部门"></el-input>
        <div @click="show_dept_selector = true" :disabled="detailData.status == 2 && managerId != 0" style=" position: absolute; top: 0; right: 0; left: 0; bottom: 0; z-index: 9;"></div>
        <!-- <EmployeeSelector :employee_not_select="employee_not_select" :can_select_employee="false" :can_select_dept="true"
          :selected.sync="dept_selected" :close_clear_data="false" :visible.sync="show_dept_selector" @confirm="move_confirm" /> -->
          
        <EmployeeSelector
          :employee_not_select="employee_not_select"
          :can_select_employee="false"
          :can_select_dept="true"
          :dept_children="false"
          :selected="dept_selected"
          :visible.sync="show_dept_selector"
          @confirm="move_confirm"
        />

      </el-form-item>
      <el-form-item label="职位" prop="post" :label-width="formLabelWidth">
        <el-input @input="change($event)" placeholder="请输入职位" v-model="detailData.post" auto-complete="off" :disabled="detailData.status == 2 && managerId != 0"></el-input>
      </el-form-item>

      <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="yyyy-MM-dd"
          placeholder="选择日期" :disabled="detailData.status == 2 && managerId != 0" :picker-options="assistantOptions"></el-date-picker>
      </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> -->
      <!-- <div style="height: 30px;"></div> -->
      <el-form-item label="状态" prop="status" :label-width="formLabelWidth" v-if="managerId > 0">
        <el-select style="width: 100%;" disabled 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"
                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-tab-pane>
        <el-tab-pane label="固定积分" name="sec">
          <div style="height: 30px;"></div>

          <el-form-item v-for="(val,index) in fixed_rule" :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="danger" v-if="managerId!=0" v-show="detailData.status == 2 || detailData.status == 0"
          plain @click="delteOpert">删除</el-button>
        <el-button type="primary" :loading="join_loading" v-if="managerId!=0" v-show="detailData.status == 0 && get_employee_data.invite == 0" plain
          @click="join(false)">邀请加入</el-button>
        <el-button type="warning" @click="quit" v-if="managerId!=0" v-show="detailData.status == 1 && emportwdf !== '创始人'">办理离职</el-button>
        <el-button plain @click="discardBack">取消</el-button> 
        <el-button type="primary" :loading="loading" v-show="detailData.status != 2 || managerId == 0" plain @click="submitForm('detailForm')">保存</el-button>
      </div>
    </el-form>
    <commonDepartment :isMore='false' @changishow="cchangeDepart" @check="check" :isDepart="isDepart" />
  </div>
</template>

<script>
  import qs from "qs";
  import commonDepartment from '@/views/integral/commonDepartment'
  import EmployeeSelector from '@/views/common/EmployeeSelector'
  import clip from '@/utils/clipboard' // use clipboard directly

  export default {
    props: {
      managerId: {
        type: [String,Number,Array],
        default: 0
      },
      emportwdf:{
        type:  [String,Array]
      },
      dialogTableVisibleNone:{
         type:Boolean,
      }
    },
    components: {
      commonDepartment,
      EmployeeSelector
    },

    data() {

      let 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();
        }
      };
      // let validateName = (rule, value, callback) => {
      //   let validValue = value
      //     ? value.replace(/\s/g, "").replace(/&nbsp;/gi, "")
      //     : value;
      //   if (!validValue) {
      //     return callback(new Error("请填写姓名"));
      //   } else {
      //     callback();
      //   }
      // };
      let validateTel = (rule, value, callback) => {
        let validValue = value ?
          value.replace(/\s/g, "").replace(/&nbsp;/gi, "") :
          value;
        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 {
        name: '',
        isDepart: false,
        loading: false,
        join_loading: false,
        show_loading: false,
        activeName: "first",
        editMode: false,
        profile: this.$store.getters.user_info,
        dialogTableVisible: false,
        dialogCreateCategoryVisible: false,
        formLabelWidth: "85px",
        fixed_rule: [],
        detailData: {
          id: "",
          company_id: "",
          name: "",
          tel: "",
          status: 1,
          sex: 0,
          mail_address: "",
          accedence_time: "",
          post: '',
          // post: "",   职位  暂定
          dept_id: []
        },
        get_employee_data: {},
        dept_selected: {
          employee: [],
          dept: []
        },
        employeeStatus: [{
            value: 0,
            label: "待加入"
          },
          {
            value: 1,
            label: "在职"
          },
          {
            value: 2,
            label: "离职"
          },{
            value: 3,
            label: "再次邀请"
          }
        ],
        sexOptions: [{
            value: 0,
            label: "男"
          },
          {
            value: 1,
            label: "女"
          }
        ],
        idArray: [],
        deptTree: [],
        employeeList: [],

        employee_not_select: [],
        show_dept_selector: false,

        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"
            },
            {
              min: 1,
              max: 20,
              message: '长度在 2 到 20 个字符',
              trigger: 'blur'
            }
          ],
          name: [{
              required: true,
              message: '请输入姓名',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 20,
              message: '长度在 2 到 20 个字符',
              trigger: 'blur'
            }
          ],
          tel: [{
              required: true,
              message: '请输入手机号码',
              trigger: 'blur'
            },
            {
              validator: validateTel,
              trigger: "blur"
            }
          ],
          password: [{
            validator: validatePassword,
            trigger: "blur"
          }],
          password_check: [{
            validator: validatePasswordCheck,
            trigger: "blur"
          }],
          mail_address: [{
            validator: validateMailAddress,
            trigger: "blur"
          }]
        },
      };
    },
    methods: {
      handleCopy(text, event){
        clip(text, event)
      },
      // 邀请加入
      join(id) {
        let self = this
        self.join_loading = true
        let formid = null
        if (id) {
          formid = id
        } else {
          formid = self.managerId
        }
        self.$http('post','/api/invite/create', {id: formid}).then(res => {
          if (res.data.code == 1) {
            self.$message.success("已发送邀请加入信息")
          } else {
            self.$message.error(res.data.msg)
          }
        }).finally(() => {
          self.join_loading = false
        })
      },
      change(e) {
        this.$forceUpdate();
      },
      changeIsDepart() {
        this.isDepart = true;
      },
      cchangeDepart() {
        this.isDepart = false;
      },
      // 获取回传的上级部门id
      check(val) {
        console.log(val)
        let nearray = []
        let dept_id = '';
        for (let i = 0; i < val.length; i++) {
          dept_id = val[i].label + ',' + dept_id;
          nearray.push({
            dept_id: val[i].id
          })
        }
        this.name = dept_id
        this.idArray = nearray
      },
      // 二级菜单获取
      handleChange(label) {
        console.log(label)
      },
      //获取基本数据
      loadBaseData: function() {
        // let params = {
        //   site_id: this.profile.site_id,
        //   get_employee_list: 1
        // };
        var self = this;
        self.show_loading = true
        this.$http('get',"/api/department/tree")
          .then(function(response) {
            if (response.data.code == 1) {

              self.deptTree = response.data.data.list

              //  for(let i = 0; i < self.deptTree.length; i++) {
              //      self.deptTree[i].value = self.deptTree[i].id
              //      if(self.deptTree[i].children.length!=0) {
              //         for(let j = 0; j< self.deptTree[i].children.length;j++) {
              //           self.deptTree[i].children[j].value = self.deptTree[i].children[j].id
              //         }
              //      }

              // }
            }
          })
          .catch(function(error) {
            console.log(error);
          }).finally(() => {
            self.show_loading = false
          });
      },
      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.managerId = employeeId
        this.getDetial();
      },
      // 删除员工
      delteOpert() {
        this.$confirm('确定要删除该员工吗?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteItem();
        }).catch(() => {})
      },
      // 办理离职
      quit() {
        let self = this
        self.$confirm('给此员工办理离职将不可恢复，确认要办理离职吗？', '办理离职', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          self.$http('POST','/api/employee/quit',{id: self.managerId}).then((res) => {
            if (res.data.code == 1) {
              self.$message.success(res.data.msg)
              self.$emit("closeDetai");
              self.$emit("refresh");
            } else {
              self.$message.error(res.data.msg)
            }
          }).catch((e) => {
            self.$message.error(e.data.msg)
          })
        }).catch(()=>{

        })
      },
      deleteItem() {
        let self = this;
        console.log(self.$parent.$parent);
        this.$http('post','' + '/api/employee/delete?id=' + this.managerId)
          .then(res => {
            if (res.data.code == 1) {
              self.$refs["detailForm"].resetFields();
              self.$emit("closeDetai");
              self.$emit("refresh");
              self.$message({
                message: '删除成功',
                type: 'success'
              })
            }
          })
      },
      discardBack: function() {
        this.$emit("closeDetai");
        this.formrset();
      },
      formrset: function() {
        this.name = ''
        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 {

            return false;
          }
        });
      },
      // 获取部门详情
      getDetial() {
        if (this.managerId != 0) {
          this.show_loading = true
          this.$http('get','' + '/api/employee/info?id=' + this.managerId)
            .then(res => {
              if (res.data.code == 1) {
                let data = res.data.data;
                this.detailData.id = data.id;
                this.detailData.accedence_time = data.accedence_time;
                this.detailData.tel = data.tel;
                this.detailData.name = data.name;
                this.detailData.post = data.post;
                this.detailData.company_id = data.company_id;
                this.detailData.status = data.status;
                this.dept_selected.dept = data.employee_detail.dept_list||[];
                this.get_employee_data = data
                let ids = 0;
                let nearray = [];
                let newname = ''
                if (data.employee_detail.dept_list.length != 0) {
                  let newData = data.employee_detail.dept_list;
                  for (let i = 0; i < newData.length; i++) {
                    newname = newData[i].dept_name + ',' + newname
                    nearray.push({
                      dept_id: newData[i].dept_id,
                      dept_name: newData[i].dept_name
                    })
                  }
                  this.idArray = nearray;
                  this.name = newname;
                }
                // this.move_confirm()
                this.detailData.dept_list = nearray
                //  this.detailData.dept_id = nearray;
                //  console.log(this.detailData.dept_id)
              }
            }).catch(()=>{}).finally(()=>{
              this.show_loading = false
            })


        }
      },

      sendSaveRequest: function() {
        this.loading = true
        let formData = this.detailData;
        let length = 0;
        let url = this.managerId == 0 ? "/api/employee/create" : "/api/employee/update";
        if (this.managerId == 0 || this.managerId == '') {

        } else {
          formData.id = this.managerId;
          if(formData.dept_list.length == 0){
            formData.dept_list = ""
          }
        }
        var self = this;
        this.$http("post",url,formData,
          // headers: {
          //   "Content-Type": "application/x-www-form-urlencoded"
          // }
        ).then(function(response) {
          self.loading = false
          if (response.data.code == 1) {
            if (self.managerId == 0 || self.managerId == '') {
              self.join(response.data.data.id)
            }else if (self.$store.getters.user_info.id == formData.id) {
              self.$store.getters.user_info.name = formData.name
            }
            // self.$parent.$parent.dialogTableVisible = false;
            // self.$parent.$parent.currentPage = 0;
            // self.$parent.$parent.managerId = 0;
            // self.name = '';
            // self.idArray = [];
            // self.$parent.$parent.loadBaseData();
            self.$emit("closeDetai");
            self.$emit("refresh");
            self.$message({
              message: this.managerId == 0 ? '新增员工成功' : '编辑员工成功',
              type: 'success'
            })
            // self.$refs["detailForm"].resetFields();
          } else {
            self.$message({
              message: response.data.msg,
              type: 'error'
            })
          }
        }).catch(function(error) {
          self.loading = false
        });
      },
      clearForm() {
        this.detailData = {
          company_id: "",
          name: "",
          tel: "",
          status: '',
          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;
      },
      move_confirm(data) {
        if (data.dept !== null && data.dept.length != 0) {
          let arr = [],
            name = '',
            dept_list = []
          for (let i = 0; i < data.dept.length; i++) {
            arr.push(data.dept[i].dept_name)
          }
          this.name = arr.join(',')
          data.dept.forEach(element => {
            dept_list.push((({dept_id,dept_name}) => ({dept_id,dept_name}))(element));
          });
          this.detailData.dept_list = dept_list
          this.dept_selected.dept = dept_list
        } else {
          this.name = ''
          this.detailData.dept_list = []
        }
      },
    },
    watch: {
    },

    created() {
      this.getDetial();
      // 获取员工列表详
      this.loadBaseData();
      if (this.$route.params.targetId > 0) {
        // this.loadEmployeeDetail(this.$route.params.targetId);
      }
    }
  };
</script>
<style>
  .v-modal {
    z-index: 44 !important;
  }

  .bmxx .el-dialog__body {
    padding: 30px 100px 20px 10px !important;
  }

  /* .el-form .el-input {
    width: 50%;
} */
  .el-form-item {
    /* width: 50%;
    margin: 0 auto;
    margin-bottom: 22px; */
  }

  .el-form-item__label {
    font-weight: normal;

  }
</style>
