<template>
  <div>
    <el-dialog title="" v-model="dialogVisible" :show-close="false" fullscreen>
      <template #header>
        <ComponentTodoList></ComponentTodoList>
        <!-- <el-card>
          <div>
            <el-row :gutter="10">
              <el-col :span="16" class="flex items-center">
                事项期望完成时间：
                <el-date-picker
                  v-model="state.query.times"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始时间"
                  end-placeholder="完成时间"
                  value-format="YYYY-MM-DD"
                  :clearable="false"
                />
                <el-select
                  v-model="state.query.type"
                  placeholder="全部事项类型"
                  filterable
                  class="ml-2"
                >
                  <el-option label="全部事项类型" :value="-1"></el-option>
                  <el-option
                    v-for="item in state.typeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
                <el-select
                  v-model="state.query.type"
                  placeholder="全部完成状态"
                  filterable
                  class="ml-2"
                >
                  <el-option label="全部状态" :value="-1"></el-option>
                  <el-option
                    v-for="item in state.statusList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="8">
                <div class="ml-2 flex items-center text-right">
                  <el-input
                    v-model="state.query.value"
                    placeholder="请输入"
                    class="input-with-select"
                    clearable
                  >
                    <template #prepend>
                      <el-select
                        v-model="state.query.key"
                        placeholder="请选择"
                        style="width: 115px"
                        clearable
                      >
                        <el-option label="档案号" value="archive_id" />
                        <el-option label="姓名" value="name" />
                      </el-select>
                    </template>
                    <template #append>
                      <el-button :icon="Search" @click="onSearch"
                        >查询</el-button
                      >
                    </template>
                  </el-input>
                  <el-button
                    class="ml-10"
                    type="danger"
                    plain
                    @click="dialogVisible = false"
                    >关闭</el-button
                  >
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
        <el-card shadow="never" class="mt-4">
          <div>
            <el-table
              :data="state.tableData"
              style="width: 100%"
              :span-method="objectSpanMethod"
              border
            >
              <el-table-column prop="sn" label="档案号" width="100">
              </el-table-column>
              <el-table-column prop="name" label="姓名"> </el-table-column>
              <el-table-column prop="gender" label="性别" width="60">
              </el-table-column>
              <el-table-column prop="age" label="年龄" width="60">
              </el-table-column>
              <el-table-column label="待办事项类型">
                <template #default="{ row }">
                  {{ state.constType[row.todoInfo?.type] }}
                </template>
              </el-table-column>
              <el-table-column label="待办事项内容">
                <template #default="{ row }">
                  {{ row.todoInfo?.content }}
                </template>
              </el-table-column>
              <el-table-column label="任务期望完成时间">
                <template #default="{ row }">
                  <div class="flex items-center">
                    {{ row.todoInfo?.startDate }} 至 {{ row.todoInfo?.endDate }}
                    <el-tag>{{
                      state.frequencyType[row.todoInfo?.frequencyType]
                    }}</el-tag>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="事项完成情况">
                <template #default="{ row }">
                  <div
                    v-for="item in row.todoInfo?.status"
                    :key="item.id"
                    class="flex items-center"
                  >
                    {{ item }}
                    <div v-if="row.todoInfo?.status.length == 1" class="pl-2">
                      <el-tag
                        v-if="!timeDiffer(row?.todoInfo?.endDate)"
                        type="success"
                        >今天</el-tag
                      >
                      <el-tag
                        v-if="timeDiffer(row?.todoInfo?.endDate) < 0"
                        type="danger"
                        >超时{{
                          Number(0 - timeDiffer(row?.todoInfo?.endDate))
                        }}天</el-tag
                      ><el-tag v-else
                        >{{ timeDiffer(row?.todoInfo?.endDate) }}天后</el-tag
                      >
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="age" label="操作">
                <template #default="{ row }">
                  <el-button type="primary" link @click="handleBacklog(row)"
                    >事项日历</el-button
                  >
                  <el-button type="primary" link @click="handleManage(row)"
                    >管理</el-button
                  >
                </template>
              </el-table-column>
            </el-table>

            <el-pagination
              class="justify-end mt-4"
              :current-page="state.query.page"
              :page-size="state.query.pageSize"
              :total="state.total"
              background
              layout="total, prev, pager, next, jumper"
              @current-change="
                page => {
                  state.query.page = page;
                  getList();
                }
              "
            ></el-pagination>
          </div>
        </el-card> -->
      </template>

      <!-- <ComponentDialogBacklog
        v-model:show="state.visibleBacklog"
        type="preview"
      ></ComponentDialogBacklog> -->
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, defineProps, defineEmits, watch } from "vue";
import { Search, ArrowUp, ArrowDown } from "@element-plus/icons-vue";
import { useRouter, useRoute } from "vue-router";
import { request, timeDiffer } from "@/utils";
const [route, router] = [useRoute(), useRouter()];
import moment from "moment";
import ComponentDialogBacklog from "./DialogBacklog.vue";
import ComponentTodoList from "../todoList.vue";
import { useManageProjectStoreHook } from "@/store/modules/manageProject";
const useManageProject = useManageProjectStoreHook();
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  }
});
const state = reactive({
  query: {
    page: 1,
    pageSize: 15,
    times: [
      moment().startOf("month").format("YYYY-MM-DD"),
      moment().endOf("month").format("YYYY-MM-DD")
    ],
    value: "",
    key: "",
    type: -1,
    status: -1
  },
  total: 0,
  tableData: [],
  constType: ["检查", "其他事项", "回访"],
  frequencyType: ["每天事项", "每周事项", "每月事项", "指定日期事项"],
  typeList: [
    {
      label: "检查",
      value: 0
    },
    {
      label: "回访",
      value: 2
    },
    {
      label: "其他事项",
      value: 1
    }
  ],
  statusList: {
    0: {
      label: "已完成",
      value: 0
    },
    1: {
      label: "待完成",
      value: 0
    },

    2: {
      label: "未完成",
      value: 0
    }
  },
  visibleBacklog: false
});
const mergeArr = ["sn", "name", "gender", "age"];
const mergeObj = {};
const emits = defineEmits(["update:show"]);
const dialogVisible = computed({
  get() {
    return props.show;
  },
  set(n) {
    emits("update:show", n);
  }
});

watch(
  () => dialogVisible.value,
  n => {
    if (n) {
      initData();
    } else {
    }
  }
);
const getSpanArr = data => {
  mergeArr.forEach((key, index1) => {
    let count = 0; // 用来记录需要合并行的起始位置
    mergeObj[key] = []; // 记录每一列的合并信息
    data.forEach((item, index) => {
      // index == 0表示数据为第一行，直接 push 一个 1
      if (index === 0) {
        mergeObj[key].push(1);
      } else {
        // 判断当前行是否与上一行其值相等 如果相等 在 count 记录的位置其值 +1 表示当前行需要合并 并push 一个 0 作为占位
        if (
          item[key] === data[index - 1][key] &&
          item["sn"] === data[index - 1]["sn"]
        ) {
          mergeObj[key][count] += 1;
          mergeObj[key].push(0);
        } else {
          // 如果当前行和上一行其值不相等
          count = index; // 记录当前位置
          mergeObj[key].push(1); // 重新push 一个 1
        }
      }
    });
  });
};
// 默认接受四个值 { 当前行的值, 当前列的值, 行的下标, 列的下标 }
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 判断列的属性
  if (mergeArr.indexOf(column.property) !== -1) {
    // 判断其值是不是为0
    if (mergeObj[column.property][rowIndex]) {
      return [mergeObj[column.property][rowIndex], 1];
    } else {
      // 如果为0则为需要合并的行
      return [0, 0];
    }
  }
};

const transformData = data => {
  const transformedData = [];

  data.forEach(item => {
    if (item.todoStatistics.length) {
      item.todoStatistics.forEach((info, index) => {
        transformedData.push({
          ...item,
          todoInfo: info
        });
      });
    } else {
      transformedData.push({
        ...item,
        todoInfo: {}
      });
    }
  });
  return transformedData;
};

const getList = () => {
  if (!state.query?.times.length) return;
  let [startDate, endDate] = state.query.times;
  request
    .get("/platformApi/dataService/diseaseManage/archives/todoDuration", {
      params: {
        startDate,
        endDate,
        type: state.query.type,
        status: state.query.status,
        key: state.query.key,
        value: state.query.value,
        page: state.query.page,
        pageSize: state.query.pageSize
      }
    })
    .then(resp => {
      state.tableData = transformData(resp?.data?.list);
      state.total = resp?.data?.total;
      getSpanArr(state.tableData);
    });
};
const initData = () => {
  getList();
};
const onSearch = () => {
  state.query.page = 1;
  getList();
};
const handleBacklog = row => {
  state.visibleBacklog = true;
  useManageProject.SET_CURRENT_ARCHIVES(row.sn);
};
const handleManage = row => {
  router.push(
    `/healthManagement/plan/detail?archivesId=${row.sn}&type=DiseaseVisit`
  );
};
</script>
