<template>
  <div class="dropDownWrap">
    <div class="dropDown">
      <div
        :class="['dropdown-menu__org', filterType == 'org' ? 'active' : '']"
        @click="handleTabToggle('org')"
      >
        组织
      </div>

      <van-dropdown-menu
        active-color="#409EFF"
        :class="['dropdown-menu', filterType == 'policy' ? 'active' : '']"
      >
        <van-dropdown-item
          v-model="policyValue"
          title="策略"
          :options="policyOption"
          @change="(val) => handleTabToggle('policy', val)"
        />
      </van-dropdown-menu>
    </div>

    <template v-if="filterType == 'org' && orgFilterVisible">
      <div
        :style="{
          'margin-bottom': miniNavList.length < 2 ? '16px' : '',
        }"
        class="orgFilter"
        @click="handelOrgChange"
      >
        <span>{{ currentDemensionName }}</span>
        <ht-icon
          name="select"
          width="18"
          height="18"
          :rotate="270"
          fill="#8C8C8C"
        />
      </div>

      <van-action-sheet
        v-model="currentDemensionModel"
        class="bottom-action-sheet"
        :actions="demensions"
        cancel-text="取消"
        close-on-click-action
        @select="selectDemension"
        @cancel="onCancelDemensionHandle"
      />

      <div v-show="miniNavList.length > 1" class="miniNav">
        <div
          v-for="(item, idx) in miniNavList"
          :key="item.parentId"
          class="miniNav__item"
          @click.stop="handelClickMiniNavItem(item, idx)"
        >
          <span class="miniNav__item--text">{{ item.name }}</span>
          <ht-icon
            v-if="miniNavList.length > 1 && idx < miniNavList.length - 1"
            class="miniNav__item--icon"
            name="select"
            :rotate="270"
          />
        </div>
      </div>
    </template>
  </div>
</template>
<script>
  export default {
    name: 'PostSelectorMobileDropDown',
    props: {
      searchWord: {},
    },
    data() {
      return {
        contactValue: 'recently',
        contactOptions: [],
        filterType: 'org', //过滤类型(contact:联系人，org:组织，policy:策略，role:角色)

        roleValue: '',
        roleOptions: [],

        currentDemensionModel: false,
        currentDemension: null,
        currentDemensionName: '',

        orgFilterVisible: true,
        demensions: [],

        miniNavList: [
          // {
          //   demId: 'id',
          //   parentId: '0',
          //   name:'name',
          // },
        ],

        policyValue: null,
        policyOption: [
          { value: '1', text: '我的主部门' },
          { value: '2', text: '我的主部门及下属部门' },
          { value: '3', text: '我的所有部门' },
          { value: '4', text: '我的所有部门及下属部门' },
        ],
        masterOrgInfo: null,
        currentUserOrgs: [],
      }
    },
    inject: ['dialogInstance'],
    watch: {
      policyValue: {
        handler(newVal, oldVal) {
          if (newVal && newVal !== oldVal) {
            this.loadUserWithPolicy(newVal)
          }
        },
        immediate: true,
      },
    },
    mounted() {
      this.loadContactGroup()
      this.loadDemensions()
      this.loadRole()
    },

    methods: {
      // 选择切换维度
      selectDemension(data) {
        this.currentDemension = data.id
        this.currentDemensionName = data.demName
        this.miniNavList = [
          {
            demId: this.currentDemension,
            parentId: 0,
            name: this.currentDemensionName,
          },
        ]
        this.dialogInstance.$emit('load-org-withdemension', {
          demId: data.id,
          parentId: 0,
        })
        this.currentDemensionModel = false
      },
      handleTabToggle(type, val) {
        if (type != 'policy') {
          this.policyValue = ''
        }
        switch (type) {
          case 'policy':
            this.filterType = 'policy'
            this.orgFilterVisible = false
            this.dialogInstance.$emit('filter-type-change', 'policy', val)
            break

          case 'org':
            this.handleOrgTabClick()
            break
          default:
            break
        }
      },
      handelOrgChange() {
        this.currentDemensionModel = !this.currentDemensionModel
      },
      handleOrgTabClick() {
        if (this.filterType !== 'org') {
          this.filterType = 'org'
          this.dialogInstance.$emit('filter-type-change', 'org')
          this.orgFilterVisible = true
          this.$emit('load-org')
        }
      },
      async loadContactGroup() {
        if (
          this.contactOptions.length === 0 &&
          this.$requestConfig.getContactGroup
        ) {
          this.contactOptions = [{ value: 'all', text: '全部' }]
          const { rows } = await this.$requestConfig.getContactGroup({
            pageBean: {
              page: 1,
              pageSize: 100,
              total: 0,
            },
          })

          const list = rows.map((item) => {
            item.text = item.name
            item.value = item.id

            return item
          })
          if (list) {
            this.contactOptions.push(...list)
          }
        }
      },

      onCancelDemensionHandle() {},

      handelClickMiniNavItem(item, idx) {
        if (idx == this.miniNavList.length - 1) {
          return
        }

        this.dialogInstance.$emit(
          'load-org-withdemension',
          {
            demId: item.demId,
            parentId: item.parentId,
            page: 1,
          },
          () => {
            this.miniNavList = this.miniNavList.slice(0, idx + 1)
          }
        )
      },

      addMiniNavList(item) {
        if (this.miniNavList.length == 0) {
          this.miniNavList.push(item)
        } else {
          if (!this.miniNavList.some((it) => it.parentId == item.parentId)) {
            this.miniNavList.push(item)
          }
        }
      },
      // 加载维度数据
      async loadDemensions() {
        if (!this.demensions || this.demensions.length == 0) {
          const data = await this.$requestConfig.getAllDemensions()
          this.demensions = data
          let defaultIDX = 0
          data.forEach((item, idx) => {
            if (item.isDefault === 1) {
              defaultIDX = idx
            }
          })
          this.currentDemension = data[defaultIDX].id
          this.currentDemensionName = data[defaultIDX].demName

          this.addMiniNavList({
            demId: this.currentDemension,
            parentId: 0,
            name: this.currentDemensionName,
          })

          //

          this.dialogInstance.$emit('load-org-withdemension', {
            demId: data[defaultIDX].id,
            parentId: 0,
          })
        }
      },

      // 加载角色数据
      async loadRole() {
        const queryFilter = {
          querys: [
            {
              property: 'showStatus',
              value: '1',
              group: 'main2',
              operation: 'EQUAL',
              relation: 'AND',
            },
          ],
          pageBean: {
            page: 1,
            pageSize: 50,
            showTotal: true,
          },
        }

        const { rows } = await this.$requestConfig.getRoleList(queryFilter)

        const list = rows.map((item) => {
          item.text = item.name
          item.value = item.id

          return item
        })
        if (list) {
          this.roleOptions = list
        }
      },

      // 按照指定策略加载数据
      async loadUserWithPolicy(policy) {
        //1-我的主部门 2-我的主部门及下属部门
        if (['1', '2'].includes(policy)) {
          await this.getMasterOrg()
        }
        await this.loadCurrentUserOrgs()
          .then(() => {
            const param = this.getOrgIdWithPolicy(policy)
            this.dialogInstance.$emit('load-policy-org', param)
          })
          .catch(() => {
            /*    this.$message.error(
              '未获取到当前用户的部门信息，无法按照该策略加载数据。'
            ) */
            const param = { data: 'noCurrentPolicy' }
            this.dialogInstance.$emit('load-policy-org', param)
            this.policyValue = ''
          })

        //load - org - post
        //load-policy-post
      },
      // 根据策略构建不同的查询参数
      getOrgIdWithPolicy(policy) {
        let result = { type: policy }
        const masterOrg = this.currentUserOrgs.find((org) => org.isMaster == 1)
        switch (policy) {
          case '1':
            result.id = this.masterOrgInfo
              ? this.masterOrgInfo.id
              : masterOrg
              ? masterOrg.id
              : null
            break
          case '2':
            result.path = this.masterOrgInfo
              ? this.masterOrgInfo.path
              : masterOrg
              ? masterOrg.path
              : null
            break
          case '3':
            result.ids = this.currentUserOrgs.map((org) => org.id)
            break
          case '4':
            result.paths = this.currentUserOrgs.map((org) => org.path)
            break
        }
        return result
      },
      // 获取当前用户所属部门数据
      async loadCurrentUserOrgs() {
        return await new Promise((resolve, reject) => {
          if (this.currentUserOrgs && this.currentUserOrgs.length > 0) {
            resolve()
          } else if (
            this.$requestConfig.getUserId() &&
            this.$requestConfig.getOrgListByUserId
          ) {
            this.$requestConfig
              .getOrgListByUserId(this.$requestConfig.getUserId())
              .then((orgs) => {
                if (orgs && orgs.constructor == Array && orgs.length > 0) {
                  this.currentUserOrgs = orgs
                  resolve()
                } else {
                  reject()
                }
              })
              .catch(() => reject())
          } else {
            reject()
          }
        })
      },
      //获取默认维度下的主组织
      async getMasterOrg() {
        await this.$requestConfig
          .getMasterOrgByDefaultDimension()
          .then((res) => {
            if (res.state && res.value) {
              this.masterOrgInfo = res.value
            }
          })
      },
    },
  }
</script>
<style lang="scss" scoped>
  ::v-deep {
    .van-dropdown-item {
      .van-cell__title {
        flex: 9;
      }
      .van-cell__value {
        flex: 1;
        .van-icon {
          font-size: 18px;
        }
      }
    }
  }
  .dropDownWrap {
    .orgFilter {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 32px;
      margin: 0 16px;
      padding: 0 8px;
      line-height: 32px;
      background: #ffffff;

      border-radius: 8px 8px 8px 8px;
      border: 1px solid #e6e6e6;
      font-size: 12px;
      span {
        font-size: 14px;
        display: inline-block;
        width: calc(100% - 34px);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }

    .miniNav {
      &::-webkit-scrollbar {
        display: none;
      } /*火狐下隐藏滚动条*/
      scrollbar-width: none;
      display: flex;
      height: 44px;
      margin: 0 16px;
      justify-content: flex-start;
      align-items: center;
      overflow-x: auto;
      &__item {
        display: flex;
        align-items: center;
        white-space: nowrap;
        &--text {
          font-size: 14px;
          color: #409eff;
          white-space: nowrap;
        }

        &--icon {
          margin: 0 8px;
        }
      }
    }
  }

  .dropDown {
    display: flex;
    padding: 0 16px;
    justify-content: space-around;
    align-content: center;
    align-items: center;

    width: calc(100% - 36px);

    ::v-deep {
      .van-dropdown-menu__bar {
        box-shadow: none;
      }

      &.active .van-dropdown-menu__title {
        color: #409eff;
        padding-left: 0;

        &::after {
          color: #409eff;
          border-color: transparent transparent #409eff #409eff;
        }
      }
      .van-dropdown-menu__title::after {
        border-color: transparent transparent #8c8c8c #8c8c8c;
      }
      .van-dropdown-menu__title--active::after {
        border-color: transparent transparent #409eff #409eff;
      }
    }

    .dropdown-menu {
      //  flex: 1;
      &__org {
        display: flex;
        width: 48px;
        justify-content: flex-start;
        align-items: center;
        height: 48px;
        color: #323233;
        font-size: 15px;

        &.active {
          color: #409eff;
        }
      }
    }
  }
</style>
