<template>
  <div class="gyq_container">
    <div class="gyq_content">
      <headerCard icon="mjhd" name="满减活动" intro="达到指定支付金额享受减价"
        :showSwitch="shopInfo.isHeadShop == 1 || shopInfo.shopType == 'only'" v-model:isOpen="form.isEnableDiscount" />
      <div class="row">
        <el-form :model="form" inline>
          <el-form-item v-if="shopInfo.isHeadShop == 1 || shopInfo.shopType == 'only'">
            <el-button type="primary" icon="CirclePlus" @click="addDialogRef.show()">添加</el-button>
          </el-form-item>
          <el-form-item>
            <el-date-picker style="width: 300px" v-model="times" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"
              @change="selectTimeChange"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="resetSearch">搜索</el-button>
            <el-button icon="Refresh" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="row">
        <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="orderNo">
            <template #default="scope">
              {{ scope.row.validStartTime }} - {{ scope.row.validEndTime }}
            </template>
          </el-table-column>
          <el-table-column label="生效周期" prop="useDays"></el-table-column>
          <el-table-column label="生效时段" prop="validStartTime">
            <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="thresholds">
            <template #default="scope">
              <div class="column">
                <div class="item" v-for="(item, index) in scope.row.thresholds" :key="index">
                  满{{ item.fullAmount }}减{{ item.discountAmount }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="排序" prop="sort"></el-table-column>
          <el-table-column label="状态" prop="status">
            <template #default="scope">
              <el-tag disable-transitions type="primary" v-if="scope.row.status == 1">未开始</el-tag>
              <el-tag disable-transitions type="success" v-if="scope.row.status == 2">进行中</el-tag>
              <el-tag disable-transitions type="info" v-if="scope.row.status == 3">已结束</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="orderNo" width="120" fixed="right">
            <template #default="scope">
              <div class="center">
                <el-button link type="primary" @click="addDialogRef.show(scope.row)"
                  v-if="shopInfo.isHeadShop == 1 || shopInfo.shopType == 'only'">编辑</el-button>
                <el-button link type="primary" @click="addDialogRef.show(scope.row)" v-else>查看</el-button>
                <el-popconfirm title="确认要删除吗？" @confirm="deleteHandle(scope.row)"
                  v-if="shopInfo.isHeadShop == 1 || shopInfo.shopType == 'only'">
                  <template #reference>
                    <el-button type="danger" link>删除</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="row" style="margin-top: 14px;">
        <el-pagination v-model:current-page="tableData.page" v-model:page-size="tableData.size"
          :page-sizes="[10, 20, 50, 100, 500]" background layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
    <addDialog ref="addDialogRef" @success="searchHandle" />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import addDialog from './components/addDialog.vue'
import { discountActivityPage, discountActivityDelete, shopInfoPut, shopInfoGet } from '@/api/coupon/index'

const shopInfo = ref(JSON.parse(localStorage.getItem('userInfo')))
const addDialogRef = ref(null)

const form = ref({
  isEnableDiscount: false
})

watch(() => form.value.isEnableDiscount, (newVal, oldVal) => {
  if (form.value.id && !tableData.loading) {
    console.log('值改变了', form.value);
    shopInfoPutAjax()
  }
})

// 更新店铺信息
async function shopInfoPutAjax() {
  try {
    await shopInfoPut(form.value)
  } catch (error) {
    console.log(error);
  }
}

const times = ref([])
const queryForm = ref({
  startTime: '',
  endTime: ''
})

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

// 搜索
function searchHandle() {
  tableData.page = 1;
  getTableData()
}

// 重置搜索
function resetSearch() {
  queryForm.value.startTime = ''
  queryForm.value.endTime = ''
  times.value = []
  searchHandle()
}

// 选择日期
function selectTimeChange(e) {
  console.log(e);
  queryForm.value.startTime = dayjs(e[0]).format('YYYY-MM-DD 00:00:00')
  queryForm.value.endTime = dayjs(e[1]).format('YYYY-MM-DD 23:59:59')
}

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

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

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

// 获取表格数据
async function getTableData() {
  try {
    tableData.loading = true
    const res = await discountActivityPage({
      // ...queryForm.value,
      page: tableData.page,
      size: tableData.size
    })
    tableData.list = res.records
    tableData.total = +res.totalRow

    console.log(tableData);

  } catch (error) {
    console.log(error);
  }
  setTimeout(() => {
    tableData.loading = false
  }, 500)
}

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

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

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

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

.column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;

  .item {
    flex: 1;
  }
}

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

.tips {
  color: #666;
}

.footer {
  display: flex;
  justify-content: center;
}

.textarea-num {
  color: #999;
  display: flex;
  justify-content: flex-end;
}

.row {
  padding-top: 14px;
}
</style>