<template>
  <div class="app-container">
    <div class="app-container">
      <div class="filter-container">
        <el-button class="success" icon="el-icon-plus" @click="form_add"
          >新增</el-button
        >
      </div>
      <el-table
        v-loading="listLoading"
        element-loading-text="给我一点时间"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%"
        :row-style="rowStyle"
        :cell-style="cellStyle"
        class="elTable"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all
      >
        <el-table-column label="部门名称" header-align="center" width="250px">
          <template slot-scope="scope">
            <el-tag :type="scope.row.menutype | menutypeFilter" size="small">
              <span>{{ scope.row.dname }}</span>
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="备注" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="顺序"
          width="100px"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.sort }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="启用"
          width="100px"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enable"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="change_enable(scope.$index, scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          header-align="center"
          align="center"
          width="230"
          class-name="small-padding fixed-width"
          fixed="right"
        >
          <template slot-scope="{ row }">
            <el-button type="primary" size="mini" @click="form_edit(row)">
              编辑
            </el-button>
            <el-button
              v-if="row.status != '已删'"
              size="mini"
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
        width="40%"
      >
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="deptform"
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left: 50px"
        >
          <el-form-item label="上级部门" prop="parentid">
            <tree-select
              :disabled="disabled"
              :height="280"
              :width="200"
              size="small"
              :data="parent"
              :default-props="defaultProps"
              clearable
              :node-key="nodeKey"
              :checked-keys="defaultCheckedKeys"
              :expandAll="true"
              @popoverHide="popoverHide"
            />
          </el-form-item>
          <el-form-item label="部门名称" prop="dname">
            <el-input ref="dname" v-model="deptform.dname" />
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input ref="remark" v-model="deptform.remark" />
          </el-form-item>

          <el-form-item label="顺序" prop="sort">
            <el-input ref="sort" v-model="deptform.sort" />
          </el-form-item>
          <el-form-item label="启用" prop="enable">
            <el-switch
              ref="enable"
              v-model="deptform.enable"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            class="cancelClose"
            @click="
              dialogFormVisible = false;
              get_table_data();
            "
            >关闭</el-button
          >
          <el-button
            class="success"
            @click="
              dialogStatus === 'create' ? add_dialog_save() : form_edit_save()
            "
            >确认</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import TreeSelect from "@/components/TreeSelect";
import waves from "@/directive/waves"; // waves directive
import { isIntegerZero } from "@/utils/validate";
import {
  PostDataByName,
  GetDataByName,
  transData,
  failproccess,
} from "@/api/common";
import { MessageBox } from "element-ui";
export default {
  name: "DepartmentManagement",
  components: { TreeSelect },
  directives: { waves },

  filters: {
    menutypeFilter(menutype) {
      const menutypeMap = {
        menu: "",
        button: "warning",
      };
      return menutypeMap[menutype];
    },
  },
  data() {
    return {
      disabled: false,
      tableKey: 0,
      list: [{ deptname: "公司", id: 1, parentid: -1, remark: "" }],
      parent: [],
      parentmenu: [],
      parentButton: [],

      listLoading: true,
      requestParam: {
        name: "createdept",
        parammaps: {},
      },
      deptform: {
        id: "",
        dname: "",
        remark: "",
        sort: "",
        parentid: "",
        enable: "1",
      },
      get_table_dataParm: { name: "getDepartments" },
      getRecuListParm: { name: "getDepartmentCascade" },
      getRecuListBParm: {
        name: "getMenuListBRecu",
        idname: "id",
        parammaps: { id: 0 },
      },
      rules: {
        dname: [
          {
            type: "string",
            required: true,
            message: "部门名称必填",
            trigger: "change",
          },
        ],

        sort: [{ validator: isIntegerZero, trigger: "blur" }],
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "新增",
      },
      rowStyle: { maxHeight: 50 + "px", height: 45 + "px" },
      cellStyle: { padding: 0 + "px" },
      defaultProps: {
        children: "children",
        label: "title",
      },
      nodeKey: "id",
      defaultCheckedKeys: [],
    };
  },
  created() {
    this.get_table_data();
    this.get_select_list();
  },
  methods: {
    popoverHide(checkedIds, checkedData) {
      this.deptform.parentid = checkedIds;
    },

    get_table_data() {
      this.listLoading = true;
      GetDataByName(this.get_table_dataParm).then((response) => {
        if (response.data.list !== null) {
          console.log(this.list, "-----------------");
          for (var i = 0; i < response.data.list.length; i++) {
            response.data.list[i].enable = parseInt(
              response.data.list[i].enable
            );
          }
          this.list = transData(
            response.data.list,
            "id",
            "parentid",
            "children"
          );
        }

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false;
        }, 0.5 * 1000);
      });
    },
    get_select_list() {
      GetDataByName(this.getRecuListParm).then((response) => {
        if (response.data.list !== null) {
          this.parentmenu = transData(
            response.data.list,
            "id",
            "parentid",
            "children"
          );
        }
      });
    },
    refreshDownList() {
      for (var val of this.parentmenu) {
        this.parent = [];
        this.parent.push({
          id: val.id,
          title: val.title,
          parentid: val.parentid,
        });
      }
    },
    resetRequestParam() {
      this.deptform.id = "";
      this.deptform.parentid = "0";
      this.deptform.dname = "";
      this.deptform.remark = "";
      this.deptform.sort = "0";
      this.deptform.enable = 1;
    },
    form_add() {
      this.resetRequestParam();
      this.dialogStatus = "create";
      this.parent = this.parentmenu;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    add_dialog_save() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.requestParam.name = "insertDepartments";

          if (this.deptform.parentid === "") this.deptform.parentid = "0";

          this.requestParam.parammaps = {
            id: "",
            dname: this.deptform.dname,
            remark: this.deptform.remark,
            sort: this.deptform.sort,
            parentId: this.deptform.parentid,
            enable: this.deptform.enable,
          };

          PostDataByName(this.requestParam).then((response) => {
            console.log("新增保存发送参数", this.requestParam);
            if (response.msg !== "fail") {
              this.$notify({
                title: "成功",
                message: "保存成功",
                type: "success",
                duration: 2000,
              });
              this.dialogFormVisible = false;
              this.get_table_data();
              this.get_select_list();
            } else {
              this.$notify({
                title: "失败",
                message: "保存失败",
                type: "error",
                duration: 2000,
              });
            }
          });
        }
      });
    },

    form_edit(row) {
      this.parent = this.parentmenu;
      console.log("row=====>", row);
      this.defaultCheckedKeys = [row.parentid];
      console.log(this.defaultCheckedKeys);
      this.deptform.parentid = row.parentid;
      this.deptform.dname = row.dname;
      this.deptform.remark = row.remark;
      this.deptform.sort = row.sort;
      this.deptform.id = row.id;
      this.deptform.enable = row.enable;
      this.dialogStatus = "update";

      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    form_edit_save() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.requestParam.name = "updateDepartments";

          this.requestParam.parammaps = {
            id: this.deptform.id,
            dname: this.deptform.dname,
            remark: this.deptform.remark,
            sort: this.deptform.sort,
            parentId: this.deptform.parentid,
            enable: this.deptform.enable,
          };

          console.log(this.requestParam);
          PostDataByName(this.requestParam).then((response) => {
            console.log("编辑保存发送参数", this.requestParam);
            if (response.msg !== "fail") {
              this.get_table_data();
              this.dialogFormVisible = false;
              this.$notify({
                title: "成功",
                message: "保存成功",
                type: "success",
                duration: 2000,
              });
            } else {
              this.$notify({
                title: "失败",
                message: "保存失败",
                type: "error",
                duration: 2000,
              });
            }
          });
        }
      });
    },
    change_enable(index, row) {
      this.requestParam.name = "updateDepartments";
      this.requestParam.parammaps = {
        id: row.id,
        dname: row.dname,
        remark: row.remark,
        sort: row.sort,
        parentId: row.parentid,
        enable: row.enable,
      };

      PostDataByName(this.requestParam).then((response) => {
        console.log("编辑保存发送参数", this.requestParam);
        if (response.msg !== "fail") {
          this.get_table_data();
          this.dialogFormVisible = false;
          this.$notify({
            title: "成功",
            message: "保存成功",
            type: "success",
            duration: 2000,
          });
        } else {
          this.$notify({
            title: "失败",
            message: "保存失败",
            type: "error",
            duration: 2000,
          });
        }
      });
    },
    handleDelete(row) {
      MessageBox.confirm("确认删除此信息？", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.requestParam.name = "delDepartments";
        this.requestParam.parammaps = {
          id: row.id,
        };
        PostDataByName(this.requestParam).then(() => {
          this.get_table_data();
          this.dialogFormVisible = false;
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 2000,
          });
        });
      });
    },
  },
};
</script>
