<template>
  <ConfigPanelShell
    :modules="modules"
    :loading="loading"
    :saving="saving"
    storage-key="businessConfigActiveModule"
    default-module="consume"
    alert-title="左侧选择业务模块，右侧仅展示当前模块配置；保存后全量生效。"
    @save="$emit('save')"
  >
        <template #consume>
          <el-card shadow="never" class="config-section">
            <div slot="header" class="config-section__header">
              <span>小程序端</span>
              <span class="config-section__tag">门店小程序</span>
            </div>
            <p class="config-section__tip">
              耗卡发生后，超过「可修改天数」将禁止「修改 / 作废 / 重开单」；关闭「允许跨月修改」时，耗卡月份与当前月不同亦禁止操作（即使仍在天数内）。
            </p>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="可修改天数" prop="consumeEditableDays" label-width="100px">
                  <el-input-number v-model="form.consumeEditableDays" :min="1" :max="365" :precision="0" :step="1"
                    controls-position="right" />
                  <span class="field-suffix">天</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="允许跨月修改" prop="consumeAllowCrossMonthEdit" label-width="110px">
                  <el-switch v-model="form.consumeAllowCrossMonthEdit" :active-value="1" :inactive-value="0" />
                  <span class="field-suffix field-suffix--text">
                    {{ Number(form.consumeAllowCrossMonthEdit) === 1 ? '已开启' : '已关闭' }}
                  </span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <el-card shadow="never" class="config-section">
            <div slot="header" class="config-section__header">
              <span>管理后台</span>
              <span class="config-section__tag">会员耗卡</span>
            </div>
            <p class="config-section__tip">
              分别限制「作废」「删除」可操作的天数；填 0 表示不限制天数。是否显示按钮请在「菜单管理 → 按钮权限」中为角色授权。
            </p>
            <ConfigRuleRow title="作废耗卡" description="标记为无效并级联作废品项、业绩、人次，数据保留可查询。按钮权限编码：btn_cancel。"
              :days.sync="form.adminConsumeVoidEditableDays" />
            <ConfigRuleRow title="删除耗卡" description="物理删除耗卡及关联子表数据，不可恢复。按钮权限编码：btn_remove。"
              :days.sync="form.adminConsumeDeleteEditableDays" />
            <el-row :gutter="20" class="config-section__row">
              <el-col :span="12">
                <el-form-item label="异常耗卡容差" prop="abnormalConsumeAmountTolerance" label-width="110px">
                  <el-input-number v-model="form.abnormalConsumeAmountTolerance" :min="0" :max="99999" :precision="2"
                    :step="0.01" controls-position="right" />
                  <span class="field-suffix">元</span>
                </el-form-item>
              </el-col>
            </el-row>
            <p class="config-section__tip config-section__tip--inline">
              会员耗卡列表中，消费金额与健康师业绩合计之差额绝对值超过该值时，记为异常耗卡。
            </p>
          </el-card>
        </template>

        <template #tk>
          <el-card shadow="never" class="config-section">
            <div slot="header" class="config-section__header">
              <span>拓客赠送品项</span>
              <span class="config-section__tag">线索拓客</span>
            </div>
            <p class="config-section__tip">
              拓客成功后会自动创建一笔体验开单，并写入下方所选的这一个品项（金额为 0）。统计、升单、会员类型等场景会排除该品项的零金额开单。
            </p>
            <el-row :gutter="20">
              <el-col :span="16">
                <el-form-item label="赠送品项" prop="tkGiftItemIds" label-width="110px">
                  <el-select v-model="tkGiftItemId" filterable remote clearable :remote-method="remoteSearchItems"
                    :loading="itemLoading" placeholder="请选择拓客赠送品项" style="width: 100%"
                    @visible-change="onItemSelectVisible">
                    <el-option v-for="item in itemOptions" :key="item.id" :label="formatItemLabel(item)"
                      :value="String(item.id)" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </template>

        <template #sleepRemind>
          <el-card shadow="never" class="config-section">
            <div slot="header" class="config-section__header">
              <span>门店PC端</span>
              <span class="config-section__tag">会员管理</span>
            </div>
            <p class="config-section__tip">
              设置沉睡会员提醒天数，超过该天数未消费的会员将在门店PC端显示在沉睡提醒列表中。
            </p>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="沉睡天数" prop="sleepRemindDays" label-width="100px">
                  <el-input-number v-model="form.sleepRemindDays" :min="1" :max="365" :precision="0" :step="1"
                    controls-position="right" />
                  <span class="field-suffix">天</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <el-card shadow="never" class="config-section">
            <div slot="header" class="config-section__header">
              <span>报表统计</span>
              <span class="config-section__tag">沉睡回店</span>
            </div>
            <p class="config-section__tip">
              判定会员从沉睡状态回店的天数阈值；首次耗卡按注册日与回店日间隔判断，非首次按上次到店间隔判断。
            </p>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="沉睡回店判定天数" prop="sleepReturnDays" label-width="130px">
                  <el-input-number v-model="form.sleepReturnDays" :min="1" :max="365" :precision="0" :step="1"
                    controls-position="right" />
                  <span class="field-suffix">天</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </template>

        <template #trainingCheckin>
          <el-card shadow="never" class="config-section">
            <div slot="header" class="config-section__header">
              <span>动态二维码</span>
              <span class="config-section__tag">教室投屏</span>
            </div>
            <p class="config-section__tip">
              教室门口投屏页二维码自动轮换间隔；学员扫码后须在有效期内完成签到或签退。
            </p>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="二维码轮换间隔" prop="trainingCheckinQrRotateMinutes" label-width="120px">
                  <el-input-number v-model="form.trainingCheckinQrRotateMinutes" :min="1" :max="60" :precision="0"
                    :step="1" controls-position="right" />
                  <span class="field-suffix">分钟</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </template>

        <template #memberTag>
          <el-card shadow="never" class="config-section">
            <div slot="header" class="config-section__header">
              <span>自定义标签</span>
              <span class="config-section__tag">全公司</span>
            </div>
            <p class="config-section__tip">
              单名会员可绑定的自定义标签数量上限；三端打标时超过上限将拒绝添加。
            </p>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="标签上限" prop="memberCustomTagMaxCount" label-width="100px">
                  <el-input-number v-model="form.memberCustomTagMaxCount" :min="1" :max="20" :precision="0" :step="1"
                    controls-position="right" />
                  <span class="field-suffix">个</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </template>

        <template #monitorCenter>
          <el-card shadow="never" class="config-section">
            <div slot="header" class="config-section__header">
              <span>大客卡金异常</span>
              <span class="config-section__tag">金额阈值</span>
            </div>
            <p class="config-section__tip">
              开单/耗卡/退卡/转卡金额达到对应阈值时，列入「大客卡金异常」监控列表（与重复充值监控并列）。
            </p>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="大额开单" prop="largeAmountBillingThreshold" label-width="100px">
                  <el-input-number v-model="form.largeAmountBillingThreshold" :min="1" :max="99999999" :precision="2"
                    :step="1000" controls-position="right" />
                  <span class="field-suffix">元</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="大额耗卡" prop="largeAmountConsumeThreshold" label-width="100px">
                  <el-input-number v-model="form.largeAmountConsumeThreshold" :min="1" :max="99999999" :precision="2"
                    :step="1000" controls-position="right" />
                  <span class="field-suffix">元</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="大额退卡" prop="largeAmountRefundThreshold" label-width="100px">
                  <el-input-number v-model="form.largeAmountRefundThreshold" :min="1" :max="99999999" :precision="2"
                    :step="1000" controls-position="right" />
                  <span class="field-suffix">元</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="大额转卡" prop="largeAmountTransferThreshold" label-width="100px">
                  <el-input-number v-model="form.largeAmountTransferThreshold" :min="1" :max="99999999" :precision="2"
                    :step="1000" controls-position="right" />
                  <span class="field-suffix">元</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </template>

        <template #goldTriangle>
          <el-card shadow="never" class="config-section">
            <div slot="header" class="config-section__header">
              <span>员工手机端</span>
              <span class="config-section__tag">健康师</span>
            </div>
            <p class="config-section__tip">
              控制个人中心「提成缺口」与金三角业绩页「当前提成档」旁的问号说明；关闭后员工端不显示问号及档位弹窗。
            </p>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="档位说明问号" prop="commissionTierHelpSwitch" label-width="110px">
                  <el-switch v-model="form.commissionTierHelpSwitch" :active-value="1" :inactive-value="0" />
                  <span class="field-suffix field-suffix--text">
                    {{ Number(form.commissionTierHelpSwitch) === 1 ? '已开启' : '已关闭' }}
                  </span>
                </el-form-item>
              </el-col>
            </el-row>
            <commission-tier-help-preview :enabled="Number(form.commissionTierHelpSwitch) === 1" />
          </el-card>
        </template>
  </ConfigPanelShell>
</template>

<script>
import request from '@/utils/request'
import ConfigPanelShell from './config-panel-shell.vue'
import ConfigRuleRow from './config-rule-row'
import CommissionTierHelpPreview from './commission-tier-help-preview'

const MODULES = [
  { key: 'consume', label: '耗卡管理', desc: '小程序与管理后台耗卡规则', icon: 'el-icon-s-order', iconClass: 'module-icon--consume' },
  { key: 'tk', label: '拓客管理', desc: '拓客赠送品项', icon: 'el-icon-s-custom', iconClass: 'module-icon--tk' },
  { key: 'sleepRemind', label: '沉睡提醒', desc: '门店提醒与回店统计', icon: 'el-icon-bell', iconClass: 'module-icon--sleep' },
  { key: 'trainingCheckin', label: '培训签到', desc: '动态二维码轮换', icon: 'el-icon-s-check', iconClass: 'module-icon--training' },
  { key: 'memberTag', label: '会员标签', desc: '自定义标签上限', icon: 'el-icon-collection-tag', iconClass: 'module-icon--member' },
  { key: 'monitorCenter', label: '监控中心', desc: '大客卡金异常阈值', icon: 'el-icon-view', iconClass: 'module-icon--monitor' },
  { key: 'goldTriangle', label: '金三角业绩', desc: '提成档位说明', icon: 'el-icon-s-data', iconClass: 'module-icon--gold' }
]

function parseIdList(raw) {
  if (!raw) return []
  return String(raw)
    .split(/[,，;；]/)
    .map(s => s.trim())
    .filter(Boolean)
}

export default {
  name: 'BusinessConfigPanel',
  components: { ConfigPanelShell, ConfigRuleRow, CommissionTierHelpPreview },
  props: {
    form: {
      type: Object,
      required: true
    },
    loading: {
      type: Boolean,
      default: false
    },
    saving: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      modules: MODULES,
      itemOptions: [],
      itemLoading: false,
      itemOptionsLoaded: false
    }
  },
  computed: {
    tkGiftItemId: {
      get() {
        const ids = parseIdList(this.form.tkGiftItemIds)
        return ids[0] || ''
      },
      set(id) {
        const value = id != null && String(id).trim() !== '' ? String(id).trim() : '61'
        this.$set(this.form, 'tkGiftItemIds', value)
      }
    }
  },
  watch: {
    'form.tkGiftItemIds': {
      immediate: true,
      handler(val) {
        const ids = parseIdList(val)
        if (ids.length > 1) {
          this.$set(this.form, 'tkGiftItemIds', ids[0])
        }
        if (ids.length) this.ensureSelectedItems([ids[0]])
      }
    }
  },
  methods: {
    formatItemLabel(item) {
      const name = item.xmmc || item.fullName || '未命名'
      const qt1 = item.qt1 ? ` / ${item.qt1}` : ''
      return `${name}${qt1}（${item.id}）`
    },
    onItemSelectVisible(visible) {
      if (visible && !this.itemOptionsLoaded) {
        this.remoteSearchItems('')
      }
    },
    remoteSearchItems(keyword) {
      this.itemLoading = true
      request({
        url: '/api/Extend/LqXmzl',
        method: 'GET',
        data: {
          currentPage: 1,
          pageSize: 50,
          isEffective: 1,
          xmmc: (keyword || '').trim()
        }
      }).then(res => {
        const list = (res.data && res.data.list) || []
        this.mergeItemOptions(list)
        this.itemOptionsLoaded = true
      }).catch(() => {
        // 保留已选选项，避免清空
      }).finally(() => {
        this.itemLoading = false
      })
    },
    ensureSelectedItems(ids) {
      const missing = ids.filter(id => !this.itemOptions.some(o => String(o.id) === String(id)))
      if (!missing.length) return
      Promise.all(missing.map(id => request({
        url: `/api/Extend/LqXmzl/${id}`,
        method: 'GET'
      }).then(res => res.data).catch(() => null))).then(rows => {
        const valid = rows.filter(Boolean).map(row => ({
          id: String(row.id),
          xmmc: row.xmmc || row.fullName || String(row.id),
          qt1: row.qt1 || ''
        }))
        this.mergeItemOptions(valid)
      })
    },
    mergeItemOptions(list) {
      const map = {}
      this.itemOptions.forEach(item => {
        map[String(item.id)] = item
      })
      ;(list || []).forEach(item => {
        if (!item || item.id == null) return
        map[String(item.id)] = {
          id: String(item.id),
          xmmc: item.xmmc || item.fullName || String(item.id),
          qt1: item.qt1 || ''
        }
      })
      this.itemOptions = Object.keys(map).map(k => map[k])
    }
  }
}
</script>

<style lang="scss" scoped>
.module-icon {
  &--consume { color: #409EFF; }
  &--sleep { color: #E6A23C; }
  &--tk { color: #909399; }
  &--training { color: #409EFF; }
  &--member { color: #9c27b0; }
  &--monitor { color: #f56c6c; }
  &--gold { color: #43a047; }
}

.config-section {
  margin-bottom: 16px;
  border: 1px solid #ebeef5;

  &__row {
    margin-top: 4px;
  }

  &__tip--inline {
    margin-top: 0;
  }

  &:last-child {
    margin-bottom: 0;
  }

  &__header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 500;
  }

  &__tag {
    padding: 0 8px;
    height: 22px;
    line-height: 22px;
    border-radius: 4px;
    background: #f4f4f5;
    color: #909399;
    font-size: 12px;
    font-weight: normal;
  }

  &__tip {
    margin: 0 0 12px;
    color: #909399;
    font-size: 13px;
    line-height: 1.6;
  }
}

.field-suffix {
  margin-left: 8px;
  color: #909399;
  font-size: 13px;

  &--text {
    display: inline-block;
    min-width: 48px;
  }
}

/* 暗黑 */
.ncc-content-dark {
  .config-section {
    border-color: rgba(255, 255, 255, 0.08);

    &__tag {
      background: rgba(255, 255, 255, 0.08);
      color: rgba(255, 255, 255, 0.55);
    }

    &__tip {
      color: rgba(255, 255, 255, 0.55);
    }
  }

  .field-suffix {
    color: rgba(255, 255, 255, 0.55);
  }
}
</style>
