<template>
  <el-dialog
    :visible.sync="visibleProxy"
    :show-close="false"
    width="92%"
    max-width="960px"
    :close-on-click-modal="false"
    custom-class="gold-triangle-dialog"
    append-to-body
  >
    <div class="dialog-inner">
      <div class="dialog-header">
        <div class="dialog-title">{{ currentStoreName }} · 金三角设置</div>
        <div class="header-actions">
          <span class="month-badge">{{ formatMonth(monthValue) }}</span>
          <el-date-picker
            v-model="monthValue"
            type="month"
            placeholder="选择月份"
            format="yyyy年MM月"
            value-format="yyyyMM"
            size="small"
            class="month-picker"
            @change="onMonthChange"
          />
          <span class="dialog-close" @click="visibleProxy = false"><i class="el-icon-close"></i></span>
        </div>
      </div>

      <div class="tip-bar">
        <i class="el-icon-info"></i>
        <span>每月1号前完成组队，1-3人一队，2人及以上需指定顾问；单人即个人战队。</span>
      </div>

      <div class="content-grid" v-loading="loading">
        <!-- 左侧：未分配 -->
        <div class="panel panel--pool">
          <div class="panel-title">
            <span>未分配</span>
            <span class="panel-count">{{ unassignedList.length }} 人</span>
          </div>
          <div class="pool-list">
            <span
              v-for="p in unassignedList"
              :key="p.id"
              class="pool-chip"
            >{{ p.name }}</span>
            <span v-if="!unassignedList.length && !loading" class="pool-empty">全部已组队</span>
          </div>
        </div>

        <!-- 右侧：已组建战队 -->
        <div class="panel panel--teams">
          <div class="panel-title">
            <span>已组建战队</span>
            <el-button type="primary" icon="el-icon-plus" size="small" @click="openAddTeam" :disabled="!unassignedList.length">
              新建战队
            </el-button>
          </div>
          <div class="team-cards">
            <div v-for="team in teamsWithMembers" :key="team.id" class="team-card">
              <div class="team-name">{{ team.jsj || '未命名' }}</div>
              <div class="team-members">
                <span
                  v-for="(m, i) in team.members"
                  :key="m.userId"
                  :class="['member-chip', { 'member-chip--leader': m.isLeader === 1 }]"
                >
                  {{ m.userName }}
                  <i v-if="m.isLeader === 1" class="el-icon-star-on leader-icon" title="顾问"></i>
                </span>
              </div>
              <div class="team-actions">
                <el-button type="text" size="mini" icon="el-icon-edit" :disabled="team._readonly" @click="openEditTeam(team)">编辑</el-button>
                <el-button type="text" size="mini" icon="el-icon-delete" class="text-danger" :disabled="team._readonly" @click="handleDel(team)">删除</el-button>
              </div>
            </div>
            <div v-if="!teamsWithMembers.length && !loading" class="teams-empty">
              <p>暂无战队，点击「新建战队」开始组队</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 新建/编辑战队弹窗 -->
    <el-dialog
      :visible.sync="teamFormVisible"
      width="460px"
      append-to-body
      custom-class="team-form-dialog"
      :show-close="false"
      :close-on-click-modal="false"
      @close="closeTeamForm"
    >
      <div class="team-form-inner">
        <div class="team-form-header">
          <div class="team-form-title">{{ editTeam.id ? '编辑战队' : '新建战队' }}</div>
          <span class="team-form-close" @click="closeTeamForm"><i class="el-icon-close"></i></span>
        </div>
        <el-form ref="teamForm" :model="teamForm" size="small" label-width="90px" class="team-form">
          <el-form-item label="选择成员" required>
            <div class="member-select-pool">
              <span
                v-for="p in teamForm.availablePool"
                :key="p.id"
                :class="['member-select-chip', { 'member-select-chip--active': teamForm.selectedIds.includes(p.id) }]"
                @click="toggleMember(p.id)"
              >{{ p.name }}</span>
              <span v-if="!teamForm.availablePool.length" class="no-option">暂无可选成员</span>
            </div>
            <div class="form-hint">点击选择 1-3 人</div>
          </el-form-item>
          <el-form-item label="指定顾问" v-if="teamForm.selectedIds.length >= 2">
            <el-radio-group v-model="teamForm.leaderId" size="small" class="leader-radio-group">
              <el-radio
                v-for="id in teamForm.selectedIds"
                :key="id"
                :label="id"
              >{{ getMemberName(id) }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="战队名称">
            <el-input v-model="teamForm.jsj" placeholder="如：张丽战队" />
            <div class="form-hint">可选，默认以顾问姓名命名</div>
          </el-form-item>
        </el-form>
        <div class="team-form-footer">
          <el-button size="small" @click="closeTeamForm">取 消</el-button>
          <el-button type="primary" size="small" :loading="submitting" @click="submitTeam">确 定</el-button>
        </div>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { getStoreUserList } from '@/api/storeUser'
import {
  getJsjList,
  getJsjDetail,
  createJsj,
  updateJsj,
  deleteJsj,
  addUserToJsj,
  deleteJsjUserRelation
} from '@/api/lqYcsdJsj'
import {
  isTAreaTeamName,
  mapPractitionerFromUser,
  mapDetailToTeam,
  buildMembersPayload,
  syncTeamMembers
} from '@/utils/goldTriangleHelper'

const jsjApi = { addUserToJsj, deleteJsjUserRelation }

export default {
  name: 'GoldTriangleDialog',
  props: {
    visible: { type: Boolean, default: false },
    currentStoreId: { type: String, default: '' },
    currentStoreName: { type: String, default: '' }
  },
  data() {
    return {
      loading: false,
      submitting: false,
      monthValue: null,
      allPractitioners: [],
      assignmentTeams: [],
      teamsWithMembers: [],
      teamFormVisible: false,
      editTeam: { id: null },
      teamForm: {
        selectedIds: [],
        leaderId: '',
        jsj: '',
        availablePool: []
      }
    }
  },
  computed: {
    visibleProxy: {
      get() { return this.visible },
      set(v) { this.$emit('update:visible', v) }
    },
    unassignedList() {
      const assignedIds = new Set()
      const teams = this.assignmentTeams.length ? this.assignmentTeams : this.teamsWithMembers
      teams.forEach(t => {
        (t.members || []).forEach(m => { assignedIds.add(m.userId) })
      })
      return this.allPractitioners.filter(p => !assignedIds.has(p.id))
    }
  },
  watch: {
    visible(v) {
      if (!v) return
      if (!this.currentStoreId) {
        this.$message.warning('请先选择门店')
        this.$nextTick(() => { this.visibleProxy = false })
        return
      }
      this.setDefaultMonth()
      this.loadAll()
    },
    currentStoreId(id) {
      if (this.visible && id) this.loadAll()
    }
  },
  methods: {
    setDefaultMonth() {
      const now = new Date()
      const y = now.getFullYear()
      const m = String(now.getMonth() + 1).padStart(2, '0')
      this.monthValue = `${y}${m}`
    },
    formatMonth(str) {
      if (!str || str.length !== 6) return str
      return `${str.substring(0, 4)}年${str.substring(4, 6)}月`
    },
    onMonthChange() {
      this.loadAll()
    },
    async loadAll() {
      if (!this.currentStoreId || !this.monthValue) return
      this.loading = true
      try {
        const [usersRes, listRes] = await Promise.all([
          getStoreUserList({
            mdid: this.currentStoreId,
            gw: '健康师',
            currentPage: 1,
            pageSize: 500
          }),
          getJsjList({
            md: this.currentStoreId,
            yf: this.monthValue,
            currentPage: 1,
            pageSize: 500
          })
        ])
        const userList = usersRes.data?.list || []
        this.allPractitioners = userList.map(mapPractitionerFromUser)

        const allRows = listRes.data?.list || []
        if (!allRows.length) {
          this.assignmentTeams = []
          this.teamsWithMembers = []
          return
        }
        const details = await Promise.all(allRows.map(row => getJsjDetail(row.id)))
        this.assignmentTeams = details.map((res, idx) => mapDetailToTeam(allRows[idx], res))
        this.teamsWithMembers = this.assignmentTeams
          .filter(t => !isTAreaTeamName(t.jsj))
          .map(t => ({ ...t, _readonly: false }))
      } catch (e) {
        this.allPractitioners = []
        this.teamsWithMembers = []
      } finally {
        this.loading = false
      }
    },
    openAddTeam() {
      this.editTeam = { id: null }
      this.teamForm = {
        selectedIds: [],
        leaderId: '',
        jsj: '',
        availablePool: [...this.unassignedList]
      }
      this.teamFormVisible = true
    },
    openEditTeam(team) {
      if (team._readonly || isTAreaTeamName(team.jsj)) {
        this.$message.info('T区为系统战队，不可编辑')
        return
      }
      this.editTeam = {
        id: team.id,
        jsj: team.jsj,
        _originalMembers: (team.members || []).map(m => ({ ...m }))
      }
      const members = team.members || []
      const selectedIds = members.map(m => m.userId)
      const leader = members.find(m => m.isLeader === 1)
      this.teamForm = {
        selectedIds,
        leaderId: leader ? leader.userId : (selectedIds[0] || ''),
        jsj: team.jsj || '',
        availablePool: [...this.unassignedList, ...members.map(m => ({ id: m.userId, name: m.userName }))]
      }
      this.teamFormVisible = true
    },
    closeTeamForm() {
      this.teamFormVisible = false
    },
    toggleMember(id) {
      const ids = [...this.teamForm.selectedIds]
      const idx = ids.indexOf(id)
      if (idx >= 0) {
        ids.splice(idx, 1)
      } else if (ids.length < 3) {
        ids.push(id)
      } else {
        this.$message.warning('最多选择3人')
        return
      }
      this.teamForm.selectedIds = ids
      if (ids.length >= 2 && !ids.includes(this.teamForm.leaderId)) {
        this.teamForm.leaderId = ids[0]
      }
    },
    getMemberName(id) {
      const p = this.allPractitioners.find(x => x.id === id) || this.teamForm.availablePool.find(x => x.id === id)
      return p ? p.name : id
    },
    async submitTeam() {
      const { selectedIds, leaderId, jsj } = this.teamForm
      if (!this.currentStoreId) {
        this.$message.warning('门店信息异常')
        return
      }
      if (selectedIds.length === 0) {
        this.$message.warning('请选择至少1名成员')
        return
      }
      if (selectedIds.length > 3) {
        this.$message.warning('最多选择3人')
        return
      }
      const effectiveLeader = selectedIds.length >= 2 ? leaderId : (leaderId || selectedIds[0])
      if (selectedIds.length >= 2 && !effectiveLeader) {
        this.$message.warning('2人及以上需指定顾问')
        return
      }
      const teamName = (jsj || '').trim() || `${this.getMemberName(effectiveLeader || selectedIds[0])}战队`
      const members = buildMembersPayload(selectedIds, effectiveLeader, id => this.getMemberName(id))

      this.submitting = true
      try {
        if (this.editTeam.id) {
          await updateJsj(this.editTeam.id, {
            id: this.editTeam.id,
            yf: this.monthValue,
            md: this.currentStoreId,
            jsj: teamName
          })
          await syncTeamMembers(
            this.editTeam.id,
            this.editTeam._originalMembers || [],
            members,
            jsjApi
          )
          this.$message.success('保存成功')
        } else {
          await createJsj({
            yf: this.monthValue,
            md: this.currentStoreId,
            jsj: teamName,
            members
          })
          this.$message.success('创建成功')
        }
        this.closeTeamForm()
        await this.loadAll()
      } catch (e) {
        // 错误已由 request 拦截器提示
      } finally {
        this.submitting = false
      }
    },
    handleDel(team) {
      if (!team || !team.id) return
      if (team._readonly || isTAreaTeamName(team.jsj)) {
        this.$message.info('T区为系统战队，不可删除')
        return
      }
      this.$confirm('确定删除该战队？成员将回到未分配。', '提示', { type: 'warning' }).then(async () => {
        this.loading = true
        try {
          await deleteJsj(team.id)
          this.$message.success('删除成功')
          await this.loadAll()
        } finally {
          this.loading = false
        }
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .gold-triangle-dialog {
  max-width: 960px;
  margin-top: 4vh !important;
  border-radius: 20px;
  padding: 0;
  background: radial-gradient(circle at 0 0, rgba(255,255,255,0.96) 0, rgba(248,250,252,0.98) 40%, rgba(241,245,249,0.98) 100%);
  box-shadow: 0 24px 48px rgba(15,23,42,0.18), 0 0 0 1px rgba(255,255,255,0.9);
  backdrop-filter: blur(22px);
}

/* 新建战队按钮 - 与主弹窗风格统一 */
::v-deep .gold-triangle-dialog .panel-title .el-button--primary {
  height: 34px;
  padding: 0 18px;
  border-radius: 999px;
  font-size: 14px;
  font-weight: 500;
  border: none;
  background: #2563eb;
  box-shadow: 0 4px 10px rgba(37, 99, 235, 0.35);
  &:hover:not(:disabled) {
    background: #1d4ed8;
    box-shadow: 0 4px 12px rgba(37, 99, 235, 0.45);
  }
  &:disabled { opacity: 0.6; }
}

::v-deep .el-dialog__header { display: none; }
::v-deep .el-dialog__body { padding: 0; }

.dialog-inner {
  display: flex;
  flex-direction: column;
  max-height: 82vh;
}

.dialog-header {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 18px 22px 0;
  padding: 10px 14px;
  border-radius: 14px;
  background: rgba(219,234,254,0.96);
}

.dialog-title { font-size: 17px; font-weight: 600; color: #0f172a; }

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.month-badge {
  font-size: 13px;
  color: #64748b;
  font-weight: 500;
}

.month-picker { width: 120px; }

.dialog-close {
  cursor: pointer;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 999px;
  color: #64748b;
  transition: all 0.15s;
  &:hover { background: rgba(0,0,0,0.06); color: #0f172a; }
}

.tip-bar {
  flex-shrink: 0;
  margin: 12px 22px 0;
  padding: 8px 12px;
  background: rgba(251,191,36,0.15);
  border-radius: 8px;
  font-size: 12px;
  color: #92400e;
  display: flex;
  align-items: center;
  gap: 8px;
}

.tip-bar i { font-size: 14px; }

.content-grid {
  flex: 1;
  min-height: 0;
  display: grid;
  grid-template-columns: 220px 1fr;
  gap: 20px;
  padding: 16px 22px 22px;
  overflow: auto;
}

.panel {
  background: #fff;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 14px;
  overflow: auto;
}

.panel-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 14px;
  font-weight: 600;
  color: #334155;
}

.panel-count {
  font-size: 12px;
  color: #64748b;
  font-weight: 500;
}

.pool-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.pool-chip {
  padding: 6px 12px;
  background: #f1f5f9;
  border-radius: 8px;
  font-size: 13px;
  color: #475569;
}

.pool-empty {
  font-size: 12px;
  color: #94a3b8;
  font-style: italic;
}

.team-cards {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.team-card {
  padding: 12px 14px;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 10px;
  transition: all 0.15s;
  &:hover { border-color: #cbd5e1; background: #f1f5f9; }
}

.team-name {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 8px;
}

.team-members {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 8px;
}

.member-chip {
  padding: 4px 10px;
  background: #e2e8f0;
  border-radius: 6px;
  font-size: 12px;
  color: #475569;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.member-chip--leader {
  background: rgba(245,158,11,0.2);
  color: #b45309;
}

.leader-icon { font-size: 12px; color: #f59e0b; }

.team-actions {
  display: flex;
  gap: 12px;
}

.text-danger { color: #ef4444; }

.teams-empty {
  padding: 24px;
  text-align: center;
  color: #94a3b8;
  font-size: 13px;
}

/* 新建/编辑战队弹窗 - 与主弹窗风格统一 */
::v-deep .team-form-dialog {
  max-width: 460px;
  margin-top: 8vh !important;
  border-radius: 20px;
  padding: 0;
  background: radial-gradient(circle at 0 0, rgba(255,255,255,0.96) 0, rgba(248,250,252,0.98) 40%, rgba(241,245,249,0.98) 100%);
  box-shadow: 0 24px 48px rgba(15,23,42,0.18), 0 0 0 1px rgba(255,255,255,0.9);
  backdrop-filter: blur(22px);
}

::v-deep .team-form-dialog .el-dialog__header { display: none; }
::v-deep .team-form-dialog .el-dialog__body { padding: 0; }

.team-form-inner {
  padding: 18px 22px 16px;
}

.team-form-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 14px;
  padding: 10px 14px;
  border-radius: 14px;
  background: rgba(219,234,254,0.96);
}

.team-form-title {
  font-size: 17px;
  font-weight: 600;
  color: #0f172a;
}

.team-form-close {
  cursor: pointer;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 999px;
  color: #64748b;
  transition: all 0.15s;
  &:hover { background: rgba(0,0,0,0.06); color: #0f172a; }
}

.team-form { padding-top: 4px; }

::v-deep .team-form-dialog .el-form-item__label { white-space: nowrap; }

.member-select-pool {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  min-height: 44px;
  padding: 10px 12px;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
}

.member-select-chip {
  padding: 6px 14px;
  background: #e2e8f0;
  border-radius: 8px;
  font-size: 13px;
  color: #475569;
  cursor: pointer;
  transition: all 0.15s;
  &:hover { background: #cbd5e1; color: #334155; }
  &--active {
    background: rgba(99, 102, 241, 0.2);
    color: #4f46e5;
    font-weight: 500;
    &:hover { background: rgba(99, 102, 241, 0.3); }
  }
}

.leader-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.form-hint {
  font-size: 11px;
  color: #94a3b8;
  margin-top: 6px;
}

.no-option { color: #94a3b8; font-size: 13px; font-style: italic; }

.team-form-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px solid #f1f5f9;
}

::v-deep .team-form-dialog .el-input__inner {
  border-radius: 999px;
  height: 32px;
  line-height: 32px;
  border-color: #e5e7eb;
  background-color: #f9fafb;
}

::v-deep .team-form-dialog .el-input__inner:focus {
  border-color: #2563eb;
  box-shadow: 0 0 0 1px rgba(37, 99, 235, 0.18);
}

/* 新建战队弹窗 - 取消/确定按钮样式统一 */
::v-deep .team-form-dialog .el-button--primary,
::v-deep .team-form-dialog .el-button--default {
  height: 34px;
  padding: 0 20px;
  border-radius: 999px;
  font-size: 14px;
  font-weight: 500;
}

::v-deep .team-form-dialog .el-button--primary {
  border: none;
  background: #2563eb;
  box-shadow: 0 4px 10px rgba(37, 99, 235, 0.35);
  &:hover {
    background: #1d4ed8;
    box-shadow: 0 4px 12px rgba(37, 99, 235, 0.45);
  }
}

::v-deep .team-form-dialog .el-button--default {
  border: 1px solid #e2e8f0;
  background: #fff;
  color: #64748b;
  &:hover {
    background: #f8fafc;
    border-color: #cbd5e1;
    color: #475569;
  }
}
</style>
