<template>
  <el-dialog
    :visible.sync="visibleProxy"
    :show-close="false"
    width="1200px"
    :close-on-click-modal="false"
    custom-class="booking-consume-dialog"
    append-to-body
  >
    <div class="consume-dialog-inner">
      <div class="consume-header">
        <div class="consume-title-wrap">
          <div class="consume-title">预约消耗单</div>
          <div class="consume-subtitle" v-if="form.memberName">{{ form.memberName }}</div>
        </div>
        <div class="consume-header-actions">
          <el-button size="mini" class="ghost-btn" @click="roomUsageVisible = true">
            <i class="el-icon-office-building"></i> 查看房态
          </el-button>
          <span class="consume-close" @click="handleCancel">
            <i class="el-icon-close"></i>
          </span>
        </div>
      </div>

      <div class="consume-content">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="96px"
          size="small"
          class="consume-form"
        >
          <div class="consume-left">
            <div class="section-title"><i class="el-icon-document"></i> 基础信息</div>

            <el-form-item label="会员" prop="memberId">
              <el-select
                v-model="form.memberId"
                placeholder="输入姓名或手机号搜索"
                filterable
                remote
                reserve-keyword
                clearable
                :filter-method="keepMemberOptionVisible"
                :remote-method="searchMembers"
                :loading="memberLoading"
                no-data-text="未找到会员，请换关键词试试"
                @visible-change="onMemberSelectVisible"
                @change="onMemberChange"
              >
                <el-option
                  v-for="m in memberOptions"
                  :key="m.value"
                  :label="m.optionLabel"
                  :value="m.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="预约日期" prop="date">
              <el-date-picker v-model="form.date" type="date" placeholder="选择日期" style="width:100%" />
            </el-form-item>

            <el-form-item label="开始时间" prop="startTime">
              <el-time-select v-model="form.startTime" :picker-options="timeOptions" placeholder="开始时间" style="width:100%" />
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-time-select v-model="form.endTime" :picker-options="timeOptionsEnd" placeholder="结束时间" style="width:100%" />
            </el-form-item>

            <el-form-item label="房间" prop="roomId">
              <el-select v-model="form.roomId" placeholder="选择房间" filterable clearable @change="onRoomChange">
                <el-option v-for="r in roomOptions" :key="r.id" :label="r.name" :value="r.id" />
              </el-select>
            </el-form-item>

            <el-form-item label="服务健康师">
              <div class="readonly-workers">
                <span v-if="selectedTherapistNames.length" class="readonly-workers-text">{{ selectedTherapistNames.join('、') }}</span>
                <span v-else class="readonly-workers-empty">请在右侧品项中选择服务健康师</span>
              </div>
            </el-form-item>

            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注信息" />
            </el-form-item>
          </div>

          <div class="consume-right">
            <div class="section-title"><i class="el-icon-goods"></i> 品项明细</div>

            <div v-for="(item, idx) in form.items" :key="'item-' + idx" class="item-card">
              <div class="item-card-head">
                <span class="item-card-no">品项 {{ idx + 1 }}</span>
                <el-button
                  v-if="form.items.length > 1"
                  type="text"
                  class="item-remove-btn"
                  @click="removeItem(idx)"
                >
                  <i class="el-icon-delete"></i> 删除
                </el-button>
              </div>

              <el-form-item
                label="品项"
                :prop="'items.' + idx + '.projectId'"
                :rules="[{ required: true, message: '请选择品项', trigger: 'change' }]"
                label-width="56px"
              >
                <el-select
                  v-model="item.projectId"
                  placeholder="搜索品项"
                  filterable
                  clearable
                  @change="onProjectChange(idx)"
                >
                  <el-option v-for="p in availableItems" :key="p.value" :label="p.label" :value="p.value" />
                </el-select>
              </el-form-item>

              <div v-if="item.projectId" class="px-info-panel">
                <el-row :gutter="8">
                  <el-col :span="8"><span class="px-tag">单价</span> <b>¥{{ item.price }}</b></el-col>
                  <el-col :span="8"><span class="px-tag">总购买</span> <b>{{ item.totalPurchased }}</b></el-col>
                  <el-col :span="8"><span class="px-tag">已消费</span> <b>{{ item.consumed }}</b></el-col>
                </el-row>
                <el-row :gutter="8" style="margin-top:4px">
                  <el-col :span="8"><span class="px-tag">剩余</span> <b class="remaining">{{ item.remaining }}</b></el-col>
                  <el-col :span="8"><span class="px-tag">来源</span> <b>{{ item.sourceType || '无' }}</b></el-col>
                  <el-col :span="8"><span class="px-tag">健康师手工费</span> <b>{{ item.healthCoachLaborCost }}</b></el-col>
                </el-row>
                <el-row :gutter="8" style="margin-top:4px" v-if="item.qt2 === '科美'">
                  <el-col :span="8"><span class="px-tag">科美手工费</span> <b>{{ item.techBeautyLaborCost }}</b></el-col>
                </el-row>
              </div>

              <el-row :gutter="12" style="margin-top:8px">
                <el-col :span="16">
                  <el-form-item label="次数" label-width="56px">
                    <el-input-number
                      v-model="item.count"
                      :min="1"
                      :max="item.remaining || 999"
                      controls-position="right"
                      style="width:100%"
                      @change="onCountChange(idx)"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <div class="worker-section">
                <div class="worker-label">
                  <span>服务健康师</span>
                  <el-button type="text" size="mini" @click="addWorker(idx)">
                    <i class="el-icon-plus"></i> 添加健康师
                  </el-button>
                </div>
                <div v-for="(w, wi) in item.workers" :key="'w-' + wi" class="worker-row">
                  <el-select v-model="w.workerId" placeholder="选择健康师" filterable size="mini" class="worker-select">
                    <el-option v-for="h in healthWorkerOptions" :key="h.value" :label="h.label" :value="h.value" />
                  </el-select>
                  <el-button
                    v-if="item.workers.length > 1"
                    type="text"
                    size="mini"
                    class="worker-remove"
                    @click="removeWorker(idx, wi)"
                  >
                    <i class="el-icon-close"></i>
                  </el-button>
                </div>
              </div>

              <div class="worker-section" v-if="item.qt2 === '科美'">
                <div class="worker-label">
                  <span>科技部老师</span>
                  <el-button type="text" size="mini" @click="addTechTeacher(idx)">
                    <i class="el-icon-plus"></i> 添加科技部老师
                  </el-button>
                </div>
                <div v-for="(t, ti) in item.techTeachers" :key="'t-' + ti" class="worker-row">
                  <el-select v-model="t.teacherId" placeholder="选择老师" filterable size="mini" class="worker-select">
                    <el-option v-for="tt in techTeacherOptions" :key="tt.value" :label="tt.label" :value="tt.value" />
                  </el-select>
                  <el-input :value="t.performance" readonly placeholder="业绩" size="mini" class="worker-field">
                    <template slot="prepend">¥</template>
                  </el-input>
                  <el-input :value="t.laborCost" readonly placeholder="手工费" size="mini" class="worker-field" />
                  <el-input :value="t.count" readonly placeholder="次数" size="mini" class="worker-field-sm" />
                  <el-button
                    type="text"
                    size="mini"
                    class="worker-remove"
                    @click="removeTechTeacher(idx, ti)"
                  >
                    <i class="el-icon-close"></i>
                  </el-button>
                </div>
              </div>

              <div class="worker-section" v-if="item.isAllowAccompanied == 1">
                <div class="worker-label">
                  <span>陪同健康师</span>
                  <el-button type="text" size="mini" @click="addAccompanied(idx)">
                    <i class="el-icon-plus"></i> 添加陪同健康师
                  </el-button>
                </div>
                <div v-for="(a, ai) in item.accompanied" :key="'a-' + ai" class="worker-row">
                  <el-select v-model="a.workerId" placeholder="选择健康师" filterable size="mini" class="worker-select">
                    <el-option v-for="h in healthWorkerOptions" :key="h.value" :label="h.label" :value="h.value" />
                  </el-select>
                  <el-input-number v-model="a.count" :min="1" controls-position="right" size="mini" style="width:100px" />
                  <el-button
                    type="text"
                    size="mini"
                    class="worker-remove"
                    @click="removeAccompanied(idx, ai)"
                  >
                    <i class="el-icon-close"></i>
                  </el-button>
                </div>
              </div>
            </div>

            <div class="add-btn-row">
              <el-button type="text" @click="addItem">
                <i class="el-icon-circle-plus-outline"></i> 添加品项
              </el-button>
            </div>
          </div>
        </el-form>
      </div>

      <div class="consume-footer">
        <div class="footer-summary">
          <span class="footer-tip">提示：服务健康师来自右侧品项选择（用于排班占用展示）</span>
        </div>
        <div class="footer-actions">
          <el-button size="small" @click="handleCancel">取 消</el-button>
          <el-button type="primary" size="small" :loading="submitting" @click="handleSubmit">
            {{ submitting ? '提交中...' : '保 存' }}
          </el-button>
        </div>
      </div>
    </div>

    <room-usage-dialog
      :visible.sync="roomUsageVisible"
      :date="roomUsageDate"
      :store-id="storeId"
      :rooms="roomOptions"
    />
  </el-dialog>
</template>

<script>
import RoomUsageDialog from '@/components/room-usage-dialog.vue'
import { createYyjl, updateYyjl, getYyjlInfo } from '@/api/lqYyjl'
import { getKhxxList, getMemberRemainingItems } from '@/api/lqKhxx'
import { getRoomsByStoreId } from '@/api/lqMdRoom'
import { getStoreUserList } from '@/api/storeUser'
import {
  buildYyjlSubmitBody,
  mapRemainingItemToOption,
  mapYyjlInfoToFormRecord
} from '@/utils/appointmentHelper'

export default {
  name: 'BookingConsumeDialog',
  components: { RoomUsageDialog },
  props: {
    visible: { type: Boolean, default: false },
    prefill: { type: Object, default: () => ({}) }
  },
  data() {
    return {
      submitting: false,
      memberLoading: false,
      memberSearchKeyword: '',
      roomUsageVisible: false,
      form: this.createEmptyForm(),
      editId: '',
      editMeta: null,
      memberOptions: [],
      healthWorkerOptions: [],
      techTeacherOptions: [
        { value: 'kjb001', label: '赵科技老师' },
        { value: 'kjb002', label: '钱科技老师' }
      ],
      roomOptions: [],
      availableItems: [],
      timeOptions: { start: '09:00', step: '00:30', end: '21:00' },
      rules: {
        memberId: [{ required: true, message: '请选择会员', trigger: 'change' }],
        date: [{ required: true, message: '请选择预约日期', trigger: 'change' }],
        startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' },
          { validator: (rule, value, cb) => {
            if (!value || !this.form.startTime) { cb(); return }
            const [sh, sm] = this.form.startTime.split(':').map(Number)
            const [eh, em] = value.split(':').map(Number)
            if (eh < sh || (eh === sh && em <= sm)) cb(new Error('结束时间须晚于开始时间'))
            else cb()
          }, trigger: 'change' }
        ],
        roomId: [{
          validator: (rule, value, cb) => {
            if (this.roomOptions.length > 0 && !value) cb(new Error('请选择房间'))
            else cb()
          },
          trigger: 'change'
        }],
        items: [{ validator: (rule, value, cb) => {
          const list = this.form.items || []
          if (!Array.isArray(list) || list.length < 1) cb(new Error('请至少添加 1 个品项'))
          else if (list.some(x => !x || !x.projectId)) cb(new Error('请完善品项选择'))
          else if (list.some(x => !x.workers || x.workers.length < 1 || x.workers.some(w => !w.workerId))) cb(new Error('请为每个品项选择服务健康师'))
          else cb()
        }, trigger: 'change' }]
      }
    }
  },
  computed: {
    visibleProxy: {
      get() { return this.visible },
      set(v) { this.$emit('update:visible', v) }
    },
    selectedTherapistIds() {
      const set = new Set()
      ;(this.form.items || []).forEach(it => {
        ;(it.workers || []).forEach(w => {
          if (w && w.workerId) set.add(w.workerId)
        })
      })
      return Array.from(set)
    },
    selectedTherapistNames() {
      const map = new Map((this.healthWorkerOptions || []).map(x => [x.value, x.label]))
      return this.selectedTherapistIds.map(id => map.get(id) || id).filter(Boolean)
    },
    timeOptionsEnd() {
      const base = { ...this.timeOptions }
      if (this.form.startTime) {
        const [h, m] = this.form.startTime.split(':').map(Number)
        const next = (h * 60 + m + 30) % (24 * 60)
        base.start = `${String(Math.floor(next / 60)).padStart(2, '0')}:${String(next % 60).padStart(2, '0')}`
        const [eh, em] = (base.end || '21:00').split(':').map(Number)
        if (next >= eh * 60 + em) base.end = '22:00'
      }
      return base
    },
    roomUsageDate() {
      const d = this.form.date
      if (d instanceof Date) return this.formatDate(d)
      if (typeof d === 'string' && d) return d.substring(0, 10)
      return this.formatDate(new Date())
    },
    storeId() {
      return (this.$store.getters.storeInfo || {}).storeId || ''
    },
    userId() {
      const u = this.$store.getters.userInfo || {}
      return u.userId || u.id || ''
    }
  },
  watch: {
    visible(val) {
      if (val) this.resetFormForOpen()
    },
    prefill: {
      deep: true,
      handler() {
        if (this.visible) this.resetFormForOpen()
      }
    }
  },
  methods: {
    createEmptyForm() {
      return {
        memberId: '',
        memberName: '',
        date: new Date(),
        startTime: '',
        endTime: '',
        roomId: '',
        roomName: '',
        therapistIds: [],
        items: [this.createEmptyItem()],
        remark: ''
      }
    },
    createEmptyItem() {
      return {
        projectId: '',
        itemId: '',
        billingItemId: '',
        label: '',
        price: 0,
        remaining: 0,
        totalPurchased: 0,
        consumed: 0,
        sourceType: '',
        qt2: '',
        beautyType: '',
        healthCoachLaborCost: 0,
        techBeautyLaborCost: 0,
        isAllowAccompanied: 0,
        count: 1,
        workers: [{ workerId: '' }],
        techTeachers: [],
        accompanied: []
      }
    },
    async resetFormForOpen() {
      this.form = this.createEmptyForm()
      this.editId = ''
      this.editMeta = null
      this.roomUsageVisible = false
      this.submitting = false
      this.availableItems = []
      await Promise.all([
        this.loadRooms(),
        this.loadHealthWorkers(),
      ])
      await this.applyPrefill()
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate()
      })
    },
    async loadRooms() {
      if (!this.storeId) return
      try {
        const res = await getRoomsByStoreId(this.storeId)
        const list = (res.data && res.data.list) || []
        this.roomOptions = list
          .filter(r => r.enabled !== 0 && r.enabled !== '0' && r.enabled !== false)
          .map(r => ({ id: r.id, name: r.roomName }))
      } catch (e) {
        this.roomOptions = []
      }
    },
    async loadHealthWorkers() {
      if (!this.storeId) return
      try {
        const res = await getStoreUserList({
          mdid: this.storeId,
          gw: '健康师',
          currentPage: 1,
          pageSize: 200
        })
        const list = res.data?.list || []
        this.healthWorkerOptions = list.map(u => ({
          value: u.id,
          label: u.realName || u.account || u.id
        }))
      } catch (e) {
        this.healthWorkerOptions = []
      }
    },
    /** 远程下拉：禁止本地二次过滤，否则接口有数据也不显示 */
    keepMemberOptionVisible() {
      return true
    },
    onMemberSelectVisible(visible) {
      if (visible && !this.memberOptions.length) {
        this.searchMembers(this.memberSearchKeyword || '')
      }
    },
    mapKhxxToMemberOption(item) {
      const name = item.khmc || item.Khmc || '无'
      const phone = item.sjh || item.Sjh || ''
      const label = phone ? `${name}（${phone}）` : name
      return {
        value: item.id || item.Id,
        label: name,
        phone,
        optionLabel: label
      }
    },
    async searchMembers(keyword) {
      const kw = (keyword != null ? String(keyword) : '').trim()
      this.memberSearchKeyword = kw
      if (!kw) {
        this.memberOptions = []
        return
      }
      this.memberLoading = true
      try {
        const res = await getKhxxList({
          currentPage: 1,
          pageSize: 30,
          keyWord: kw
        })
        const list = res.data?.list || res.data?.List || []
        this.memberOptions = list
          .map(item => this.mapKhxxToMemberOption(item))
          .filter(item => item.value)
      } catch (e) {
        this.memberOptions = []
      } finally {
        this.memberLoading = false
      }
    },
    async applyPrefill() {
      const p = this.prefill || {}
      if (!p || typeof p !== 'object') return

      if (p.id) {
        this.editId = p.id
        try {
          const res = await getYyjlInfo(p.id)
          const info = res.data || {}
          const record = mapYyjlInfoToFormRecord(info, info.lqYyjlPxList || [])
          Object.assign(p, record)
        } catch (e) {
          this.$message.error('加载预约详情失败')
        }
      }

      if (p.memberId) {
        this.form.memberId = p.memberId
        this.form.memberName = p.memberName || ''
        if (!this.memberOptions.some(m => m.value === p.memberId)) {
          const name = p.memberName || '会员'
          this.memberOptions.unshift({
            value: p.memberId,
            label: name,
            phone: '',
            optionLabel: name
          })
        }
        await this.loadMemberItems(p.memberId)
      }
      if (p.date) {
        const d = p.date instanceof Date ? p.date : new Date(p.date)
        if (!Number.isNaN(d.getTime())) this.form.date = d
      }
      if (p.startTime) this.form.startTime = p.startTime
      if (p.endTime) this.form.endTime = p.endTime
      if (p.roomId) {
        this.form.roomId = p.roomId
        const r = this.roomOptions.find(x => x.id === p.roomId)
        this.form.roomName = (p.roomName || (r ? r.name : '')) || ''
      } else if (p.roomName) {
        this.form.roomName = p.roomName
      }
      if (p.remark != null) this.form.remark = p.remark || ''

      // items
      if (Array.isArray(p.items) && p.items.length) {
        this.form.items = p.items.map(pi => {
          const it = this.createEmptyItem()
          it.projectId = pi.projectId || ''
          it.label = pi.label || ''
          it.count = (pi.count != null ? pi.count : 1) || 1
          it.workers = Array.isArray(pi.workers) && pi.workers.length ? pi.workers.map(w => ({
            workerId: (w && (w.workerId || w.id)) || '',
            performance: '',
            laborCost: '',
            count: ''
          })) : [{ workerId: '' }]
          return it
        })
        this.$nextTick(() => {
          this.form.items.forEach((_, idx) => {
            if (this.form.items[idx].projectId) this.onProjectChange(idx)
          })
        })
      }
    },
    onMemberChange(val) {
      const m = this.memberOptions.find(x => x.value === val)
      this.form.memberName = m ? m.label : ''
      this.form.items = [this.createEmptyItem()]
      if (val) this.loadMemberItems(val)
      else this.availableItems = []
    },
    async loadMemberItems(memberId) {
      if (!memberId) {
        this.availableItems = []
        return
      }
      try {
        const res = await getMemberRemainingItems(memberId)
        const list = res.data?.RemainingItems || res.data?.remainingItems || []
        this.availableItems = (list || [])
          .filter(item => Number(item.RemainingCount) > 0)
          .map(mapRemainingItemToOption)
      } catch (e) {
        this.availableItems = []
      }
    },
    onRoomChange(val) {
      const r = this.roomOptions.find(x => x.id === val)
      this.form.roomName = r ? r.name : ''
    },
    handleCancel() {
      this.visibleProxy = false
    },
    formatDate(d) {
      const dt = d instanceof Date ? d : new Date(d)
      const y = dt.getFullYear()
      const m = String(dt.getMonth() + 1).padStart(2, '0')
      const day = String(dt.getDate()).padStart(2, '0')
      return `${y}-${m}-${day}`
    },
    handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        if (!this.storeId) {
          this.$message.warning('未获取到门店信息')
          return
        }
        if (!this.userId) {
          this.$message.warning('未获取到登录用户')
          return
        }
        this.submitting = true
        try {
          const body = buildYyjlSubmitBody(this.form, {
            storeId: this.storeId,
            userId: this.userId,
            memberName: this.form.memberName,
            healthWorkerOptions: this.healthWorkerOptions
          })
          if (this.editId) {
            body.id = this.editId
            await updateYyjl(this.editId, body)
            this.$message.success('预约已更新')
          } else {
            await createYyjl(body)
            this.$message.success('预约已创建')
          }
          this.visibleProxy = false
          this.$emit('saved')
          try {
            window.dispatchEvent(new CustomEvent('store_pc_bookings_updated'))
          } catch (e) {}
        } catch (e) {
          // 错误由拦截器提示
        } finally {
          this.submitting = false
        }
      })
    },
    addItem() {
      this.form.items.push(this.createEmptyItem())
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate('items')
      })
    },
    removeItem(idx) {
      this.form.items.splice(idx, 1)
      if (!this.form.items.length) this.form.items.push(this.createEmptyItem())
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate('items')
      })
    },
    getProjectLabel(pid) {
      const hit = this.availableItems.find(x => x.value === pid)
      if (!hit || !hit.label) return ''
      return (hit.label || '').split('（剩余')[0] || ''
    },
    onProjectChange(idx) {
      const item = this.form.items[idx]
      if (!item) return
      const p = this.availableItems.find(o => o.value === item.projectId)
      if (p) {
        item.label = (p.label || '').split('（剩余')[0] || p.label || ''
        item.itemId = p.itemId || p.value
        item.billingItemId = p.billingItemId || p.value
        item.price = p.price
        item.remaining = p.remaining
        item.totalPurchased = p.totalPurchased
        item.consumed = p.consumed
        item.sourceType = p.sourceType
        item.qt2 = p.qt2
        item.healthCoachLaborCost = p.healthCoachLaborCost
        item.techBeautyLaborCost = p.techBeautyLaborCost
        item.isAllowAccompanied = p.isAllowAccompanied
        item.count = 1
        item.workers = [{ workerId: '', performance: '', laborCost: '', count: '' }]
        item.techTeachers = []
        item.accompanied = []
      }
      this.redistributeWorkers(idx)
    },
    onCountChange(idx) {
      this.redistributeWorkers(idx)
      this.redistributeTechTeachers(idx)
    },
    redistributeWorkers(idx) {
      const item = this.form.items[idx]
      if (!item.workers || item.workers.length === 0) return
      const totalCount = item.count || 0
      const totalPerf = item.price * totalCount
      const isKemei = item.qt2 === '科美' && item.beautyType !== 'cell'
      const isCell = item.qt2 === '科美' && item.beautyType === 'cell'
      const hasTech = item.techTeachers && item.techTeachers.length > 0
      const n = item.workers.length
      if (isKemei || (isCell && hasTech)) {
        item.workers.forEach(w => {
          w.performance = (totalPerf / n).toFixed(2)
          w.laborCost = '0.00'
          w.count = '0'
        })
      } else {
        const totalLabor = (item.healthCoachLaborCost || 0) * totalCount
        item.workers.forEach(w => {
          w.performance = (totalPerf / n).toFixed(2)
          w.laborCost = (totalLabor / n).toFixed(2)
          w.count = (totalCount / n).toFixed(2)
        })
      }
    },
    redistributeTechTeachers(idx) {
      const item = this.form.items[idx]
      if (!item.techTeachers || item.techTeachers.length === 0) return
      const totalCount = item.count || 0
      const totalPerf = item.price * totalCount
      const totalLabor = (item.techBeautyLaborCost || 0) * totalCount
      const n = item.techTeachers.length
      item.techTeachers.forEach(t => {
        t.performance = (totalPerf / n).toFixed(2)
        t.laborCost = (totalLabor / n).toFixed(2)
        t.count = (totalCount / n).toFixed(2)
      })
      this.redistributeWorkers(idx)
    },
    addWorker(idx) {
      this.form.items[idx].workers.push({ workerId: '', performance: '', laborCost: '', count: '' })
      this.redistributeWorkers(idx)
    },
    removeWorker(idx, wi) {
      this.form.items[idx].workers.splice(wi, 1)
      this.redistributeWorkers(idx)
    },
    addTechTeacher(idx) {
      this.form.items[idx].techTeachers.push({ teacherId: '', performance: '', laborCost: '', count: '' })
      this.redistributeTechTeachers(idx)
    },
    removeTechTeacher(idx, ti) {
      this.form.items[idx].techTeachers.splice(ti, 1)
      this.redistributeTechTeachers(idx)
    },
    addAccompanied(idx) {
      this.form.items[idx].accompanied.push({ workerId: '', count: 1 })
    },
    removeAccompanied(idx, ai) {
      this.form.items[idx].accompanied.splice(ai, 1)
    }
  }
}
</script>

<style lang="scss" scoped>
.ghost-btn {
  border-radius: 999px !important;
  background: rgba(239, 246, 255, 0.9) !important;
  color: #2563eb !important;
  border-color: rgba(37, 99, 235, 0.18) !important;
}

/* ====== 内部结构（对齐 ConsumeDialog） ====== */
.consume-dialog-inner {
  display: flex;
  flex-direction: column;
  max-height: 85vh;
}

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

.consume-title-wrap {
  flex: 1;
}

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

.consume-subtitle {
  font-size: 12px;
  color: #475569;
  margin-top: 2px;
}

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

.consume-close {
  flex-shrink: 0;
  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;
  }
}

.consume-content {
  flex: 1;
  min-height: 0;
  overflow: hidden;
  display: flex;
}

.consume-form {
  display: flex;
  flex: 1;
  min-height: 0;
}

.consume-left {
  flex: 0 0 440px;
  overflow-y: auto;
  padding: 10px 16px 10px 22px;
  border-right: 1px solid rgba(229, 231, 235, 0.6);
  min-height: 0;
}

.consume-right {
  flex: 1;
  overflow-y: auto;
  padding: 10px 22px 10px 16px;
  min-height: 0;
}

.section-title {
  font-size: 13px;
  font-weight: 600;
  color: #334155;
  margin: 14px 0 8px;
  padding: 6px 10px;
  border-radius: 8px;
  background: rgba(241, 245, 249, 0.7);

  i {
    margin-right: 4px;
    color: #2563eb;
  }

  &:first-child {
    margin-top: 4px;
  }
}

.item-card {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 10px 12px 4px;
  margin-bottom: 10px;
  background: rgba(255, 255, 255, 0.6);
  transition: border-color 0.15s;

  &:hover {
    border-color: #93c5fd;
  }
}

.item-card-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6px;
}

.item-card-no {
  font-size: 12px;
  font-weight: 600;
  color: #2563eb;
}

.item-remove-btn {
  color: #ef4444 !important;
  font-size: 12px;
  padding: 0;
}

.px-info-panel {
  margin: 4px 0 6px;
  padding: 8px 10px;
  border-radius: 8px;
  background: rgba(241, 245, 249, 0.5);
  font-size: 12px;
  color: #475569;
  line-height: 1.8;

  .px-tag {
    color: #94a3b8;
    margin-right: 2px;
  }

  b {
    color: #0f172a;
    font-weight: 600;
  }

  .remaining {
    color: #2563eb;
  }
}

.worker-section {
  margin: 2px 0 6px;
  padding: 8px 10px;
  border-radius: 8px;
  background: rgba(241, 245, 249, 0.5);
}

.worker-label {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6px;
  font-size: 12px;
  color: #475569;
  font-weight: 500;
}

.worker-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}

.worker-select {
  flex: 1;
}

.worker-field {
  width: 120px;
  flex-shrink: 0;
}

.worker-field-sm {
  width: 70px;
  flex-shrink: 0;
}

.worker-remove {
  color: #ef4444 !important;
  padding: 0;
}

.add-btn-row {
  text-align: center;
  margin-bottom: 6px;
}

.consume-footer {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 22px 14px;
  border-top: 1px solid rgba(229, 231, 235, 0.6);
}

.footer-summary {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #64748b;

  b {
    color: #0f172a;
  }

  .highlight {
    color: #2563eb;
    font-size: 14px;
  }
}

.footer-actions {
  display: flex;
  gap: 10px;
}

::v-deep .booking-consume-dialog {
  max-width: 1200px;
  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);
  -webkit-backdrop-filter: blur(22px);
}

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

::v-deep .booking-consume-dialog .el-form-item__label { white-space: nowrap; }
::v-deep .booking-consume-dialog .el-input__inner {
  border-radius: 999px;
  height: 32px;
  line-height: 32px;
  border-color: #e5e7eb;
  background-color: #f9fafb;
}
::v-deep .booking-consume-dialog .el-input__inner:focus {
  border-color: #2563eb;
  box-shadow: 0 0 0 1px rgba(37, 99, 235, 0.18);
}
::v-deep .booking-consume-dialog .el-textarea__inner {
  border-radius: 12px;
  border-color: #e5e7eb;
  background-color: #f9fafb;
}
::v-deep .booking-consume-dialog .el-input-group__prepend {
  border-radius: 999px 0 0 999px;
  background: #f1f5f9;
  border-color: #e5e7eb;
  padding: 0 10px;
  color: #64748b;
}
::v-deep .booking-consume-dialog .el-input-group .el-input__inner {
  border-radius: 0 999px 999px 0;
}
::v-deep .booking-consume-dialog .el-input-number {
  .el-input__inner {
    border-radius: 999px;
  }
}
::v-deep .booking-consume-dialog .el-button--primary {
  border-radius: 999px;
  padding: 0 20px;
  height: 30px;
  line-height: 30px;
  background: #2563eb;
  border-color: #2563eb;
  box-shadow: 0 4px 10px rgba(37, 99, 235, 0.35);
  font-size: 12px;
}
::v-deep .booking-consume-dialog .el-button--default {
  border-radius: 999px;
  padding: 0 18px;
  height: 30px;
  line-height: 30px;
  background: rgba(239, 246, 255, 0.9);
  color: #2563eb;
  border-color: rgba(37, 99, 235, 0.18);
  font-size: 12px;
}
::v-deep .booking-consume-dialog .el-form-item {
  margin-bottom: 12px;
}
::v-deep .booking-consume-dialog .el-select {
  width: 100%;
}
</style>

