<template>
  <div class="p-2">
    <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="title">
              <el-input v-model="queryParams.title" placeholder="请输入问卷标题" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="参与范围" prop="scope">
              <el-input v-model="queryParams.scope" placeholder="请输入参与范围 0全体业主 1部分业主" 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 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="['questionnaire:questionnaire:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['questionnaire:questionnaire:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['questionnaire:questionnaire: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="questionnaireList" @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="description" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="com_questionnaire_status" :value="scope.row.status"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="参与范围" align="center" prop="scope">
          <template #default="scope">
            <dict-tag :options="com_questionnaire_scope" :value="scope.row.scope"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" fixed="right" width="200">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['questionnaire:questionnaire:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['questionnaire:questionnaire:remove']"
              ></el-button>
            </el-tooltip>
          </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>
  </div>
</template>

<script setup name="Questionnaire" lang="ts">
import { listQuestionnaire, getQuestionnaire, delQuestionnaire, addQuestionnaire, updateQuestionnaire } from '@/api/system/Questionnaire/index';
import { QuestionnaireVO, QuestionnaireQuery, QuestionnaireForm } from '@/api/system/Questionnaire/type';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { com_questionnaire_scope } = toRefs<any>(proxy?.useDict('com_questionnaire_scope'));
const { com_questionnaire_status } = toRefs<any>(proxy?.useDict('com_questionnaire_status'));
console.log(com_questionnaire_scope);

const questionnaireList = ref<QuestionnaireVO[]>([]);
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 questionnaireFormRef = ref<ElFormInstance>();

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

const initFormData: QuestionnaireForm = {
  id: undefined,
  villageId: undefined,
  title: undefined,
  description: undefined,
  content: undefined,
  status: undefined,
  scope: undefined,
  residents: undefined,
  remark: undefined
};
const data = reactive<PageData<QuestionnaireForm, QuestionnaireQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    villageId: undefined,
    title: undefined,
    description: undefined,
    content: undefined,
    status: undefined,
    scope: undefined,
    residents: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '问卷ID不能为空', trigger: 'blur' }],
    title: [{ required: true, message: '问卷标题不能为空', trigger: 'blur' }],
    content: [{ required: true, message: '问卷题目结构不能为空', trigger: 'blur' }]
  }
});

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

/** 查询问卷调查列表 */
const getList = async () => {
  loading.value = true;
  const res = await listQuestionnaire(queryParams.value);
  questionnaireList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: QuestionnaireVO[]) => {
  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/addQuestionnaire'
  });
};

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

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

/** 删除按钮操作 */
const handleDelete = async (row?: QuestionnaireVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除问卷调查编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delQuestionnaire(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

onMounted(() => {
  getList();
});
</script>
