<template>
  <div>
    <el-card title="" v-model="dialogVisible" :show-close="false" fullscreen>
      <template #header>
        <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"
                  :shortcuts="shortcuts"
                  :clearable="false"
                />
                <el-select
                  v-model="state.query.type"
                  placeholder="全部事项类型"
                  filterable
                  class="ml-2"
                >
                  <el-option label="全部事项类型" :value="-1" />
                  <el-option
                    v-for="item in state.typeList"
                    :key="item.value"
                    :label="item.key"
                    :value="item.value"
                  />
                </el-select>
                <el-select
                  v-model="state.query.status"
                  placeholder="全部完成状态"
                  filterable
                  class="ml-2"
                >
                  <el-option label="全部状态" :value="-1" />
                  <el-option
                    v-for="item in state.statusList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </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>
                      <div class="flex">
                        <el-button :icon="Search" @click="onSearch"
                          >查询</el-button
                        >
                      </div>
                    </template>
                  </el-input>
                  <el-button class="ml-2" type="info" plain @click="onRefresh"
                    >重置</el-button
                  >

                  <!-- <el-button
                    class="ml-10"
                    type="danger"
                    plain
                    @click="dialogVisible = false"
                    >关闭</el-button
                  > -->
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </template>

      <el-card shadow="never" class="mt-4">
        <div>
          <el-table :data="state.tableData" style="width: 100%" border>
            <el-table-column prop="sn" label="档案号" width="100" />
            <el-table-column label="待办事项类型" width="140">
              <template #default="{ row }">
                <div>
                  {{ row.name }}
                  <div class="text-sm" style="font-size: 12px">
                    {{ row.gender }}，{{ row.age }}岁
                  </div>
                </div>
              </template>
            </el-table-column>

            <!-- <el-table-column prop="name" label="姓名" width="100" />
            <el-table-column prop="gender" label="性别" width="60" />
            <el-table-column prop="age" label="年龄" width="60" /> -->
            <el-table-column label="待办事项类型" width="140">
              <template #default="{ row }">
                <div
                  class="todo-tag"
                  :style="`border: 1px solid ${
                    state.constType[row.todoInfo?.type]?.color
                  }; color: ${state.constType[row.todoInfo?.type]?.color}`"
                >
                  {{ state.constType[row.todoInfo?.type]?.name }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="theme" label="事项主题">
              <template #default="{ row }">
                <div>{{ row.todoInfo.theme }}</div>
              </template>
            </el-table-column>

            <el-table-column prop="content" label="事项内容">
              <template #default="{ row }">
                <div v-if="row.todoInfo.type == 2">
                  <el-space wrap>
                    <div v-if="row.todoInfo?.content?.questions?.length">
                      随访问卷
                    </div>
                    <div v-if="row.todoInfo?.content?.healthGuidance">
                      随访健康指导
                    </div>
                  </el-space>
                </div>
                <div v-else-if="row.todoInfo.type == 0">
                  {{ row.todoInfo.content }}
                </div>
                <div v-else>
                  <el-space wrap>
                    <div v-for="item in row.todoInfo.content" :key="item.id">
                      <el-tag plain> {{ item.properties.name }}</el-tag>
                    </div>
                  </el-space>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="事项期望完成时间" width="200">
              <template #default="{ row }">
                <div class="flex items-center">
                  <el-text
                    v-if="row.todoInfo?.startDate === row.todoInfo?.endDate"
                    >{{ row.todoInfo?.startDate }}</el-text
                  >
                  <el-text v-else>
                    {{ row.todoInfo?.startDate }} 至
                    {{ row.todoInfo?.endDate }}
                  </el-text>

                  <!-- <el-tag>{{
                      state.frequencyType[row.todoInfo?.frequencyType]
                    }}</el-tag> -->
                </div>
              </template>
            </el-table-column>
            <el-table-column label="事项完成情况">
              <template #default="{ row }">
                <div class="flex items-center">
                  <template
                    v-if="row.todoInfo?.startDate !== row.todoInfo?.endDate"
                  >
                    <el-tag type="success" class="mr-2 mt-2">
                      {{ row.todoInfo.statusMap?.completed }}次已完成</el-tag
                    >
                    <el-tag type="info" class="mr-2 mt-2"
                      >{{ row.todoInfo.statusMap?.incomplete }}次未完成</el-tag
                    >
                    <el-tag class="mr-2 mt-2"
                      >{{ row.todoInfo.statusMap?.todo }}次待完成</el-tag
                    >
                  </template>
                  <template v-else>
                    <div class="flex items-center">
                      <el-tag
                        type="success"
                        v-if="row.todoInfo.statusMap?.completed"
                        class="mr-2 mt-2"
                      >
                        已完成</el-tag
                      >
                      <el-tag
                        type="info"
                        v-if="row.todoInfo.statusMap?.incomplete"
                        class="mr-2 mt-2"
                        >未完成</el-tag
                      >
                      <el-tag
                        v-if="row.todoInfo.statusMap?.todo"
                        class="mr-2 mt-2"
                        >待完成</el-tag
                      >
                      <div
                        v-if="!row.todoInfo?.statusMap?.completed"
                        class="pl-2 mt-2"
                      >
                        <el-tag
                          v-if="!timeDiffer(row?.todoInfo?.endDate)"
                          type="success"
                          class="mr-2"
                          >今天</el-tag
                        >
                        <el-tag
                          v-if="timeDiffer(row?.todoInfo?.endDate) < 0"
                          type="danger"
                          class="mr-2"
                          >超时{{
                            Number(0 - timeDiffer(row?.todoInfo?.endDate))
                          }}天</el-tag
                        >
                        <div v-else>
                          <el-tag
                            class="mr-2"
                            v-if="timeDiffer(row?.todoInfo?.endDate)"
                            >{{
                              timeDiffer(row?.todoInfo?.endDate)
                            }}天后</el-tag
                          >
                        </div>
                      </div>
                    </div>
                  </template>
                  <el-text style="font-size: 11px" class="mt-2">{{
                    row.todoInfo.comment
                  }}</el-text>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="age" label="操作" width="100">
              <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();
              }
            "
          />
        </div>
      </el-card>

      <ComponentDialogBacklog
        v-model:show="state.visibleBacklog"
        type="preview"
        :complateTime="state.rowData.todoInfo?.startDate"
        @success="getList()"
      />
    </el-card>
  </div>
</template>
<script lang="ts" setup>
import { reactive, computed, defineProps, defineEmits, onMounted } from "vue";
import { Search } 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 "./components/DialogBacklog.vue";

import { useManageProjectStoreHook } from "@/store/modules/manageProject";
import { useUserStoreHook } from "@/store/modules/user";

const useManageProject = useManageProjectStoreHook();
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  }
});
const initStart = moment().startOf("isoWeek");
const initEnd = moment().endOf("isoWeek");

const state = reactive({
  query: {
    page: 1,
    pageSize: 15,
    times: [
      moment(initStart).format("YYYY-MM-DD"),
      moment(initEnd).format("YYYY-MM-DD")
    ],
    value: "",
    key: "",
    type: -1,
    status: -1
  },
  rowData: {},
  total: 0,
  tableData: [],
  constType: [
    {
      name: "其他事项",
      color: "#6CAD1F"
    },
    {
      name: "复查",
      color: "#FC40FF"
    },
    {
      name: "随访",
      color: "#5EBCFB"
    },
    {
      name: "日常监测",
      color: "#F56C6C"
    }
  ],
  frequencyType: ["每天事项", "每周事项", "每月事项", "指定日期事项"],
  typeList: [
    {
      key: "复查",
      value: 1
    },
    {
      key: "随访",
      value: 2
    },
    {
      key: "日常监测",
      value: 3
    },

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

    // {
    //   key: "检查",
    //   value: 4
    // },
    // {
    //   key: "回访",
    //   value: 5
    // }
  ],
  statusList: {
    0: {
      label: "未完成",
      value: 0
    },
    1: {
      label: "待完成",
      value: 1
    },

    2: {
      label: "已完成",
      value: 2
    }
  },
  visibleBacklog: false
});
const mergeArr = ["sn", "name", "gender", "age"];
const mergeObj = {};
const emits = defineEmits(["update:show"]);

const shortcuts = [
  {
    text: "本周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [initStart, initEnd];
    }
  },
  {
    text: "本月",
    value: () => {
      return [
        moment().startOf("month").format("YYYY-MM-DD"),
        moment().endOf("month").format("YYYY-MM-DD")
      ];
    }
  },
  {
    text: "上个月",
    value: () => {
      return [
        moment().subtract(1, "months").startOf("month").format("YYYY-MM-DD"),
        moment().subtract(1, "months").endOf("month").format("YYYY-MM-DD")
      ];
    }
  },
  {
    text: "上三个月",
    value: () => {
      return [
        moment().subtract(3, "months").startOf("month").format("YYYY-MM-DD"),
        moment().startOf("month").format("YYYY-MM-DD")
      ];
    }
  },
  {
    text: "上六个月",
    value: () => {
      return [
        moment().subtract(6, "months").startOf("month").format("YYYY-MM-DD"),
        moment().startOf("month").format("YYYY-MM-DD")
      ];
    }
  },
  {
    text: "下个月",
    value: () => {
      return [
        moment().add(1, "months").startOf("month").format("YYYY-MM-DD"),
        moment().add(1, "months").endOf("month").format("YYYY-MM-DD")
      ];
    }
  },
  {
    text: "下三个月",
    value: () => {
      return [
        moment().startOf("month").format("YYYY-MM-DD"),
        moment().add(3, "months").startOf("month").format("YYYY-MM-DD")
      ];
    }
  },
  {
    text: "下六个月",

    value: () => {
      return [
        moment().startOf("month").format("YYYY-MM-DD"),
        moment().add(6, "months").startOf("month").format("YYYY-MM-DD")
      ];
    }
  }
];

const dialogVisible = computed({
  get() {
    return props.show;
  },
  set(n) {
    emits("update:show", n);
  }
});

onMounted(() => {
  initData();
});
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 => {
  if (!data) return [];
  const transformedData = [];

  data.forEach(item => {
    if (!item.scheduleStatistics) {
      item.scheduleStatistics = [];
    }

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

const getList = () => {
  if (!state.query?.times.length) return;
  const [startDate, endDate] = state.query.times;
  request
    .get("dataService/schedule/archive/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 onRefresh = () => {
  state.query = {
    page: 1,
    pageSize: 15,
    times: [
      // moment().startOf("month").format("YYYY-MM-DD"),
      // moment().endOf("month").format("YYYY-MM-DD")
      moment(initStart).format("YYYY-MM-DD"),
      moment(initEnd).format("YYYY-MM-DD")
    ],
    value: "",
    key: "",
    type: -1,
    status: -1
  };
  initData();
};
const handleBacklog = row => {
  state.visibleBacklog = true;
  state.rowData = row;
  useManageProject.SET_CURRENT_ARCHIVES(row.sn);
};
const handleManage = row => {
  const profile = useUserStoreHook()?.profile as any;
  console.log("profile", profile);
  if (!profile?.nickname) {
    return;
  }
  const permissions = profile?.permissions;
  if (profile?.isSuper == 1 || permissions.includes("archives:managePlan")) {
    return router.push(
      `/healthManagement/plan/detail?archivesId=${row.sn}&type=DiseaseVisit`
    );
  }
  if (permissions.includes("archives:managePlanHealth")) {
    useManageProject?.SET_CURRENT_ARCHIVES(row.sn);
    router.push({
      path: "/healthManagement/plan/detail",
      query: {
        archivesId: row.sn,
        type: "health"
      }
    });
  }
  return;
  router.push(
    `/healthManagement/plan/detail?archivesId=${row.sn}&type=DiseaseVisit`
  );
};
</script>
<style lang="scss" scoped>
.todo-tag {
  display: inline-block;
  padding: 2px 10px;
  border-radius: 4px;
}
</style>
