<template>
  <div class="organize pagePadding">
    <div
      v-loading="loading"
      v-if="powers && powers.length > 0 && powers.some((item) => item == '001')"
    >
      <el-row>
        <el-col :span="24">
          <el-col :span="24" style="padding: 12px 0 15px 0">
            <div class="my-breadcrumb clear">
              <div
                class="my-breadcrumb-item"
                v-for="(item, index) in titleList"
                :key="item + index"
                :class="{ chover: true }"
                @click="changeBreadcrumb(index)"
              >
                <span class="label">{{ item.titleName }}</span
                ><span class="separator" v-if="index + 1 !== titleList.length"
                  >/</span
                >
              </div>
            </div>
          </el-col>
          <el-col :span="24">
            <el-row style="padding: 0 0 3px 0">
              <el-col :span="8" style="width: 200px">
                <el-input
                  placeholder="部门名称"
                  :size="searchSize"
                  v-model="parmValue.name"
                >
                </el-input>
              </el-col>
              <el-col :span="8" style="width: 250px; padding: 0 0 0 10px">
                <el-input
                  placeholder="员工姓名"
                  :size="searchSize"
                  v-model="parmValue.nickname"
                >
                  <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="searchList"
                  ></el-button>
                </el-input>
              </el-col>

              <el-col :span="3" style="width: 195px; float: right">
                <el-button
                  type="primary"
                  :size="searchSize"
                  style="float: right; margin-left: 5px"
                  @click="searchList"
                >
                  刷新
                </el-button>
                <el-button
                  v-if="powers.some((item) => item == '003')"
                  type="success"
                  :size="searchSize"
                  style="float: right"
                  @click="
                    addEditFn(
                      0,
                      parmValue && parmValue.pid !== '' ? parmValue.pid : '0',
                      1,
                      false,
                      true,
                      {}
                    )
                  "
                >
                  添加
                </el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col
          :span="24"
          v-if="
            powers && powers.length > 0 && powers.some((item) => item == '001')
          "
        >
          <organize-tree
            style="margin-left: -5px"
            :list="depart"
            :level="1"
            :pid="0"
            @addEdit="addEditFn"
            @openChildren="openChildren"
            @status="setstatus"
            @del="del"
          />
          <staff-tree
            style="margin-left: -5px"
            :list="item"
            :level="1"
            :pid="0"
            @setUpEdit="setUpEdit"
          />
        </el-col>
        <div
          class="no-data"
          v-if="item && item.length === 0 && depart && depart.length === 0"
        >
          暂无数据
        </div>
      </el-row>

      <add-edit
        :id="modelId"
        :show-model="showModel"
        :level="level"
        :pid="parentIds"
        :is-add="isAdd"
        :form-data="formData"
        :type="parmValue.type"
        :is-detail="isDetail"
        @refresh="searchList"
        @cancel="showModel = false"
      />
    </div>
    <div v-else>
      <no-auth></no-auth>
    </div>
  </div>
</template>
<script>
import mixinPage from "@/mixins/elPaginationHandle";
import asyncRequest from "@/apis/service/interest/organize";
import addEdit from "./addEdit";
import statusList from "@/assets/js/statusList";
import { mapGetters } from "vuex";
import resToken from "@/mixins/resToken";
export default {
  name: "organize",
  components: {
    addEdit,
  },
  mixins: [mixinPage, resToken],
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      let tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "organize"
        ) || {};
      if (tran && tran.action && tran.action.length > 0) {
        return tran.action;
      } else {
        return [];
      }
    },
  },
  data() {
    return {
      titleList: [],
      sitem: null,
      statusList: statusList,
      loading: true,
      showModel: false,
      showInterface: false,
      isDetail: false,
      isAdd: true,
      level: 1,
      modelId: 0,
      formData: {},
      parentIds: "",
      parmValue: {
        pid: "", //父级部门ID
        name: "", // 部门/公司名称
        nickname: "", // 员工名称
      },
      depart: [],
      item: [],
      passwordModel: false,
      passwordModelId: 0,
      // 表格 - 数据
      // depart: [],
    };
  },
  mounted() {
    this.searchList();
  },
  methods: {
    restSearch() {
      this.parmValue = {
        pid: "", //父级部门ID
        name: "", // 部门/公司名称
        nickname: "", // 员工名称
      };
      this.searchList();
    },
    // 原来
    // async changeBreadcrumb(index) {
    //   if (index + 1 !== this.titleList.length) {
    //     this.parmValue.pid = this.titleList[index].id;
    //     this.titleList = this.titleList.slice(0, index + 1);
    //   } else {
    //     this.parmValue.pid = 0;
    //     this.titleList = [];
    //   }
    //   await this.searchList();
    // },
    // 修改后
    async changeBreadcrumb(index) {
      if (index + 1 === this.titleList.length) {
        return;
      } else {
        this.parmValue.pid = this.titleList[index].id;
        this.titleList = this.titleList.slice(0, index + 1);
      }
      if (this.titleList.length === 1) {
        this.titleList = [];
      }

      await this.searchList();
    },
    // 原来
    // async openChildren(item) {
    //   this.parmValue.pid = item.id;
    //   let model = {
    //     id: item.id,
    //     titleName: item.name,
    //   };
    //   this.titleList.push(model);
    //   await this.searchList();
    // },
    // 修改后
    async openChildren(item) {
      this.parmValue.pid = item.id;
      let model = {
        id: item.id,
        titleName: item.name,
      };
      if (this.titleList.length === 0) {
        this.titleList.push({ id: "", titleName: "全部分类" });
      }
      this.titleList.push(model);
      await this.searchList();
    },
    openModal(id, isDetail, sitem) {
      this.showModel = true;
      this.modelId = id;
      this.isDetail = isDetail;
      this.sitem = sitem;
    },
    openPasswordModal(id, isDetail) {
      this.passwordModel = true;
      this.passwordModelId = id;
      this.isPasswordDetail = isDetail;
    },
    async setUpEdit(id, position) {
      if (position === "1") {
        const model = {
          id: id,
          position: "2",
        };
        let res = await asyncRequest.userp(model);
        if (res && res.code === 0) {
          this.$notify.success({
            title: "设置成功！",
            message: "",
          });
          await this.searchList();
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(res.message);
        }
      } else {
        this.$message.warning("该账户已是部门负责人！");
      }
    },
    addEditFn(id, pid, level, isDetail, isAdd, formData) {
      this.showModel = true;
      this.modelId = id;
      this.level = level;
      this.parentIds = pid;
      this.isDetail = isDetail;
      this.isAdd = isAdd;
      this.formData = formData;
    },

    async setstatus(id, parentIds, level, status) {
      console.log(
        `openChildren-id, parentIds, level:${id}-${parentIds}-${level}-${status}`
      );
      await this.$confirm(`确定要${status === "0" ? "启用" : "禁用"}？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const model = {
            id: id,
            status: status === "1" ? "0" : "1",
          };
          let res = await asyncRequest.status(model);

          if (res && res.code === 0) {
            this.$notify.success({
              title: "修改成功！",
              message: "",
            });
            await this.searchList();
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },

    async del(id, parentIds, level, status) {
      console.log(
        `openChildren-id, parentIds, level:${id}-${parentIds}-${level}-${status}`
      );
      await this.$confirm(`确定要删除？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const model = {
            id: id,
          };
          let res = await asyncRequest.delete(model);

          if (res && res.code === 0) {
            this.$notify.success({
              title: "删除成功！",
              message: "",
            });
            await this.searchList();
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },

    async concatData(id, parentIds, level) {
      this.loading = true;
      const res = await asyncRequest.list({});
      let depart = [];
      if (res && res.code === 0 && res.data) {
        depart = res.data;
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
      let arr = JSON.parse(JSON.stringify(this.depart));
      // if (level === 1) {
      arr = arr.map((val, index) => {
        if (level === 1 ? id : parentIds === val.id) {
          val.child = depart[index].child;
        }
        return val;
      });

      this.depart = arr;
      this.loading = false;
    },
    async deleteById(id, status) {
      await this.$confirm("确定要删除？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const model = {
            id: id,
            status: status === "1" ? "0" : "1",
          };
          const res = await asyncRequest.status(model);
          if (res && res.code === 0) {
            this.$notify.success({
              title: "删除成功",
              message: "",
            });
            this.searchList();
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },
    async searchList() {
      this.loading = true;
      const res = await asyncRequest.list(this.parmValue);
      if (res && res.code === 0 && res.data) {
        const { depart, item } = res.data;
        this.depart = depart;
        this.item = item;
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.depart = [];
        this.item = [];
      }
      this.loading = false;
    },
    async statusConfirm(id, status) {
      await this.$confirm(`确定要改为${status === "1" ? "禁用" : "启用"}？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.loading = true;
          const model = {
            id: id,
            status: status === "1" ? "0" : "1",
          };
          const res = await asyncRequest.status(model);
          if (res && res.code === 0) {
            this.loading = false;
            this.$notify.success({
              title: "状态修改成功！",
              message: "",
            });
            await this.searchList();
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },
  },
};
</script>
   <style lang="scss" scoped>
.organize {
  .no-data {
    padding: 25px 0;
    text-align: center;
    color: #909399;
    margin: 30px 10px 0 10px;
    border-radius: 8px;
    border: 1px solid #dfe6ec;
    // border-right: 1px solid #dfe6ec;
    // border-bottom: 1px solid #dfe6ec;
  }
  .my-breadcrumb {
    .my-breadcrumb-item {
      float: left;
      span {
        height: 21px;
        line-height: 21px;
      }
      .label {
        padding: 0 5px 0 0;
        color: 010101;
      }
      .separator {
        color: #787878;
        font-size: 13px;
        padding: 0 5px 0 0;
      }
      &:last-child {
        .label {
          color: #787878;
        }
      }
      &.chover {
        cursor: pointer;
      }
    }
  }
}
</style>
