<template>
  <div class="flex flex-col h-full p-2">
    <Pageheader title="活动管理"></Pageheader>
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="标题" prop="titile">
              <el-input v-model="queryParams.titile" placeholder="请输入标题" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card class="flex-1" shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['activity:activity:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['activity:activity:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['activity:activity:remove']"
              >删除</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="activityList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="标题" align="center" prop="title" />
        <el-table-column label="作者" align="center" prop="author" />
        <el-table-column label="发布状态" align="center" prop="status">
          <template #default="scope">
            <DictTag :value="scope.row.status" :options="com_publish_status"></DictTag>
          </template>
        </el-table-column>
        <el-table-column label="浏览量" align="center" prop="pageViews" />
        <el-table-column label="发布人" align="center" prop="createName" />
        <el-table-column label="操作" align="center" width="300px" fixed="right">
          <template #default="scope">
            <el-button v-if="scope.row.status === '0'" link type="primary" @click="handleSend(scope.row)">发布</el-button>
            <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['activity:activity:edit']">修改</el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['activity:activity:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="activityFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="发布人姓名" prop="createName">
          <el-input v-model="form.createName" placeholder="请输入发布人姓名" />
        </el-form-item>
        <el-form-item label="发布后状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="item in com_publish_status" :key="item.value" :label="item.label" :value="item.value"></el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Activity" lang="ts">
import { listActivity, delActivity, updateActivity } from '@/api/system/Activity/index';
import { ActivityVO, ActivityQuery, ActivityForm } from '@/api/system/Activity/type';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { com_publish_status } = toRefs<any>(proxy?.useDict('com_publish_status'));

const activityList = ref<ActivityVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const activityFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: '发布活动'
});

const initFormData: ActivityForm = {
  id: undefined,
  titile: undefined,
  author: undefined,
  content: undefined,
  status: undefined,
  pageViews: undefined,
  createName: undefined
};
const data = reactive<PageData<ActivityForm, ActivityQuery>>({
  form: { ...initFormData },
  queryParams: {
    villageId: Number(localStorage.getItem('villageid')),
    pageNum: 1,
    pageSize: 10,
    titile: undefined,
    author: undefined,
    content: undefined,
    status: undefined,
    pageViews: undefined,
    createName: undefined,
    params: {}
  },
  rules: {
    createName: [{ required: true, message: '发布人姓名不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询活动管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listActivity(queryParams.value);
  activityList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
/** 发布按钮 */
const handleSend = (row: ActivityVO) => {
  form.value = {
    ...form.value,
    ...row
  };
  console.log(form.value);
  dialog.visible = true;
};
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  activityFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ActivityVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
const router = useRouter();
/** 新增按钮操作 */
const handleAdd = () => {
  router.push({
    path: '/repair/addActivity'
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ActivityVO) => {
  router.push({
    path: '/repair/addActivity',
    query: {
      id: row.id
    }
  });
};

/** 提交按钮 */
const submitForm = () => {
  activityFormRef.value?.validate(async (valid: boolean) => {
    console.log(valid);
    if (valid) {
      buttonLoading.value = true;
      await updateActivity(form.value).finally(() => (buttonLoading.value = false));
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ActivityVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('该信息删除后无法恢复，确定要删除吗？').finally(() => (loading.value = false));
  await delActivity(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'activity/activity/export',
    {
      ...queryParams.value
    },
    `activity_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
.el-table {
  height: calc(100% - 80px);
}
</style>
