<template>
  <div style=" background-color: #fff; padding:15px;">
    <div style="margin-top:15px; margin-bottom:15px;" class="inline-block-btn-list">
      <el-button
        class="first-element-btn"
        plain
        type="primary"
        @click="dialogCreateVisible = true"
        v-show="accessEnabled.add == 1"
      >新增部门</el-button>

      <div style="display:inline-block; width:220px;">
        <el-input
          placeholder="输入关键词查找"
          ref="search-bar"
          v-model="filter.keywords"
          class="input-with-select"
          @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="multipleTable"
      :data="tableData"
      :border="false"
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column prop="name" label="部门名称"></el-table-column>
      <el-table-column prop="parent_name" label="从属部门"></el-table-column>
      <el-table-column prop="main_manager_name" label="管理者"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            style="margin-right:15px;"
            type="text"
            @click="loadEmployeeList(1, scope.row.id)"
            :disabled="accessEnabled.assign != 1"
            v-bind:title="accessEnabled.assign != 1 ? '没有设置管理者的权限' : ''"
          >设置管理者</el-button>
          <el-button
            style="margin-right:15px;"
            type="text"
            @click="loadDeptInfo(scope.row.id)"
            :disabled="accessEnabled.edit != 1"
            v-bind:title="accessEnabled.edit != 1 ? '没有修改权限' : ''"
          >修改</el-button>

          <el-button
            type="text"
            @click="confirmDeleteItem(scope.row.id,scope.row.employee_count)"
            :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"
      :page-size="pageLimit"
      :page-sizes="[10, 20, 50, 100]"
      :total="totalCount"
      :current-page.sync="currentPage"
      @size-change="handleSizeChange"
      @current-change="changePage"
    ></el-pagination>
    <el-dialog
      title="新增部门"
      width="600px"
      :visible.sync="dialogCreateVisible"
      :close-on-click-modal="false"
      @open="loadDeptTree"
      @close="onDismissCreateDialog"
    >
      <el-form
        ref="newDeptForm"
        :model="newDeptForm"
        :rules="rules"
        @submit.native.prevent
        style="padding-right:20px;"
      >
        <el-form-item label="部门名称" prop="name" :label-width="formLabelWidth">
          <el-input v-model="newDeptForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="从属部门" prop="pid" :label-width="formLabelWidth">
          <el-cascader v-model="newDeptForm.pid" clearable :options="deptTree" change-on-select></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCreateVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCreateForm('newDeptForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="编辑部门"
      width="600px"
      :visible.sync="dialogEditVisible"
      :close-on-click-modal="false"
      @close="onDismissEditDialog"
    >
      <el-form
        ref="deptForm"
        :model="deptForm"
        :rules="rules"
        @submit.native.prevent
        style="padding-right:20px;"
      >
        <el-form-item label="部门名称" prop="name" :label-width="formLabelWidth">
          <el-input v-model="deptForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="从属部门" prop="pid" :label-width="formLabelWidth">
          <el-cascader v-model="deptForm.pid" clearable :options="deptTree" change-on-select></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm('deptForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="dialogAssignManager.title"
      width="660px"
      :visible.sync="dialogAssignManagerVisible"
      :close-on-click-modal="false"
      @close="resetDialogAssignManager"
    >
      <div style="padding-left:60px; padding-bottom:10px;">
        <el-transfer
          v-model="assignedValues"
          filterable
          target-order="origin"
          :titles="dialogAssignManager.transferTitles"
          :data="assignableList"
        ></el-transfer>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button @click="dialogAssignManagerVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveManagerAssigns">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    let validateName = (rule, value, callback) => {
      var validValue = value
        ? value.replace(/\s/g, "").replace(/&nbsp;/gi, "")
        : value;
      if (!validValue) {
        return callback(new Error("请填写部门名称"));
      } else {
        callback();
      }
    };
    return {
      profile: this.$store.getters.user_info,
      pageLimit: 10,
      category_list: [],
      totalCount: 0,
      loading: false,
      tableData: null,
      currentPage: 1,
      dialogCreateVisible: false,
      dialogEditVisible: false,
      dialogAssignManagerVisible: false,
      formLabelWidth: "90px",
      newDeptForm: {
        name: "",
        pid: []
      },
      deptForm: {
        id: "",
        name: "",
        pid: []
      },
      rules: {
        name: [{ validator: validateName, trigger: "blur" }]
      },
      deptTree: [],
      filter: {
        keywords: ""
      },
      assignableList: [],
      assignedValues: [],
      dialogAssignManager: {
        manager_type: 0,
        title: "",
        transferTitles: []
      },
      dialogTypeDepartment: {
        manager_type: 1,
        title: "部门管理",
        transferTitles: ["员工列表", "部门管理"]
      },
      dialogTypeDeputy: {
        manager_type: 2,
        title: "公司管理",
        transferTitles: ["员工列表", "公司管理"]
      },
      dialogTypeCompany: {
        manager_type: 3,
        title: "积分管理员",
        transferTitles: ["员工列表", "积分管理员"]
      },
      accessEnabled: {
        add: 0,
        delete: 0,
        edit: 0,
        assign: 0
      }
    };
  },
  methods: {
    onFilterChanged: function() {
      this.currentPage = 1;
      this.loadDeptList();
    },

    toggleSelection: function(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    onDismissCreateDialog: function() {
      //更新树形图

      var form = this.$refs["newDeptForm"];
      form.clearValidate();
      this.newDeptForm = {
        name: "",
        pid: []
      };
    },
    onDismissEditDialog: function() {
      var form = this.$refs["deptForm"];
      form.clearValidate();
      this.deptForm = {
        id: "",
        name: "",
        pid: []
      };
    },
    submitCreateForm: function(formName) {
      let form = this.$refs[formName];
      var self = this;
      form.validate(valid => {
        if (valid) {
          if (form) {
            self.sendCreateRequest();
          }
        } else {
          //console.log('验证未通过');
          return false;
        }
      });
    },
    submitEditForm: function(formName) {
      var form = this.$refs[formName];
      var self = this;
      form.validate(valid => {
        if (valid) {
          if (form) {
            self.sendEditRequest(form);
          }
        } else {
          //console.log('验证未通过');
          return false;
        }
      });
    },
    sendCreateRequest: function() {
      let dataObj = this.newDeptForm;
      let formData = {};
      for (let item in dataObj) {
        if (item == "pid") {
          let 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;
      var self = this;
      this.$http("post","/integral.php/ajax_request_common/add_dept",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) {
          let message = "";
          let status = 0;
          if (response.status == 200) {
            let 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.currentPage = 1;
            self.loadDeptList();
            self.dialogCreateVisible = false;
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    sendEditRequest: function() {
      let dataObj = this.deptForm;
      let formData = {};
      for (let item in dataObj) {
        if (item == "pid") {
          let length = dataObj[item].length;
          formData[item] = length == 0 ? 0 : dataObj[item][length - 1];
        } else {
          if (!dataObj[item]) {
            continue;
          }
          formData[item] = dataObj[item];
        }
      }
      var self = this;
      this.$http("post","/integral.php/ajax_request_common/update_dept",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) {
          let message = "";
          let status = 0;
          if (response.status == 200) {
            let 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;
              case -3:
                message = "组织架构冲突，不能将子部门设置为从属部门";
                break;
              default:
                message = "修改部门失败";
            }
          } else {
            message = "服务器出现问题";
          }
          self.$message({
            message: message,
            type: status == 1 ? "success" : "error"
          });
          if (status == 1) {
            self.loadDeptList();
            self.dialogEditVisible = false;
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    //获取部门列表
    loadDeptList: function() {
      this.loading = true;
      let params = {
        site_id: this.profile.site_id,
        page: this.currentPage,
        interval: this.pageLimit
      };
      for (let item in this.filter) {
        let value = this.filter[item];
        if (value) {
          params[item] = value;
        }
      }
      var self = this;
      this.$http('get',"/integral.php/ajax_request_common/get_dept_list",params)
        .then(function(response) {
          if (response.status == 200) {
            self.loading = false;
            var jsonData = response.data;
            try {
              self.totalCount = jsonData.total_count;
              self.tableData = jsonData.list_data;
            } catch (err) {
              console.log(err);
            }
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    handleSizeChange(val){
      this.pageLimit = val
      this.onFilterChanged()
    },
    changePage: function(current) {
      if (isNaN(current) || current < 1) {
        return false;
      }
      this.loadDeptList();
    },
    confirmDeleteItem: function(deptId, employCount) {
      if (employCount == 0) {
        this.$confirm("确定要删除此部门吗?", "删除部门", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.deleteItem(deptId);
          })
          .catch(() => {
            //console.log('已取消删除');
          });
      }else{
        this.deleteItem(deptId);
      }
    },
    deleteItem: function(deptId) {
      if (isNaN(deptId) || deptId < 1) {
        return false;
      }
      var self = this;
      this.$http('get',"/integral.php/ajax_request_common/delete_dept",{id: deptId})
        .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 = data.info;
                break;
              default:
                message = "删除部门失败";
            }
          } else {
            message = "服务器出现问题";
          }
          self.$message({
            message: message,
            type: status == 1 ? "success" : "error"
          });
          if (status == 1) {
            self.loadDeptList();
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    //获取级联部门选单
    loadDeptTree: function() {
      var self = this;
      this.$http('get',"/integral.php/ajax_request_common/get_dept_list_cascaded",{site_id: this.profile.site_id})
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data;
            try {
              self.deptTree = jsonData;
            } catch (err) {
              console.log(err);
            }
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    //获取部门信息
    loadDeptInfo: function(deptId) {
      console.log(deptId);
      var self = this;
      this.$http('get',"/integral.php/ajax_request_common/get_dept_info",{id: deptId})
        .then(function(response) {
          if (response.status == 200) {
            let jsonData = response.data;
            try {
              self.deptTree = jsonData.tree;
              self.deptForm.id = jsonData.dept_info.id;
              self.deptForm.name = jsonData.dept_info.name;
              if (jsonData.path) {
                let pathStrArray = jsonData.path.split(",");
                let pathArray = pathStrArray.map(data => {
                  return +data;
                });
                self.deptForm.pid = pathArray;
              } else {
                self.deptForm.pid = [];
              }
              self.dialogEditVisible = true;
            } catch (err) {
              console.log(err);
            }
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    resetDialogAssignManager: function() {
      this.dialogAssignManager = {
        manager_type: 0,
        title: "",
        transferTitles: []
      };
      this.assignableList = this.assignedValues = [];
    },
    loadEmployeeList: function(managerType, deptId) {
      deptId = deptId || 0;
      switch (managerType) {
        case 1:
          this.dialogTypeDepartment.dept_id = deptId;
          this.dialogAssignManager = this.dialogTypeDepartment;
          break;
        case 2:
          this.dialogAssignManager = this.dialogTypeDeputy;
          break;
        case 3:
        case 4:
          this.dialogAssignManager = this.dialogTypeCompany;
          break;
      }
      let params = {
        site_id: this.profile.site_id,
        manager_type: managerType
      };
      if (deptId > 0) {
        params.dept_id = deptId;
      }
      var self = this;
      this.$http('get',"/integral.php/ajax_request_common/get_manager_transfer",params)
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data;
            try {
              let assignableList = [];
              for (let employee in jsonData.assignable_list) {
                let value = jsonData.assignable_list[employee];
                let item = {
                  key: value.id,
                  label: value.name
                };
                if (value.id == jsonData.creator_id) {
                  item.disabled = true;
                }
                assignableList.push(item);
              }
              self.assignableList = assignableList;
              self.assignedValues = jsonData.assigned_values;
              console.log(self.assignableList, self.assignedValues);
              self.dialogAssignManagerVisible = true;
            } catch (err) {
              console.log(err);
            }
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    saveManagerAssigns: function() {
      let params = {
        site_id: this.profile.site_id,
        manager_type: this.dialogAssignManager.manager_type,
        values: this.assignedValues.join(",")
      };
      if (this.dialogAssignManager.dept_id) {
        params.dept_id = this.dialogAssignManager.dept_id;
      }
      var self = this;
      this.$http('get',"/integral.php/ajax_request_common/save_manager_assigns",params)
        .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.loadDeptList();
            self.dialogAssignManagerVisible = false;
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    //获取具体权限（对积分管理员/公司管理员生效）
    loadAccessItemFlag: function() {
      var self = this;
      this.$http('get',"/integral.php/ajax_request_common/get_access_flag",{id: this.profile.id,page_name: "dept_master"})
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data;
            try {
              self.accessEnabled = jsonData;
            } catch (err) {
              console.log(err);
            }
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    }
  },
  created() {
    this.loadDeptList();
    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();
    }
  }
};
</script>

<style>
.el-pagination {
  text-align: center;
  margin-top: 15px;
}
</style>
