<!-- 店铺配置管理 -->
<template>
  <div class="gyq_container">
    <div class="gyq_content">
      <div class="row">
        <div class="center">
          <el-select v-model="status" placeholder="状态" style="width: 200px;">
            <el-option label="全部" value=""></el-option>
            <el-option label="启用中" value="1"></el-option>
            <el-option label="已禁用" value="0"></el-option>
          </el-select>
          <el-button type="primary" @click="searchHandle">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" plain @click="recordRef.show()">商家申请记录</el-button>
        </div>
      </div>
      <div class="row mt14">
        <el-button type="primary" @click="visible = true">添加模板</el-button>
      </div>
      <div class="row  mt14">
        <el-table :data="tableData.list" stripe border v-loading="tableData.loading">
          <el-table-column prop="id" label="ID"></el-table-column>
          <el-table-column prop="title" label="模版名称" />
          <el-table-column prop="content" label="短信模版内容" width="500" />
          <el-table-column prop="shopUse" label="启用状态">
            <template #default="scope">
              <el-switch v-model="scope.row.shopUse" :active-value="1" :inactive-value="0"
                @change="statusChange($event, scope.row)" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button type="primary" link @click="editorHandle(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, 20, 50, 100]" background layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-dialog :title="`${selectRow.id ? '编辑' : '添加'}模板`" width="500px" v-model="visible" @closed="onClose">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addFormRef">
        <el-form-item label="模板名称" prop="title">
          <el-input v-model="addForm.title" :maxlength="20" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板内容" prop="content">
          <div class="ipt">
            <el-input type="textarea" :maxlength="maxLength" :rows="4" v-model="addForm.content"
              placeholder="请输入模板内容" />
            <span>{{ addForm.content.length }}/{{ maxLength }}</span>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="handleOk" :loading="confirmLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <record ref="recordRef" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import record from './record.vue'
import { smsTemplatePage, smsTemplate, smsTemplateResubmit, shopUseDelStatus } from '@/api/coupon/index.js'

const recordRef = ref(null)

const status = ref('')

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

// 重置搜索
function resetSearch() {
  status.value = ''
  tableData.page = 1
  getTableData()
}

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

// 添加模板 statr
const selectRow = ref({ id: '' })
const visible = ref(false)
const confirmLoading = ref(false)
const maxLength = ref(500)
const addForm = ref({
  title: '',
  content: ''
})

const addFormRules = {
  title: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入模板内容', trigger: 'blur' },
    { min: 1, max: maxLength.value, message: `长度在 1 到 ${maxLength.value} 个字符`, trigger: 'blur' }
  ]
}

const addFormRef = ref(null)

function onClose() {
  selectRow.value = { id: '' }
  visible.value = false
  addForm.value = {
    title: '',
    content: ''
  }
  if (addFormRef.value) {
    addFormRef.value.clearValidate()
  }
}

// 取消提交
function handleCancel() {
  onClose()
}

// 显示编辑
function editorHandle(row) {
  selectRow.value = { ...row }
  addForm.value = { ...row }
  visible.value = true
}

// 开始提交
function handleOk() {
  if (!addFormRef.value) return
  addFormRef.value.validate(async (valid) => {
    try {
      if (valid) {
        confirmLoading.value = true
        if (selectRow.value.id) {
          await smsTemplateResubmit(addForm.value)
        } else {
          await smsTemplate({
            ...addForm.value,
            shopId: localStorage.getItem('shopId'),
          })
        }
        onClose()
        getTableData()
      }
    } catch (error) {
      console.log(error);
    }
    confirmLoading.value = false
  })
}
// 添加模板 end

// 状态改变
async function statusChange(e, row) {
  try {
    if (tableData.loading) return
    await shopUseDelStatus({
      id: row.id,
      shopUse: row.shopUse
    })
    getTableData()
  } catch (error) {
    console.log(error);
  }
}

// 删除
async function deleteHandle(row) {
  try {
    await shopUseDelStatus({
      id: row.id,
      isDel: 1,
    });
    getTableData();
  } catch (err) {
    console.log(err);
  }
}

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

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

async function getTableData() {
  try {
    tableData.loading = true
    const res = await smsTemplatePage({
      page: tableData.page,
      size: tableData.size,
      shopUse: status.value,
      shopId: localStorage.getItem('shopId')
    })
    tableData.list = res.records
    tableData.total = +res.totalRow
  } catch (error) {
    console.log(error);
  }
  setTimeout(() => {
    tableData.loading = false
  }, 500);
}

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

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

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

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

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

.ipt {
  width: 100%;
  position: relative;

  span {
    position: absolute;
    right: 10px;
    bottom: 0;
    color: #999;
    font-size: 12px;
  }
}
</style>