<template>
  <div class="transition-page">
    <el-collapse v-model="activeNames" class="transition-collapse">
      <el-collapse-item title="基础信息" name="1">
        <p @click="database" class="CPC">
          数据入库风场统计数: <span>{{ windFarmCount || 0 }}</span>个
        </p>

        <el-drawer
          title="入库统计"
          :visible.sync="drawer"
          custom-class="transition-drawer"
        >
          <div class="card" v-for="(item, index) in Rklist" :key="index">
            <p>{{ item.windFarmName }}</p>

            <ul>
              <li
                v-for="(type, typeIndex) in item.typeCountDataList"
                :key="typeIndex"
                @click="details(item.windFarmCode, type)"
              >
                <span class="sp1">{{ type.transferName }}</span>
                <span class="sp2">{{ type.count }}</span>
                <span class="sp3">{{
                  type.latestStorageTime || "无数据"
                }}</span>
              </li>
            </ul>
          </div>
        </el-drawer>

        <el-dialog
          title="统计信息"
          :visible.sync="dialogVisible"
          width="50%"
          custom-class="transition-dialog"
        >
          <ul class="scrollable-list">
            <li v-for="(item, index) in dataset" :key="index">
              任务名称： <span>{{ item.taskName }}</span> 时间跨度：<span>{{
                item.dataMinTime
              }}</span
              >~<span>{{ item.dataMaxTime }}</span>
            </li>
          </ul>
        </el-dialog>

        <el-descriptions
          class="incoming-desc"
          title="最新入库详情"
          :column="4"
          size="small"
          border
        >
          <el-descriptions-item label="任务名称">{{
            incoming.taskName || "--"
          }}</el-descriptions-item>
          <el-descriptions-item label="数据类型">{{
            incoming.transferTypeName || "--"
          }}</el-descriptions-item>
          <el-descriptions-item label="时间颗粒度">
            {{ incoming.timeGranularity ? `${incoming.timeGranularity}(秒)` : "--" }}
          </el-descriptions-item>
          <el-descriptions-item label="时间范围">
            {{
              incoming.dataMinTime && incoming.dataMaxTime
                ? `${incoming.dataMinTime}~${incoming.dataMaxTime}`
                : "--"
            }}
          </el-descriptions-item>
          <el-descriptions-item label="风场名称">{{
            incoming.windFarmName || "--"
          }}</el-descriptions-item>
          <el-descriptions-item label="机组数量">{{
            incoming.engineCount || "--"
          }}</el-descriptions-item>
          <el-descriptions-item label="入库时间">{{
            incoming.transferFinishTime || "--"
          }}</el-descriptions-item>
          <el-descriptions-item label="收资人">{{
            incoming.dataCollector || "--"
          }}</el-descriptions-item>
        </el-descriptions>
      </el-collapse-item>
    </el-collapse>

    <div class="condition">
      <div class="condition-item">
        <span class="condition-label">风场名称</span>
        <el-select v-model="windvalue" placeholder="请选择" size="small" clearable>
          <el-option
            v-for="item in windoptions"
            :key="item.fieldCode"
            :label="item.fieldName"
            :value="item.fieldCode"
          >
          </el-option>
        </el-select>
      </div>
      <div class="condition-item">
        <span class="condition-label">导入类型</span>
        <el-select v-model="typevalue" placeholder="请选择" size="small" clearable>
          <el-option
            v-for="item in typeoptions"
            :key="item.paramKey"
            :label="item.paramValue"
            :value="item.paramKey"
          >
          </el-option>
        </el-select>
      </div>
      <div class="condition-item">
        <span class="condition-label">导入状态</span>
        <el-select v-model="statevalue" placeholder="请选择" size="small" clearable>
          <el-option
            v-for="item in stateoptions"
            :key="item.transferStatus"
            :label="item.label"
            :value="item.transferStatus"
          >
          </el-option>
        </el-select>
      </div>

      <div class="condition-actions">
        <el-button size="small" @click="query">查询</el-button>
        <el-button size="small" @click="reset">重置</el-button>
        <el-button size="small" @click="newtransition" type="primary">新增转换</el-button>
      </div>
    </div>

    <el-dialog
      title="转换"
      :visible.sync="transitionShow"
      width="30%"
      custom-class="transition-dialog"
    >
      <el-form ref="form" :model="form" :rules="formRules" label-width="80px">
        <el-form-item label="选择风场" prop="wind">
          <el-select v-model="form.wind" clearable placeholder="请选择风场">
            <el-option
              v-for="item in windoptions"
              :key="item.fieldCode"
              :label="item.fieldName"
              :value="item.fieldCode"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="转换类型" prop="type">
          <el-select v-model="form.type" clearable placeholder="请选择转换类型">
            <el-option
              v-for="item in typeoptions"
              :key="item.paramKey"
              :label="item.paramValue"
              :value="item.paramKey"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="读取路径" prop="path">
          <el-input v-model="form.path" clearable />
        </el-form-item>

        <el-form-item label="收资人" prop="name">
          <el-input v-model="form.name" clearable />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
        </el-form-item>
      </el-form>

      <el-dialog
        width="40%"
        title="提交"
        :visible.sync="innerVisible"
        append-to-body
        custom-class="transition-dialog"
      >
        <div class="renwu">
          <p>
            任务名称：<el-input
              placeholder="请输入内容"
              v-model="nameinput"
              clearable
            >
            </el-input>
          </p>
          <el-button @click="onruku">确定</el-button>
        </div>
      </el-dialog>
    </el-dialog>

    <div class="table-section">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="风场编号:">
                <span>{{ props.row.windFarmCode }}</span>
              </el-form-item>
              <el-form-item label="风场名称:">
                <span>{{ props.row.windFarmName }}</span>
              </el-form-item>
              <el-form-item label="任务名称:">
                <span>{{ props.row.taskName }}</span>
              </el-form-item>
              <el-form-item label="收资人:">
                <span>{{ props.row.dataCollector }}</span>
              </el-form-item>
              <el-form-item label="原始数据读取路径:">
                <span>{{ props.row.readDir }}</span>
              </el-form-item>
              <el-form-item label="标准化数据保存路径:">
                <span>{{ props.row.archivePath }}</span>
              </el-form-item>
              <el-form-item label="时间跨度:">
                <span
                  >{{ props.row.dataMinTime }}~{{ props.row.dataMaxTime }}</span
                >
              </el-form-item>

              <el-form-item label="时间颗粒度(秒):">
                <span>{{ props.row.timeGranularity }}</span>
              </el-form-item>

              <el-form-item label="异常信息:" class="form-item">
                <span>{{ props.row.errInfo }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="风场名称" prop="windFarmName" width="200">
        </el-table-column>
        <el-table-column label="任务名称" prop="taskName"> </el-table-column>
        <el-table-column label="转换类型" prop="transferTypeName" width="130">
        </el-table-column>
        <el-table-column label="导入状态" prop="transferStatus" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.transferStatus === -1">等待导入</span>
            <span v-if="scope.row.transferStatus === 0">导入中</span>
            <span v-if="scope.row.transferStatus === 1">导入成功</span>
            <span v-if="scope.row.transferStatus === 2">导入失败</span>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" prop="createTime" width="300">
        </el-table-column>
        <el-table-column label="操作" prop="desc" width="150">
          <template slot-scope="scope">
            <el-button @click="editor(scope.row)" type="text" size="small">
              编辑
            </el-button>

            <el-button
              @click="restart(scope.row)"
              type="text"
              size="small"
              v-if="scope.row.transferStatus !== 1"
            >
              重新导入
            </el-button>
          </template></el-table-column
        >
      </el-table>
      <el-pagination
        class="fenye"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { getWindFieldNames } from "@/api/ledger.js";
import { log } from "plotly.js-dist";
export default {
  data() {
    return {
      dialogVisible: false,
      dataset: [],
      windFarmCount: "",
      typevalue: "",
      typeoptions: [],
      statevalue: "",
      incoming: {},
      stateoptions: [
        {
          transferStatus: -1,

          label: "等待导入",
        },
        {
          transferStatus: 0,

          label: "导入中",
        },
        {
          transferStatus: 1,

          label: "导入成功",
        },
        {
          transferStatus: 2,

          label: "导入失败",
        },
      ],
      activeNames: ["1"],
      windvalue: "",
      windoptions: [],
      currentPage: 1, // 当前页
      pageSize: 10, // 每页显示条数
      total: 0,
      drawer: false,
      tableData: [],
      Rklist: [],
      nameinput: "",
      transitionShow: false,
      innerVisible: false,
      form: {
        wind: "",
        type: "",
        path: "",
        name: "",
        id: null,
      },
      formRules: {
        wind: [{ required: true, message: "请选择风场", trigger: "blur" }],
        type: [{ required: true, message: "请选择转换类型", trigger: "blur" }],
        path: [{ required: true, message: "请输入读取路径", trigger: "blur" }],
        name: [{ required: true, message: "请输入收资人", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getchaxun();
    this.gettongji();
    this.getzuijin();
    this.windsite();
    this.query();
  },
  methods: {
    load() {
      this.count += 2;
    },

    async getchaxun() {
      const params = {
        type: "trans_type", // 假设 trans_type 是你传递的参数
      };
      try {
        const res = await axios.get("/ETLapi/sysConf/getByType", { params });
        this.typeoptions = res.data.datas;
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    },

    async gettongji() {
      try {
        const res = await axios.post("/ETLapi/dataTransfer/getStatisticalData");
        this.windFarmCount = res.data.datas.windFarmCount;
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    },

    async getzuijin() {
      try {
        const res = await axios.post(
          "/ETLapi/dataTransfer/recentlyImportedSuccessfulData"
        );
        this.incoming = res.data.datas;
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    },

    async windsite() {
      try {
        const res = await getWindFieldNames();
        this.windoptions = res.data;
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    },

    async query() {
      const params = {
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        transferStatus: this.statevalue,
        transferType: this.typevalue,
        windFarmCode: this.windvalue,
      };
      try {
        const res = await axios.post(
          "/ETLapi/dataTransfer/getDataTransfer",
          params
        );
        this.tableData = res.data.datas;
        this.total = res.data.totalCount;
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    },

    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.query(); // 更新后重新请求数据
    },

    // 处理页码变化
    handleCurrentChange(page) {
      this.currentPage = page; // 更新当前页
      this.query(); // 重新请求数据
    },
    reset() {
      this.windvalue = "";
      this.typevalue = "";
      this.statevalue = "";
      this.currentPage = 1;
      this.query();
    },

    restart(row) {
      axios
        .get(`/ETLapi/dataTransfer/reTransfer/${row.id}`)
        .then((res) => {
          if (res.data.code === 200) {
            this.$message({
              message: "重新导入成功",
              type: "success",
            });
            this.query();
          }
          if (res.data.code === 500) {
            this.$message.error(res.data.message);
          }
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
        });
    },

    database() {
      this.drawer = true;
      axios
        .post(`/ETLapi/dataTransfer/classificationImportDataDetails`)
        .then((res) => {
          if (res.data.code === 200) {
            this.Rklist = res.data.datas;
          }
          if (res.data.code === 500) {
            this.$message.error(res.data.message);
          }
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
        });
    },

    details(windFarmCode, type) {
      // console.log(windFarmCode, type);
      // return;
      const params = {
        pageNo: "1",
        pageSize: "999",
        transferStatus: 1,
        transferType: type.transferType,
        windFarmCode: windFarmCode,
      };
      axios
        .post("/ETLapi/dataTransfer/getDataTransfer", params)
        .then((res) => {
          if (res.data.datas.length === 0) {
            // 判断是否为0，避免与字符串 "0" 比较
            this.$message("当前数据暂无入库信息！");
          } else {
            this.dialogVisible = true;
            this.dataset = res.data.datas;
          }
        })

        .catch((error) => {
          console.error("Error fetching data:", error);
        });
    },

    newtransition() {
      this.transitionShow = true;
    },

    editor(row) {
      // return
      this.transitionShow = true;
      this.form.name = row.dataCollector;
      this.form.path = row.readDir;
      this.form.type = row.transferType;
      this.form.wind = row.windFarmCode;

      this.form.id = row.id;
    },

    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 表单验证通过，执行提交操作
          const currentTime = this.$formatDateTWO(new Date());
          const selectedWind = this.windoptions.find(
            (option) => option.fieldCode === this.form.wind
          );
          const selectedType = this.typeoptions.find(
            (option) => option.paramKey === this.form.type
          );
          const windLabel = selectedWind ? selectedWind.fieldName : "";
          const typeLabel = selectedType ? selectedType.paramValue : "";

          // 拼接 nameinput
          this.nameinput = `${windLabel}${typeLabel}${currentTime}`;
          this.innerVisible = true;
        } else {
          console.log("表单验证失败");
        }
      });
    },
    onruku() {
      const params = {
        dataCollector: this.form.name,
        readDir: this.form.path,
        taskName: this.nameinput,
        transferType: this.form.type,
        windFarmCode: this.form.wind,
        windFarmName:
          this.windoptions.find((option) => option.fieldCode === this.form.wind)
            ?.fieldName || "",
      };

      let apiUrl = "/ETLapi/dataTransfer/addDataTransferTask"; // 默认是新增
      if (this.form.id) {
        // 如果有 id，说明是编辑
        apiUrl = "/ETLapi/dataTransfer/editDataTransferTask";
        params.id = this.form.id; // 传递 id
      }

      axios.post(apiUrl, params).then((res) => {
        this.innerVisible = false;
        this.transitionShow = false;
        if (res.data.code === 200) {
          this.$message({
            message: "操作成功",
            type: "success",
          });
          this.query();
        }
        if (res.data.code === 500) {
          this.$message.error(res.data.message);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.transition-page {
  min-height: calc(100vh - 120px);
  width: 100%;
  padding: 12px 16px;
  background: var(--transition-page-bg, var(--panel-bg, #ffffff));
  color: var(--transition-page-text, #303133);
  box-sizing: border-box;

  ::v-deep .transition-collapse {
    border: 1px solid var(--transition-border-color, #ebeef5) !important;
    border-radius: 4px;
    overflow: hidden;

    .el-collapse-item__header {
      height: 40px;
      line-height: 40px;
      padding: 0 12px;
      font-weight: 600;
      font-size: 15px;
      background: var(--transition-collapse-header-bg, var(--primary-color, #008080)) !important;
      color: var(--transition-collapse-header-text, #ffffff) !important;
      border-bottom-color: var(--transition-border-color, #ebeef5) !important;
    }

    .el-collapse-item__wrap {
      background: var(--transition-collapse-body-bg, #ffffff) !important;
      border-bottom-color: var(--transition-border-color, #ebeef5) !important;
    }

    .el-collapse-item__content {
      padding: 10px 12px 6px;
      color: var(--transition-page-text, #303133);
      background: var(--transition-collapse-body-bg, #ffffff);
    }
  }

  .incoming-desc {
    margin-top: 8px;

    ::v-deep .el-descriptions__header {
      margin-bottom: 8px;
    }

    ::v-deep .el-descriptions__title {
      font-size: 14px;
      color: var(--transition-page-text, #303133);
    }

    ::v-deep .el-descriptions__label {
      color: #606266;
    }

    ::v-deep .el-descriptions__content {
      color: var(--transition-page-text, #303133);
    }

    ::v-deep .el-descriptions-item__cell {
      padding: 6px 10px !important;
    }
  }

  .condition {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 12px 16px;
    padding: 10px 0 8px;
    margin-top: 4px;
    border-bottom: 1px solid var(--transition-border-color, #ebeef5);
  }

  .condition-item {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .condition-label {
    color: var(--transition-label-color, #606266);
    white-space: nowrap;
    font-size: 14px;
  }

  .condition-actions {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-left: auto;
  }

  .table-section {
    margin-top: 8px;
  }
}

.CPC {
  border: 1px solid var(--transition-badge-border, var(--primary-color, #008080));
  background: var(--transition-badge-bg, rgba(0, 128, 128, 0.08));
  display: inline-block;
  padding: 6px 12px;
  margin: 0 0 4px;
  color: var(--transition-page-text, #303133);
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  line-height: 1.4;

  span {
    color: var(--transition-badge-accent, var(--primary-color, #008080));
    font-weight: 600;
  }

  &:hover {
    background: var(--transition-badge-bg-hover, rgba(0, 128, 128, 0.15));
  }
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: var(--transition-label-color, #606266);
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.fenye {
  display: flex;
  justify-content: center;
  padding: 12px 0 4px;
}
.card {
  margin: 8px 16px;
  border-radius: 4px;
  padding: 12px 16px;
  border: 1px solid var(--transition-border-color, #ebeef5);
  background: var(--transition-card-bg, #ffffff);
  color: var(--transition-page-text, #303133);
  box-shadow: none;

  p {
    font-weight: 600;
    font-size: 15px;
    margin: 0 0 8px;
  }

  ul {
    padding-left: 0;
    margin: 0;
    list-style: none;

    li {
      padding: 6px 8px;
      border-radius: 4px;
    }

    li:hover {
      background: var(--transition-card-hover-bg, rgba(0, 128, 128, 0.08));
      color: var(--transition-page-text, #303133);
      cursor: pointer;
    }

    span {
      display: inline-block;
    }

    .sp1 {
      width: 120px;
    }

    .sp2 {
      width: 50px;
    }
  }
}

.renwu {
  display: flex;
  .el-input {
    width: 400px;
    margin-right: 20px;
  }
}
.demo-table-expand {
  display: flex;
  flex-wrap: wrap;
  /* 允许换行 */
  gap: 0px;
  /* 子元素间距 */
}

.demo-table-expand .el-form-item {
  flex: 1 1 100%;
  /* 每个表单项占满一行 */
  display: inline-flex;
  /* 让每个项都在一行显示 */
  margin-bottom: 0;
  /* 去掉多余的底部边距 */
}

.demo-table-expand .el-form-item label {
  width: 120px;
  /* 可以根据需要调整标签宽度 */
  margin-right: 10px;
  /* 标签和内容的间距 */
}

.demo-table-expand .el-form-item span {
  flex: 1;
  /* 内容占满剩余空间 */
}

/* 确保 label 能根据内容换行 */
.form-item {
  display: flex;
  /* 使用 Flexbox 布局 */
  flex-wrap: wrap;
  /* 允许换行 */
  align-items: center;
  /* 标签和内容在垂直方向上对齐 */
}

.form-item label {
  white-space: normal;
  /* 允许标签文本换行 */
  word-wrap: break-word;
  /* 自动断行 */
  max-width: 150px;
  /* 限制标签宽度，防止过长 */
}

.form-item span {
  flex: 1;
  /* 内容部分占满剩余空间 */
  word-wrap: break-word;
  /* 内容部分也允许换行 */
  white-space: normal;
  /* 内容部分的文本能自动换行 */
}

.scrollable-list {
  height: 400px;
  overflow-y: auto;
  color: var(--transition-page-text, #303133);
  padding: 0;
  margin: 0;
  list-style: none;
}

.scrollable-list::-webkit-scrollbar {
  width: 8px;
}

.scrollable-list::-webkit-scrollbar-track {
  background: var(--transition-scrollbar-track, #f5f7fa);
  border-radius: 4px;
}

.scrollable-list::-webkit-scrollbar-thumb {
  background: var(--transition-scrollbar-thumb, #dcdfe6);
  border-radius: 4px;
}

.scrollable-list::-webkit-scrollbar-thumb:hover {
  background: var(--transition-scrollbar-thumb-hover, #c0c4cc);
}

::v-deep .transition-drawer .el-drawer__header > :first-child,
::v-deep .transition-dialog .el-dialog__title {
  font-size: 16px;
  font-weight: 600;
  color: var(--transition-page-text, #303133);
}

.demo-table-expand {
  padding-left: 60px;
}
</style>
