<template>
  <div
    class="page-archives-module"
    :class="{
      'pb-32': !props.isPlat
    }"
  >
    <div
      v-if="curIdx >= 0"
      class="mx-4"
      :class="{
        'rounded-lg bg-white': props.isPlat
      }"
    >
      <div
        v-for="(item, index) in list"
        :key="index"
        :class="{
          'py-2 px-4 border-0 border-b last:border-b-0 hover:bg-gray-50 border-gray-100 border-solid':
            props.isPlat,
          'py-2 px-4 bg-white mb-2 rounded-lg': !props.isPlat,
          'active:bg-gray-100': !props.isPlat && !item.isModule
        }"
        @click="goEditArchives(item)"
      >
        <div v-if="!props.isPlat && item.isModule" class="border-0">
          <div class="text-lg leading-8">{{ item.name }}</div>
          <div
            v-for="(child, childIdx) in item.children"
            :key="childIdx"
            class="py-2 px-4 border-0 border-b last:border-b-0 active:bg-gray-100 border-gray-100 border-solid"
            @click="goEditArchives(child)"
          >
            <div class="flex flex-row justify-between items-center">
              <div>
                <div class="text-lg leading-8">{{ child.name }}</div>
                <div class="text-gray-500 text-base">
                  <div
                    v-for="(
                      moduleVal, moduleValIndex
                    ) in formateArchivesModuleValue(child, false)"
                    :key="moduleValIndex"
                  >
                    <template v-if="moduleVal.isPlaceholder">
                      <div v-html="moduleVal.value" :style="moduleVal.style"></div
                    ></template>
                    <template v-else>
                      <span>{{ moduleVal.label }}</span>
                      <template v-if="moduleVal.opt?.isFile">
                        <span class="align-middle">：</span>
                        <div
                          v-for="(val, valIdx) in moduleVal.value"
                          :key="valIdx"
                          class="inline-block mr-2 drop-shadow"
                        >
                          <el-image
                            v-if="moduleVal.opt?.isImage(val.url)"
                            :src="val.url"
                            :alt="val.name"
                            :preview-src-list="moduleVal.value.map(v => v.url)"
                            preview-teleported
                            :initial-index="valIdx"
                            fit="cover"
                            class="h-12 w-12 rounded align-middle"
                          ></el-image>
                          <el-button
                            v-else
                            class="align-middle"
                            type="primary"
                            link
                            tag="a"
                            :download="val.name"
                            :href="
                              val.url +
                              '?response-content-type=application/octet-stream'
                            "
                            target="_blank"
                            >下载附件</el-button
                          >
                        </div>
                      </template>
                      <span v-else class="text-gray-400"
                        >：{{ moduleVal.value }}{{ moduleVal.unit }}</span
                      >
                      <div v-if="moduleVal.date">
                        <span>检查时间：</span
                        ><span class="text-gray-400">{{ moduleVal.date }}</span>
                      </div>
                    </template>
                  </div>
                </div>
              </div>
              <ArrowRight
                v-if="!!(route.query.isSelf || route.query.isOwner)"
                class="text-gray-400"
              />
            </div>
          </div>
        </div>
        <div v-else class="flex flex-row justify-between items-center">
          <div>
            <div class="text-lg leading-8">{{ item.name }}</div>
            <div v-if="item.isModule" class="pl-4">
              <div v-for="(child, childIdx) in item.children" :key="childIdx">
                <div>
                  <div
                    v-for="(
                      moduleVal, moduleValIndex
                    ) in formateArchivesModuleValue(child, false)"
                    :key="moduleValIndex"
                    class="py-2"
                    :class="{
                      'pl-2': moduleVal.isChild
                    }"
                  >
                    <template v-if="moduleVal.isPlaceholder">
                      <div v-html="moduleVal.value" :style="moduleVal.style"></div
                    ></template>
                    <template v-else>
                      <span>{{ moduleVal.label }}</span>
                      <template v-if="!moduleVal.isLabel">
                        <template v-if="moduleVal.opt?.isFile">
                          <span class="align-middle">：</span>
                          <div
                            v-for="(val, valIdx) in moduleVal.value"
                            :key="valIdx"
                            class="inline-block mr-2 drop-shadow"
                          >
                            <el-image
                              v-if="moduleVal.opt?.isImage(val.url)"
                              :src="val.url"
                              :alt="val.name"
                              :preview-src-list="
                                moduleVal.value.map(v => v.url)
                              "
                              preview-teleported
                              :initial-index="valIdx"
                              fit="cover"
                              class="h-12 w-12 rounded align-middle"
                            ></el-image>
                            <el-button
                              v-else
                              class="align-middle"
                              type="primary"
                              link
                              tag="a"
                              :download="val.name"
                              :href="
                                val.url +
                                '?response-content-type=application/octet-stream'
                              "
                              target="_blank"
                              >下载附件</el-button
                            >
                          </div>
                        </template>
                        <span v-else class="text-gray-400"
                          >：{{ moduleVal.value }}{{ moduleVal.unit }}</span
                        >
                      </template>
                      <div v-if="moduleVal.date">
                        <span>检查时间：</span
                        ><span class="text-gray-400">{{ moduleVal.date }}</span>
                      </div>
                    </template>
                  </div>
                </div>
              </div>
              <div
                v-if="!item.children.find(v => v.hasValue)"
                class="text-gray-400"
              >
                暂未填写
              </div>
            </div>
            <div v-else class="text-gray-500 text-base">
              <div
                v-for="(
                  moduleVal, moduleValIndex
                ) in formateArchivesModuleValue(item, false)"
                :key="moduleValIndex"
              >
                <template v-if="moduleVal.isPlaceholder">
                  <div v-html="moduleVal.value" :style="moduleVal.style"></div
                ></template>
                <template v-else>
                  <span>{{ moduleVal.label }}</span>
                  <template v-if="!moduleVal.isLabel">
                    <template v-if="moduleVal.opt?.isFile">
                      <span class="align-middle">：</span>
                      <div
                        v-for="(val, valIdx) in moduleVal.value"
                        :key="valIdx"
                        class="inline-block mr-2 drop-shadow"
                      >
                        <el-image
                          v-if="moduleVal.opt?.isImage(val.url)"
                          :src="val.url"
                          :alt="val.name"
                          :preview-src-list="moduleVal.value.map(v => v.url)"
                          preview-teleported
                          :initial-index="valIdx"
                          fit="cover"
                          class="h-12 w-12 rounded align-middle"
                        ></el-image>
                        <el-button
                          v-else
                          class="align-middle"
                          type="primary"
                          link
                          tag="a"
                          :download="val.name"
                          :href="
                            val.url +
                            '?response-content-type=application/octet-stream'
                          "
                          target="_blank"
                          >下载附件</el-button
                        >
                      </div>
                    </template>
                    <span v-else class="text-gray-400"
                      >：{{ moduleVal.value }}{{ moduleVal.unit }}</span
                    >
                  </template>
                  <div v-if="moduleVal.date">
                    <span>检查时间：</span
                    ><span class="text-gray-400">{{ moduleVal.date }}</span>
                  </div>
                </template>
              </div>

              <div v-if="!item.hasValue" class="text-gray-400">暂未填写</div>
            </div>
          </div>
          <div v-if="props.isPlat">
            <el-button type="primary" link @click="editArchivesModule(item)"
              >编辑数据</el-button
            >
            <!-- <el-button type="primary" link @click="item.type == 2 ? showPatIndicator(item) : editArchivesModule(item)">查看历史数据</el-button> -->
          </div>
          <ArrowRight
            v-else-if="
              !item.isModule && !!(route.query.isSelf || route.query.isOwner)
            "
            class="text-gray-400"
          />
        </div>
      </div>
    </div>

    <el-dialog
      v-model="platEditFileConfig.show"
      :title="platEditFileConfig.indicator?.name"
      fullscreen
      style="width: 50%; margin-right: 0"
    >
      <div class="p-4">
        <EditArchivesModule
          v-if="platEditFileConfig.show"
          is-plat
          :indicator="platEditFileConfig.indicator"
          :id="platEditFileConfig.id"
          :module-id="platEditFileConfig.moduleId"
          @close="editFileClose"
        />
      </div>
    </el-dialog>

    <el-drawer
      v-model="submoduleConfig.show"
      direction="rtl"
      class="filter-container w-full rounded-l-lg"
      :with-header="false"
      size="60%"
    >
      <h3 class="text-xl mb-4">{{ submoduleConfig.name }}</h3>
      <div class="rounded-lg bg-gray-50 overflow-hidden">
        <div
          v-for="(item, index) in submoduleConfig.list"
          :key="index"
          class="py-2 px-4 border-0 border-b last:border-b-0 hover:bg-gray-100 border-gray-200 border-solid"
        >
          <div class="flex flex-row justify-between items-center">
            <div>
              <div class="text-lg leading-8">{{ item.name }}</div>
              <div class="text-gray-500 text-base">
                <div
                  v-for="(
                    moduleVal, moduleValIndex
                  ) in formateArchivesModuleValue(item, true)"
                  :key="moduleValIndex"
                >
                  <span>{{ moduleVal.label }}</span>
                  <span class="text-gray-400"
                    >：{{ moduleVal.value }}{{ moduleVal.unit }}</span
                  >
                  <div v-if="moduleVal.date">
                    <span>检查时间：</span
                    ><span class="text-gray-400">{{ moduleVal.date }}</span>
                  </div>
                </div>
                <div v-if="!item.hasValue" class="text-gray-400">暂未填写</div>
              </div>
            </div>
            <el-button type="primary" link @click="editArchivesModule(item)"
              >编辑数据</el-button
            >
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script setup>
import {
  computed,
  watch,
  ref,
  reactive,
  inject,
  onActivated,
  onMounted,
  defineAsyncComponent
} from "vue";
import { useRoute, useRouter } from "vue-router";
import { request, formateArchivesModuleValue, deepClone } from "@/utils";
import EditArchivesModule from "./EditArchivesModule.vue";

import { ArrowRight } from "@element-plus/icons-vue";
const props = defineProps({
  isPlat: {
    type: Boolean,
    default: false
  },
  form: {
    type: Object,
    default: undefined
  },
  moduleId: {
    type: String,
    default: undefined
  }
});
const list = ref([]);
const test = ref();

const route = useRoute();
const router = useRouter();
const curIdx = ref(0);
const moduleList = ref([]);

const getMobileModules = async (isInit = true) => {
  const { data } = await request.get(`/archivesService/api/module/list`);
  const moduleMenu = data.list?.map(v => {
    return {
      icon: v.icon,
      selectIcon: v.icon,
      name: v.name,
      id: v.id,
      value: v.id
    };
  });
  moduleList.value = moduleMenu;
  moduleList.value.length && isInit && fetchModuleIndicators();
};

const fetchModuleIndicators = async () => {
  list.value = props?.form?.fields || [];
  console.log(list.value);
  list.value?.length && getFillFormData();
};
const transferRawJson = inject("transferRawJson");
const getFillFormData = async () => {
  const returnAnswer = {};
  (transferRawJson.value || []).forEach((v, k) => {
    returnAnswer[v.answer?.questionNo] = v.answer;
  });
  console.log("return answer", returnAnswer);

  fillFormData(list.value, returnAnswer);
  console.log("test", list.value);
};
const fillFormData = (arr, data) => {
  arr.forEach(v => {
    if (v.fields?.length) {
      v.fields.forEach(filed => {
        if (filed.extra?.subjects) {
          filed.extra?.subjects.forEach(subject => {
            subject.returnAnswer = data[subject.sn];
          });
        } else {
          if (filed.extra?.sn) {
            filed.extra.returnAnswer = data[filed.extra.sn];
          }
        }
      });
    }
    if (v.extra?.subjects) {
      v.extra?.subjects.forEach(subject => {
        subject.returnAnswer = data[subject.sn];
      });
    } else {
      if (v.extra?.sn) {
        v.extra.returnAnswer = data[v.extra.sn];
      }
    }
  });
  return arr;
};
watch(
  () => [props.form, transferRawJson.value],
  () => {
    fetchModuleIndicators();
  },
  {
    immediate: true
  }
);
const back = () => {
  router.back();
};
const transformData = list => {
  const result = [];
  const pId = {};
  list.forEach((v, k) => {
    if (!v.parentId) {
      return result.push(v);
    }
    if (!pId[v.parentId] && pId[v.parentId] !== 0) {
      pId[v.parentId] = result.length;
      result.push({
        ...v.parent,
        isModule: true,
        children: [v]
      });
    } else {
      result[pId[v.parentId]].children.push(v);
    }
  });
  return result;
};

const changeHealthFile = async (item, index) => {
  curIdx.value = index;
  if (index > -1) {
    fetchModuleIndicators();
  }
};
const editFileClose = async (flag = false) => {
  platEditFileConfig.show = flag;
  console.log("触发close");
  await fetchModuleIndicators();
  if (submoduleConfig.show) {
    submoduleConfig.list =
      list.value.find(v => submoduleConfig.id == v.id)?.fields || [];
  }
};

const platEditFileConfig = reactive({
  show: false,
  id: "",
  indicator: undefined,
  moduleId: undefined
});
const submoduleConfig = reactive({
  show: false,
  id: "",
  list: [],
  name: ""
});
const goEditArchives = item => {
  if (item.isModule || props.isPlat) {
    return;
  }
  editArchivesModule(item);
};
const editArchivesModule = item => {
  if (item.type == 1) {
    submoduleConfig.list = item.fields || [];
    submoduleConfig.name = item.name;
    submoduleConfig.id = item.id;
    submoduleConfig.show = true;
    console.log(item);
  } else if (props.isPlat) {
    platEditFileConfig.id = props.id;
    platEditFileConfig.moduleId = props.moduleId;
    platEditFileConfig.indicator = item;
    platEditFileConfig.show = true;
    console.log(platEditFileConfig);
  } else {
  }
};
const platIndicatorHistory = reactive({
  show: false,
  id: "",
  archivesId: "",
  label: "",
  unit: "",
  total: 0,
  item: undefined,
  list: []
});

const getPlatIndicatorHistory = async () => {
  const { data } = await request.get(
    `/archivesServiceV2/mechanism/archives/indicator/history/list`,
    {
      params: {
        extraId: platIndicatorHistory.id,
        type: 2,
        archivesId: platIndicatorHistory.archivesId
      }
    }
  );
  platIndicatorHistory.list = (data.list || []).map(v => {
    const temp = deepClone(platIndicatorHistory.item);
    temp.archivesIndicator.surveyTemplateRawValue = v.surveyTemplateRawValue;

    return {
      ...v,
      values: formateArchivesModuleValue(temp)
    };
  });
  console.log(platIndicatorHistory.list);
};
const showPatIndicator = item => {
  platIndicatorHistory.label = item.name;
  platIndicatorHistory.unit = item.unit;
  platIndicatorHistory.id = item.extraId;
  platIndicatorHistory.item = item;
  console.log(item);

  platIndicatorHistory.archivesId = props.isPlat ? props.id : route.query.id;
  getPlatIndicatorHistory();
  platIndicatorHistory.show = true;
};

onActivated(() => {
  const refreshArchives = !!sessionStorage.getItem("refreshArchives");
  refreshArchives && fetchModuleIndicators();
});
</script>
<style lang="scss">
.page-archives-module {
  .healthy-file-list {
    padding: 15px;
    white-space: nowrap;
    overflow: hidden;
    overflow-x: auto;
    background-color: #f6f6f6;
    .healthy-file-item {
      display: inline-flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      background: #fff;
      border-radius: 8px;
      padding: 10px;
      font-size: 14px;
      box-shadow: 0px 3px 9px 1px rgba(175, 202, 222, 0.16);
      border: 1px solid #fff;
      &:not(:last-of-type) {
        margin-right: 10px;
      }
      &.active {
        color: #4b72f6;
        background: #fff;
        border: 1px solid #4b72f6;
        box-shadow: 0px 3px 6px 1px rgba(68, 68, 68, 0.16);
      }
      .file-item-icon {
        width: 32px;
        height: 32px;
      }
      .file-item-name {
        margin-top: 6px;
        min-width: 4em;
        line-height: 1em;
        text-align: center;
      }
    }
  }

  .child-item {
    & + .child-item {
      margin-top: 5px;
    }
    .label {
      // color: #444;
      font-weight: bold;
    }
  }
}
</style>
