<template>
  <div>
    <!--    部门信息相关-->
    <el-card>
      <el-form
        :inline="true"
        :model="filterQuery"
        class="query-form"
        size="mini"
      >
        <el-row>
          <el-form-item class="query-form-item" label="部门名称:">
            <el-input
              v-model="filterQuery.name"
              placeholder="请输入部门名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item class="query-form-item" label="状态:">
            <el-select
              v-model="filterQuery.status"
              placeholder="请选择状态:"
              clearable
            >
              <el-option label="全部" value=""></el-option>
              <el-option label="禁用" :value="0"></el-option>
              <el-option label="正常" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button-group>
              <el-button type="primary" icon="el-icon-refresh" @click="onReset"
              >重置
              </el-button>
              <el-button type="primary" @click="onSubmit" icon="el-icon-search"
              >查询
              </el-button>
              <!--              <el-button type="primary" @click="addDeptDialog"-->
              <!--                         icon="el-icon-plus"-->
              <!--              >新增-->
              <!--              </el-button-->
              <!--              >-->
              <el-button
                type="primary"
                icon="el-icon-sort"
                @click="toggleExpandAll"
              >展开/折叠
              </el-button>
            </el-button-group>
          </el-form-item>
        </el-row>
      </el-form>
      <el-table
        v-loading="loading"
        :data="list"
        style="width: 100%"
        ref="deptTableRef"
        highlight-current-row
        border
        v-if="refreshTable"
        row-key="id"
        @current-change="handleDeptChange"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="部门名称" prop="name"></el-table-column>
        <el-table-column label="部门编码" prop="code"></el-table-column>
        <el-table-column label="状态" prop="status">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status | statusFilterType"
            >{{ scope.row.status | statusFilterName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="允许供应商使用" prop="spUse">
          <template slot-scope="scope">
            <el-tag :type="scope.row.spUse | spUerFilterType"
            >{{ scope.row.spUse | spUerFilterName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否为维修部门" prop="isMaintenance">
          <template slot-scope="scope">
            <el-tag :type="scope.row.maintenance |maintenanceFilterType"
            >{{ scope.row.maintenance | maintenanceFilterName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              :disabled="scope.row.status == 0"
              @click.native.stop="subAddDeptDialog(scope.row)"
            >新增
            </el-button>

            <el-button
              type="text"
              @click.native.stop="updateDeptDialog(scope.row)"
            >编辑
            </el-button>

            <el-button type="text" @click.native.stop="deleteDialog(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        :title="formMap[formName]"
        :before-close="cancelDialog"
        :visible.sync="formVisible"
        width="45%"
      >
        <el-form
          :model="formData"
          ref="dataForm"
          :rules="rules"
          label-width="150px"
        >
          <el-row>
            <el-form-item label="上级部门:" v-if="formData.pid != 0">
              <treeselect
                v-model="formData.pcode"
                :options="deptOptions"
                :normalizer="normalizer"
                :disabled="isShow"
                style="width: 90%"
                placeholder="选择上级部门"
              />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="部门名称:" prop="name">
              <el-input
                v-model="formData.name"
                style="width: 90%"
                clearable
                size="small"
              ></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="状态:" prop="status">
              <el-radio-group
                :disabled="formData.pid == 0"
                v-model="formData.status"
              >
                <el-radio :label="1">正常</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-row>

          <el-form-item
            label="是否能被供应商使用"
            prop="spUse"
            class="query-form-item"
          >
            <el-radio-group v-model="formData.spUse">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="是否为维修部门"
            prop="isMaintenance"
            class="query-form-item"
          >
            <el-radio-group v-model="formData.maintenance">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-row>
            <el-form-item label="备注:" prop="remark">
              <el-input
                v-model="formData.remark"
                size="small"
                clearable
                type="textarea"
                style="width: 90%"
              ></el-input>
            </el-form-item>
          </el-row>
          <!--          <el-row>
                      <el-form-item label="数据权限" label-width="100px">
                        <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
                        <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
                        <el-tree
                          class="tree-border"
                          :data="menuOptions"
                          show-checkbox
                          ref="menu"
                          node-key="id"
                          style="width: 90%"
                          empty-text="加载中，请稍候"
                          :props="defaultProps"
                        ></el-tree>
                      </el-form-item>
                    </el-row>-->
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" size="small" @click.native="formSubmit()" :loading="fromLoading"
          >提交
          </el-button>
          <el-button @click.native="cancelDialog" size="small">取消</el-button>
        </div>
      </el-dialog>
    </el-card>
    <el-tabs type="border-card" style="margin: 15px">
      <!--      部门绑定用户列表-->
      <el-tab-pane>
        <span slot="label">{{ currentRow.name }}-用户列表</span>
        <el-form
          :inline="true"
          :model="userQuery"
          class="query-form"
          size="mini"
        >
          <el-form-item class="query-form-item" label="用户名称/账号:">
            <el-input
              v-model="userQuery.key"
              placeholder="请输入用户名称或用户账号"
              clearable
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button-group>
              <el-button
                type="primary"
                icon="el-icon-refresh"
                @click="onUserReset"
              >重置
              </el-button>
              <el-button
                type="primary"
                @click="onUserSubmit"
                icon="el-icon-search"
              >查询
              </el-button>
              <el-tooltip
                content="请移步至权限管理-用户管理-编辑界面选择所属部门信息"
                placement="top"
                style="margin-left: 20px"
              >
                <i class="el-icon-question">帮助</i>
              </el-tooltip>
            </el-button-group>
          </el-form-item>
        </el-form>
        <el-table
          v-loading="userloading"
          :data="userlist"
          style="width: 100%"
          border
          row-key="id"
        >
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column
            label="用户名称"
            prop="employeeName"
          ></el-table-column>
          <el-table-column label="用户账号" prop="userName"></el-table-column>
          <el-table-column label="备注" prop="comments"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                :disabled="scope.row.userId == 1"
                @click.native.stop="removeUserDialog(scope.row)"
              >移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="userTotal > 0"
          :total="userTotal"
          :page.sync="userQuery.page"
          :limit.sync="userQuery.limit"
          @pagination="getUerList"
        />
      </el-tab-pane>

      <!--      部门绑定仓库信息-->
      <el-tab-pane>
        <span slot="label">{{ currentRow.name }}-仓库列表</span>
        <el-form
          :inline="true"
          :model="invQuery"
          class="query-form"
          size="mini"
        >
          <el-form-item class="query-form-item" label="仓库名称/编码:">
            <el-input
              v-model="invQuery.key"
              placeholder="请输入仓库名称或仓库编码"
              clearable
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button-group>
              <el-button
                type="primary"
                icon="el-icon-refresh"
                @click="onInvReset"
              >重置
              </el-button>
              <el-button
                type="primary"
                @click="onInvSubmit"
                icon="el-icon-search"
              >查询
              </el-button>
              <el-tooltip
                content="请移步至系统管理-组织管理-仓库信息管理界面绑定仓库信息"
                placement="top"
                style="margin-left: 20px"
              >
                <i class="el-icon-question">帮助</i>
              </el-tooltip>
            </el-button-group>
          </el-form-item>
        </el-form>
        <el-table
          v-loading="invLoading"
          :data="invlist"
          style="width: 100%"
          border
          row-key="id"
        >
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column label="仓库名称" prop="name"></el-table-column>
          <el-table-column label="仓库编码" prop="code"></el-table-column>
          <el-table-column label="备注" prop="remark"></el-table-column>
          <!--          <el-table-column label="操作">-->
          <!--            <template slot-scope="scope">-->
          <!--              <el-button-->
          <!--                type="text"-->
          <!--                @click.native.stop="deleteDialog(scope.row)"-->
          <!--              >移除-->
          <!--              </el-button-->
          <!--              >-->
          <!--            </template>-->
          <!--          </el-table-column>-->
        </el-table>

        <pagination
          v-show="invTotal > 0"
          :total="invTotal"
          :page.sync="invQuery.page"
          :limit.sync="invQuery.limit"
          @pagination="getInvList"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {
  filterList,
  deleteWarehouse,
  saveWarehouse,
} from "@/api/system/invWarehouse";

import {treeList, treeSelectedList} from "@/api/system/dataStatus";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listDeptUser, removeUser} from "@/api/system/deptUser";
import {filterSubAll} from "@/api/system/invSubWarehouse";

export default {
  data() {
    return {
      filterQuery: {
        status: 1,
        companyName: "",
        checkType: "",
      },
      isShow: null,
      loading: false,
      formVisible: false,
      isExpandAll: true,
      refreshTable: true,
      userflag: {
        0: "禁用",
        1: "正常",
        2: "未验证",
      },
      list: [],
      formData: {},
      formMap: {
        add: "部门管理-新增",
        edit: "部门管理-编辑",
      },
      formName: null,
      deptOptions: [],
      rules: {
        name: [
          {required: true, message: "部门名称不能为空", trigger: "blur"},
        ],
        status: [{required: true, message: "状态不能为空", trigger: "blur"}],
      },
      menuExpand: false,
      menuNodeAll: false,
      menuOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      currentRow: {
        name: "部门",
      },

      //部门用户
      userQuery: {
        key: null,
        deptId: null,
        page: 1,
        limit: 10,
      },
      userlist: [],
      userloading: false,
      userTotal: 0,
      selectUserList: [],
      selectAddUser: [],
      selectUserToatl: 0,
      selectUserQuery: {
        code: null,
        page: 1,
        limit: 10,
      },

      //部门仓库
      invQuery: {
        key: null,
        page: 1,
        limit: 10,
      },
      invlist: [],
      invTotal: 0,
      invLoading: false,
      fromLoading: false,
    };
  },
  filters: {
    statusFilterType(status) {
      const statusMap = {
        0: "gray",
        1: "success",
        2: "danger",
      };
      return statusMap[status];
    },
    statusFilterName(status) {
      const statusMap = {
        0: "禁用",
        1: "正常",
        2: "未验证",
      };
      return statusMap[status];
    },

    spUerFilterType(status) {
      const upUerMap = {
        true: "success",
        false: "danger",
      };
      return upUerMap[status];
    },
    maintenanceFilterType(status) {
      const upUerMap = {
        true: "success",
        false: "danger",
      };
      return upUerMap[status];
    },
    spUerFilterName(status) {
      const upUerMap = {
        true: "允许",
        false: "不允许",
      };
      return upUerMap[status];
    },
    maintenanceFilterName(status) {
      const upUerMap = {
        true: "是",
        false: "否",
      };
      return upUerMap[status];
    },
  },
  methods: {
    onReset() {
      this.$router.push({
        path: "",
      });
      this.filterQuery = {
        name: "",
      };
      this.getList();
    },
    formSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          if (this.$isBlank(this.formData.name)) {
            this.$message.error("部门名称不能为空！");
            return;
          }
          // this.formData.statusIds = this.getMenuAllCheckedKeys();
          this.fromLoading = true
          if (this.formName == "add") {
            saveWarehouse(this.formData, "save")
              .then((response) => {
                this.fromLoading = false
                this.cancelDialog();
                this.getList();
                if (response.code === 20000) {
                  this.$message({
                    type: "success",
                    message: "添加成功！",
                  });
                } else {
                  this.$message.warning("添加失败," + response.message);
                }
              })
              .catch(() => {
                this.cancelDialog();
                this.loading = false;
                this.fromLoading = false
              });
          } else if (this.formName == "edit") {
            saveWarehouse(this.formData, "edit")
              .then((response) => {
                this.fromLoading = false
                this.loading = false;
                this.cancelDialog();
                this.getList();
                if (response.code === 20000) {
                  this.$message({
                    type: "success",
                    message: "更新成功！",
                  });
                } else {
                  this.$message.warning(response.message);
                }
              })
              .catch(() => {
                this.fromLoading = false
                this.cancelDialog();
                this.loading = false;
              });
          }
        }
      });
    },
    onSubmit() {
      this.getList();
    },
    addDeptDialog() {
      this.resetForm();
      this.formName = "add";
      this.formVisible = true;
      this.formData = {
        name: "",
        status: 1,
        remark: "",
        pcode: "0",
        maintenance:false,
        pid: 0,
        level: 1,
      };
    },
    subAddDeptDialog(row) {
      this.formName = "add";
      this.formVisible = true;
      this.isShow = true;
      this.formData = {
        pid: row.id,
        pcode: row.code,
        status: 1,
        spUse: false,
        maintenance:false,
      };
      // this.getStatusTreeselect();
      filterList().then((response) => {
        let depList = response.data.list || [];
        this.deptOptions = this.handleTree(depList, "code", "pcode");
      });
    },
    // 刷新表单
    resetForm() {
      if (this.$refs["dataForm"]) {
        // 清空验证信息表单
        this.$refs["dataForm"].clearValidate();
        // 刷新表单
        this.$refs["dataForm"].resetFields();
      }
    },
    updateDeptDialog(row) {
      this.resetForm();
      this.formName = "edit";
      this.formVisible = true;
      this.isShow = true;
      this.formData = row;
      // const roleMenu = this.getDeptStatusMenuTreeselect(this.formData.id);
      filterList().then((response) => {
        let depList = response.data.list || [];
        this.deptOptions = this.handleTree(depList, "code", "pcode");
      });
      console.log(row.id);
      //   this.$nextTick(() => {
      //   this.$refs.deptTableRef.setCurrentRow(this.list[row.pid]);
      // });
    },
    getList() {
      this.loading = true;
      filterList(this.filterQuery)
        .then((response) => {
          this.loading = false;
          let depList = response.data.list || [];
          this.list = this.handleTree(depList, "code", "pcode");
          this.$nextTick(() => {
            this.$refs.deptTableRef.setCurrentRow(this.list[0]);
          });
          console.log(this.list);
        })
        .catch(() => {
          this.loading = false;
          this.list = [];
        });
    },
    cancelDialog() {
      this.formVisible = false;
      // 刷新表单
      this.$refs["dataForm"].resetFields();
      this.getList();
    },
    deleteDialog(row) {
      this.$confirm("是否删除该部门?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let tQuery = {
            id: row.id,
          };
          deleteWarehouse(tQuery).then((res) => {
            if (res.code == 20000) {
              this.getList();
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {
        });
    },
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.code,
        label: node.name,
        children: node.children,
      };
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value) {
      let treeList = this.menuOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
    },
    /** 查询菜单树结构 */
    getStatusTreeselect() {
      treeList().then((response) => {
        this.menuOptions = response.data;
      });
    },
    getDeptStatusMenuTreeselect(deptId) {
      let query = {deptId: deptId};
      return treeSelectedList(query).then((response) => {
        this.menuOptions = response.data.menus;
        return response;
      });
    },
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    handleDeptChange(row) {
      this.currentRow = row;
      this.onUserSubmit();
      this.onInvSubmit();
    },

    //用户相关
    handleUserSelectionChange(val) {
      this.selectAddUser = val;
    },
    onUserReset() {
      this.userQuery = {
        key: null,
        deptId: this.currentRow.id,
        page: 1,
        limit: 10,
      };
      this.getUerList();
    },
    onUserSubmit() {
      this.userQuery.deptId = this.currentRow.id;
      this.userQuery.page = 1;
      this.getUerList();
    },
    getUerList() {
      listDeptUser(this.userQuery)
        .then((response) => {
          this.loading = false;
          this.userlist = response.data.list || [];
          this.userTotal = response.data.total;
        })
        .catch(() => {
          this.loading = false;
          this.userlist = [];
          this.userTotal = 0;
        });
    },
    onInvReset() {
      this.invQuery = {
        key: "",
        parentId: this.currentRow.code,
        page: 1,
        limit: 20,
      };
      this.onInvSubmit();
    },
    removeUserDialog(row) {
      this.$confirm("是否确定移除该用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let tQuery = {
            deptId: row.deptId,
            userId: row.userId,
          };
          removeUser(tQuery).then((res) => {
            if (res.code == 20000) {
              this.getUerList();
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {
        });
    },

    //仓库相关
    getInvList() {
      filterSubAll(this.invQuery)
        .then((response) => {
          this.loading = false;
          this.invlist = response.data || [];
          this.invTotal = response.data.total;
        })
        .catch(() => {
          this.invlist = false;
          this.list = [];
        });
    },
    onInvSubmit() {
      this.invQuery.parentId = this.currentRow.code;
      this.getInvList();
    },
  },
  components: {Treeselect},
  mounted() {
  },
  created() {
    this.getList();
  },
};
</script>
