<template>
  <el-dialog
    v-if="dialogVisible"
    width="1060px"
    :title="title"
    class="userdialog-selector__wrapper"
    :class="appendToBody ? 'high-z-index-dialog' : ''"
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :append-to-body="appendToBody"
    :modal-append-to-body="appendToBody"
  >
    <div class="dialog-selector__body">
      <el-input
        v-model="searchWord"
        size="small"
        clearable
        :placeholder="searchPlaceholder"
        @clear="reset"
        @keyup.enter.native="search"
      >
        <i
          slot="suffix"
          :title="t('ht.common.search')"
          class="el-input__icon el-icon-search"
          @click="search"
        />
      </el-input>
      <ht-list-selector
        ref="selector"
        v-model="selectors"
        class="user-selector"
        title="用户列表"
        :data="data"
        :pagination="pagination"
        :select-label="selectLabel"
        :quick-search-props="quickSearchProps"
        :single="single"
        :search-placeholder="searchPlaceholder"
        :primary-field="primaryField"
        :mode="mode"
        @reset="reset"
        @row-click="(row) => $emit('row-click', row)"
        @page-change="(page) => $emit('page-change', page)"
        @size-change="(size) => $emit('size-change', size)"
      >
        <el-card slot="header" class="selector-range__card" shadow="hover">
          <el-tabs v-model="activeRange">
            <el-tab-pane label="常用联系人" name="contact"></el-tab-pane>
            <el-tab-pane label="组织" name="org"></el-tab-pane>
            <el-tab-pane label="策略" name="policy"></el-tab-pane>
            <el-tab-pane label="角色" name="role"></el-tab-pane>
          </el-tabs>
        </el-card>
        <el-card
          slot="range"
          class="selector-range__card selector-range__content"
          shadow="hover"
        >
          <el-tabs v-model="activeRange">
            <el-tab-pane label="常用联系人" name="contact">
              <top-contact-user
                v-if="activeRange == 'contact'"
                ref="topContactUser"
                :mode="mode"
                @contact-group-change="
                  (group) => $emit('contact-group-change', group)
                "
              />
            </el-tab-pane>
            <el-tab-pane label="组织" name="org">
              <organization
                v-if="activeRange == 'org'"
                ref="organization"
                :mode="mode"
                :current-org-obj="currentOrgObj"
                @load-org-user="(org) => $emit('load-org-user', org)"
              />
            </el-tab-pane>
            <el-tab-pane label="策略" name="policy">
              <policy-user
                v-if="activeRange == 'policy'"
                ref="policyUser"
                :mode="mode"
                :current-policy-id="currentPolicyId"
                @load-policy-user="
                  (policy) => $emit('load-policy-user', policy)
                "
              />
            </el-tab-pane>
            <el-tab-pane label="角色" name="role">
              <role-user
                v-if="activeRange == 'role'"
                ref="RoleUser"
                :mode="mode"
                :current-role-id="currentRoleId"
                @load-role-user="(role) => $emit('load-role-user', role)"
              />
            </el-tab-pane>
          </el-tabs>
        </el-card>
        <template #detail="{ item }">
          <ht-avatar-image
            class="follow-theme-background-color"
            style="margin-left: 15px"
            :username="item[selectLabel]"
            background-color="#409EFF"
            color="#fff"
            :size="36"
          />
          <div class="selector-item__detail">
            <div class="selector-detail__name">
              <label>{{ item[selectLabel] }}</label>
              <span>({{ item['account'] }})</span>
            </div>
            <div class="selector-detail__desc">
              <span :title="item.pathname">
                <ht-icon name="org-tree" />
                {{ item.orgname || '暂无组织' }}
              </span>
              <span :title="item.postname">
                <ht-icon name="users" />
                {{ item.postname || '暂无岗位' }}
              </span>
            </div>
          </div>
        </template>
        <template #selected="{ select }">
          <ht-avatar-image
            class="follow-theme-background-color"
            style="margin-left: 15px"
            :username="select[selectLabel]"
            background-color="#409EFF"
            color="#fff"
            :size="30"
          />
          <p
            class="selector-selected__label"
            :title="`${select[selectLabel]}${
              select['account'] ? `(${select['account']})` : ''
            }`"
          >
            {{
              `${select[selectLabel]}${
                select['account'] ? `(${select['account']})` : ''
              }`
            }}
          </p>
        </template>
      </ht-list-selector>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleDialogCancel">取 消</el-button>
      <el-button type="primary" size="small" @click="handleDialogSure">
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
  import Locale from '@/mixins/locale'
  import HtListSelector from '../../ListSelector/index'
  import TopContactUser from './TopContactUser.vue'
  import Organization from './Organization.vue'
  import PolicyUser from './PolicyUser.vue'
  import RoleUser from './RoleUser.vue'

  export default {
    name: 'UserSelectorDialog',
    components: {
      HtListSelector,
      TopContactUser,
      Organization,
      PolicyUser,
      RoleUser,
    },
    mixins: [Locale],
    props: {
      value: {
        type: Array,
        default: () => {
          return []
        },
      },
      title: {
        type: String,
        default: '选择用户',
      },
      appendToBody: {
        type: Boolean,
        default: true,
      },
      data: {
        type: Array,
        default: () => {
          return []
        },
      },
      pagination: {
        type: Object,
        default: () => {
          return {
            page: 1,
            pageSize: 50,
            total: 0,
          }
        },
      },
      selectLabel: {
        type: String,
        default: 'fullname',
      },
      quickSearchProps: {
        type: String,
        required: true,
      },
      single: {
        type: Boolean,
        default: false,
      },
      searchPlaceholder: {
        type: String,
        default: '用户名称、账号',
      },
      primaryField: {
        type: String,
        default: '',
      },
      mode: {
        type: String,
      },
      currentPolicyId: {
        type: String,
        default: '',
      },
      currentRoleId: {
        type: String,
        default: '',
      },
      maxLength: {
        // 最大选中长度
        type: Number,
        default: 0,
      },
      minLength: {
        // 最小选中长度
        type: Number,
        default: 0,
      },
      currentOrgObj: { type: Object, default: () => {} },
    },
    data() {
      return {
        dialogVisible: false,
        activeRange: 'contact',
        searchWord: null,
        loading: false,
      }
    },
    computed: {
      selectors: {
        get: function () {
          return this.value
        },
        set: function (val) {
          this.$emit('input', val)
        },
      },
    },
    watch: {
      activeRange: {
        handler(newVal) {
          if (newVal == 'contact') {
            setTimeout(() => {
              if (
                this.$refs.topContactUser &&
                this.$refs.topContactUser.contactGroups
              ) {
                this.$refs.topContactUser.currentContactGroup =
                  this.$refs.topContactUser.contactGroups[0].id
              }
              this.$emit('filter-type-change', newVal)
            }, 500)
          } else if (newVal == 'org') {
            setTimeout(() => {
              this.$refs.organization.currentDemension =
                this.$refs.organization &&
                this.$refs.organization.demensions[0].id
              this.$refs.organization.$refs.tree.$refs.elTree.setCurrentKey(
                this.$refs.organization.demensions[0].id
              )
              this.$emit('filter-type-change', newVal)
            }, 500)
          } else if (newVal == 'policy') {
            setTimeout(() => {
              this.$refs.policyUser.currentPolicy =
                this.$refs.policyUser && this.$refs.policyUser.policies[0].id
              this.$emit('filter-type-change', newVal)
            }, 500)
          } else if (newVal == 'role') {
            setTimeout(() => {
              this.$refs.RoleUser.currentRole =
                this.$refs.RoleUser && this.$refs.RoleUser.roles[0].id
              this.$emit('filter-type-change', newVal)
            }, 500)
          }
        },
        deep: true,
        immediate: true,
      },
    },
    methods: {
      search() {
        if (this.loading) {
          return
        }
        if (!this.searchWord || this.searchWord == '') {
          this.reset()
          return
        }
        if (this.activeRange != '0') {
          this.activeRange = ''
        }
        this.$emit('search', this.searchWord)
      },
      reset() {
        if (this.activeRange == '') {
          this.activeRange = 'contact'
        }
        this.$emit('reset')
        this.searchWord = null
      },
      showDialog(reset = false) {
        this.dialogVisible = true
        if (this.mode == 'search') {
          this.activeRange = '0'
        }
        ;(reset || this.searchWord) && this.reset()
        setTimeout(() => {
          this.$refs.selector.onShow()
        }, 10)
      },
      handleClose(done) {
        this.$refs.selector.onHide()
        done && done()
      },
      handleDialogSure() {
        var data = this.$refs.selector.getSelectedData()
        if (this.maxLength && data.length > this.maxLength) {
          try {
            this.$message.warning('超出最大选择数量,请重新选择')
          } catch (error) {
            this.$notify({
              type: 'warning',
              message: '超出最大选择数量,请重新选择',
            })
          }

          return
        }
        if (this.minLength && data.length < this.minLength) {
          try {
            this.$message.warning(`至少选择${this.minLength}个`)
          } catch (error) {
            this.$notify({
              type: 'warning',
              message: `至少选择${this.minLength}个`,
            })
          }
          return
        }

        this.$emit('select-data', data)
        if (data && data.length > 0) {
          // 记录为最近联系人
          var userAccountList = data.map((user) => user.account)
          this.$requestConfig
            .addLogUserSelector(userAccountList)
            .finally(() => {
              this.dialogVisible = false
              this.$refs.selector.onHide(true)
            })
        } else {
          this.dialogVisible = false
          this.$refs.selector.onHide(true)
        }
      },
      handleDialogCancel() {
        this.dialogVisible = false
        this.$refs.selector.onHide()
      },
    },
  }
</script>
<style lang="scss" scoped>
  .userdialog-selector__wrapper {
    ::v-deep {
      .el-dialog__header {
        border-bottom: 1px solid #ebebeb;
        span {
          font-weight: bold;
          color: #222;
        }
      }

      .el-dialog__body {
        padding: 24px;
        border-top-width: 0;
        max-height: 600px;
        overflow: hidden;
      }

      .el-dialog__footer {
        border-top: 1px solid #ebebeb;
        text-align: right;
      }
    }
    .dialog-selector__body {
      .el-icon-search {
        cursor: pointer;
      }
    }

    .user-selector {
      margin-top: 10px;
    }

    .selector-range__content {
      ::v-deep .el-tabs__nav-wrap {
        height: 0;
      }
    }
    .selector-range__card {
      ::v-deep {
        .el-card__body {
          height: 480px;

          .el-tabs {
            height: 100%;

            .el-tabs__content {
              height: calc(100% - 16px);
              padding: 0;

              .el-tab-pane {
                height: 100%;
              }
            }
          }
        }
        .el-tabs__nav-wrap {
          background-color: #fcfcfc;
          padding: 0;

          .el-tabs__nav-scroll {
            display: flex;
            justify-content: flex-start;
          }
        }
        .el-tabs__item {
          padding: 0 20px;
          height: 48px;
          line-height: 48px;
        }
      }
    }
    .selector-item__detail {
      display: flex;
      flex-direction: column;
      margin-left: 10px;
      width: calc(100% - 36px - 15px - 20px);

      .selector-detail__name {
        max-width: 220px;

        label {
          color: #111;
          font-size: 14px;
        }
        span {
          margin-left: 10px;
          color: #777;
        }
      }

      .selector-detail__desc {
        margin-top: 5px;
        display: flex;
        justify-content: flex-start;
        align-items: center;

        span {
          display: inline-block;
          font-size: 12px;
          color: #777;
          max-width: 115px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        span + span {
          margin-left: 10px;
          min-width: calc(100% - 115px);
        }
      }
    }
    .selector-selected__label {
      margin-left: 10px;
      width: 115px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
</style>
<style>
  .high-z-index-dialog {
    z-index: 9999 !important;
  }
  .high-z-index-dialog + .v-modal {
    z-index: 9998 !important;
  }
</style>
