<template lang="pug">
.comp
  span.comp-department(@click.stop="changeDepartmentRelation") {{ title }}
    i.el-icon-link(v-if="isRelation")
    i.el-icon-paperclip(v-else)
  el-cascader(
    v-model="deptId",
    size="small",
    :options="deptList",
    :props="deptConf",
    clearable,
    filterable,
    collapse-tags,
    :show-all-levels="false",
    @change="departmentChanged",
    ref="refDepartment"
  )
</template>

<script>
import { LS } from "@/utils/storage";

export default {
  name: "comp-cascader",
  props: {
    title: {
      type: String,
      default: "部门名称"
    },
    deptIds: {
      type: Array,
      default: () => [] // 工厂函数
    }
  },
  data () {
    // 部门级联是否关联选项: 级联更新配置不能动态刷新, 配置两个级联组件会配置对象也会串
    const isRelation = LS.GET("DEPARTMENT_RELATION") != "false";

    return {
      // 部门级联数据源
      deptList: [],
      // 部门级联组件选项
      deptConf: {
        expandTrigger: "hover",
        value: "departmentId",
        label: "name",
        emitPath: isRelation,
        checkStrictly: !isRelation,
        multiple: true
      },
      // 部门级联是否关联选项:
      isRelation,
      // 过滤部门
      deptId: []
    };
  },
  computed: {
    // 当前选择的部门集合: 不缓存
    current: {
      get () {
        return [];
      },
      set (val) {
        this.$emit("update:deptIds", val);
      }
    }
  },
  watch: {},
  filters: {},
  created () {
    this.syncDepartInfo();
  },
  mounted () { },
  methods: {
    // 部门级别数据查询
    async syncDepartInfo () {
      // this.deptList = await this.$store.dispatch("common/syncDepartInfo");
    },
    // 部门级联关系变更
    changeDepartmentRelation () {
      this.$el_confirm(
        "此操作将会刷新当前页面, 是否继续?",
        "变更部门勾选关联"
      ).then(() => {
        LS.SET("DEPARTMENT_RELATION", !this.isRelation);
        window.location.reload();
      });
    },
    // 过滤当前部门前的父节点: 记录当前部门, 选中后关闭
    departmentChanged (values) {
      if (this.isRelation) {
        const deptIds = values.reduce((acc, cur) => {
          acc.push(
            ...cur.filter(dept => {
              return (
                dept >= this.$refs["refDepartment"].getCheckedNodes()[0].value
              );
            })
          );
          return acc;
        }, []);
        this.current = [...new Set(deptIds)];
      } else {
        this.current = this.deptId;
      }
    }
  }
};
</script>

<style lang="stylus">
.comp
  &-department
    color: $-color-theme-second
    margin-right: 10px
    margin-left: 20px
  .el-input
    width: 200px
  &-department
    cursor: pointer
    &:hover
      text-decoration: underline
    i
      margin-left: 3px
</style>
