<template>
  <div class="storage-page">
    <div class="operate-box">
      <div class="targetYm-date">
        <div class="title">时间范围：</div>
        <el-radio-group v-model="formData.intervalMonths" @change="monthsRangeChangeFun">
          <el-radio-button
            v-for="item in monthList"
            :key="item.value"
            :value="item.value"
            :label="item.name"
          />
        </el-radio-group>
      </div>

      <div class="targetYm-date" v-show="radio === 'increment'">
        <div class="title">增量月份：</div>
        <el-date-picker
          class="date-style"
          v-model="formData.targetYm"
          type="month"
          placeholder="请请选择月份"
          format="YYYY-MM"
          value-format="YYYY-MM"
          @change="intervalMonthsChangeFun"
        />
      </div>

      <el-radio-group v-model="radio" @change="radioChangeFun">
        <el-radio value="default" size="large">默认</el-radio>
        <el-radio value="increment" size="large">增量</el-radio>
      </el-radio-group>
    </div>

    <div class="chart-content">
      <!-- 项目存储空间统计 -->
      <div class="chart-item">
        <div class="chart-content">
          <EchartCard
            :title="$t('系统管理.项目存储空间统计')"
            ref="projectStorageSpaceStatisticsRef"
            :charts-id="'chart1'"
            :bar-type="'barChart'"
            @refresh="initProjectStorageSpaceStatisticsFun"
          >
            <template #formSlot>
              <el-form :model="projectStorageSpaceStatisticsFormData" label-width="auto">
                <el-form-item label="项目名称：">
                  <ProjectSelect
                    class="select-width margin-right-12"
                    v-model="projectStorageSpaceStatisticsFormData.nodeId"
                    multiple
                    resStr="nodeName"
                    @change="initProjectStorageSpaceStatisticsFun"
                  />
                </el-form-item>
                <el-form-item label="项目编号：">
                  <ProjectSelect
                    class="select-width margin-right-12"
                    v-model="projectStorageSpaceStatisticsFormData.nodeId"
                    :showCodeList="true"
                    multiple
                    resStr="nodeName"
                    @change="initProjectStorageSpaceStatisticsFun"
                  />
                </el-form-item>
              </el-form>
            </template>
          </EchartCard>
        </div>
      </div>
      <!-- 学科存储空间统计 -->
      <div class="chart-item">
        <div class="chart-content">
          <EchartCard
            :title="$t('系统管理.学科存储空间统计')"
            ref="statisticsOfSubjectStorageSpaceRef"
            :charts-id="'chart2'"
            :bar-type="'barChart'"
            @refresh="initStatisticsOfSubjectStorageSpaceFun"
          >
            <template #formSlot>
              <el-form :model="statisticsOfSubjectStorageSpaceFormData" label-width="auto">
                <el-form-item label="学科：">
                  <el-select
                    class="select-width"
                    clearable
                    v-model="statisticsOfSubjectStorageSpaceFormData.nodeId"
                    multiple
                    collapse-tags
                    @change="initStatisticsOfSubjectStorageSpaceFun"
                  >
                    <el-option
                      v-for="item in DISCIPLINE_TYPE.A"
                      :label="item.label"
                      :value="item.label"
                      :key="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </template>
          </EchartCard>
        </div>
      </div>
      <!-- 用户存储空间统计 -->
      <div class="chart-item">
        <div class="chart-content">
          <EchartCard
            :title="$t('系统管理.用户存储空间统计')"
            ref="userStorageSpaceStatisticsRef"
            :charts-id="'chart3'"
            :bar-type="'barChart'"
            @refresh="initUserStorageSpaceStatisticsFun"
          >
            <template #formSlot>
              <el-form :model="userStorageSpaceStatisticsFormData" label-width="auto">
                <el-form-item label="用户组：">
                  <el-select
                    :clearable="false"
                    class="select-width margin-right-12"
                    v-model="userStorageSpaceStatisticsFormData.userGroupId"
                    @change="groupChangeFun"
                  >
                    <el-option
                      v-for="item in userGroupOptions"
                      :label="item.label"
                      :value="item.value"
                      :key="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="用户：">
                  <el-select
                    v-model="userStorageSpaceStatisticsFormData.userIds"
                    collapse-tags
                    multiple
                    :clearable="false"
                    class="mw200"
                    @change="initUserStorageSpaceStatisticsFun"
                  >
                    <el-option
                      v-for="item in userList"
                      :key="item.userId"
                      :label="item.nickname"
                      :value="item.userId"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </template>
          </EchartCard>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import ProjectSelect from '@/components/common/projectSelect/index.vue';
import { userQueryGroupApi, userQueryGroupDetailApi } from '@/api/system/user';
import { getDirectorySizeByUserIdApi } from '@/api/data/dataStorageAnalysis';
import EchartCard from '@/components/common/echartCard/index.vue';
import { useDict } from '@/utils/useDict';
import dayjs from 'dayjs';
import {
  getNodeSizeByNodeTypeApi,
  getNodeSizeByDisciplineApi,
} from '@/api/data/dataStorageAnalysis';

const { DISCIPLINE_TYPE } = useDict('DISCIPLINE_TYPE');

const userList = ref<any>([]);
const groupChangeFun = () => {
  queryGroupUserListFun(userStorageSpaceStatisticsFormData.userGroupId);
};
const queryGroupUserListFun = async (id: any) => {
  if (!id) {
    userList.value = [];
    return;
  }
  const res: any = await userQueryGroupDetailApi({
    id,
    current: 1,
    size: 999,
  });

  if (res && res.code === 200) {
    userList.value = res.data.users.data;
    userStorageSpaceStatisticsFormData.userIds = userList.value.map((item: any) => item.userId);
    initUserStorageSpaceStatisticsFun();
  } else {
    userList.value = [];
  }
};

const radio = ref('default');

const formData = reactive({
  targetYm: dayjs().format('YYYY-MM'),
  intervalMonths: 6,
});

const monthList = ref([
  {
    value: 6,
    name: '近6个月',
  },
  {
    value: 12,
    name: '近1年',
  },
  {
    value: 24,
    name: '近2年',
  },
  {
    value: 36,
    name: '近3年',
  },
]);

const radioChangeFun = async () => {
  // formData.targetYm = '';
  await initProjectStorageSpaceStatisticsFun();
  await initStatisticsOfSubjectStorageSpaceFun();
  await initUserStorageSpaceStatisticsFun();
};

// 切换时间范围
const monthsRangeChangeFun = () => {
  if (radio.value === 'default') {
    updateChartFun();
  }
};
// 切换增量月份
const intervalMonthsChangeFun = () => {
  if (radio.value === 'increment') {
    updateChartFun();
  }
};

const updateChartFun = async () => {
  await initProjectStorageSpaceStatisticsFun();
  await initStatisticsOfSubjectStorageSpaceFun();
  await initUserStorageSpaceStatisticsFun();
};

// 项目存储空间统计
const projectStorageSpaceStatisticsRef = ref();
const projectStorageSpaceStatisticsFormData = reactive<any>({
  nodeId: '',
});

const initProjectStorageSpaceStatisticsFun = async () => {
  const xData: any = [];
  const seriesData: any = [];
  const datas: any = [];
  const beforeData: any = [];
  const incrementData: any = [];

  const res: any = await getNodeSizeByNodeTypeApi({
    queryNodeType: 'project',
    queryNodeNames: projectStorageSpaceStatisticsFormData.nodeId,
    ...(radio.value === 'default' && { intervalMonths: formData.intervalMonths }),
    ...(radio.value === 'increment' && formData.targetYm && { targetYm: formData.targetYm }),
  });

  if (res && res.code === 200) {
    for (let i = 0; i < res.data.length; i++) {
      xData.push(res.data[i]?.nodeName);
      datas.push(res.data[i]?.totalSize);
      beforeData.push(
        res.data[i]?.BEFORE && Number(res.data[i]?.BEFORE) !== 0 ? res.data[i]?.BEFORE : 0
      );
      incrementData.push(
        res.data[i]?.INCREMENT && Number(res.data[i]?.INCREMENT) !== 0 ? res.data[i]?.INCREMENT : 0
      );
    }
  }
  if (radio.value === 'default') {
    seriesData.push({
      name: '存储空间',
      type: 'bar',
      barWidth: '30%',
      data: datas,
    });
  } else {
    seriesData.push(
      {
        name: '故有量',
        type: 'bar',
        barWidth: '30%',
        stack: 'total',
        data: beforeData,
        label: {
          show: true,
          color: '#409eff',
          position: 'right',
          formatter: (params: any) => {
            return params.value == 0 ? '' : params.value;
          },
        },
      },
      {
        name: '增量',
        type: 'bar',
        barWidth: '30%',
        stack: 'total',
        data: incrementData,
        label: {
          show: true,
          color: '#67c23a',
          position: 'top',
          formatter: (params: any) => {
            return params.value == 0 ? '' : params.value;
          },
        },
      }
    );
  }
  if (
    !projectStorageSpaceStatisticsRef.value ||
    !projectStorageSpaceStatisticsRef.value.commonChartRef
  )
    return;
  projectStorageSpaceStatisticsRef.value.commonChartRef.disposeEchartsByKey('chart1');
  projectStorageSpaceStatisticsRef.value.commonChartRef.option = {
    color: ['#409eff', '#67c23a'],
    title: {
      show: false,
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params: any) {
        return params.reverse().reduce((result: string, param: any, index: number) => {
          return (
            result +
            (index === 0 ? param.name + '<br/>' : '') +
            param.marker +
            param.seriesName +
            ' ： ' +
            '<span style="font-weight:bold">' +
            param.value +
            ' GB</span>' +
            (index === params.length - 1 ? '' : '<br/>')
          );
        }, '');
      },
    },
    legend: {
      show: false,
      top: '0%',
      left: 'center',
    },
    grid: {
      top: '10%',
      bottom: '50',
      left: '5%',
      right: '5%',
    },
    xAxis: {
      type: 'category',
      data: xData,
    },
    yAxis: {
      type: 'value',
      name: '单位：GB',
    },
    dataZoom: xData.length > 3 ? [] : null,
    series: seriesData,
  };
  projectStorageSpaceStatisticsRef.value.commonChartRef.initChart();
};

// 学科存储空间统计
const statisticsOfSubjectStorageSpaceRef = ref();
const statisticsOfSubjectStorageSpaceFormData = reactive<any>({
  nodeId: [],
});

const initStatisticsOfSubjectStorageSpaceFun = async () => {
  const xData: any = [];
  const seriesData: any = [];
  const datas: any = [];
  const beforeData: any = [];
  const incrementData: any = [];
  const res: any = await getNodeSizeByDisciplineApi({
    queryNodeType: 'discipline',
    disciplines: statisticsOfSubjectStorageSpaceFormData.nodeId,
    // queryNodeNames: statisticsOfSubjectStorageSpaceFormData.nodeId?.join(','),
    ...(radio.value === 'default' && { intervalMonths: formData.intervalMonths }),
    ...(radio.value === 'increment' && formData.targetYm && { targetYm: formData.targetYm }),
  });

  if (res && res.code === 200) {
    for (let i = 0; i < res.data.length; i++) {
      xData.push(res.data[i]?.nodeName);
      datas.push(res.data[i]?.totalSize);
      beforeData.push(
        res.data[i]?.BEFORE && Number(res.data[i]?.BEFORE) !== 0 ? res.data[i]?.BEFORE : 0
      );
      incrementData.push(
        res.data[i]?.INCREMENT && Number(res.data[i]?.INCREMENT) !== 0 ? res.data[i]?.INCREMENT : 0
      );
    }
  }
  if (radio.value === 'default') {
    seriesData.push({
      name: '存储空间',
      type: 'bar',
      barWidth: '30%',
      data: datas,
    });
  } else {
    seriesData.push(
      {
        name: '故有量',
        type: 'bar',
        barWidth: '30%',
        stack: 'total',
        data: beforeData,
        label: {
          show: true,
          color: '#409eff',
          position: 'right',
          formatter: (params: any) => {
            return params.value == 0 ? '' : params.value;
          },
        },
      },
      {
        name: '增量',
        type: 'bar',
        barWidth: '30%',
        stack: 'total',
        data: incrementData,
        label: {
          show: true,
          color: '#67c23a',
          position: 'top',
          formatter: (params: any) => {
            return params.value == 0 ? '' : params.value;
          },
        },
      }
    );
  }
  if (
    !statisticsOfSubjectStorageSpaceRef.value ||
    !statisticsOfSubjectStorageSpaceRef.value.commonChartRef
  )
    return;
  statisticsOfSubjectStorageSpaceRef.value.commonChartRef.disposeEchartsByKey('chart2');
  statisticsOfSubjectStorageSpaceRef.value.commonChartRef.option = {
    color: ['#409eff', '#67c23a'],
    title: {
      show: false,
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params: any) {
        return params.reverse().reduce((result: string, param: any, index: number) => {
          return (
            result +
            (index === 0 ? param.name + '<br/>' : '') +
            param.marker +
            param.seriesName +
            ' ： ' +
            '<span style="font-weight:bold">' +
            param.value +
            ' GB</span>' +
            (index === params.length - 1 ? '' : '<br/>')
          );
        }, '');
      },
    },
    legend: {
      show: false,
      top: '0%',
      left: 'center',
    },
    grid: {
      top: '10%',
      bottom: '50',
      left: '5%',
      right: '5%',
    },
    xAxis: {
      type: 'category',
      data: xData,
    },
    yAxis: {
      type: 'value',
      name: '单位：GB',
    },
    dataZoom: xData.length > 4 ? [] : null,
    series: seriesData,
  };
  statisticsOfSubjectStorageSpaceRef.value.commonChartRef.initChart();
};

// 用户存储空间统计
const userStorageSpaceStatisticsRef = ref();
const userStorageSpaceStatisticsFormData = reactive({
  userIds: [],
  userGroupId: '',
});

const initUserStorageSpaceStatisticsFun = async () => {
  const xData: any = [];
  const seriesData: any = [];
  const datas: any = [];
  const beforeData: any = [];
  const incrementData: any = [];

  const res: any = await getDirectorySizeByUserIdApi({
    userIds: userStorageSpaceStatisticsFormData.userIds.join(','),
    ...(radio.value === 'default' && { intervalMonths: formData.intervalMonths }),
    ...(radio.value === 'increment' && formData.targetYm && { targetYm: formData.targetYm }),
  });
  if (res && res.code === 200 && userStorageSpaceStatisticsFormData.userIds.length) {
    for (let i = 0; i < res.data.length; i++) {
      xData.push(res.data[i].userName);
      datas.push(res.data[i].totalFileSize);
      beforeData.push(
        res.data[i]?.BEFORE && Number(res.data[i]?.BEFORE) !== 0 ? res.data[i]?.BEFORE : 0
      );
      incrementData.push(
        res.data[i]?.INCREMENT && Number(res.data[i]?.INCREMENT) !== 0 ? res.data[i]?.INCREMENT : 0
      );
    }
  }

  if (radio.value === 'default') {
    seriesData.push({
      name: '存储空间',
      type: 'bar',
      barWidth: '30%',
      data: datas,
    });
  } else {
    seriesData.push(
      {
        name: '故有量',
        type: 'bar',
        barWidth: '30%',
        stack: 'total',
        data: beforeData,
        label: {
          show: true,
          color: '#409eff',
          position: 'right',
          formatter: (params: any) => {
            return params.value == 0 ? '' : params.value;
          },
        },
      },
      {
        name: '增量',
        type: 'bar',
        barWidth: '30%',
        stack: 'total',
        data: incrementData,
        label: {
          show: true,
          color: '#67c23a',
          position: 'top',
          formatter: (params: any) => {
            return params.value == 0 ? '' : params.value;
          },
        },
      }
    );
  }

  if (!userStorageSpaceStatisticsRef.value || !userStorageSpaceStatisticsRef.value.commonChartRef)
    return;
  userStorageSpaceStatisticsRef.value.commonChartRef.disposeEchartsByKey('chart3');
  userStorageSpaceStatisticsRef.value.commonChartRef.option = {
    color: ['#409eff', '#67c23a'],
    title: {
      show: false,
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params: any) {
        return params.reverse().reduce((result: string, param: any, index: number) => {
          return (
            result +
            (index === 0 ? param.name + '<br/>' : '') +
            param.marker +
            param.seriesName +
            ' ： ' +
            '<span style="font-weight:bold">' +
            param.value +
            ' GB</span>' +
            (index === params.length - 1 ? '' : '<br/>')
          );
        }, '');
      },
    },
    legend: {
      show: false,
      top: '0%',
      left: 'center',
    },
    grid: {
      top: '10%',
      bottom: '50',
      left: '5%',
      right: '5%',
    },
    xAxis: {
      type: 'category',
      data: xData,
    },
    yAxis: {
      type: 'value',
      name: '单位：GB',
    },
    dataZoom: xData.length > 2 ? [] : null,
    series: seriesData,
  };
  userStorageSpaceStatisticsRef.value.commonChartRef.initChart();
};

const userGroupOptions = ref<any>([]);

const getGroupList = async () => {
  const res: any = await userQueryGroupApi({
    current: 1,
    size: 1000,
  });
  if (res && res.code === 200) {
    userGroupOptions.value = [];
    res.data.data.forEach((item: any) => {
      userGroupOptions.value.push({
        label: item.groupName,
        value: item.id,
      });
    });
    if (userGroupOptions.value?.length) {
      userStorageSpaceStatisticsFormData.userGroupId = userGroupOptions.value[0].value;
      queryGroupUserListFun(userStorageSpaceStatisticsFormData.userGroupId);
    }
  }
};

onMounted(async () => {
  await getGroupList();
  statisticsOfSubjectStorageSpaceFormData.nodeId = DISCIPLINE_TYPE.value.A.map(
    (item: any) => item.label
  );
  nextTick(() => {
    initProjectStorageSpaceStatisticsFun();
    initStatisticsOfSubjectStorageSpaceFun();
    // initUserStorageSpaceStatisticsFun();
  });
});
</script>

<style lang="scss" scoped>
.storage-page {
  width: 100%;
  height: 100%;
  padding: 10px;
  display: flex;
  flex-direction: column;

  .select-width {
    width: 120px;
  }

  .operate-box {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding-right: 10px;

    .targetYm-date {
      display: flex;
      height: 50px;
      display: flex;
      align-items: center;
      margin-right: 12px;

      .title {
        padding-right: 5px;
      }

      :deep(.date-style) {
        width: 150px !important;
      }
    }
  }
  .chart-content {
    width: 100%;
    flex: 1;
    overflow: auto;
    display: flex;
    flex-wrap: wrap;
  }

  .chart-item {
    width: calc(50% - 10px);
    height: 400px;
    margin-right: 10px;
    margin-bottom: 10px;
    border: 1px solid var(--el-border-color);

    .chart-filter {
      width: 100%;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      padding: 10px;
      .project-name-content {
        width: 150px;
        margin-left: 10px;
      }
      .mr10 {
        margin-right: 10px;
      }
    }
    .chart-content {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
