<!-- 点单智能推荐 -->
<template>
  <div class="gyq_container">
    <div class="gyq_content">
      <HeaderCard name="点单智能推荐" intro="进入点单页X秒未点自动推荐商品，此推荐设置启用即生效" icon="dczntj" show-switch
        v-model:isOpen="form.isProductSuggest">
      </HeaderCard>
      <div class="row mt14">
        <div class="center">
          <el-button type="primary" @click="addRef.show()">添加</el-button>
          <el-button type="primary" plain :loading="showDialogLoading" @click="showDialogHandle">首次弹窗触发事件</el-button>
          <span class="tips">多个弹窗时，每个弹窗之间关闭和弹出间隔为30秒</span>
        </div>
      </div>
      <div class="row mt14">
        <el-table :data="tableData.list" stripe border v-loading="tableData.loading">
          <el-table-column label="ID" prop="id" width="80"></el-table-column>
          <el-table-column label="模版名称" prop="title"></el-table-column>
          <el-table-column label="生效周期" prop="useDays"></el-table-column>
          <el-table-column label="生效时段" prop="useTimeType">
            <template #default="scope">
              <div v-if="scope.row.useTimeType == 'all'">全天</div>
              <div v-else>{{ scope.row.useStartTime }} - {{ scope.row.useEndTime }}</div>
            </template>
          </el-table-column>
          <el-table-column label="启用状态" prop="status" width="150">
            <template #default="scope">
              <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
                @change="statusChange($event, scope.row)" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button link type="primary" @click="addRef.show(scope.row)">编辑</el-button>
              <el-popconfirm title="确认要删除吗？" @confirm="deleteHandle(scope.row)">
                <template #reference>
                  <el-button type="danger" link>删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="row mt14">
        <el-pagination v-model:current-page="tableData.page" v-model:page-size="tableData.size"
          :page-sizes="[10, 30, 50, 100]" background layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
    <add ref="addRef" @success="getTableData" />
    <el-dialog title="弹窗时间" width="500px" v-model="visible" @closed="closedHandle">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="200px" label-position="right">
        <el-form-item label="首次弹窗触发时间（秒）" prop="suggestTime">
          <div class="column">
            <div>
              <el-input v-model="form.suggestTime" placeholder="请输入触发时间"
                @input="e => form.suggestTime = filterNumberInput(e, 0)"></el-input>
            </div>
            <div class="tips">
              设置为0时，进入点餐页立即弹出
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="handleOk" :loading="confirmLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import HeaderCard from "../components/headerCard.vue";
import add from "./add.vue";
import { filterNumberInput } from '@/utils'
import { ref, reactive, onMounted, watch } from "vue";
import { suggestPage, suggestDel, suggestPostPut, shopInfoGet, shopInfoPut } from "@/api/coupon/index.js";

const addRef = ref(null);

const form = ref({
  id: '',
  isProductSuggest: 0,
  suggestTime: ''
});

const rules = ref({
  suggestTime: [
    {
      required: true,
      validator: (rule, value, callback) => {
        console.log('value==', value);
        if (value === '' || value < 0) {
          callback(new Error('请输入触发时间'))
          return
        } else {
          callback()
        }
      },
      triiger: 'blur'
    }
  ]
})

watch(
  () => form.value.isProductSuggest,
  (newVal) => {
    if (!tableData.loading) {
      shopInfoPutAjax();
    }
  }
);

// 更新店铺信息
async function shopInfoPutAjax() {
  try {
    await shopInfoPut(form.value)
    ElNotification({
      title: '注意',
      message: '更新成功',
      type: 'success'
    })
  } catch (error) {
    console.log(error);
  }
}

// 获取店铺信息
async function shopInfoGetAjax() {
  try {
    const res = await shopInfoGet()
    form.value.id = res.id
    form.value.isProductSuggest = res.isProductSuggest
    form.value.suggestTime = res.suggestTime
  } catch (error) {
    console.log(error);
  }
}

// 限时弹窗
const showDialogLoading = ref(false)
async function showDialogHandle() {
  showDialogLoading.value = true
  await shopInfoGetAjax()
  showDialogLoading.value = false
  visible.value = true
}

const visible = ref(false)
const confirmLoading = ref(false)
const formRef = ref(null)
function handleOk() {
  formRef.value.validate(async valid => {
    try {
      if (valid) {
        confirmLoading.value = true
        await shopInfoPutAjax()
        shopInfoGetAjax()
        visible.value = false
      }
    } catch (error) {
      console.log(error);
    }
    confirmLoading.value = false
  })
}

function closedHandle() {
  formRef.value.resetFields()
}

const tableData = reactive({
  loading: true,
  page: 1,
  size: 10,
  total: 0,
  list: [],
})

// 修改状态
async function statusChange(e, row) {
  try {
    await suggestPostPut(row, 'put');
    getTableData();
  } catch (error) {
    console.log("状态修改失败", error);
  }
}

// 分页大小发生变化
function handleSizeChange(e) {
  tableData.pageSize = e;
  consumeCashbackRecordAjax();
}

// 分页发生变化
function handleCurrentChange(e) {
  tableData.page = e;
  consumeCashbackRecordAjax();
}

// 删除
async function deleteHandle(row) {
  try {
    tableData.loading = true;
    await suggestDel({
      id: row.id
    });
    ElNotification({
      title: '注意',
      type: 'success',
      message: '删除成功',
    });
    getTableData();
  } catch (err) {
    console.log(err);
  }
}

// 获取表格数据
async function getTableData() {
  try {
    tableData.loading = true;
    const res = await suggestPage({
      page: tableData.page,
      size: tableData.size,
    });
    tableData.list = res.records;
    tableData.total = res.totalRow;
  } catch (error) {
    console.log("获取表格数据失败", error);
  }
  setTimeout(() => {
    tableData.loading = false;
  }, 500);
}

onMounted(() => {
  getTableData();
  shopInfoGetAjax()
});
</script>

<style scoped lang="scss">
.gyq_container {
  padding: 14px;

  .gyq_content {
    padding: 14px;
    background-color: #fff;
    border-radius: 8px;
  }
}

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

.tips {
  color: #999;
  font-size: 12px;
}

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

.column {
  display: flex;
  flex-direction: column;
}
</style>