<template>
  <div style=" position: relative;" class>
    <el-tabs v-model="activeName1" type="card">
      <!-- <div
        class="left"
        style=" background-color: #fff; padding:15px; min-height: 10px; overflow: hidden;"
       > -->
        <el-tab-pane style=" background-color: #fff; padding:15px; min-height: 10px; overflow: hidden;" class="top" label="管理职位" name="second">
          <el-col>
            <div style="margin-top:2px; margin-bottom:15px;" class="inline-block-btn-list">
              <el-button
                class="first-element-btn"
                style
                v-show="!assignMode"
                @click="getAssignJob"
                :disabled="accessEnabled.assign != 1"
                v-bind:title="accessEnabled.assign != 1 ? '没有指定职位的权限' : ''"
                type="primary"
                plain
              >任命职位</el-button>
              <!-- assignMode = true -->
              <el-select
                v-model="jobType"
                v-show="assignMode"
                @change="jobSelect"
                size="small"
                clearable
              >
                <el-option
                  v-for="item in allJobList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>

              <el-button
                type="primary"
                plain
                v-show="assignMode"
                @click="saveJobAssigns"
                style="margin-left:0px;"
              >应用</el-button>
              <el-button v-show="assignMode" @click="assignMode = false" plain>取消</el-button>
              <el-cascader
                v-if="false"
                clearable
                :options="deptTree"
                change-on-select
                v-show="!assignMode"
                v-model="employeeFilter.dept_id"
                @change="onFilterChanged"
                placeholder="选择部门进行筛选"
              ></el-cascader>

              <div style="position:relative; display:inline-block;">
                <el-button
                  @click.stop="show3 = !show3"
                  style="color:rgb(192 196 204); padding-right:25px;"
                >
                  <span
                    style="max-width: 150px; display: inline-block; overflow: hidden;"
                    :class="{'treeActice':textTip != '选择部门进行筛选'}"
                  >{{textTip}}</span>
                  <span class="el-input__suffix">
                    <span class="el-input__suffix-inner">
                      <i :class="{'arrRotation': show3}" class="el-input__icon el-icon-arrow-down"></i>
                    </span>
                  </span>
                </el-button>
                <el-collapse-transition>
                  <div
                    v-show="show3"
                    style="margin-top:10px;
             padding:6px 0;
             max-height:250px;
             min-width: 180px;
             overflow: auto;
             position:absolute;
             z-index:99;
             border: 1px solid #e4e7ed;
             border-radius: 2px;
             background:#fff;
             box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);"
                  >
                    <el-tree
                      node-key="value"
                      ref="tree"
                      :data="deptTree"
                      :accordion="true"
                      :highlight-current="true"
                      :props="defaultProps"
                      show-checkbox
                      @check="handleCheck"
                    ></el-tree>
                  </div>
                </el-collapse-transition>
              </div>

              <div
                class="gap-right-8"
                v-show="!assignMode"
                style="display:inline-block; width:250px;"
              >
                <el-input
                  placeholder="输入关键词查找"
                  ref="search-bar"
                  v-model="employeeFilter.keywords"
                  class="input-with-select"
                  @change="onFilterChanged"
                  @keyup.enter.native="onFilterChanged"
                >
                  <el-button slot="append" icon="el-icon-search" @click="onFilterChanged"></el-button>
                </el-input>
              </div>
            </div>
            <el-table
              v-loading="loading"
              ref="employeeTable"
              :data="employeeList"
              :border="false"
              tooltip-effect="dark"
              @selection-change="handleSelectionChange"
              style="width: 100%"
            >
              <el-table-column
                :selectable="isSelectable"
                type="selection"
                width="55"
                v-if="assignMode"
              ></el-table-column>
              <el-table-column prop="name" label="名称"></el-table-column>
              <el-table-column label="职位">
                <template slot-scope="scope">
                  <!-- <div>
                    <el-select v-model="scope.row.job_id" v-show="assignMode" size="small" clearable>
                      <el-option
                        v-for="item in allJobList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                    <span v-show="!assignMode" style="line-height:32px;">{{ scope.row.job_name ? scope.row.job_name : '未指定' }}</span>
                  </div>-->
                  <span
                    style="line-height:32px;"
                  >{{ scope.row.job_name ? scope.row.job_name : '未指定' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="dept_name" label="部门"></el-table-column>
              <el-table-column prop="manager_type_name" label="用户类型"></el-table-column>
            </el-table>
            <el-pagination
              background
              layout="total,sizes, prev, pager, next"
              @size-change="handleSizeChange"
              :page-size="pageLimit"
              :page-sizes="[10, 20, 50, 100]"
              :total="employeeCount"
              :current-page.sync="employeePage"
              @current-change="changeEmployeePage"
            ></el-pagination>
          </el-col>
        </el-tab-pane>
      <!-- </div> -->
      <!-- <div
        class="right"
        style=" background-color: #fff; min-height: 10px; padding:0 15px 15px 15px; overflow: hidden;"
      > -->
        <el-tab-pane style=" background-color: #fff; min-height: 10px; padding: 15px; overflow: hidden;" label="新建职位" name="first">
          <el-col>
            <el-button
              type="primary"
              plain
              @click="dialogCreateJobVisible=true"
              v-show="accessEnabled.add == 1"
              style="margin-left:0px;"
            >增加职位</el-button>
            <el-table
              ref="jobTable"
              :data="jobList"
              :border="false"
              tooltip-effect="dark"
              style="width: 100%"
            >
              <el-table-column prop="name" label="名称"></el-table-column>
              <el-table-column prop="remark" label="备注"></el-table-column>
              <el-table-column label="操作" width="158">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click="loadJobInfo(scope.row.id)"
                    size="small"
                    :disabled="accessEnabled.edit != 1"
                    v-bind:title="accessEnabled.edit != 1 ? '没有编辑权限' : ''"
                  >编辑</el-button>
                  <el-button
                    type="text"
                    @click="confirmDelete(scope.row.id)"
                    size="small"
                    :disabled="accessEnabled.delete != 1"
                    v-bind:title="accessEnabled.delete != 1 ? '没有删除权限' : ''"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              background
              layout="total,sizes, prev, pager, next"
              @size-change="handleSizeChange"
              :page-size="pageLimit"
              :page-sizes="[10, 20, 50, 100]"
              :total="jobCount"
              :current-page.sync="jobPage"
              @current-change="changeJobPage"
            ></el-pagination>
          </el-col>
          <el-dialog
            title="新建职位"
            width="600px"
            :visible.sync="dialogCreateJobVisible"
            :close-on-click-modal="false"
            @close="onDismissCreateJobDialog"
          >
            <el-form
              ref="newJobForm"
              :model="newJobForm"
              :rules="jobRules"
              @submit.native.prevent
              style="padding-right:20px;"
            >
              <el-form-item label="职位名称" prop="name" :label-width="formLabelWidth">
                <el-input v-model="newJobForm.name" placeholder="输入职位名称" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="备注" prop="remark" :label-width="formLabelWidth">
                <el-input
                  v-model="newJobForm.remark"
                  placeholder="输入备注（最多50字）"
                  auto-complete="off"
                  type="textarea"
                  :rows="3"
                  resize="none"
                  style="margin-top:5px;"
                ></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogCreateJobVisible = false">取 消</el-button>
              <el-button type="primary" @click="submitCreateJobForm('newJobForm')">确 定</el-button>
            </div>
          </el-dialog>
          <el-dialog
            title="编辑职位"
            width="600px"
            :visible.sync="dialogEditJobVisible"
            :close-on-click-modal="false"
            @close="onDismissEditJobDialog"
          >
            <el-form
              ref="jobForm"
              :model="jobForm"
              :rules="jobRules"
              @submit.native.prevent
              style="padding-right:20px;"
            >
              <el-form-item label="职位名称" prop="name" :label-width="formLabelWidth">
                <el-input v-model="jobForm.name" placeholder="输入职位名称" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="备注" prop="remark" :label-width="formLabelWidth">
                <el-input
                  v-model="jobForm.remark"
                  placeholder="输入备注（最多50字）"
                  auto-complete="off"
                  type="textarea"
                  :rows="3"
                  resize="none"
                  style="margin-top:5px;"
                ></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogEditJobVisible = false">取 消</el-button>
              <el-button type="primary" @click="submitEditJobForm('jobForm')">确 定</el-button>
            </div>
          </el-dialog>
        </el-tab-pane>
      <!-- </div> -->
    </el-tabs>
  </div>
</template>


<script>
export default {
  data() {
    const validateName = (rule, value, callback) => {
      var validValue = value
        ? value.replace(/\s/g, '').replace(/&nbsp;/gi, '')
        : value
      if (!validValue) {
        return callback(new Error('请填写职位名称'))
      } else {
        callback()
      }
    }
    return {
      show3: false,
      textTip: '选择部门进行筛选',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      jobType: '',
      multipleSelection: [],
      profile: this.$store.getters.user_info,
      jobList: [],
      allJobList: [],
      employeeList: [],
      jobCount: 0,
      loading: false,
      jobPage: 1,
      pageLimit: 10,
      employeeCount: 0,
      employeePage: 1,
      formLabelWidth: '90px',
      dialogCreateJobVisible: false,
      dialogEditJobVisible: false,
      activeName1: 'second',
      newJobForm: {
        name: '',
        remark: ''
      },
      jobForm: {
        id: '',
        name: '',
        remark: ''
      },
      jobRules: {
        name: [{ validator: validateName, trigger: 'blur' }]
      },
      assignMode: false,
      employeeFilter: {
        dept_id: [],
        keywords: ''
      },
      deptTree: [],
      accessEnabled: {
        add: 0,
        delete: 0,
        edit: 0,
        assign: 0
      }
    }
  },
  methods: {
    handleCheck(target, param) {
      this.textTip = ''
      const textTip = []
      this.$refs.tree.getCheckedNodes().forEach(item => {
        textTip.push(item.label)
      })
      this.textTip = textTip.join('、')
      if (param.checkedKeys.length == 0) {
        this.textTip = '选择部门进行筛选'
        this.show3 = false
      }
      this.employeeFilter.dept_id = param.checkedKeys
      this.onFilterChanged()
    },
    jobSelect() {
      this.multipleSelection.forEach(item => {
        item.job_id = this.jobType
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      // 先选择职位类型
      if (this.jobType) {
        this.multipleSelection.forEach(item => {
          item.job_id = this.jobType
        })
      }
    },
    isSelectable(row, index) {
      return true
    },
    handleSizeChange(val) {
      this.pageLimit = val
      this.onFilterChanged()
    },

    onFilterChanged: function() {
      this.employeePage = 1
      this.loadEmployeeList()
    },
    handleClick(tab, event) {
      console.log(tab, event)
    },
    getAssignJob() {
      this.assignMode = true
      this.loadAllJobList()
    },
    loadAllJobList() {
      this.loading = true
      this.$http('get','/integral.php/ajax_request_common/get_job_list',{
            site_id: this.profile.site_id,
            interval: 1000
          })
        .then(response => {
          if (response.status == 200) {
            this.loading = false
            var jsonData = response.data
            try {
              // this.jobCount = jsonData.count
              this.allJobList = jsonData.data
              this.allJobList.push({ id: -1, name: '未指定', remark: null, site_id: jsonData.data[0].site_id })
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    loadJobList: function() {
      var self = this
      self.loading = true
      this.$http('get','/integral.php/ajax_request_common/get_job_list',{
            site_id: this.profile.site_id,
            page: this.jobPage
          })
        .then(function(response) {
          if (response.status == 200) {
            self.loading = false
            var jsonData = response.data
            try {
              self.jobCount = jsonData.count
              self.jobList = jsonData.data
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    changeJobPage: function(currentVal) {
      if (isNaN(currentVal) || currentVal < 1) {
        return false
      }
      this.loadJobList()
    },
    changeEmployeePage: function(currentVal) {
      if (isNaN(currentVal) || currentVal < 1) {
        return false
      }
      this.loadEmployeeList()
    },
    onDismissCreateJobDialog: function() {
      const form = this.$refs['newJobForm']
      form.resetFields()
      form.clearValidate()
    },
    onDismissEditJobDialog: function() {
      const form = this.$refs['jobForm']
      form.resetFields()
      form.clearValidate()
    },
    submitCreateJobForm: function(formName) {
      var form = this.$refs[formName]
      var self = this
      form.validate(valid => {
        if (valid) {
          if (form) {
            self.sendCreateJobRequest()
          }
        } else {
          // console.log('验证未通过')
          return false
        }
      })
    },
    submitEditJobForm: function(formName) {
      var form = this.$refs[formName]
      var self = this
      form.validate(valid => {
        if (valid) {
          if (form) {
            self.sendEditJobRequest()
          }
        } else {
          // console.log('验证未通过');
          return false
        }
      })
    },
    confirmDelete(jobId) {
      this.$confirm('确定要删除此职位吗?', '删除职位', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteJob(jobId)
        })
        .catch(() => {
          // console.log('已取消删除');
        })
    },
    loadJobInfo(jobId) {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/get_job_info',{
            id: jobId
          })
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.jobForm = jsonData
              self.dialogEditJobVisible = true
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    sendCreateJobRequest: function() {
      var dataObj = this.newJobForm
      var formData = {}
      for (const item in dataObj) {
        if (!dataObj[item]) {
          continue
        }
        formData[item] = dataObj[item]
      }
      formData['site_id'] = this.profile.site_id
      var self = this
      this.$http('post','/integral.php/ajax_request_common/add_job',formData,'','',
        {transformRequest: [
          data => {
            const paramArray = new Array()
            for (const 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)
            switch (status) {
              case 1:
                message = '新增职位成功'
                break
              case -1:
                message = '表单参数错误'
                break
              case -2:
                message = '该职位名称已经存在，请改用其他名称'
                break
              default:
                message = '新增部门失败'
            }
          } else {
            message = '服务器出现问题'
          }
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          })
          if (status == 1) {
            self.jobPage = 1
            self.dialogCreateJobVisible = false
            self.loadJobList()
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    sendEditJobRequest: function() {
      var dataObj = this.jobForm
      var formData = {}
      for (const item in dataObj) {
        if (!dataObj[item]) {
          continue
        }
        formData[item] = dataObj[item]
      }
      var self = this
      this.$http('post','/integral.php/ajax_request_common/update_job',formData,'','',
        {transformRequest: [
          data => {
            const paramArray = new Array()
            for (const 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)
            switch (status) {
              case 1:
                message = '修改职位成功'
                break
              case -1:
                message = '表单参数错误'
                break
              case -2:
                message = '该职位名称已经存在，请改用其他名称'
                break
              default:
                message = '修改职位失败'
            }
          } else {
            message = '服务器出现问题'
          }
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          })
          if (status == 1) {
            self.dialogEditJobVisible = false
            self.loadJobList()
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    deleteJob(jobId) {
      if (isNaN(jobId) || jobId < 1) {
        return false
      }
      var self = this
      this.$http('get','/integral.php/ajax_request_common/delete_job',{id: jobId})
        .then(function(response) {
          var message = ''
          var status = 0
          if (response.status == 200) {
            var data = response.data
            status = isNaN(data.status) ? 0 : parseInt(data.status)
            switch (status) {
              case 1:
                message = '删除职位成功'
                break
              case -1:
                message = '表单参数错误'
                break
              default:
                message = '删除职位失败'
            }
          } else {
            message = '服务器出现问题'
          }
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          })
          if (status == 1) {
            self.loadJobList()
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    // 获取基本数据
    loadBaseData() {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/get_org_base',{site_id: this.profile.site_id})
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.deptTree = jsonData.tree
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    // 获取员工列表
    loadEmployeeList() {
      var self = this
      var params = {
        site_id: this.profile.site_id,
        page: this.employeePage,
        interval: this.pageLimit
      }
      for (const item in this.employeeFilter) {
        const value = this.employeeFilter[item]
        if (item == 'dept_id') {
          if (!value || value.length == 0) {
            continue
          }
          params[item] = value
          // params[item] = value[value.length - 1]
        } else {
          const valueStr = value.toString()
          if (valueStr && valueStr.length > 0) {
            params[item] = valueStr
          }
        }
      }
      this.$http('get','/integral.php/ajax_request_common/get_employee_list',params)
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.employeeCount = jsonData.total_count
              self.employeeList = jsonData.list_data.map(value => {
                value.job_id = value.job_id > 0 ? value.job_id : ''
                return value
              })
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    saveJobAssigns() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请先选择员工',
          type: 'warning'
        })
        return false
      }
      console.log('this.jobType--------??')
      console.log(this.jobType)
      if (!this.jobType) {
        this.$message({
          message: '请指定职位',
          type: 'warning'
        })
        return false
      }
      const jobPairs = this.multipleSelection.map(value => {
        const item = {
          id: value.id,
          job_id: value.job_id
        }
        return item
      })
      var self = this
      this.$http('post','/integral.php/ajax_request_common/assign_jobs',{pairs: JSON.stringify(jobPairs)},'','',
        {transformRequest: [
          data => {
            const paramArray = new Array()
            for (const 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)
            switch (status) {
              case 1:
                message = '职位设置成功'
                break
              case -1:
                message = '表单参数错误'
                break
              default:
                message = data.info ? data.info : '职位设置失败'
            }
          } else {
            message = '服务器出现问题'
          }
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          })
          if (status == 1) {
            self.loadEmployeeList()
            self.assignMode = false
          }
        })
    },
    // 获取具体权限（对积分管理员/公司管理员生效）
    loadAccessItemFlag: function() {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/get_access_flag',{id: this.profile.id,page_name: 'job_master'})
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.accessEnabled = jsonData
            } catch (err) {
              console.log(err)
            }
          }
        })
    }
  },
  created() {
    this.loadJobList()
    this.loadBaseData()
    this.loadEmployeeList()
    if (this.profile.manager_type == 4) {
      this.accessEnabled = {
        add: 1,
        delete: 1,
        edit: 1,
        assign: 1
      }
    } else if (this.profile.manager_type > 1) {
      this.loadAccessItemFlag()
    }

    this.$nextTick(() => {
      document.querySelector('#app').addEventListener('click', () => {
        if (this.show3) {
          this.show3 = false
        }
      })
    })
  }
}
</script>

<style>
.paiming .el-tabs__content {
  overflow: visible;
}

.paiming .el-tabs__nav-wrap {
  background-color: #5b8bf7;
  padding: 3px 3px 0 3px;
  border-radius: 3px 3px 0 0;
}

.paiming .el-tabs__item {
  color: #fff;
  border: none;
  font-weight: normal;
}

.paiming .el-tabs--card > .el-tabs__header .el-tabs__nav {
  border: none;
}

.paiming .el-tabs--card > .el-tabs__header .el-tabs__item {
  border: none;
}

.paiming .is-active {
  background-color: #fff;
  color: rgba(96, 98, 102, 1);
  border-radius: 3px 3px 0 0;
}

.paiming .el-tabs__item.is-active {
  color: rgba(96, 98, 102, 1);
}

.el-tabs__header {
  margin: 0;
}

.el-pagination {
  text-align: center;
  margin-top: 15px;
}

.arrRotation {
  transform: rotate(180deg);
}
.treeActice {
  color: #606266;
}
.el-tree-node__content {
  height: 34px;
}
</style>
