<template>
  <el-dialog
    :visible.sync="visible"
    custom-class="user-batch-dialog user-batch-dialog--punch"
    width="68%"
    top="6vh"
    append-to-body
    :close-on-click-modal="false"
    @closed="onClosed"
  >
    <template slot="title">
      <div class="ubd-title">
        <div class="ubd-title__icon-wrap ubd-title__icon-wrap--punch">
          <i class="el-icon-location-outline ubd-title__icon" />
        </div>
        <div class="ubd-title__meta">
          <div class="ubd-title__heading">批量设置可打卡门店</div>
          <div class="ubd-title__desc">统一限制选中员工在手机端可打卡的门店范围</div>
        </div>
      </div>
    </template>

    <div class="ubd-body ubd-body--punch">
      <div class="ubd-stat-bar">
        <div class="ubd-stat-bar__main">
          <span class="ubd-stat-bar__num">{{ userIds.length }}</span>
          <span class="ubd-stat-bar__unit">人</span>
          <span class="ubd-stat-bar__dash">将应用本次门店配置</span>
        </div>
        <p class="ubd-stat-bar__hint">
          未勾选任何门店时与单人编辑一致：仅可在各自<strong>主门店</strong>打卡。
        </p>
      </div>

      <div class="ubd-panel">
        <div class="ubd-toolbar">
          <el-input
            v-model="filterKw"
            placeholder="搜索门店名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            class="ubd-toolbar__search"
          />
          <div class="ubd-toolbar__btns">
            <el-button type="text" class="ubd-link-btn" icon="el-icon-circle-check" @click="addFilteredToSelection">
              全选可见
            </el-button>
            <el-button type="text" class="ubd-link-btn ubd-link-btn--muted" @click="punchAllowedMdids = []">
              清空选择
            </el-button>
          </div>
        </div>

        <div class="ubd-tags-row">
          <span class="ubd-tag ubd-tag--primary">
            <i class="el-icon-check" />
            {{ punchAllowedMdids.length }} 个已选
          </span>
          <span class="ubd-tag ubd-tag--neutral">
            {{ filteredStoreList.length }} 条可见
          </span>
        </div>

        <div class="ubd-chip-area">
          <el-checkbox-group v-model="punchAllowedMdids" class="ubd-chip-group">
            <el-checkbox
              v-for="item in filteredStoreList"
              :key="item.id"
              :label="item.id"
              border
              class="ubd-chip"
            >
              <span class="ubd-chip__text" :title="item.fullName || '无'">{{ item.fullName || '无' }}</span>
            </el-checkbox>
          </el-checkbox-group>
          <div v-if="flatStoreList.length && !filteredStoreList.length" class="ubd-empty-state">
            <i class="el-icon-search" />
            <p>无匹配门店，请调整搜索关键词</p>
          </div>
          <div v-if="!flatStoreList.length" class="ubd-empty-state">
            <i class="el-icon-s-home" />
            <p>暂无门店数据，请稍后重试</p>
          </div>
        </div>
      </div>
    </div>

    <div slot="footer" class="ubd-footer">
      <el-button class="ubd-footer__cancel" @click="visible = false">取消</el-button>
      <el-button type="primary" class="ubd-footer__ok" :loading="submitting" @click="submit">
        应用到所选用户
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getStoreSelector } from '@/api/extend/store'
import { batchUpdateUserPunchRest } from '@/api/permission/user'

export default {
  name: 'user-batch-punch-stores-dialog',
  data() {
    return {
      visible: false,
      userIds: [],
      submitting: false,
      storeTreeData: [],
      punchAllowedMdids: [],
      filterKw: ''
    }
  },
  computed: {
    flatStoreList() {
      const rows = this.flattenStoreNodes(this.storeTreeData)
      return rows.sort((a, b) => String(a.fullName || '').localeCompare(String(b.fullName || ''), 'zh-CN'))
    },
    filteredStoreList() {
      const kw = (this.filterKw || '').trim().toLowerCase()
      const list = this.flatStoreList
      if (!kw) return list
      return list.filter(s => String(s.fullName || '').toLowerCase().includes(kw))
    }
  },
  methods: {
    open(userIds) {
      this.userIds = Array.isArray(userIds) ? userIds.filter(Boolean) : []
      this.punchAllowedMdids = []
      this.filterKw = ''
      this.visible = true
      this.loadStores()
    },
    loadStores() {
      getStoreSelector().then(res => {
        if (res.data && res.data.list) {
          this.storeTreeData = res.data.list
        } else {
          this.storeTreeData = []
        }
      }).catch(() => {
        this.storeTreeData = []
      })
    },
    flattenStoreNodes(nodes) {
      const byId = new Map()
      const walk = arr => {
        if (!Array.isArray(arr)) return
        arr.forEach(n => {
          if (!n) return
          const id = n.id
          if (id && !byId.has(id)) {
            const fullName = n.fullName != null ? n.fullName : (n.label != null ? n.label : String(id))
            byId.set(id, { id, fullName })
          }
          if (n.children && n.children.length) walk(n.children)
        })
      }
      walk(nodes)
      return Array.from(byId.values())
    },
    addFilteredToSelection() {
      const next = new Set(this.punchAllowedMdids || [])
      this.filteredStoreList.forEach(s => next.add(s.id))
      this.punchAllowedMdids = Array.from(next)
    },
    onClosed() {
      this.userIds = []
      this.punchAllowedMdids = []
      this.submitting = false
    },
    submit() {
      if (!this.userIds.length) {
        this.$message.warning('没有可更新的用户')
        return
      }
      const payload = {
        userIds: this.userIds,
        updatePunchAllowedStores: true,
        updateAttendanceRestGroup: false,
        punchAllowedStoreIds:
          this.punchAllowedMdids && this.punchAllowedMdids.length
            ? JSON.stringify(this.punchAllowedMdids)
            : null,
        attendanceRestGroupId: ''
      }
      this.submitting = true
      batchUpdateUserPunchRest(payload)
        .then(res => {
          this.$message.success(res.msg || '批量设置成功')
          this.visible = false
          this.$emit('success')
        })
        .finally(() => {
          this.submitting = false
        })
    }
  }
}
</script>

<style lang="scss">
/* append-to-body 时标题/外壳挂在 body 下，需非 scoped */
.user-batch-dialog--punch.el-dialog {
  width: 68% !important;
  max-width: 1320px;
  min-width: 800px;
  border-radius: 14px;
  overflow: hidden;
  box-shadow: 0 24px 48px rgba(15, 23, 42, 0.12), 0 8px 16px rgba(15, 23, 42, 0.06);

  .el-dialog__header {
    padding: 20px 24px 16px;
    border-bottom: 1px solid #eef0f4;
    background: linear-gradient(180deg, #fafbfd 0%, #fff 100%);
  }

  .el-dialog__title {
    width: 100%;
    line-height: 1.3;
  }

  .el-dialog__body {
    padding: 20px 28px 12px;
    background: #f5f7fb;
    overflow: visible;
    max-height: none;
  }

  .el-dialog__footer {
    padding: 16px 24px 20px;
    border-top: 1px solid #eef0f4;
    background: #fff;
  }

  .el-dialog__headerbtn {
    top: 18px;
    right: 18px;
  }

  .el-dialog__headerbtn .el-dialog__close {
    font-size: 18px;
    color: #909399;
  }

  .el-dialog__headerbtn .el-dialog__close:hover {
    color: #409eff;
  }
}

@media (max-width: 900px) {
  .user-batch-dialog--punch.el-dialog {
    width: 92% !important;
    min-width: 0;
  }
}
</style>

<style lang="scss" scoped>
.ubd-title {
  display: flex;
  align-items: flex-start;
  gap: 14px;
  padding-right: 36px;
}

.ubd-title__icon-wrap {
  width: 44px;
  height: 44px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.ubd-title__icon-wrap--punch {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  box-shadow: 0 8px 20px rgba(64, 158, 255, 0.35);
}

.ubd-title__icon {
  font-size: 22px;
  color: #fff;
}

.ubd-title__heading {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  letter-spacing: 0.02em;
}

.ubd-title__desc {
  margin-top: 4px;
  font-size: 13px;
  color: #6b7280;
  line-height: 1.45;
}

.ubd-body--punch {
  margin: 0 -4px;
}

.ubd-stat-bar {
  margin-bottom: 16px;
  padding: 14px 18px;
  border-radius: 12px;
  background: linear-gradient(110deg, #e8f2ff 0%, #f0f7ff 48%, #faf5ff 100%);
  border: 1px solid rgba(64, 158, 255, 0.18);
  box-shadow: 0 1px 3px rgba(15, 23, 42, 0.04);
}

.ubd-stat-bar__main {
  display: flex;
  align-items: baseline;
  flex-wrap: wrap;
  gap: 4px 8px;
}

.ubd-stat-bar__num {
  font-size: 28px;
  font-weight: 700;
  color: #409eff;
  line-height: 1;
  letter-spacing: -0.03em;
}

.ubd-stat-bar__unit {
  font-size: 14px;
  font-weight: 600;
  color: #409eff;
}

.ubd-stat-bar__dash {
  font-size: 14px;
  color: #374151;
  font-weight: 500;
}

.ubd-stat-bar__hint {
  margin: 10px 0 0;
  font-size: 12px;
  color: #6b7280;
  line-height: 1.55;
}

.ubd-stat-bar__hint strong {
  color: #409eff;
  font-weight: 600;
}

.ubd-panel {
  background: #fff;
  border-radius: 12px;
  border: 1px solid #e8ebf0;
  padding: 16px;
  box-shadow: 0 4px 20px rgba(15, 23, 42, 0.04);
}

.ubd-toolbar {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
  margin-bottom: 14px;
}

.ubd-toolbar__search {
  flex: 1;
  min-width: 200px;
}

.ubd-toolbar ::v-deep .el-input__inner {
  border-radius: 10px;
  border-color: #e4e7ed;
}

.ubd-toolbar ::v-deep .el-input__inner:focus {
  border-color: #409eff;
}

.ubd-toolbar__btns {
  display: flex;
  align-items: center;
  gap: 4px;
}

.ubd-link-btn {
  padding: 6px 10px;
  font-weight: 500;
  color: #409eff !important;
}

.ubd-link-btn--muted {
  color: #909399 !important;
}

.ubd-tags-row {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 12px;
}

.ubd-tag {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
  padding: 5px 12px;
  border-radius: 999px;
  font-weight: 500;
}

.ubd-tag i {
  font-size: 12px;
}

.ubd-tag--primary {
  background: rgba(64, 158, 255, 0.12);
  color: #1976d2;
}

.ubd-tag--neutral {
  background: #f3f4f6;
  color: #6b7280;
}

.ubd-chip-area {
  margin: 0;
  padding: 12px;
  border-radius: 10px;
  background: #f9fafb;
  overflow: visible;
}

.ubd-chip-group {
  display: grid;
  grid-template-columns: repeat(6, minmax(0, 1fr));
  gap: 10px 12px;
  align-items: stretch;
  width: 100%;
}

@media (max-width: 1600px) {
  .ubd-chip-group {
    grid-template-columns: repeat(5, minmax(0, 1fr));
  }
}

@media (max-width: 1280px) {
  .ubd-chip-group {
    grid-template-columns: repeat(4, minmax(0, 1fr));
  }
}

@media (max-width: 1000px) {
  .ubd-chip-group {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }
}

.ubd-chip-group ::v-deep .ubd-chip.el-checkbox {
  margin-right: 0;
  margin-left: 0;
  height: auto;
  padding: 0;
  border: none;
  background: transparent;
}

.ubd-chip-group ::v-deep .ubd-chip.el-checkbox.is-bordered {
  padding: 0;
  border: none;
}

.ubd-chip-group ::v-deep .ubd-chip .el-checkbox__input {
  display: none;
}

.ubd-chip-group ::v-deep .ubd-chip .el-checkbox__label {
  padding: 0 !important;
  line-height: 1.25;
  width: 100%;
  min-width: 0;
  text-align: center;
}

.ubd-chip-group ::v-deep .ubd-chip .el-checkbox__inner {
  display: none;
}

/* 网格内等宽对齐，圆角矩形（与列宽一致） */
.ubd-chip-group ::v-deep .el-checkbox.ubd-chip.is-bordered {
  width: 100%;
  min-width: 0;
  height: 100%;
  margin: 0 !important;
  border: 1px solid #e5e7eb !important;
  border-radius: 10px !important;
  padding: 0 12px !important;
  min-height: 44px;
  display: flex !important;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  background: #fff !important;
  box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
  transition: border-color 0.2s ease, box-shadow 0.2s ease, background 0.2s ease;
}

.ubd-chip-group ::v-deep .el-checkbox.ubd-chip.is-bordered:hover {
  border-color: #b3d8ff !important;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.12);
}

.ubd-chip-group ::v-deep .el-checkbox.ubd-chip.is-bordered.is-checked {
  border-color: #409eff !important;
  background: linear-gradient(180deg, #ecf5ff 0%, #fff 100%) !important;
  box-shadow: 0 4px 14px rgba(64, 158, 255, 0.2);
}

.ubd-chip-group ::v-deep .el-checkbox.ubd-chip.is-checked .ubd-chip__text {
  color: #1d4ed8;
  font-weight: 600;
}

.ubd-chip__text {
  display: block;
  width: 100%;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 13px;
  color: #374151;
  text-align: center;
}

.ubd-empty-state {
  text-align: center;
  padding: 36px 16px;
  color: #9ca3af;
}

.ubd-empty-state i {
  font-size: 40px;
  margin-bottom: 10px;
  opacity: 0.45;
  display: block;
}

.ubd-empty-state p {
  margin: 0;
  font-size: 13px;
  color: #6b7280;
}

.ubd-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 12px;
}

.ubd-footer__cancel {
  min-width: 88px;
  border-radius: 10px;
}

.ubd-footer__ok {
  min-width: 140px;
  border-radius: 10px;
  font-weight: 500;
  box-shadow: 0 4px 14px rgba(64, 158, 255, 0.35);
}
</style>
