<template>
  <div class="h-full rounded bg-white pb-2">
    <div class="h-full">
      <div
        class="flex items-center p-3 cursor-pointer hover:bg-gray-50"
        @click="openDialog"
      >
        <img
          src="./imgs/gailan.png"
          style="width: 24px; height: 24px; margin-right: 5px"
          alt=""
        />
        <h3>数据概览</h3>
        <div class="flex justify-end flex-1">
          <ArrowRight class="w-4 h-4"></ArrowRight>
        </div>
      </div>
      <div class="grid-cols-3 grid py-3">
        <div class="text-center">
          <el-statistic title="累计建档" :value="outputValue">
            <template #suffix>
              <span class="text-gray-500 text-xs">人</span>
            </template>
          </el-statistic>
        </div>
        <div class="text-center">
          <el-statistic
            title="累计上传报告"
            :value="largeScreenGlobalData.medicalReportTotal"
          >
            <template #suffix>
              <span class="text-gray-500 text-xs">份</span>
            </template>
          </el-statistic>
        </div>
        <div class="text-center">
          <el-statistic title="报告上传率" :value="reportUploadRate"
            ><template #suffix>
              <span class="text-gray-500 text-xs">%</span>
            </template>
          </el-statistic>
        </div>
      </div>
    </div>

    <el-dialog v-model="dialogVisible" title="建档数据概览" width="80%">
      <div class="py-2 flex items-center">
        <div>
          <el-button type="primary" @click="openDataCountDialog"
            >数据统计</el-button
          >
        </div>
        <div class="flex-1 flex items-center justify-end">
          <el-select
            v-model="dialogData.queryType"
            class="h-auto"
            placeholder="请选择"
            @change="initQueryKey"
          >
            <el-option
              v-for="item in searchList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
          <el-input
            v-model="dialogData.keyword"
            class="w-fit mx-2"
            clearable
            placeholder="请输入姓名或档案号"
          ></el-input>
          <el-button type="primary" @click="dialogPageChange(1)"
            >搜索</el-button
          >
        </div>
      </div>
      <el-table :data="dialogData.list">
        <el-table-column label="档案号" prop="id"> </el-table-column>
        <el-table-column label="基本信息"
          ><template #default="{ row }">
            <div>
              <div>{{ row.name }}</div>
              <div>
                <span>{{ row.gender == 1 ? "男" : "女" }}</span>
                <span>,{{ formatAge(row.birthday) }}岁</span>
              </div>
              <div
                v-if="row.archivesRelationText != '本人'"
                class="text-sm text-gray-500"
              >
                [{{ row.archivesRelationText || "" }}]
              </div>
            </div>
          </template></el-table-column
        >
        <el-table-column label="账号"
          ><template #default="{ row }">
            <div
              v-for="(item, index) in row.accounts"
              :key="index"
              class="space-x-4"
              :class="{
                hidden: !accountTypes[item.type]
              }"
            >
              <span class="inline-block whitespace-nowrap w-[4em]">{{
                accountTypes[item.type]
              }}</span>
              <span>{{ item.account }}</span>
            </div>
          </template></el-table-column
        >
        <el-table-column label="上传报告份数">
          <template #default="{ row }">
            {{
              row.medicalReportConfirmTotal.awaitTotal +
              row.medicalReportConfirmTotal.confirmTotal +
              row.medicalReportConfirmTotal.doneTotal +
              row.medicalReportConfirmTotal.processTotal +
              row.medicalReportConfirmTotal.successTotal
            }}
          </template>
        </el-table-column>
        <el-table-column label="建档时间" prop="createdAt"> </el-table-column>
      </el-table>

      <el-pagination
        class="justify-end mt-4"
        v-model:current-page="dialogData.page"
        :page-size="dialogData.pageSize"
        background
        size="small"
        layout="total, prev, pager, next"
        :total="dialogData.total"
        @current-change="dialogPageChange"
      />
    </el-dialog>

    <el-dialog v-model="dataCountDialogVisible" title="数据统计" width="80%">
      <div class="p-2 font-bold text-gray-800">性别统计</div>
      <div class="flex items-center">
        <div class="w-1/2">
          <el-table :data="genderCount" border>
            <el-table-column label="类别" prop="label"></el-table-column>
            <el-table-column label="人数" prop="value"></el-table-column>
            <el-table-column label="占比" prop="scale">
              <template #default="{ row }"> {{ row.scale }}% </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="w-1/2 ml-4 relative">
          <div class="absolute male__text flex items-center">
            <img
              src="@/assets/employee1.png"
              style="width: 40px; height: 40px"
              alt=""
              srcset=""
            />
            <div class="ml-3 text-center">
              <div>男性占比</div>
              <el-text tag="b">{{ maleScale }}%</el-text>
            </div>
          </div>
          <div class="absolute famale__text flex items-center">
            <img
              src="@/assets/team-women.png"
              style="width: 40px; height: 40px"
              alt=""
              srcset=""
            />
            <div class="ml-3 text-center">
              <div>女性占比</div>
              <el-text tag="b">{{ femaleScale }}%</el-text>
            </div>
          </div>
          <div style="height: 16vh">
            <ComponentChart ref="genderChartsRef"></ComponentChart>
          </div>
        </div>
      </div>
      <div class="p-2 font-bold text-gray-800">年龄段统计</div>
      <div class="flex items-center">
        <div class="w-1/2">
          <el-table :data="largeScreenGlobalData?.ageMap" border>
            <el-table-column label="年龄段" prop="ageText"></el-table-column>
            <el-table-column label="年龄段人数" prop="total"></el-table-column>
            <el-table-column label="占比">
              <template #default="{ row }">
                {{ ((row.total / agePersonCount) * 100).toFixed(2) }}%
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="height: 25vh" class="w-1/2 ml-4 relative">
          <ComponentChart ref="ageChartsRef"></ComponentChart>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { useTransition } from "@vueuse/core";
import { reactive, ref, computed, onMounted, watch } from "vue";

import { ArrowRight } from "@element-plus/icons-vue";
import ComponentChart from "@/components/Chart.vue";
import { useLargeScreenStoreHook } from "@/store/modules/largeScreen";
import { nextTick } from "process";
import { formatAge, request } from "@/utils";
const useLargeScreenHook = useLargeScreenStoreHook();

const largeScreenGlobalData = computed(() => {
  return useLargeScreenHook?.largeScreenGlobalData;
});
const chartsRef = ref();
const sumTotal = ref(0);
const outputValue = useTransition(sumTotal, {
  duration: 1500
});

const reportUploadRate = computed(() =>
  sumTotal
    ? Number(
        (
          ((largeScreenGlobalData.value.medicalReportArchivesTotal || 0) /
            sumTotal.value) *
          100
        ).toFixed(1)
      )
    : 0
);
const maleScale = computed(() => {
  return (
    (largeScreenGlobalData.value.maleTotal /
      largeScreenGlobalData.value.total) *
    100
  ).toFixed(2);
});
const femaleScale = computed(() => {
  return (
    (largeScreenGlobalData.value.femaleTotal /
      largeScreenGlobalData.value.total) *
    100
  ).toFixed(2);
});
const genderCount = computed(() => {
  return [
    {
      label: "男",
      value: largeScreenGlobalData.value.maleTotal,
      scale: maleScale.value
    },
    {
      label: "女",
      value: largeScreenGlobalData.value.femaleTotal,
      scale: femaleScale.value
    },
    {
      label: "总计",
      value:
        largeScreenGlobalData.value.maleTotal +
        largeScreenGlobalData.value.femaleTotal,
      scale: 100
    }
  ];
});
watch(
  largeScreenGlobalData,
  (n, o) => {
    console.log("监听成功", n);
    nextTick(() => {
      sumTotal.value = largeScreenGlobalData.value?.total;
      // initChart();
    });
  },
  {
    deep: true
  }
);
onMounted(() => {});

const dialogVisible = ref(false);

const dialogData = reactive({
  page: 1,
  pageSize: 10,
  list: [],
  keyword: "",
  total: 0,
  queryType: "archivesId",
  filter: {
    name: "",
    archivesId: "",
    phone: "",
    idCard: "",
    account: ""
  }
});
const accountTypes = {
  1: "手机号",
  2: "身份证号",
  3: "特殊编号"
};
const searchList = [
  {
    name: "姓名",
    value: "name"
  },
  {
    name: "档案号",
    value: "archivesId"
  },
  {
    name: "手机号",
    value: "phone"
  },
  {
    name: "身份证号",
    value: "idCard"
  },
  {
    name: "特殊编号",
    value: "account"
  }
];

const initQueryKey = () => {
  searchList.forEach(v => {
    dialogData.filter[v.value] =
      v.value == queryType.value ? dialogData.filter[v.value] : "";
  });
};
const openDialog = () => {
  dialogData.keyword = "";
  dialogData.page = 1;
  getArchivesList();
  dialogVisible.value = true;
};
const getArchivesList = async () => {
  if (dialogData.queryType) {
    dialogData.filter[dialogData.queryType] = dialogData.keyword;
  }
  const { data } = await request.get(
    `/archivesService/agency/archives/paginate`,
    {
      params: {
        ...dialogData.filter,
        page: dialogData.page
      }
    }
  );
  dialogData.total = data.total;
  dialogData.list = data.list;
};
const dialogPageChange = (page = 1) => {
  dialogData.page = page;
  getArchivesList();
};

const dataCountDialogVisible = ref(false);
const openDataCountDialog = async () => {
  dataCountDialogVisible.value = true;
  nextTick(() => {
    initGenderChart();
    initAgeChart();
  });
};
const genderChartsRef = ref();
const ageChartsRef = ref();

const initGenderChart = () => {
  const option = {
    legend: {
      show: false
    },
    color: ["#5E8CFB", "#DA7A82"],
    grid: {
      left: 0,
      right: 0,
      bottom: 0,
      top: "40%"
    },
    xAxis: {
      axisLine: {
        show: false
      },
      axisLabel: {
        show: false
      },
      show: true,
      type: "value",
      axisTick: {
        show: false
      },
      splitLine: {
        show: false
      }
    },
    yAxis: {
      data: [""],
      axisLine: {
        show: false
      },
      axisLabel: {
        textStyle: {
          color: "#fff"
        }
      },
      axisTick: {
        show: false
      },
      splitLine: {
        show: false
      }
    },
    series: [
      {
        name: "男生占比",
        type: "bar",
        stack: "all",
        barWidth: 42,
        data: [largeScreenGlobalData.value?.maleTotal]
      },
      {
        name: "集体收入",
        type: "bar",
        stack: "all",
        barWidth: 42,
        data: [largeScreenGlobalData.value?.femaleTotal]
      }
    ]
  };
  genderChartsRef.value.setOption(option);
};

const formatterScale = value => {
  return ((value / largeScreenGlobalData.value.total) * 100).toFixed(2);
};
const agePersonCount = ref(0);
const initAgeChart = () => {
  let ageMap = largeScreenGlobalData.value?.ageMap;
  var salvProName = ageMap
    ?.sort((a, b) => {
      return b["sort"] - a["sort"];
    })
    .map(v => v.ageText);
  var salvProValue = ageMap?.map(v => v.total);

  agePersonCount.value = ageMap.reduce((pre, cur) => {
    return pre + cur.total;
  }, 0);
  var salvProMax = [100]; //背景按最大值
  const option = {
    grid: {
      left: "2%",
      right: "8%",
      bottom: "2%",
      top: "2%",
      containLabel: true
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "none"
      },
      formatter: function (params) {
        return params[0].name + " : " + formatterScale(params[0].value) + "%";
      }
    },
    xAxis: {
      show: true,
      type: "value"
    },
    yAxis: [
      {
        type: "category",
        inverse: true,
        axisLabel: {
          show: true,
          textStyle: {
            color: "#648cfa" // 左边坐标轴颜色
          }
        },
        splitLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLine: {
          show: true
        },
        data: salvProName
      }
    ],
    series: [
      {
        name: "值",
        type: "bar",
        zlevel: 1,
        itemStyle: {
          normal: {
            // barBorderRadius: 30,
            color: "#5E8CFB" // 柱体颜色
          }
        },
        label: {
          show: true,
          position: "right",
          distance: 10,
          textStyle: {
            color: "#648cfa" // 右边百分比数值
          },
          formatter: params => {
            return formatterScale(params.value) + "%";
          }
        },
        barWidth: 23,
        data: salvProValue
      },
      {
        name: "背景",
        type: "bar",
        barWidth: 20,
        barGap: "-100%",
        data: salvProMax,
        itemStyle: {
          normal: {
            color: "#fff" // 柱体背景色，白色或者透明色都可以
          }
        }
      }
    ]
  };

  ageChartsRef.value.setOption(option);
};
</script>
<style scoped lang="scss">
.male__text {
  top: 32%;
  left: 10%;
}
.famale__text {
  top: 32%;
  left: 60%;
}
</style>
