<template>
  <!-- <el-scrollbar height="800px" v-loading="loading"> -->
  <div class="main-top">
    <span style="font-weight: bold; font-size: 18px; color: #3596eb">任务描述</span>
    <p style="font-weight: 400; font-size: 12px; color: #e6e6e6">（给出任务清单参考，做哪些数据的统计分析）Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum laoreet. Proin gravida dolor sit amet lacus accumsan et viverra justo commodo. Proin sodales pulvinar sic tempor. Sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam fermentum, nulla luctus pharetra vulputate, felis tellus mollis orci, sed rhoncus pronin sapien nunc accuan eget.</p>
  </div>
  <div class="main-but">
    <el-button @click="knowledgeImport">
      <img src="../../../assets/images/导入.png" alt="" />
      算法知识导入
    </el-button>
    <el-button @click="taskSubmit">
      <img src="../../../assets/images/提交.png" alt="" />
      实训任务提交
    </el-button>
  </div>
  <div class="app-main">
    <div class="main-left">
      <div>
        <div class="left-top">
          <span>一、选择指标</span>
        </div>
        <div class="metrics">
          <el-select v-model="n_dataTableQuery.tableName" placeholder="请选择数据" style="width: 180px" @change="selectType">
            <el-option v-for="item in algorithmStore.userDataLabel" :key="item" :label="item" :value="item" />
          </el-select>
        </div>
        <div class="metrics-table" style="margin-top: 10px">
          <el-table border ref="multipleTableRef" :data="algorithmStore.indexLibrary" style="width: 100%" :header-cell-style="headerCellStyle" @selection-change="handleSelectionChange">
            <el-table-column type="selection" prop="date" label="Date" align="center" />
            <el-table-column label="指标" align="center" prop="label" />
          </el-table>
          <el-button @click="submit">确定</el-button>
        </div>
        <div class="left-top">
          <span>二、数据预处理</span>
        </div>
        <div class="metrics">
          <el-select v-model="preProcessText.text1" placeholder="请选择数据" style="width: 180px">
            <el-option label="数据去重" value="数据去重" />
          </el-select>
        </div>
        <div class="metrics" style="margin-top: 15px">
          <el-select v-model="preProcessText.text2" placeholder="请选择数据" style="width: 180px" @change="preProcess">
            <el-option label="缺失值处理-剔除数据" value="缺失值处理-剔除数据" />
            <el-option label="缺失值处理一均值替代" value="缺失值处理一均值替代" />
          </el-select>
        </div>
        <div class="left-top" style="margin-top: 10px">
          <span>三、模型参数设置</span>
        </div>
        <div class="metrics-table" style="margin-top: 10px">
          <el-table border ref="multipleTableRef" :data="modelParams" style="width: 100%" :header-cell-style="headerCellStyle" @selection-change="handlemodelSelectionChange">
            <el-table-column type="selection" prop="date" label="Date" align="center" />
            <el-table-column prop="name" label="统计量" align="center" />
          </el-table>
          <el-button @click="modelCalculation">计算</el-button>
        </div>
      </div>
      <div style="margin-top: auto">
        <div class="startOver" @click="restart">
          <img src="../../../assets/images/重新开始.png" alt="" />
          <span>重新开始</span>
        </div>
      </div>
    </div>
    <div class="main-right">
      <div>
        <span style="font-weight: bold; font-size: 18px; color: #3596eb">分析数据：</span>
        <el-table :data="analysisData" style="width: 100%; margin-top: 10px" :header-cell-style="headerCellStyle">
          <el-table-column v-for="column in analysisHanderKry" :key="column" :prop="column" :label="column" align="center" />
        </el-table>
        <pagination v-show="n_analyzeTheNumberOfDataItems > 0" :total="n_analyzeTheNumberOfDataItems" v-model:page="n_dataTableQuery.index" v-model:limit="n_dataTableQuery.size" @pagination="analyzeDataNext" />
      </div>
      <div class="analysisResults" style="margin-top: 20px">
        <span style="font-weight: bold; font-size: 18px; color: #3596eb; display: block">分析结果：</span>
        <el-button @click="download">下载</el-button>
        <el-table :data="tableData" style="width: 100%; margin-top: 10px" :header-cell-style="headerCellStyle" height="350">
          <el-table-column v-for="column in tableLabel" :key="column.label" :prop="column.prop" :label="column.label" align="center"></el-table-column>
        </el-table>
        <pagination v-show="nNumberOfAnalysisResults > 0" :total="nNumberOfAnalysisResults" v-model:page="gAnalysisResults.index" v-model:limit="gAnalysisResults.size" @pagination="updatePageAnalysisResults" />
      </div>
    </div>
  </div>
  <!-- </el-scrollbar> -->
  <el-dialog v-model="dialogVisible" title="实训任务提交" width="565" custom-class="dialogClass" :show-close="false">
    <template #header="{ close, titleId, titleClass }">
      <div class="my-header">
        <span :id="titleId" :class="titleClass">实训任务提交</span>
        <img class="gbImg" src="../../../assets/images/关闭.png" @click="close" alt="" />
      </div>
      <img class="xtImg" src="../../../assets/images/线条.png" alt="" />
    </template>
    <div class="from-item">
      <el-form :inline="true" label-position="right" label-width="84px" :model="form" class="demo-form-inline">
        <el-form-item label="平均数：">
          <el-input style="width: 120px" v-model="formInline.average" clearable />
        </el-form-item>
        <el-form-item label="众数：">
          <el-input style="width: 120px" v-model="formInline.mode" clearable />
        </el-form-item>
        <el-form-item label="中位数：">
          <el-input style="width: 120px" v-model="formInline.median" clearable />
        </el-form-item>
        <el-form-item label="标准差：">
          <el-input style="width: 120px" v-model="formInline.standardDeviation" clearable />
        </el-form-item>
        <el-form-item label="方差：">
          <el-input style="width: 120px" v-model="formInline.variance" clearable />
        </el-form-item>
        <el-form-item label="峰度：">
          <el-input style="width: 120px" v-model="formInline.kurtosis" clearable />
        </el-form-item>
        <el-form-item label="标准误差：">
          <el-input style="width: 120px" v-model="formInline.standardError" clearable />
        </el-form-item>
        <el-form-item label="偏度：">
          <el-input style="width: 120px" v-model="formInline.skewness" clearable />
        </el-form-item>
        <el-form-item label="最大值：">
          <el-input style="width: 120px" v-model="formInline.max" clearable />
        </el-form-item>
        <el-form-item label="最小值：">
          <el-input style="width: 120px" v-model="formInline.min" clearable />
        </el-form-item>
        <el-form-item label="求和：">
          <el-input style="width: 120px" v-model="formInline.summation" clearable />
        </el-form-item>
        <el-form-item label="观测数：">
          <el-input style="width: 120px" v-model="formInline.observations" clearable />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="submitTask">确定</el-button>
        <el-button type="primary" @click="dialogVisible = false">返回</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="b_introductionOfAlgorithmKnowledge" title="算法知识导入" width="60%" :show-close="false">
    <template #header="{ close, titleId, titleClass }">
      <div class="my-header">
        <span :id="titleId" :class="titleClass">实训任务提交</span>
        <img class="gbImg" src="../../../assets/images/关闭.png" @click="close" alt="" />
      </div>
      <img class="xtImg" src="../../../assets/images/线条.png" alt="" />
    </template>
    <div class="from-item"></div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="submitTask">确定</el-button>
        <el-button type="primary" @click="dialogVisible = false">返回</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import * as portraitModel from "@/api/portraitModel";
import { paginate } from "@/utils/index.js";
import * as API from "@/api/AI.js";
import * as marketingAlgorithmApi from "@/api/marketing-algorithm.js";
import useAlgorithmStore from "@/store/modules/algorithm.js";
import useUserStore from "@/store/modules/user";
import { getUserInfo } from "@/utils/auth";
const userInfo = JSON.parse(getUserInfo());
const loading = ref(false);
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const algorithmStore = useAlgorithmStore();
const multipleTableRef = ref(null);
const b_introductionOfAlgorithmKnowledge = ref(false);
const n_dataTableQuery = ref({
  index: 1,
  size: 5,
  tableName: "用户属性表",
  userId: userInfo.userId,
});
const gAnalysisResults = ref({
  index: 1,
  size: 5,
});
const dialogVisible = ref(false);
// 模型参数
const modelParams = reactive([
  {
    name: "平均数",
  },
  {
    name: "中位数",
  },
  {
    name: "众数",
  },
  {
    name: "标准差",
  },
  {
    name: "方差",
  },
  {
    name: "标准误差",
  },
  {
    name: "峰度;",
  },
  {
    name: "偏度",
  },
  {
    name: "最大值",
  },
  {
    name: "最小值",
  },
  {
    name: "求和",
  },
  {
    name: "观测数",
  },
]);
const analysisData = ref([]);
const analysisHanderKry = ref([]);
const tableLabel = reactive([
  { prop: "average", label: "平均数" },
  { prop: "median", label: "中位数" },
  { prop: "mode", label: "众数" },
  { prop: "standardDeviation", label: "标准差" },
  { prop: "variance", label: "方差" },
  { prop: "standardError", label: "标准误差" },
  { prop: "kurtosis", label: "峰度" },
  { prop: "skewness", label: "偏度" },
  { prop: "max", label: "最大值" },
  { prop: "min", label: "最小值" },
  { prop: "summation", label: "求和" },
  { prop: "observations", label: "观测数" },
]);
const formInline = ref({
  average: "",
  median: "",
  mode: "",
  standardDeviation: "",
  variance: "",
  standardError: "",
  kurtosis: "",
  skewness: "",
  max: "",
  min: "",
  summation: "",
  observations: "",
});
const g_indicatorData = ref([]);
const preProcessText = ref({
  text1: "数据去重",
  text2: "",
});
// 分析数据
const n_analyzeTheNumberOfDataItems = ref(0);
const aAnalyzeTheRawData = ref([]);
//分析结果
const nNumberOfAnalysisResults = ref(0);
const aOriginalDataOfAnalysisResults = ref([]);
const aOriginalDataOfAnalysisResults2 = ref({});

// 模型参数
const g_modelParameter = ref([]);
// 预处理
const preProcess = (tetx) => {
  if (analysisData.value.length == 0) {
    proxy.$modal.msgWarning("请先选择指标进行数据分析!");
    preProcessText.value.text2 = "";
  }
  API.dataPreprocessing({
    mapList: analysisData.value,
    method: preProcessText.value.text2,
    userId: n_dataTableQuery.value.userId,
  }).then((res) => {
    proxy.$modal.msgSuccess("预处理成功");
    analysisData.value = res.data;
  });
};
// 提交
const taskSubmit = () => {
  dialogVisible.value = true;
};
const tableData = ref([]);
const headerCellStyle = () => {
  return {
    backgroundColor: "#1882DE !important", // 设置表头背景颜色
    color: "#ffffff !important",
  };
};
// 选择指标
const selectType = (type) => {
  n_dataTableQuery.value.tableName = type;
  getIndicator();
};
// 选择数据
const handleSelectionChange = (type) => {
  g_indicatorData.value = type.map((item) => item.label);
};
// 提交指標
const submit = () => {
  if (g_indicatorData.value.length == 0) return proxy.$modal.msgWarning("请选择指标");
  marketingAlgorithmApi.getMarketingAlgorithm({ userId: n_dataTableQuery.value.userId, tableName: n_dataTableQuery.value.tableName, fieldList: g_indicatorData.value }).then((res) => {
    analysisData.value = res.data;
    analysisHanderKry.value = Object.keys(res.data[0]);
    if (res.data.length > 5) {
      n_analyzeTheNumberOfDataItems.value = res.data.length;
      aAnalyzeTheRawData.value = res.data;
      analysisData.value = res.data.slice(0, 5);
    }
    proxy.$modal.msgSuccess("分析数据成功");
  });
};
// 选择模型
const handlemodelSelectionChange = (type) => {
  g_modelParameter.value = type.map((item) => item.name);
};
//计算
const modelCalculation = () => {
  if (analysisData.value.length == 0 && g_modelParameter.value.length == 0) {
    proxy.$modal.msgWarning("请先分析数据/未选择模型参数!");
    return;
  }
  const processedData = processArrayData(analysisHanderKry.value, analysisData.value);
  marketingAlgorithmApi.getMarketingAlgorithmPreprocessing(JSON.stringify({ map: processedData, statistic: g_modelParameter.value, userId: n_dataTableQuery.value.userId })).then((res) => {
    aOriginalDataOfAnalysisResults2.value = res.data;
    tableData.value = res.data.map((item) => item.statistics);
    if (res.data.length > 5) {
      nNumberOfAnalysisResults.value = res.data.length;
      aOriginalDataOfAnalysisResults.value = res.data.map((item) => item.statistics);
      tableData.value = res.data.map((item) => item.statistics).slice(0, 5);
    }
  });
};
function processArrayData(keys, data) {
  // 创建结果对象
  const result = {};

  // 遍历每个键
  keys.forEach((key) => {
    // 为每个键创建一个数组，包含 data 数组中该键的所有值
    const values = data.map((item) => item[key]);
    // 将键和对应的值数组添加到结果对象中
    result[key] = values;
  });

  return result;
}
onMounted(() => {
  getIndicator();
});
// 获取指标
const getIndicator = () => {
  algorithmStore.getUserDatabase({ userId: n_dataTableQuery.value.userId, tableName: n_dataTableQuery.value.tableName, algorithmName: "描述性统计" });
};
// 算法知识导入
const knowledgeImport = () => {
  b_introductionOfAlgorithmKnowledge.value = true;
};
// 实训任务提交
const submitTask = () => {
  for (let key in formInline.value) {
    if (formInline.value[key] == "") {
      const label = tableLabel.find((item) => item.prop == key);
      proxy.$modal.msgWarning(`${label.label}不能为空`);
      return;
    }
  }
  portraitModel
    .submit({
      userId: n_dataTableQuery.value.userId,
      taskName: "描述性统计",
      numberOfErrors: 0,
    })
    .then((res) => {
      dialogVisible.value = false;
      proxy.$modal.msgSuccess("提交成功");
    });
};
// 重新开始
const restart = () => {
  // 清空
  formInline.value = {
    average: "",
    median: "",
    mode: "",
    standardDeviation: "",
    variance: "",
    standardError: "",
    kurtosis: "",
    skewness: "",
    max: "",
    min: "",
    summation: "",
    observations: "",
  };
  analysisData.value = [];
  analysisHanderKry.value = [];
  tableData.value = [];
  g_indicatorData.value = [];
  g_modelParameter.value = [];
  preProcessText.value.text2 = "";
  n_dataTableQuery.value.tableName = "用户属性表";
  getIndicator();
  proxy.$modal.msgSuccess("重新开始成功");
  multipleTableRef.value.clearSelection();
};
//
const analyzeDataNext = () => {
  analysisData.value = paginate(aAnalyzeTheRawData.value, n_dataTableQuery.value.index, n_dataTableQuery.value.size).data;
};
const updatePageAnalysisResults = () => {
  tableData.value = paginate(aOriginalDataOfAnalysisResults.value, gAnalysisResults.value.index, gAnalysisResults.value.size).data;
};
// 下载
const download = () => {
  aOriginalDataOfAnalysisResults2.value.forEach((item) => {
    item.statistics.field = item.field;
    for (let key in item.statistics) {
      item.statistics[key] = item.statistics[key] ?? 0;
    }
  });

  marketingAlgorithmApi.getMarketingAlgorithmDownload(aOriginalDataOfAnalysisResults2.value).then((res) => {
    const blob = new Blob([res], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "描述性统计.xlsx";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
    proxy.$modal.msgSuccess("下载成功");
  });
};
</script>

<style lang="scss" scoped>
.main-top {
  margin: 20px 20px 0;
  margin-top: 10px;
  height: 85px;
  background: #001d40;
  border: 1px solid #0452c6;
  padding: 5px 20px;
}
.main-but {
  margin: 5px 20px 0;
  display: flex;
  .el-button:nth-child(1) {
    width: 180px;
    height: 56px;
    background: url("../../../assets/images/011.png");
    color: #ffffff;
    border-color: #ffffff00;
  }
  .el-button:nth-child(2) {
    width: 180px;
    height: 56px;
    background: url("../../../assets/images/022.png");
    color: #ffffff;
    border-color: #ffffff00;
  }
}
.app-main {
  //   background-color: #f5f5f5;
  min-height: 965px;
  margin: 5px 20px 0;
  height: 100%;
  display: flex;
  overflow: auto;
  .main-left {
    //水平居中
    flex-direction: column;
    min-height: 965px;
    display: flex;
    width: 205px;
    height: 100%;
    background: #041c49;
    padding: 0px 10px;
    .left-top {
      padding: 10px;
      span {
        font-weight: bold;
        font-size: 18px;
        color: #3596eb;
      }
    }
    .metrics-table {
      .el-button {
        width: 149px;
        height: 48px;
        background: url("../../../assets/images/确定.png");
        color: #ffffff;
        border-color: #ffffff00;
        background-size: 100% 100%;
        margin: 15px;
      }
    }
    .startOver {
      margin-left: -10px;
      width: 205px;
      height: 55px;
      background: #00f4ff;
      //水平居中
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }
    :deep(.el-table) {
      --el-table-row-hover-bg-color: #002651 !important;
      --el-table-border-color: #7ac1ff;
      .el-table__row {
        background-color: #002652 !important;
        color: #e6e6e6;
      }
    }
  }
  .main-right {
    width: 1639px;
    // height: 100%;
    padding: 20px;
    border: 1px solid #0452c6;
    :deep(.el-table__header) {
      .el-table__cell {
        background: linear-gradient(0deg, #5304be 0%, #9126fe 100%) !important;
      }
    }
    :deep(.el-table) {
      --el-table-row-hover-bg-color: #002651 !important;
      --el-table-border-color: #002651;
      --el-table-bg-color: #ffffff00;
      .el-table__row {
        background-color: #002652 !important;
        color: #e6e6e6;
      }
    }
  }
  .metrics {
    :deep(.el-input) {
      .el-input__wrapper {
        background-color: #ffffff00;
        background-image: url("../../../assets/images/下拉框.png");
        background-size: 100% 100%;
      }
      --el-input-text-color: #ffffff;
      --el-input-border-color: #ffffff00;
      --el-input-hover-border-color: #ffffff00;
      --el-input-hover-border: #ffffff00;
      --el-select-border-color-hover: #ffffff00;
      --el-select-input-focus-border-color: #ffffff00;
      --el-input-placeholder-color: #ffffff;
      .el-input__inner {
        color: #ffffff;
      }
    }
  }
}
.analysisResults {
  .el-button {
    width: 89px;
    height: 31px;
    background: url("../../../assets/images/下载.png");
    color: black;
    border-color: #ffffff00;
    // background-size: 100% 100%;
    margin: 15px 0px 5px;
  }
}
:deep(.el-form-item__label) {
  color: #ffffff;
}
.from-item {
  padding: 20px;
  .el-input {
    --el-input-text-color: #ffffff;
    --el-input-bg-color: #002651;
    --el-input-border-color: #67b3d6;
  }
}
.dialog-footer {
  margin-bottom: 20px;
}
</style>
<style lang="scss">
.el-dialog {
  background: url("../../../assets/images/弹框.png") !important;
  background-size: 100% 100% !important;
  .el-dialog__header {
    padding: 5px 0px;
    margin-right: 5px !important;
    .gbImg {
      cursor: pointer;
      width: 51px;
      height: 31px;
      background-size: 100% 100%;
    }
  }
  .xtImg {
    margin-left: 18px;
    width: 530px;
  }
}
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 16px;
  text-align: center;
  span {
    color: #ffffff;
    padding: 38px 20px 0;
  }
}
.el-table__body-wrapper {
  // background: #020620 !important;
}
</style>
