<template>
  <el-dialog :title="form.id ? '编辑' : '添加'" width="800px" v-model="visible" @closed="resetForm">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="left">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入轮播图名称" :maxlength="20" style="width: 300px;"></el-input>
      </el-form-item>
      <el-form-item label="轮播图片" prop="imageUrl">
        <div class="column">
          <div class="center">
            <SingleImageUpload v-model="form.imageUrl" />
          </div>
          <div class="tips" style="margin-bottom: 8px;">建议尺寸：750x300像素，支持jpg、png、gif格式，大小不超过2MB</div>
        </div>
      </el-form-item>
      <el-form-item label="是否可分享" prop="isShareable">
        <div class="column">
          <div>
            <el-radio-group v-model="form.isShareable">
              <el-radio label="开启" :value="1"></el-radio>
              <el-radio label="关闭" :value="0"></el-radio>
            </el-radio-group>
          </div>
          <div class="tips">开启时，用户端会显示单独的分享按钮</div>
        </div>
      </el-form-item>
      <el-form-item label="跳转页面" prop="jumpPageId">
        <linkCard :includes-names="includesNames" v-model="form.jumpPageId" v-model:extendParam="form.extendParam" />
      </el-form-item>
      <el-form-item label="排序值" prop="sort">
        <el-input v-model="form.sort" @input="e => form.sort = filterNumberInput(e, 1)" style="width: 300px;"
          placeholder="排序值越大越靠前"></el-input>
      </el-form-item>
      <el-form-item label="是否启用">
        <el-radio-group v-model="form.isEnabled">
          <el-radio label="启用" :value="1"></el-radio>
          <el-radio label="禁用" :value="0"></el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import _ from 'lodash';
import { ref } from 'vue';
import { filterNumberInput } from '@/utils';
import SingleImageUpload from '@/components/Upload/SingleImageUpload.vue';
import linkCard from './linkCard.vue';
import { shareCarouselPost } from '@/api/coupon/index.js';

const visible = ref(false);
const loading = ref(false);
const formObj = ref({
  id: '',                 // 轮播图ID，编辑时传递
  name: '',               // 轮播图名称（20字内）
  imageUrl: '',           // 轮播图片地址
  isShareable: 1,        // 是否可分享 1=开启 0=关闭
  jumpPageId: '',         // 跳转页面 tb_mini_app_pages的 id
  extendParam: '',        // 扩展参数
  sort: '',               // 排序值，数值越大越靠前
  isEnabled: 1,          // 是否启用 1=启用 0=禁用
});
const form = ref(_.cloneDeep(formObj.value));
function resetForm() {
  form.value = _.cloneDeep(formObj.value);
}
const formRef = ref(null);
const rules = {
  name: [
    { required: true, message: '请输入轮播图名称', trigger: 'blur' }
  ],
  imageUrl: [
    { required: true, message: '请上传轮播图片', trigger: 'change' }
  ],
  jumpPageId: [
    {
      validator: (rule, value, callback) => {
        if (form.value.jumpPageId && _.includes(includesNames.value.map(item => item.id), form.value.jumpPageId)) {
          if (!form.value.extendParam) {
            callback(new Error('请选择具体菜品'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ],
}

const includesNames = ref([
  {
    id: '4',
    name: '套餐推广商品详情页'
  },
  {
    id: '6',
    name: '商品拼团详情页'
  },
  {
    id: '10',
    name: '点餐商品详情弹窗页'
  },
  {
    id: '12',
    name: '积分商品详情页面'
  }
]);

function submitForm() {
  console.log(form.value);

  formRef.value.validate((valid) => {
    if (valid) {
      shareCarouselPostAjax();
    }
  });
}

const emits = defineEmits(['success']);

// 轮播图配置:新增/修改
async function shareCarouselPostAjax() {
  try {
    loading.value = true;
    await shareCarouselPost(form.value);
    ElNotification({
      title: '成功',
      message: '保存成功',
      type: 'success',
      duration: 2000
    });
    emits('success');
    visible.value = false;
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
}

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

defineExpose({
  show
})
</script>

<style scoped lang="scss">
.center {
  display: flex;
}

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

.tips {
  font-size: 14px;
  color: #999;
}
</style>