<template>
  <div>
    <el-card shadow="never">
      <el-row :gutter="10">
        <el-col :span="18">
          <el-row>
            <el-select
              multiple
              v-model="state.query.channelIds"
              placeholder="全部渠道"
              clearable
              style="width: 200px"
              class="mr-2"
            >
              <el-option
                v-for="item in channelList"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              />
            </el-select>
            <el-cascader
              v-model="state.query.groupIds"
              :props="selectGroupsProps"
              clearable
              placeholder="全部管理分组"
              :options="state.groups"
              class="mr-2"
            />
            <div class="mr-2">
              <el-date-picker
                v-model="state.query.times"
                type="daterange"
                clearable
                range-separator="至"
                value-format="YYYY-MM-DD"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              />
            </div>

            <!-- <el-cascader
              v-model="state.query.tagIds"
              :props="selectProps"
              clearable
              placeholder="请选择标签"
              :options="state.tagCategoryList"
            /> -->
            <el-select
              v-model="state.query.tagIds"
              placeholder="全部标签"
              filterable
              clearable
              multiple
            >
              <el-option
                v-for="item in state.tagCategoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-button type="primary" class="ml-2" @click="onSearch"
              >查询</el-button
            >
            <el-button type="primary" plain @click="onReset">重置</el-button>

            <!-- <el-button
              type="primary"
              link
              class="ml-2"
              @click="() => (state.visibleMore = !state.visibleMore)"
              :icon="state.visibleMore ? ArrowUp : ArrowDown"
              >{{ state.visibleMore ? "收起" : "展开" }}</el-button
            > -->
          </el-row>
          <!-- <el-row class="mt-2" v-if="state.visibleMore">
            <el-select
              multiple
              v-model="state.query.preventLevel"
              placeholder="全部预防级别"
              clearable
              style="width: 200px"
              class="mr-2"
            >
              <el-option
                v-for="item in levelList"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              />
            </el-select>
            <el-select
              multiple
              v-model="state.query.confirmedDiseases"
              placeholder="全部已确诊疾病"
              filterable
              clearable
              style="width: 200px"
              class="mr-2"
            >
              <el-option
                v-for="item in state.nodeList"
                :key="item.id"
                :label="item.properties?.name"
                :value="item.id"
              />
            </el-select>

            <el-select
              multiple
              v-model="state.query.highRiskDiseases"
              placeholder="全部高风险疾病"
              clearable
              filterable
              style="width: 200px"
              class="mr-2"
            >
              <el-option
                v-for="item in state.nodeList"
                :key="item.id"
                :label="item.properties?.name"
                :value="item.id"
              />
            </el-select>

            <el-select
              class="mr-2"
              multiple
              v-model="state.query.diseases"
              placeholder="全部管理中的疾病"
              clearable
              filterable
              style="width: 200px"
            >
              <el-option
                v-for="item in state.nodeList"
                :key="item.id"
                :label="item.properties?.name"
                :value="item.id"
              />
            </el-select>
          </el-row> -->
        </el-col>
        <el-col class="text-right" :span="6">
          <!-- <el-button
            type="primary"
            @click="state.visibleCurrentMonthBacklog = true"
            >本月待办事项列表</el-button
          > -->
          <div class="ml-2">
            <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>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-card shadow="never" class="mt-4">
      <div>
        <el-table :data="state.tableData" style="width: 100%" border>
          <el-table-column label="用户信息" width="150">
            <template #default="{ row }">
              <div>
                <el-text>{{ row.sn }}</el-text>
                <div class="mt-1">{{ row.name }}</div>
              </div>
              <div class="flex items-center">
                <el-button link type="primary" v-if="row.gender == '男'"
                  >男</el-button
                >
                <el-button type="danger" v-else link>女</el-button>
                <el-text class="">,{{ row.age }}岁</el-text>
              </div>
              <!-- <div class="mt-2 flex items-center">
                <el-text>年龄：</el-text>
                <el-text tag="b">{{ row.age }}岁</el-text>
              </div> -->
              <div class="mt-1 flex items-center">
                <div style="font-size: 12px">
                  <span v-for="(channel, index) in row.channels" :key="index"
                    >{{ channel }}
                    <span v-if="index < row.channels.length - 1">、</span>
                  </span>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="标签">
            <template #default="{ row }">
              <el-scrollbar>
                <div v-if="row?.tags?.length" style="width: 100%">
                  <el-space wrap>
                    <el-tag
                      class="mr-2"
                      v-for="(tag, index) in row.tags"
                      :key="tag + index"
                      >{{ tag }}</el-tag
                    >
                  </el-space>
                </div>
              </el-scrollbar>
            </template>
          </el-table-column>

          <el-table-column label="管理分组">
            <template #default="{ row }">
              <div>
                <el-tag class="mr-2" v-if="row?.managementInfo?.levelName">{{
                  formatLevel(row.managementInfo?.levelName)
                }}</el-tag>
                {{ row?.managementInfo?.groupName }}
              </div>
            </template>
          </el-table-column>

          <el-table-column label="现存主要问题">
            <template #default="{ row }">
              <div v-if="row?.managementInfo?.focus?.length">
                <el-tag
                  v-for="(item, index) in row?.managementInfo?.focus"
                  :key="index"
                  class="mr-2"
                  >{{ item }}</el-tag
                >
              </div>
            </template>
          </el-table-column>

          <el-table-column label="目前健康状况">
            <template #default="{ row }">
              <div v-if="row?.managementInfo?.level">
                <span
                  :style="{
                    color: managementEffect[row?.managementInfo?.effect['程度']]
                  }"
                >
                  {{ row?.managementInfo?.effect?.name }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="评估时间"
            :formatter="v => v?.managementInfo?.createdAt?.split(' ')[0]"
          />
          <el-table-column
            label="下阶段管理目标"
            :formatter="v => v?.managementInfo?.target"
          />
          <el-table-column label="下阶段评估时间">
            <template #default="{ row }">
              <div v-if="row.status">
                <el-text tag="b">已暂停管理</el-text>
              </div>
              <div v-else>
                <span
                  v-if="
                    moment().format('YYYY-MM-DD') ==
                    row?.managementInfo?.nextTime?.split(' ')[0]
                  "
                  style="color: #67c23a"
                >
                  今天 （{{
                    row?.managementInfo?.nextTime?.split(" ")[0]
                  }}）</span
                >
                <span
                  v-else-if="
                    moment().valueOf() >
                    moment(
                      row?.managementInfo?.nextTime?.split(' ')[0].valueOf()
                    )
                  "
                  style="color: #f56c6c"
                >
                  超时{{
                    Number(
                      0 -
                        timeDiffer(row?.managementInfo?.nextTime?.split(" ")[0])
                    )
                  }}天 （{{
                    row?.managementInfo?.nextTime?.split(" ")[0]
                  }}）</span
                >
                <span v-else-if="!row?.managementInfo?.nextTime">-</span>
                <span v-else
                  >还剩{{
                    timeDiffer(row?.managementInfo?.nextTime?.split(" ")[0])
                  }}天（{{
                    row?.managementInfo?.nextTime?.split(" ")[0]
                  }}）</span
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="" label="操作">
            <template #default="{ row }">
              <Auth value="headlthManage:todoList:view">
                <el-button type="primary" link @click="handleBacklog(row)"
                  >待办事项</el-button
                >
              </Auth>
              <Auth value="healthManage">
                <el-button type="primary" link @click="handleManage(row)"
                  >管理</el-button
                >
              </Auth>
            </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"
    />

    <ComponentDialogCurrentMonthBacklog
      v-model:show="state.visibleCurrentMonthBacklog"
    />
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, 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 ComponentDialogBacklog from "./components/DialogBacklog.vue";
import ComponentDialogCurrentMonthBacklog from "./components/DialogCurrentMonthBacklog.vue";
import ComponentCopy from "@/components/Copy/index.vue";
import {
  manageLevel,
  managementEffect,
  formatLevel
} from "@/enums/managementPlan.ts";

import type { CascaderProps } from "element-plus";

import { useManageProjectStoreHook } from "@/store/modules/manageProject";
import moment from "moment";
const useManageProject = useManageProjectStoreHook();
const state = reactive({
  query: {
    page: 1,
    pageSize: 15,
    peopleType: [],
    preventLevel: [],
    channelIds: [],
    groupIds: [],
    times: [],
    value: "",
    key: "",
    confirmedDiseases: [], //  确诊疾病id多选，多个使用,隔开
    highRiskDiseases: [], // 高风险疾病id多选，多个使用,隔开
    diseases: [], // 多选疾病名称，多个使用,隔开
    tagIds: []
  },
  total: 0,
  nodeList: [],
  tableData: [],
  visibleBacklog: false,
  rowData: {},
  visibleMore: false,
  tagCategoryList: [], // 标签类别
  groups: [],
  visibleCurrentMonthBacklog: false
});
const mergeArr = ["sn", "name", "gender", "age", " "];
const mergeObj = {};
const peopleTypeList = [
  {
    label: "有已确诊疾病人群",
    value: 3
  },
  {
    label: "有高风险疾病人群",
    value: 1
  },
  {
    label: "有正在服药人群",
    value: 4
  },
  {
    label: "有易感疾病基因携带人群",
    value: 2
  },
  {
    label: "有管理中的疾病人群",
    value: 5
  },
  {
    label: "无管理中的疾病人群",
    value: 6
  }
];
const channelList = ref([]);
const levelList = manageLevel;
const getChannelList = () => {
  request
    .get("archivesService/mechanism/channel/paginate?key=&page=1&pageSize=9999")
    .then(res => {
      channelList.value = res.data.list;
    });
};
const getList = () => {
  let startTime = undefined;
  let endTime = undefined;
  let tagIds = [];
  let groupIds = undefined;
  if (state.query?.times?.length) {
    [startTime, endTime] = state.query.times;
  } else {
    [startTime, endTime] = [undefined, undefined];
  }
  if (state.query.tagIds?.length) {
    tagIds = state.query.tagIds?.join(",");
  } else {
    tagIds = undefined;
  }
  if (state.query.groupIds?.length) {
    groupIds = state.query.groupIds?.map(v => v[1])?.join(",");
  } else {
    groupIds = undefined;
  }
  request
    .get("/platformApi/dataService/diseaseManage/paginate", {
      params: {
        key: state.query.key,
        value: state.query.value,
        page: state.query.page,
        pageSize: state.query.pageSize,
        channelIds: state.query.channelIds?.join(","),
        groupIds: groupIds,
        // levels: state.query.preventLevel.join(","),
        start: startTime,
        end: endTime,
        tagIds: tagIds
      }
    })
    .then(resp => {
      state.tableData = transformData(resp.data.list);
      state.total = resp.data.total;
      getSpanArr(state.tableData);

      console.log(state.tableData);
    });
};

const getNodeList = () => {
  request
    .get("/platformApi/graphService/open/node/paginate", {
      params: {
        pageSize: 9999,
        tag: "可管理"
      }
    })
    .then(resp => {
      state.nodeList = resp.data.list;
    });
};
const onSearch = () => {
  state.query.page = 1;
  getList();
};
const onReset = () => {
  state.query.channelIds = [];
  state.query.groupIds = [];
  state.query.tagIds = [];
  state.query.times = [];
  state.query.value = "";
  state.query.key = "";
  onSearch();
};
const handleBacklog = row => {
  state.visibleBacklog = true;
  state.rowData = row;
  useManageProject?.SET_CURRENT_ARCHIVES(row.sn);
};
const handleManage = row => {
  // router.push("/archives/assess");

  useManageProject?.SET_CURRENT_ARCHIVES(row.sn);
  router.push(`/healthManagement/plan/detail?archivesId=${row.sn}`);
};
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.managements.length) {
      item.managements.forEach((management, index) => {
        transformedData.push({
          ...item,
          managementInfo: management
        });
      });
    } else {
      transformedData.push({
        ...item,
        managementInfo: {}
      });
    }
  });
  return transformedData;
};
const getTagCategoryList = () => {
  request
    .get("dataService/schemeManage/tag/paginate?page=1&pageSize=999")
    .then(resp => {
      state.tagCategoryList = resp.data.list;
    });
};
const getTagList = id => {
  if (!id) return;
  return new Promise(resolve => {
    request
      .get(`/tagService/mechanism/tag/list?categoryId=${id}&type=1`)
      .then(resp => {
        resolve(resp.data.list);
      });
  });
};
const getGroups = () => {
  request.get("dataService/schemeManage/diseaseManageLevels").then(resp => {
    state.groups = resp.data?.map(v => {
      return {
        ...v,
        value: v.id,
        label: v.title
      };
    });
  });
};
const getDiseaseManageGroup = value => {
  if (!value) return;
  return new Promise(resolve => {
    request
      .get(`dataService/schemeManage/diseaseManageGroup/paginate`, {
        params: {
          levelId: value,
          pageSize: 999
        }
      })
      .then(resp => {
        resolve(resp.data.list);
      });
  });
};

const selectProps: CascaderProps = {
  lazy: true,
  multiple: true,
  lazyLoad: async (node, resolve) => {
    const { value } = node;
    let list = await getTagList(value);
    console.log(list);
    list = list?.map(v => {
      return {
        ...v,
        value: v.id,
        label: v.name,
        leaf: true
      };
    });
    console.log("list", list);

    // Invoke `resolve` callback to return the child nodes data and indicate the loading is finished.
    resolve(list);
  }
};
const selectGroupsProps: CascaderProps = {
  lazy: true,
  multiple: true,
  lazyLoad: async (node, resolve) => {
    const { value } = node;
    let list = await getDiseaseManageGroup(value);
    list = list?.map(v => {
      return {
        ...v,
        value: v.id,
        label: v.name,
        leaf: true
      };
    });
    resolve(list);
  }
};
// watch(
//   () => [
//     state.query.peopleType,
//     state.query.preventLevel,
//     state.query.confirmedDiseases,
//     state.query.highRiskDiseases,
//     state.query.diseases,
//     state.query.tagIds
//   ],
//   () => {
//     console.log("监听成功");

//     onSearch();
//   },
//   { deep: true }
// );
const initData = () => {
  getNodeList();
  getList();
  getGroups();
  getTagCategoryList();
  getChannelList();
};
initData();
</script>
