<!-- 添加团购商品 -->
<template>
  <div>
    <el-dialog :title="form.id ? '编辑商品' : '添加商品'" width="800px" 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="120">
          <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="wareName">
            <div class="column">
              <el-input v-model="form.wareName" placeholder="请输入商品名称" :maxlength="30" style="width: 300px;"></el-input>
              <div>
                <el-button link type="primary" @click="selecProductDialogRef.show()">导入已有商品信息</el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="商品描述">
            <el-input type="textarea" :rows="5" placeholder="请输入商品描述" :maxlength="50" show-password
              v-model="form.wareDetail" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item label="商品图片" prop="wareImgs">
            <MultiImageUpload v-model="wareImgs" @uploadStart="loading = true"
              @uploadAllSuccess="wareImgsMultiOnSuccess" />
          </el-form-item>
          <el-form-item label="原价" prop="originalPrice">
            <el-input v-model="form.originalPrice" placeholder="请输入商品原价" :maxlength="8"
              @input="e => form.originalPrice = filterNumberInput(e)" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item label="拼团价" prop="groupPrice">
            <el-input v-model="form.groupPrice" placeholder="请输入拼团价" :maxlength="8"
              @input="e => form.groupPrice = filterNumberInput(e)" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item label="成团人数" prop="groupPeopleNum">
            <el-input v-model="form.groupPeopleNum" placeholder="当参与人数达到成团人数才能完成拼团" :maxlength="8"
              @input="e => form.groupPeopleNum = filterNumberInput(e, 2)" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item label="成团期限" prop="groupTimeoutHour">
            <el-input v-model="form.groupTimeoutHour" placeholder="最小不低于1小时，最大不超过72小时" :maxlength="8"
              @input="e => form.groupTimeoutHour = filterNumberInput(e, 1)" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item label="限购数量" prop="limitBuyNum">
            <div class="center">
              <el-switch v-model="limitBuyNumSwitch" @change="limitBuyNumSwitchChange"></el-switch>
              <div class="ipt" v-if="limitBuyNumSwitch">
                <el-input :maxlength="8" v-model="form.limitBuyNum" placeholder="每人最多购买次数"
                  @input="e => form.limitBuyNum = filterNumberInput(e, 1)" style="width: 250px;"></el-input>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="上架状态">
            <el-switch v-model="form.onlineStatus" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
          <el-form-item label="商品详情">
            <MultiImageUpload v-model="wareCommentImgs" @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" />
  </div>
</template>

<script setup>
import _ from 'lodash'
import { ref, onMounted } from 'vue'
import { filterNumberInput } from '@/utils'
import { addGbWare, updateGbWareById } from '@/api/market/ware'
import selecProductDialog from './selecProductDialog.vue'

const shopInfo = ref(null)

const selecProductDialogRef = ref(null)

// 选择商品导入
function selectProduceHandle(obj) {
  form.value.wareName = obj.name
  form.value.wareImgs = obj.coverImg
  form.value.originalPrice = obj.price
  wareImgs.value = [obj.coverImg]
}

const visible = ref(false)
const limitBuyNumSwitch = ref(false) // 如果limitBuyNum = -10086 就是false，不限购，true为限购
const loading = ref(false)
const wareImgs = ref([])
const wareCommentImgs = ref([])
const formRef = ref(null)
const formObj = {
  id: '',
  useShopType: 'only',              // only-仅本店 all全部 /custom 指定
  useShops: '',                     // 可用门店（指定门店时存储门店ID，逗号分隔）
  wareName: '',                     // 商品名称
  wareDetail: '',                   // 商品描述
  wareImgs: '',                     // 商品图片（多个用逗号分隔）
  originalPrice: '',                // 原价
  groupPrice: '',                   // 拼团价
  groupPeopleNum: '',               // 成团人数 最小为1
  groupTimeoutHour: '',             // 成团期限（小时）不低于1小时，最大72小时
  limitBuyNum: '',                  // 限购数量（每人最多购买次数） -10086
  onlineStatus: 1,                  // 上架状态（0下架 1上架）
  wareCommentImgs: '',              // 商品详情图片（多个用逗号分隔）
}
const form = ref(_.cloneDeep(formObj))

const rules = ref({
  useShops: [
    {
      required: true,
      message: "请选择门店",
      trigger: "blur",
    }
  ],
  wareName: [
    {
      required: true,
      message: "请输入商品名称",
      trigger: "blur",
    }
  ],
  wareImgs: [
    {
      required: true,
      message: "请选择商品图片",
      trigger: "change",
    }
  ],
  originalPrice: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (form.value.originalPrice <= 0 || !form.value.originalPrice) {
          callback(new Error('请输入商品原价'))
        } else {
          callback()
        }
      },
      trigger: "blur",
    }
  ],
  groupPrice: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (form.value.groupPrice <= 0 || !form.value.groupPrice) {
          callback(new Error('请输入拼团价'))
        } else {
          callback()
        }
      },
      trigger: "blur",
    }
  ],
  groupPeopleNum: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (form.value.groupPeopleNum < 1 || !form.value.groupPeopleNum) {
          callback(new Error('请输入成团人数'))
        } else {
          callback()
        }
      },
      trigger: "blur",
    }
  ],
  groupTimeoutHour: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (form.value.groupTimeoutHour < 1 || !form.value.groupTimeoutHour) {
          callback(new Error('请输入成团期限'))
        } else if (form.value.groupTimeoutHour > 72) {
          callback(new Error('最大不超过72小时'))
        } else {
          callback()
        }
      },
      trigger: "blur",
    }
  ],
  limitBuyNum: [
    {
      validator: (rule, value, callback) => {
        if (limitBuyNumSwitch.value && !form.value.limitBuyNum) {
          callback(new Error('请输入每人最多购买次数'))
        } else {
          callback()
        }
      },
      trigger: "blur",
    }
  ]
})

function limitBuyNumSwitchChange(e) {
  if (e) {
    form.value.limitBuyNum = ''
  } else {
    form.value.limitBuyNum = -10086
  }
}

// 多图上传成功
function wareImgsMultiOnSuccess(response) {
  loading.value = false
  form.value.wareImgs = wareImgs.value.join(',')
}

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

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

// 提交保存
const emits = defineEmits(['success'])
function submitHandle() {
  form.value.wareImgs = wareImgs.value.join(',')
  form.value.wareCommentImgs = wareCommentImgs.value.join(',')
  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
        if (form.value.id) {
          await updateGbWareById(data)
        } else {
          await addGbWare(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)
  limitBuyNumSwitch.value = false
  wareImgs.value = []
  wareCommentImgs.value = []

  formRef.value.resetFields()
}


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

function show(obj) {
  visible.value = true
  if (obj && obj.id) {
    console.log(obj);
    form.value = { ...obj }

    form.value.useShops = obj.useShops ? obj.useShops.split(',') : []

    if (form.value.wareImgs != '') {
      wareImgs.value = form.value.wareImgs.split(',')
    }
    if (form.value.wareCommentImgs != '') {
      wareCommentImgs.value = form.value.wareCommentImgs.split(',')
    }
    if (form.value.limitBuyNum != -10086) {
      limitBuyNumSwitch.value = true
    } else {
      limitBuyNumSwitch.value = false
    }
  }
}

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;
  }
}
</style>