<template>
  <el-dialog
    :visible.sync="visibleProxy"
    :show-close="false"
    width="1200px"
    :close-on-click-modal="false"
    custom-class="billing-dialog"
    append-to-body
  >
    <div class="billing-dialog-inner">
      <div class="billing-header">
        <div class="billing-title-wrap">
          <div class="billing-title">快速开单</div>
          <div class="billing-subtitle" v-if="form.memberName">{{ form.memberName }}</div>
        </div>
        <div class="booking-source-tag" v-if="prefill && prefill.fromBooking">
          <i class="el-icon-date"></i>
          <span>预约开单</span>
          <span class="booking-source-detail">
            {{ prefill.bookingProject }} · {{ prefill.bookingDate }} {{ prefill.bookingTimeRange }}
            <template v-if="prefill.bookingStaff"> · {{ prefill.bookingStaff }}</template>
          </span>
        </div>
        <span class="billing-close" @click="handleCancel">
          <i class="el-icon-close"></i>
        </span>
      </div>

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

            <el-form-item label="开单活动">
              <el-select
                v-model="form.activityId"
                placeholder="请选择活动（可选）"
                filterable
                clearable
                :loading="activityLoading"
                @visible-change="loadActivities"
              >
                <el-option v-for="a in activityOptions" :key="a.value" :label="a.label" :value="a.value" />
              </el-select>
            </el-form-item>

            <el-form-item label="开单会员" prop="memberId">
              <el-select
                v-model="form.memberId"
                placeholder="输入姓名/电话搜索"
                filterable
                remote
                clearable
                reserve-keyword
                :remote-method="searchMembers"
                :loading="memberLoading"
                :filter-method="keepMemberOptionVisible"
                @change="onMemberChange"
                @visible-change="onMemberSelectVisible"
              >
                <el-option v-for="m in memberOptions" :key="m.value" :label="m.optionLabel || `${m.label}（${m.phone || '无'}）`" :value="m.value" />
              </el-select>
            </el-form-item>

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

            <el-form-item label="整单业绩" prop="totalPerformance">
              <el-input v-model="form.totalPerformance" placeholder="请输入整单业绩">
                <template slot="prepend">¥</template>
              </el-input>
            </el-form-item>

            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="实付业绩">
                  <el-input :value="actualPaid" readonly>
                    <template slot="prepend">¥</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="欠款">
                  <el-input :value="arrears" readonly>
                    <template slot="prepend">¥</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 储扣设置 -->
            <div class="section-title"><i class="el-icon-wallet"></i> 储扣设置</div>

            <el-form-item label="是否储扣">
              <el-radio-group v-model="form.isDeduct">
                <el-radio label="否">否</el-radio>
                <el-radio label="是">是</el-radio>
              </el-radio-group>
            </el-form-item>

            <template v-if="form.isDeduct === '是'">
              <div
                v-for="(d, di) in form.deductItems"
                :key="'deduct-' + di"
                class="item-card deduct-card"
              >
                <div class="item-card-head">
                  <span class="item-card-no">储扣 {{ di + 1 }}</span>
                  <el-button
                    v-if="form.deductItems.length > 1"
                    type="text"
                    class="item-remove-btn"
                    @click="removeDeductItem(di)"
                  >
                    <i class="el-icon-delete"></i> 删除
                  </el-button>
                </div>
                <el-row :gutter="12">
                  <el-col :span="12">
                    <el-form-item label="品项" label-width="56px">
                      <el-select v-model="d.deductId" placeholder="选择储扣品项" filterable clearable @change="onDeductChange(di)">
                        <el-option v-for="dd in deductOptions" :key="dd.value" :label="dd.label" :value="dd.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="单价" label-width="48px">
                      <el-input :value="d.price" readonly />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="12">
                  <el-col :span="12">
                    <el-form-item label="数量" label-width="56px">
                      <el-input-number v-model="d.quantity" :min="1" :max="d.maxQty || 999" controls-position="right" style="width:100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="小计" label-width="48px">
                      <el-input :value="deductSubtotal(d)" readonly />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

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

            <!-- 付款与其他 -->
            <div class="section-title"><i class="el-icon-bank-card"></i> 付款与其他</div>

            <el-form-item label="付款方式" prop="paymentMethod">
              <el-select v-model="form.paymentMethod" placeholder="请选择付款方式">
                <el-option v-for="p in paymentOptions" :key="p.value" :label="p.label" :value="p.value" />
              </el-select>
            </el-form-item>

            <el-form-item v-if="form.paymentMethod === '合作'" label="合作机构">
              <el-select v-model="form.cooperateOrg" placeholder="请选择合作机构" filterable clearable>
                <el-option v-for="o in orgOptions" :key="o.value" :label="o.label" :value="o.value" />
              </el-select>
            </el-form-item>
            <el-form-item v-else label="结算机构">
              <el-select v-model="form.settleOrg" placeholder="请选择结算机构" filterable clearable>
                <el-option v-for="o in orgOptions" :key="o.value" :label="o.label" :value="o.value" />
              </el-select>
            </el-form-item>

            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="是否首开">
                  <el-select v-model="form.isFirstOrder" placeholder="自动判断" disabled>
                    <el-option label="是" value="是" />
                    <el-option label="否" value="否" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="简介">
                  <el-input v-model="form.intro" placeholder="简要说明（可选）" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 附件与备注 -->
            <div class="section-title"><i class="el-icon-paperclip"></i> 附件与备注</div>

            <el-form-item label="收据文件">
              <oss-file-upload
                v-model="form.scwj"
                button-text="上传收据"
                tip="上传后自动保存至 OSS，支持图片、PDF"
              />
            </el-form-item>

            <el-form-item label="方案文件">
              <oss-file-upload
                v-model="form.f_FileUrl"
                button-text="上传方案/其他文件"
                tip="上传后自动保存至 OSS"
              />
            </el-form-item>

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

          <!-- ===== 右栏：品项明细 ===== -->
          <div class="billing-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-row :gutter="12">
                <el-col :span="12">
                  <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
                      remote
                      clearable
                      reserve-keyword
                      :remote-method="searchProjects"
                      :loading="projectLoading"
                      :filter-method="keepOptionVisible"
                      @change="onProjectChange(idx)"
                      @visible-change="v => v && !projectOptions.length && searchProjects('')"
                    >
                      <el-option v-for="p in projectOptions" :key="p.value" :label="p.label" :value="p.value" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="类型" label-width="48px">
                    <el-select v-model="item.type" placeholder="类型">
                      <el-option label="购买" value="购买" />
                      <el-option label="体验" value="体验" />
                      <el-option label="赠送" value="赠送" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="12">
                <el-col :span="8">
                  <el-form-item label="总价" label-width="48px">
                    <el-input
                      v-model="item.totalPrice"
                      placeholder="总价"
                      :disabled="item.isStoredValue"
                      @input="onItemPriceInput(idx)"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="数量" label-width="48px">
                    <el-input-number
                      v-model="item.quantity"
                      :min="1"
                      :max="999"
                      controls-position="right"
                      style="width:100%"
                      @change="onItemQtyChange(idx)"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="单价" label-width="48px">
                    <el-input :value="itemUnitPrice(item)" readonly />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="备注" label-width="56px">
                <el-input v-model="item.remark" placeholder="品项备注（可选）" />
              </el-form-item>

              <!-- 健康师 -->
              <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"
                    @change="onHealthWorkerChange(idx, wi)"
                  >
                    <el-option v-for="h in healthWorkerOptions" :key="h.value" :label="h.label" :value="h.value" />
                  </el-select>
                  <el-input v-model="w.amount" placeholder="业绩金额" size="mini" class="worker-amount">
                    <template slot="prepend">¥</template>
                  </el-input>
                  <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
                v-if="item.qt2 === '科美' || (item.kjbWorkers && item.kjbWorkers.length)"
                class="worker-section kjb-section"
              >
                <div class="worker-label">
                  <span>科技部老师业绩</span>
                  <el-button type="text" size="mini" @click="addKjbWorker(idx)">
                    <i class="el-icon-plus"></i> 添加老师
                  </el-button>
                </div>
                <div v-for="(k, ki) in item.kjbWorkers" :key="'k-' + ki" class="worker-row">
                  <el-select
                    v-model="k.workerId"
                    placeholder="科技部老师"
                    filterable
                    size="mini"
                    class="worker-select"
                    @change="onKjbWorkerChange(idx, ki)"
                  >
                    <el-option v-for="h in kjbWorkerOptions" :key="h.value" :label="h.label" :value="h.value" />
                  </el-select>
                  <el-input v-model="k.amount" placeholder="业绩金额" size="mini" class="worker-amount">
                    <template slot="prepend">¥</template>
                  </el-input>
                  <el-button type="text" size="mini" class="worker-remove" @click="removeKjbWorker(idx, ki)">
                    <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="billing-footer">
        <div class="footer-summary">
          <span>品项合计 <b>¥{{ itemsTotal }}</b></span>
          <span v-if="form.isDeduct === '是'">储扣合计 <b>¥{{ deductTotal }}</b></span>
          <span>实付 <b class="highlight">¥{{ actualPaid }}</b></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>
  </el-dialog>
</template>

<script>
import { createKdKdjlb, getPackageInfoList, getHzfList } from '@/api/lqKdKdjlb'
import { getXmzlList, getXmzlInfo } from '@/api/lqXmzl'
import { getKhxxList, getMemberRemainingItems, getMemberOrderType, getJsjInfo } from '@/api/lqKhxx'
import { getStoreUserList } from '@/api/storeUser'
import {
  buildBillingSubmitBody,
  validateBillingForm,
  calcSfyj,
  calcQk,
  billingDateYmd
} from '@/utils/billingHelper'
import { mapRemainingItemToOption } from '@/utils/appointmentHelper'
import OssFileUpload from '@/components/oss-file-upload.vue'

export default {
  name: 'BillingDialog',
  components: { OssFileUpload },
  props: {
    visible: { type: Boolean, default: false },
    prefill: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      submitting: false,
      memberLoading: false,
      projectLoading: false,
      activityLoading: false,
      activityLoaded: false,
      form: this.createEmptyForm(),
      activityOptions: [],
      memberOptions: [],
      projectOptions: [],
      healthWorkerOptions: [],
      kjbWorkerOptions: [],
      paymentOptions: [
        { value: '现金', label: '现金' },
        { value: '微信', label: '微信' },
        { value: '支付宝', label: '支付宝' },
        { value: '银行卡', label: '银行卡' },
        { value: '合作', label: '合作' },
        { value: '直播收款', label: '直播收款' },
        { value: '合作方退', label: '合作方退' },
        { value: '抖音', label: '抖音' }
      ],
      orgOptions: [],
      deductOptions: [],
      rules: {
        memberId: [{ required: true, message: '请选择开单会员', trigger: 'change' }],
        billingDate: [{ required: true, message: '请选择开单日期', trigger: 'change' }],
        totalPerformance: [{ required: true, message: '请输入整单业绩', trigger: 'blur' }],
        paymentMethod: [{ required: true, message: '请选择付款方式', trigger: 'change' }]
      }
    }
  },
  computed: {
    visibleProxy: {
      get() { return this.visible },
      set(val) { this.$emit('update:visible', val) }
    },
    itemsTotal() {
      return this.form.items.reduce((sum, it) => {
        return sum + (parseFloat(it.totalPrice) || 0)
      }, 0).toFixed(2)
    },
    deductTotal() {
      if (this.form.isDeduct !== '是') return '0.00'
      return this.form.deductItems.reduce((sum, d) => {
        return sum + (parseFloat(d.price) || 0) * (d.quantity || 0)
      }, 0).toFixed(2)
    },
    actualPaid() {
      return calcSfyj(this.form).toFixed(2)
    },
    arrears() {
      return calcQk(this.form).toFixed(2)
    },
    storeId() {
      return (this.$store.getters.storeInfo || {}).storeId || ''
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.initDialog()
      }
    },
    prefill: {
      deep: true,
      handler() {
        if (this.visible) this.applyPrefill()
      }
    },
    'form.memberId'(id) {
      if (id) this.loadMemberDeductOptions(id)
      else this.deductOptions = []
    },
    'form.isDeduct'(val) {
      if (val !== '是') {
        this.form.deductItems = [this.createEmptyDeduct()]
      }
    }
  },
  methods: {
    keepMemberOptionVisible() {
      return true
    },
    async initDialog() {
      await Promise.all([
        this.searchProjects(''),
        this.loadHealthWorkers(),
        this.loadKjbWorkers(),
        this.loadOrgOptions()
      ])
      await this.applyPrefill()
    },
    keepOptionVisible() {
      return true
    },
    async searchProjects(keyword) {
      this.projectLoading = true
      try {
        const res = await getXmzlList({
          currentPage: 1,
          pageSize: 50,
          isEffective: 1,
          sort: 'asc',
          xmmc: (keyword || '').trim()
        })
        const list = res.data?.list || []
        this.projectOptions = list.map(p => ({
          value: p.id,
          label: p.xmmc || p.id,
          price: Number(p.pxjg || p.bzjg) || 0,
          qt2: p.qt2 || '',
          remark: p.bz || ''
        }))
      } catch (e) {
        this.projectOptions = []
      } finally {
        this.projectLoading = false
      }
    },
    async loadHealthWorkers() {
      if (!this.storeId) return
      try {
        const res = await getStoreUserList({
          mdid: this.storeId,
          gw: '健康师',
          currentPage: 1,
          pageSize: 500
        })
        const list = res.data?.list || []
        this.healthWorkerOptions = list.map(u => ({
          value: u.id,
          label: u.realName || u.account || u.id
        }))
      } catch (e) {
        this.healthWorkerOptions = []
      }
    },
    async loadKjbWorkers() {
      try {
        const res = await getStoreUserList({
          gw: '科技老师',
          currentPage: 1,
          pageSize: 500
        })
        const list = res.data?.list || []
        this.kjbWorkerOptions = list.map(u => ({
          value: u.id,
          label: u.realName || u.account || u.id
        }))
      } catch (e) {
        this.kjbWorkerOptions = []
      }
    },
    async loadOrgOptions() {
      try {
        const res = await getHzfList({ currentPage: 1, pageSize: 200 })
        const list = res.data?.list || []
        this.orgOptions = list.map(o => ({
          value: o.id,
          label: o.hzmc || o.id
        }))
      } catch (e) {
        this.orgOptions = []
      }
    },
    loadActivities(visible) {
      if (!visible || this.activityLoaded) return
      this.activityLoading = true
      getPackageInfoList({ currentPage: 1, pageSize: 200, isEffective: 1 })
        .then(res => {
          const list = res.data?.list || []
          this.activityOptions = list.map(a => ({
            value: a.id,
            label: a.activityName || a.id
          }))
          this.activityLoaded = true
        })
        .finally(() => {
          this.activityLoading = false
        })
    },
    onMemberSelectVisible(visible) {
      if (visible && !this.memberOptions.length) {
        this.searchMembers('')
      }
    },
    async searchMembers(keyword) {
      this.memberLoading = true
      try {
        const res = await getKhxxList({
          currentPage: 1,
          pageSize: 30,
          keyWord: (keyword || '').trim()
        })
        const list = res.data?.list || []
        this.memberOptions = list.map(m => {
          const name = m.khmc || m.name || '无'
          const phone = m.sjh || m.mobile || ''
          return {
            value: m.id,
            label: name,
            phone,
            type: m.khlx || m.gjlx || '',
            optionLabel: phone ? `${name}（${phone}）` : name
          }
        })
      } catch (e) {
        this.memberOptions = []
      } finally {
        this.memberLoading = false
      }
    },
    async loadMemberDeductOptions(memberId) {
      if (!memberId) {
        this.deductOptions = []
        return
      }
      try {
        const res = await getMemberRemainingItems(memberId)
        const list = res.data?.RemainingItems || res.data?.remainingItems || []
        this.deductOptions = list.map(item => {
          const opt = mapRemainingItemToOption(item)
          return {
            value: opt.billingItemId || opt.itemId,
            label: opt.label,
            price: opt.price,
            remaining: opt.remaining,
            itemId: opt.itemId,
            billingItemId: opt.billingItemId
          }
        })
      } catch (e) {
        this.deductOptions = []
      }
    },
    createEmptyForm() {
      return {
        activityId: '',
        memberId: '',
        memberName: '',
        memberPhone: '',
        memberType: '',
        appointmentId: '',
        billingDate: new Date(),
        totalPerformance: '',
        paymentMethod: '微信',
        cooperateOrg: '',
        settleOrg: '',
        isFirstOrder: '否',
        isDeduct: '否',
        intro: '',
        remark: '',
        scwj: [],
        f_FileUrl: [],
        items: [this.createEmptyItem()],
        deductItems: [this.createEmptyDeduct()]
      }
    },
    createEmptyItem() {
      return {
        projectId: '',
        label: '',
        totalPrice: '',
        quantity: 1,
        unitPrice: 0,
        type: '购买',
        remark: '',
        qt2: '',
        isStoredValue: false,
        workers: [{ workerId: '', workerName: '', amount: '', jsjId: '', jsjName: '' }],
        kjbWorkers: []
      }
    },
    createEmptyDeduct() {
      return {
        deductId: '',
        label: '',
        price: '',
        quantity: 1,
        maxQty: 999,
        itemId: '',
        deductType: '品项'
      }
    },
    async applyPrefill() {
      this.form = this.createEmptyForm()
      const p = this.prefill || {}
      if (p.memberId) {
        this.form.memberId = p.memberId
        this.form.memberName = p.memberName || p.name || ''
        if (!this.memberOptions.some(m => m.value === p.memberId)) {
          this.memberOptions.unshift({
            value: p.memberId,
            label: this.form.memberName || '会员',
            phone: p.mobile || p.phone || '',
            type: '',
            optionLabel: this.form.memberName
          })
        }
      } else if (p.name) {
        await this.searchMembers(p.name)
        const found = this.memberOptions.find(m => m.label === p.name)
        if (found) {
          this.form.memberId = found.value
          this.form.memberName = found.label
        }
      }
      if (p.appointmentId) this.form.appointmentId = p.appointmentId
      if (p.fromBooking) {
        this.form.remark = [p.bookingProject, p.bookingDate, p.bookingTimeRange, p.bookingStaff]
          .filter(Boolean)
          .join(' · ')
      }
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate()
      })
    },
    async onMemberChange(val) {
      const m = this.memberOptions.find(o => o.value === val)
      this.form.memberName = m ? m.label : ''
      this.form.memberPhone = m ? m.phone : ''
      this.form.memberType = m ? (m.type || m.khlx) : ''
      if (val) {
        try {
          const res = await getMemberOrderType(val)
          if (res.code === 200 && res.data) {
            this.form.isFirstOrder = res.data.HasOrderRecord ? '否' : '是'
          }
        } catch (e) {}
      }
    },
    async onProjectChange(idx) {
      const item = this.form.items[idx]
      const p = this.projectOptions.find(o => o.value === item.projectId)
      if (!p) return
      item.label = p.label
      item.qt2 = p.qt2 || ''
      item.remark = p.remark || item.remark
      item.isStoredValue = !!(p.label && p.label.includes('储值'))
      item.workers = [{ workerId: '', workerName: '', amount: '', jsjId: '', jsjName: '' }]
      item.kjbWorkers = []
      if (item.isStoredValue) {
        item.unitPrice = 1
        item.totalPrice = String((item.quantity || 1) * 1)
      } else {
        item.unitPrice = p.price || 0
        item.totalPrice = String((p.price || 0) * (item.quantity || 1))
      }
      if (item.qt2 === '科美' && (!item.kjbWorkers || !item.kjbWorkers.length)) {
        item.kjbWorkers = [{ workerId: '', workerName: '', amount: '' }]
      }
    },
    onItemQtyChange(idx) {
      const item = this.form.items[idx]
      if (item.isStoredValue) {
        item.totalPrice = String((Number(item.quantity) || 1) * (Number(item.unitPrice) || 1))
      } else {
        const unit = Number(item.unitPrice) || 0
        item.totalPrice = String(unit * (Number(item.quantity) || 1))
      }
    },
    onItemPriceInput(idx) {
      const item = this.form.items[idx]
      if (item.isStoredValue) return
      const qty = Number(item.quantity) || 1
      const total = parseFloat(item.totalPrice) || 0
      item.unitPrice = qty > 0 ? total / qty : total
    },
    async onDeductChange(di) {
      const d = this.form.deductItems[di]
      const dup = this.form.deductItems.findIndex((x, i) => i !== di && x.deductId === d.deductId)
      if (dup >= 0) {
        this.$message.warning('该储扣品项已添加，请勿重复')
        d.deductId = ''
        return
      }
      const found = this.deductOptions.find(o => o.value === d.deductId)
      if (!found) return
      d.label = found.label
      d.price = found.price
      d.itemId = found.itemId
      d.maxQty = found.remaining
      if (d.quantity > found.remaining) d.quantity = found.remaining
      try {
        const info = await getXmzlInfo(found.itemId)
        const detail = info.data || {}
        d.deductType = detail.qt1 === '储值' ? '储值卡' : '品项'
      } catch (e) {
        d.deductType = '品项'
      }
    },
    onHealthWorkerChange(idx, wi) {
      const w = this.form.items[idx].workers[wi]
      const opt = this.healthWorkerOptions.find(o => o.value === w.workerId)
      w.workerName = opt ? opt.label : ''
      if (w.workerId) this.fetchJsjForWorker(idx, wi)
    },
    async fetchJsjForWorker(pxIdx, wIdx) {
      const w = this.form.items[pxIdx].workers[wIdx]
      if (!w || !w.workerId) return
      try {
        const res = await getJsjInfo(w.workerId, billingDateYmd(this.form))
        if (res.code === 200 && res.data) {
          w.jsjId = res.data.jsjId || ''
          w.jsjName = res.data.jsjName || ''
        }
      } catch (e) {}
    },
    onKjbWorkerChange(idx, ki) {
      const k = this.form.items[idx].kjbWorkers[ki]
      const opt = this.kjbWorkerOptions.find(o => o.value === k.workerId)
      k.workerName = opt ? opt.label : ''
    },
    itemUnitPrice(item) {
      if (item.isStoredValue) return '1.00'
      const qty = item.quantity || 1
      const total = parseFloat(item.totalPrice) || 0
      if (item.unitPrice != null && item.unitPrice !== '') {
        return Number(item.unitPrice).toFixed(2)
      }
      return qty > 0 ? (total / qty).toFixed(2) : '0.00'
    },
    deductSubtotal(d) {
      return ((parseFloat(d.price) || 0) * (d.quantity || 0)).toFixed(2)
    },
    addItem() {
      this.form.items.push(this.createEmptyItem())
    },
    removeItem(idx) {
      this.form.items.splice(idx, 1)
    },
    addWorker(idx) {
      this.form.items[idx].workers.push({
        workerId: '',
        workerName: '',
        amount: '',
        jsjId: '',
        jsjName: ''
      })
    },
    removeWorker(idx, wi) {
      this.form.items[idx].workers.splice(wi, 1)
    },
    addKjbWorker(idx) {
      if (!this.form.items[idx].kjbWorkers) {
        this.$set(this.form.items[idx], 'kjbWorkers', [])
      }
      this.form.items[idx].kjbWorkers.push({ workerId: '', workerName: '', amount: '' })
    },
    removeKjbWorker(idx, ki) {
      this.form.items[idx].kjbWorkers.splice(ki, 1)
    },
    addDeductItem() {
      this.form.deductItems.push(this.createEmptyDeduct())
    },
    removeDeductItem(di) {
      this.form.deductItems.splice(di, 1)
    },
    resetForm() {
      this.form = this.createEmptyForm()
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate()
      })
    },
    handleCancel() {
      this.visibleProxy = false
      this.resetForm()
    },
    handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        if (!this.storeId) {
          this.$message.warning('未获取到当前门店')
          return
        }
        const err = validateBillingForm(this.form)
        if (err) {
          this.$message.warning(err)
          return
        }
        const member = this.memberOptions.find(m => m.value === this.form.memberId)
        const body = buildBillingSubmitBody(this.form, {
          storeId: this.storeId,
          member
        })
        this.submitting = true
        try {
          const res = await createKdKdjlb(body)
          if (res.code === 200) {
            this.$message.success(res.msg || '开单成功')
            this.$emit('submitted', body)
            try {
              window.dispatchEvent(new Event('store_pc_billing_updated'))
            } catch (e) {}
            this.visibleProxy = false
            this.resetForm()
          }
        } catch (e) {
          /* 错误由 request 拦截器提示 */
        } finally {
          this.submitting = false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
/* ====== 弹窗外壳（统一风格） ====== */
::v-deep .billing-dialog {
  max-width: 1200px;
  margin-top: 5vh !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 .el-dialog__header {
  display: none;
}

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

/* ====== 内部结构 ====== */
.billing-dialog-inner {
  display: flex;
  flex-direction: column;
  max-height: 85vh;
}

.billing-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);
}

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

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

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

.booking-source-tag {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-left: auto;
  margin-right: 12px;
  padding: 4px 14px;
  border-radius: 999px;
  background: rgba(249, 115, 22, 0.12);
  font-size: 12px;
  color: #ea580c;
  font-weight: 500;
  white-space: nowrap;

  i {
    font-size: 13px;
  }

  .booking-source-detail {
    color: #9a3412;
    font-weight: 400;
  }
}

.billing-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;
  }
}

/* ====== 双栏主体 ====== */
.billing-content {
  flex: 1;
  min-height: 0;
  overflow: hidden;
  display: flex;
}

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

.billing-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;
}

.billing-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;
  }
}

.deduct-card {
  border-color: #fde68a;

  &:hover {
    border-color: #fbbf24;
  }
}

.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;
}

/* ====== 健康师行 ====== */
.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-amount {
  width: 140px;
  flex-shrink: 0;
}

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

/* ====== 添加按钮行 ====== */
.add-btn-row {
  text-align: center;
  margin-bottom: 6px;
}

/* ====== 上传提示 ====== */
.upload-tip {
  font-size: 11px;
  color: #9ca3af;
  margin-left: 8px;
}

/* ====== footer 固定底部 ====== */
.billing-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 .billing-dialog .el-form-item__label {
  white-space: nowrap;
}

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

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

::v-deep .billing-dialog .el-input-group__prepend {
  border-radius: 999px 0 0 999px;
  background: #f1f5f9;
  border-color: #e5e7eb;
  padding: 0 10px;
  color: #64748b;
}

::v-deep .billing-dialog .el-input-group .el-input__inner {
  border-radius: 0 999px 999px 0;
}

::v-deep .billing-dialog .el-textarea__inner {
  border-radius: 12px;
  border-color: #e5e7eb;
  background-color: #f9fafb;
}

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

::v-deep .billing-dialog .el-input-number {
  .el-input__inner {
    border-radius: 999px;
  }
}

::v-deep .billing-dialog .el-upload-list__item {
  border-radius: 8px;
}

::v-deep .billing-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 .billing-dialog .el-button--primary.is-disabled {
  box-shadow: none;
}

::v-deep .billing-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 .billing-dialog .el-button--default:hover {
  background: rgba(219, 234, 254, 0.95);
  color: #1d4ed8;
}

::v-deep .billing-dialog .el-radio__input.is-checked .el-radio__inner {
  border-color: #2563eb;
  background: #2563eb;
}

::v-deep .billing-dialog .el-radio__input.is-checked + .el-radio__label {
  color: #2563eb;
}

::v-deep .billing-dialog .el-form-item {
  margin-bottom: 12px;
}

::v-deep .billing-dialog .el-picker-panel {
  border-radius: 12px;
}

::v-deep .billing-dialog .el-select {
  width: 100%;
}
</style>
