<template>
  <div>
    <el-card class="box-card" shadow="never">
      <el-row>
        <el-col :span="16">
          <el-row>
            <el-space wrap>
              <el-select v-model="query.type" placeholder="">
                <el-option label="全部事项类别" :value="-1" />
                <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.key + '事项'"
                  :value="item.value"
                />
              </el-select>
              <el-date-picker
                value-format="YYYY-MM-DD"
                v-model="queryTime"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
              <el-select v-model="query.status" placeholder="">
                <el-option label="全部完成情况" :value="-1" />
                <el-option
                  v-for="item in statusList"
                  :key="item.value"
                  :label="item.key"
                  :value="item.value"
                />
              </el-select>
            </el-space>
          </el-row>
        </el-col>
        <el-col :span="8" class="flex">
          <el-input
            v-model="query.theme"
            placeholder="输入事项主题"
            clearable
          />
          <el-button
            class="ml-2"
            type="primary"
            :icon="Search"
            @click="onSearch"
            :loading="loading"
            >查询</el-button
          >
        </el-col>
      </el-row>
    </el-card>
    <div class="mt-4">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="type" label="事项类别">
          <template #default="{ row }">
            {{ formatTypeStr(row.type) }}事项
          </template>
        </el-table-column>
        <el-table-column prop="theme" label="事项主题" />
        <el-table-column prop="content" label="事项内容">
          <template #default="{ row }">
            <div v-if="row.type == 2">
              <el-space wrap>
                <div v-if="row.content?.questions?.length">随访问卷</div>
                <div v-if="row.content?.healthGuidance?.length">
                  随访健康指导
                </div>
              </el-space>
            </div>
            <div v-else-if="row.type == 0">
              {{ row.content }}
            </div>
            <div v-else>
              <el-space wrap>
                <div v-for="item in row.content" :key="item.id">
                  <el-tag plain> {{ item.properties.name }}</el-tag>
                </div>
              </el-space>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="事项时间">
          <template #default="{ row }">
            <el-space wrap>
              <div v-if="row.frequencyType == 3">
                {{ row.dates }}
              </div>
              <div v-else>
                {{ row.startDate }} 至 {{ row.endDate }}
                {{ frequencyType[row.frequencyType] }}
              </div>
            </el-space>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="完成情况">
          <template #default="{ row }">
            <div :class="statusList[row.status]?.color">
              {{ statusList[row.status]?.key }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作" width="180">
          <template #default="scope">
            <Auth value="headlthManage:todoList:view">
              <el-space spacer="|">
                <el-button
                  type="primary"
                  :disabled="scope.row.status == 1"
                  link
                  @click="handleEdit(scope.row)"
                  >编辑</el-button
                >
                <el-popconfirm
                  title="确定要删除此标签吗"
                  @confirm="onDelete(scope.row.id)"
                  width="200"
                >
                  <template #reference>
                    <el-link type="danger" :disabled="scope.row.status == 1"
                      >删除</el-link
                    >
                  </template>
                </el-popconfirm>
              </el-space>
            </Auth>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="mt-4 justify-end"
        background
        :current-page="query.page"
        :page-size="query.pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="onChangePage"
      />
    </div>
    <el-dialog title="" v-model="visibleEdit" append-to-body>
      <div>
        <component :is="cmps[rowData?.type]" isEdit ref="cmpsRef" />
      </div>
      <template #footer>
        <el-button type="primary" @click="handleSaveSubmit">保存修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {
  ref,
  onMounted,
  onBeforeUnmount,
  computed,
  defineAsyncComponent,
  defineExpose,
  defineEmits
} from "vue";
import { Search } from "@element-plus/icons-vue";
import { request } from "@/utils/http";
import { ElMessage } from "element-plus";
import { useManageProjectStoreHook } from "@/store/modules/manageProject";

const emits = defineEmits(["success"]);
const cmps = {
  0: defineAsyncComponent(() => import("./TodoItemOther.vue")), // 其他
  1: defineAsyncComponent(() => import("./TodoItemCheck.vue")), // 复查
  2: defineAsyncComponent(() => import("./TodoItemFollowUp.vue")), // 随访
  3: defineAsyncComponent(() => import("./TodoItemMonitor.vue")), // 监测
  4: defineAsyncComponent(() => import("./TodoItemInspect.vue")), // 检查
  5: defineAsyncComponent(() => import("./TodoItemReturnVisit.vue")) // 回访
};
const tableData = ref([]);
const query = ref({
  page: 1,
  pageSize: 15,
  theme: "",
  type: -1,
  status: -1
});
const cmpsRef = ref();
const queryTime = ref("");
const loading = ref(false);
const total = ref(0);
const frequencyType = ["每天", "每周", "每月", "指定日期"];
const typeList = [
  {
    key: "复查",
    value: 1
  },
  {
    key: "随访",
    value: 2
  },
  {
    key: "日常监测",
    value: 3
  },

  {
    key: "其他",
    value: 0
  }

  // {
  //   key: "检查",
  //   value: 4
  // },

  // {
  //   key: "回访",
  //   value: 5
  // }
];
const statusList = [
  {
    key: "待完成",
    value: 0,
    color: "text-gray-500"
  },
  {
    key: "已完成",
    value: 1,
    color: "text-green-500"
  },
  {
    key: "部分完成",
    value: 2,
    color: "text-blue-500"
  }
];
const formatTypeStr = type => {
  return typeList.find(v => v.value === type)?.key;
};
const visibleEdit = ref(false);

const rowData = ref({
  type: 0
});

const currentArchiveId = computed(() => {
  return useManageProjectStoreHook()?.currentArchiveId;
});
const getList = () => {
  loading.value = true;
  request
    .get("dataService/schedule/archive/paginate", {
      params: {
        ...query.value,
        startDate: queryTime.value && queryTime.value[0],
        endDate: queryTime.value && queryTime.value[1],
        archiveId: currentArchiveId.value
      }
    })
    .then(resp => {
      tableData.value = resp.data.list;
      total.value = resp.data.total;
    })
    .finally(() => {
      loading.value = false;
    });
};
const onSearch = () => {
  query.value.page = 1;
  getList();
};
const onChangePage = page => {
  query.value.page = page;
  getList();
};
const handleEdit = row => {
  visibleEdit.value = true;
  rowData.value = row;
  setTimeout(() => {
    cmpsRef.value?.onInitEditData(row);
  }, 500);
  // nextTick(() => {}).then(() => {
  //   cmpsRef.value?.onInitEditData(row);
  // });
};
const handleSaveSubmit = () => {
  cmpsRef.value?.onSubmit(pramas => {
    request
      .post("/dataService/schedule/update", {
        // ...rowData.value,
        id: rowData.value.id,
        ...pramas
      })
      .then(resp => {
        ElMessage.success(resp.message);
        visibleEdit.value = false;
        getList();
        emits("success");
      });
  });
};
const onDelete = id => {
  request.post("dataService/schedule/delete", { id }).then(resp => {
    ElMessage.success(resp.message);
    emits("success");
    getList();
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }) {
  if (code === "Enter") {
    onSearch();
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});

const initData = () => {
  getList();
};
initData();

defineExpose({
  initData
});
</script>
