<!-- 添加套餐推广商品 -->
<template>
  <div>
    <el-dialog :title="form.id ? '编辑套餐' : '添加套餐'" width="1000px" v-model="visible" @submit.prevent @closed="resetHandle"
      @open="openDialog">
      <div class="form_warap" ref="targetScrollRef">
        <el-form ref="formRef" :model="form" :rules="rules" label-position="right" label-width="150">
          <el-form-item label="可用门店">
            <el-radio-group v-model="form.useShopType" @change="useShopTypeChange">
              <el-radio label="仅本店" value="only"></el-radio>
              <template v-if="shopInfo.isHeadShop && shopInfo.shopType != 'only'">
                <el-radio label="全部门店" value="all"></el-radio>
                <el-radio label="指定门店可用" value="custom"></el-radio>
              </template>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.useShopType == 'custom'" prop="useShops">
            <selectBranchs all v-model="form.useShops" />
          </el-form-item>
          <el-form-item label="套餐名称" prop="packageName">
            <div class="column">
              <el-input v-model="form.packageName" placeholder="请输入套餐名称" :maxlength="30"
                style="width: 300px;"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="套餐描述">
            <el-input type="textarea" :rows="5" placeholder="请输入套餐描述" :maxlength="50" show-password
              v-model="form.description" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item label="套餐图片" prop="images">
            <MultiImageUpload v-model="form.images" @uploadStart="loading = true"
              @uploadAllSuccess="wareImgsMultiOnSuccess" />
          </el-form-item>
          <el-form-item label="原价" prop="originPrice">
            <el-input v-model="form.originPrice" placeholder="请输入套餐原价" :maxlength="8"
              @input="e => form.originPrice = filterNumberInput(e)" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item label="价格" prop="price">
            <el-input v-model="form.price" placeholder="请输入套餐价格" :maxlength="8"
              @input="e => form.price = filterNumberInput(e)" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item label="选择商品" prop="packageContent">
            <div class="group_wrap">
              <div class="row padding" v-for="(item, index) in form.packageContent" :key="index">
                <el-form inline>
                  <el-form-item label="菜品组名">
                    <el-input v-model="item.name" placeholder="请输入菜品组名"></el-input>
                  </el-form-item>
                  <el-form-item :label="`本组菜品${item.packageProducts.length}选`">
                    <el-input-number v-model="item.num" :min="1"
                      :max="item.packageProducts.length ? item.packageProducts.length : 1" :step="1" placeholder="选择数量"
                      @blur="item.num = 1"></el-input-number>
                  </el-form-item>
                  <el-form-item>
                    <el-button @click="form.packageContent.splice(index, 1)">删除</el-button>
                  </el-form-item>
                </el-form>
                <div class="mt14">
                  <el-table :data="item.packageProducts" border stripe>
                    <el-table-column label="名称" prop="name">
                      <template v-slot="scope">
                        <el-input v-model="scope.row.name" placeholder="请输入名称"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="价格" prop="price">
                      <template v-slot="scope">
                        <el-input v-model="scope.row.price" placeholder="请输入价格"
                          @input="e => scope.row.price = filterNumberInput(e)"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="数量" prop="num">
                      <template v-slot="scope">
                        <el-input-number :min="1" :step="1" v-model="scope.row.num"
                          @blur="scope.row.num = 1"></el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column width="200">
                      <template #header="scope">
                        <el-button size="small" type="primary" @click="addGoodsHandle($event, item)">添加商品</el-button>
                        <el-button size="small" type="primary" plain
                          @click="showGoodsDialogHandle(index)">导入商品</el-button>
                      </template>
                      <template v-slot="scope">
                        <el-button link type="primary"
                          @click="item.packageProducts.splice(scope.$index, 1)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
              <div class="row">
                <el-button type="primary" @click="addGroupHandle">添加套餐组</el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="可用周期" prop="useWeeks">
            <el-checkbox-group v-model="form.useWeeks">
              <el-checkbox value="周一" label="周一" />
              <el-checkbox value="周二" label="周二" />
              <el-checkbox value="周三" label="周三" />
              <el-checkbox value="周四" label="周四" />
              <el-checkbox value="周五" label="周五" />
              <el-checkbox value="周六" label="周六" />
              <el-checkbox value="周日" label="周日" />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="指定时间段" prop="useTimes">
            <div style="width: 200px">
              <el-time-picker v-model="useTimeScope" is-range range-separator="至" start-placeholder="开始时间"
                end-placeholder="结束时间" @change="useTimeScopeChange" />
            </div>
          </el-form-item>
          <el-form-item label="其他描述">
            <el-input type="textarea" :rows="5" placeholder="请输入商品描述" :maxlength="50" show-password
              v-model="form.otherDesc" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item label="分享优惠阶梯">
            <div class="group_wrap">
              <div class="row">
                <el-table :data="form.tieredDiscount" stripe border>
                  <el-table-column label="分享人数" prop="peopleNum"></el-table-column>
                  <el-table-column label="价格（元）" prop="price"></el-table-column>
                  <el-table-column label="操作" width="150">
                    <template v-slot="scope">
                      <el-button link type="primary" @click="editorStepFormHandle(scope.$index)">编辑</el-button>
                      <el-button link type="danger" @click="form.tieredDiscount.splice(scope.$index, 1)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div class="row">
                <el-button type="primary" @click="addStepHandle" :disabled="!form.price"
                  v-if="form.tieredDiscount.length < 3">
                  {{ form.price ? '添加阶梯' : '请填写套餐价格后添加阶梯' }}
                </el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="分享期限（小时）" prop="expireHours">
            <el-input v-model="form.expireHours" placeholder="最小不低于1小时，最大不超过72小时" :maxlength="8"
              @input="e => form.expireHours = filterNumberInput(e, 1)" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item label="上架状态" v-if="!form.id">
            <el-switch v-model="form.onlineStatus" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
          <el-form-item label="商品详情">
            <MultiImageUpload v-model="form.detailImages" @uploadStart="loading = true"
              @upload-all-success="wareCommentImgsMultiOnSuccess" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog_footer">
          <div class="btn">
            <el-button size="large" @click="visible = false" style="width: 100%;">取 消</el-button>
          </div>
          <div class="btn">
            <el-button size="large" type="primary" :loading="loading" @click="submitHandle" style="width: 100%;">确
              定</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
    <selecProductDialog ref="selecProductDialogRef" @success="selectProduceHandle" />
    <!-- 添加阶梯 -->
    <el-dialog :title="stepFormType == 'add' ? '添加阶梯' : '编辑阶梯'" v-model="showStepDialog" width="400px"
      @closed="stepDialogReset">
      <el-form ref="stepFormRef" :model="stepForm" :rules="stepFormRules" label-width="80px">
        <el-form-item label="分享人数" prop="peopleNum">
          <el-input v-model="stepForm.peopleNum" @input="e => stepForm.peopleNum = filterNumberInput(e, 1)">
            <template #append>人</template>
          </el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="stepForm.price" @input="e => stepForm.price = filterNumberInput(e)">
            <template #append>元</template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog_footer">
          <div class="btn">
            <el-button size="large" @click="showStepDialog = false" style="width: 100%;">取 消</el-button>
          </div>
          <div class="btn">
            <el-button size="large" type="primary" @click="stepFormSubmitHandle" style="width: 100%;">确
              定</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import _ from 'lodash'
import dayjs from 'dayjs'
import { ref, onMounted } from 'vue'
import { filterNumberInput } from '@/utils'
import { packageAddEdit, updateGbWareById } from '@/api/market/ware'
import selecProductDialog from './selecProductDialog.vue'
const shopInfo = ref(null)

const selecProductDialogRef = ref(null)

const packageContentItem = ref({
  name: '',
  num: 1,
  packageProducts: []
})

const packageProductsItem = ref({
  name: '',
  price: '',
  num: 1
})

// 添加套餐组
function addGroupHandle() {
  form.value.packageContent.push(_.cloneDeep(packageContentItem.value))
}

// 添加商品
function addGoodsHandle(e, item) {
  item.packageProducts.push(_.cloneDeep(packageProductsItem.value))
}

// 显示导入商品弹窗
const portGoodsIndex = ref(0)
function showGoodsDialogHandle(index) {
  portGoodsIndex.value = index
  selecProductDialogRef.value.show()
}

// 选择的商品
function selectProduceHandle(obj) {
  let data = _.cloneDeep(packageProductsItem.value)
  data.name = obj.name
  data.price = obj.price
  form.value.packageContent[portGoodsIndex.value].packageProducts.push(data)
}

const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const formObj = {
  id: '',
  useShopType: 'only',            // only-仅本店 all全部 /custom 指定
  useShops: '',                   // 可用门店（指定门店时存储门店ID，逗号分隔）
  packageName: '',                // 套餐名称
  description: '',                // 商品描述
  images: [],                     // 商品图片（多个用逗号分隔）
  originPrice: '',                // 原价
  price: '',                      // 售价
  packageContent: [],             // 套餐内容
  useTimes: '',                   // 可用时段：08:00~21:30
  useWeeks: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],                   // 可用周期： [周一,周二]
  otherDesc: '',                  // 其他描述
  tieredDiscount: [],             // 阶梯优惠
  expireHours: '',                // 分享期限（小时）不低于1小时，最大72小时
  onlineStatus: 1,                // 上架状态（0下架 1上架）
  detailImages: [],               // 商品详情图片（多个用逗号分隔）
}

const form = ref(_.cloneDeep(formObj))

const addStepIndex = ref(0)
const showStepDialog = ref(false)
const stepFormRef = ref(null)
const stepForm = ref({
  peopleNum: '',
  price: ''
})
const stepFormType = ref('add')
const stepFormRules = ref({
  peopleNum: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (addStepIndex.value == 1 && +stepForm.value.peopleNum <= +form.value.tieredDiscount[0].peopleNum) {
          callback(new Error('二阶段价格分享人数不可小于一阶段分享人数'))
        } else if (addStepIndex.value == 2 && +stepForm.value.peopleNum <= +form.value.tieredDiscount[1].peopleNum) {
          callback(new Error('三阶段价格分享人数不可小于二阶段分享人数'))
        } else {
          callback()
        }
      },
      trigger: "blur",
    }
  ],
  price: [
    {
      required: true,
      validator: (rule, value, callback) => {
        // 1. 空值校验（优先处理）
        if (stepForm.value.price.trim() === '') {
          return callback(new Error('请输入价格'));
        }

        // 统一转数值（避免字符串比较问题）
        const currentPrice = +stepForm.value.price;
        const originPrice = +form.value.price;
        // 解构阶梯价格（转数值）
        const [firstPrice, secondPrice, thirdPrice] = form.value.tieredDiscount.map(item => +item.price);

        // 2. 新增模式（原有逻辑不变）
        if (stepFormType.value === 'add') {
          if (addStepIndex.value === 0 && currentPrice > originPrice) {
            callback(new Error(`一阶段价格不可大于商品售价￥${originPrice}`));
          } else if (addStepIndex.value === 1 && currentPrice >= firstPrice) {
            callback(new Error('二阶段价格不可大于等于一阶段价格'));
          } else if (addStepIndex.value === 2 && currentPrice >= secondPrice) {
            callback(new Error('三阶段价格不可大于等于二阶段价格'));
          } else {
            callback(); // 校验通过
          }
        }
        // 3. 编辑模式（新增逻辑：瞻前顾后）
        else if (stepFormType.value === 'editor') {
          // 编辑第一阶段
          if (addStepIndex.value === 0) {
            // 规则：不大于原价 + 不小于第二阶段（若第二阶段存在）
            if (currentPrice > originPrice) {
              callback(new Error(`一阶段价格不可大于商品售价￥${form.value.originPrice}`));
            } else if (secondPrice && currentPrice <= secondPrice) { // 第二阶段有值时，第一阶段需大于第二阶段
              callback(new Error('一阶段价格不可小于等于二阶段价格'));
            } else {
              callback();
            }
          }
          // 编辑第二阶段
          else if (addStepIndex.value === 1) {
            // 规则：不小于第一阶段 + 不大于第三阶段（若第三阶段存在）
            const errors = [];
            if (currentPrice >= firstPrice) {
              errors.push('二阶段价格不可大于等于一阶段价格');
            }
            if (thirdPrice && currentPrice <= thirdPrice) { // 第三阶段有值时，第二阶段需大于第三阶段
              errors.push('二阶段价格不可小于等于三阶段价格');
            }
            if (errors.length > 0) {
              callback(new Error(errors.join('；')));
            } else {
              callback();
            }
          }
          // 编辑第三阶段
          else if (addStepIndex.value === 2) {
            // 规则：仅校验不大于等于第二阶段（和新增一致）
            if (currentPrice >= secondPrice) {
              callback(new Error('三阶段价格不可大于等于二阶段价格'));
            } else {
              callback();
            }
          }
        }
        // 兜底：无匹配模式时校验通过
        else {
          callback();
        }
      },
      trigger: "blur",
    }
  ]
})

// 显示添加阶梯
function addStepHandle() {
  stepFormType.value = 'add'
  showStepDialog.value = true
  addStepIndex.value = form.value.tieredDiscount.length

  console.log(addStepIndex.value);
}

// 编辑优惠阶梯
function editorStepFormHandle(index) {
  stepFormType.value = 'editor'
  showStepDialog.value = true
  addStepIndex.value = index

  stepForm.value.peopleNum = form.value.tieredDiscount[index].peopleNum
  stepForm.value.price = form.value.tieredDiscount[index].price
}

// 关闭dialog后初始化stepForm
function stepDialogReset() {
  stepForm.value.peopleNum = ''
  stepForm.value.price = ''
  stepFormRef.value.resetFields()
}

// 确认添加阶段
function stepFormSubmitHandle() {
  stepFormRef.value.validate((vaild) => {
    if (vaild) {
      console.log('stepFormType.value', stepFormType.value);
      console.log('addStepIndex.value', addStepIndex.value);
      if (stepFormType.value == 'add') {
        form.value.tieredDiscount.push(_.cloneDeep(stepForm.value))
      } else {
        form.value.tieredDiscount[addStepIndex.value] = _.cloneDeep(stepForm.value)
      }
      showStepDialog.value = false
    }
  })
}

// 可用时间
const useTimeScope = ref([]);
function useTimeScopeChange(e) {
  if (e && e.length) {
    form.value.useTimes = `${dayjs(e[0]).format("HH:mm")}~${dayjs(e[1]).format("HH:mm")}`
  } else {
    form.value.useTimes = "";
  }
}

const rules = ref({
  useShops: [
    {
      required: true,
      message: "请选择门店",
      trigger: "blur",
    }
  ],
  packageName: [
    {
      required: true,
      message: "请输入商品名称",
      trigger: "blur",
    }
  ],
  images: [
    {
      required: true,
      message: "请选择商品图片",
      trigger: "change",
    }
  ],
  originPrice: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (form.value.originPrice <= 0 || !form.value.originPrice) {
          callback(new Error('请输入商品原价'))
        } else {
          callback()
        }
      },
      trigger: "blur",
    }
  ],
  price: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (form.value.price <= 0 || !form.value.price) {
          callback(new Error('请输入价格'))
        } else {
          callback()
        }
      },
      trigger: "blur",
    }
  ],
  packageContent: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (form.value.packageContent.length == 0) {
          return callback(new Error(`请添加套餐组`))
        } else {
          let index = 0
          form.value.packageContent.forEach((item, idx) => {
            if (item.name == '') {
              index = idx
              return callback(new Error(`请输入第${index + 1}组的菜品组名`))
            }
            if (item.packageProducts.length == 0) {
              return callback(new Error(`请给第${index + 1}组添加商品`))
            }

            item.packageProducts.forEach((val, i) => {
              if (val.name == '') {
                return callback(new Error(`请输入第${index + 1}组菜品的第${i + 1}项的商品名称`))
              }
              if (val.price == '') {
                return callback(new Error(`请输入第${index + 1}组菜品的第${i + 1}项的商品价格`))
              }
            })
            callback()
          })
        }
      },
      trigger: "change",
    }
  ],
  useWeeks: [
    {
      required: true,
      message: "请选择可用周期",
      trigger: "change",
    }
  ],
  useTimes: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (form.value.useTimes == '') {
          callback(new Error('请选择可用时段'))
        } else {
          callback()
        }
      },
      trigger: "change",
    }
  ],
  tieredDiscount: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (form.value.tieredDiscount.length == 0) {
          callback(new Error('请添加优惠阶梯'))
        } else {
          callback()
        }
      },
      trigger: "blur",
    }
  ],
  expireHours: [
    {
      validator: (rule, value, callback) => {
        if (form.value.tieredDiscount.length && (form.value.expireHours < 1 || !form.value.expireHours)) {
          callback(new Error('请输入分享期限'))
        } else if (form.value.expireHours > 72) {
          callback(new Error('最大不超过72小时'))
        } else {
          callback()
        }
      },
      trigger: "blur",
    }
  ]
})

// 多图上传成功
function wareImgsMultiOnSuccess(response) {
  loading.value = false
}

// 商品详情图片上传成功
function wareCommentImgsMultiOnSuccess(res) {
  loading.value = false
}

function useShopTypeChange(e) {
  form.value.useShops = ''
}

// 提交保存
const emits = defineEmits(['success'])
function submitHandle() {
  formRef.value.validate(async vaild => {
    try {
      if (vaild) {
        const data = { ...form.value }
        if (form.value.useShopType == 'custom' && form.value.useShops.length) {
          data.useShops = form.value.useShops.join(',')
        } else {
          data.useShops = ''
        }
        loading.value = true
        await packageAddEdit(data)
        ElNotification({
          title: '注意',
          message: '保存成功',
          type: 'success'
        })
        emits('success')
        visible.value = false
      }
    } catch (error) {
      console.log(error);
    }
    setTimeout(() => {
      loading.value = false
    }, 500);
  })
}

// 重置表单
function resetHandle() {
  form.value = _.cloneDeep(formObj)
  formRef.value.resetFields()
  useTimeScope.value = []

}

const targetScrollRef = ref(null)
function openDialog() {
  if (targetScrollRef.value) {
    targetScrollRef.value.scrollTop = 0
  }
}

function show(obj) {
  visible.value = true
  if (obj && obj.id) {
    form.value = { ...obj }
    form.value.useShops = obj.useShops ? obj.useShops.split(',') : []
    useTimeScope.value = obj.useTimes ? obj.useTimes.split('~').map(item => dayjs().format(`YYYY-MM-DD ${item}`)) : []
  }
}

defineExpose({
  show
})

onMounted(() => {
  shopInfo.value = JSON.parse(localStorage.getItem('userInfo'))
})
</script>

<style scoped lang="scss">
.form_warap {
  height: 60vh;
  overflow-y: auto;
}

.column {
  display: flex;
  flex-direction: column;
}

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

.dialog_footer {
  display: flex;
  gap: 14px;

  .btn {
    flex: 1;
  }
}

.group_wrap {
  flex: 1;
  width: 100%;

  .row {
    .mt14 {
      margin-top: 14px;
    }

    &.padding {
      padding: 14px;
      border-radius: 2px;
      background-color: #f8f8f8;
    }

    &:not(:first-child) {
      margin-top: 14px;
    }
  }
}
</style>