<template>
  <div>
    <div class="card content-box">
      <div class="name">{{ supertype }}</div>
      <el-divider />
      <div class="user_box">
        <div class="user_left">
          <el-form ref="formRef" :model="numberValidateForm" label-width="auto" class="demo-ruleForm">
            <div class="elform1">
              <!-- <el-form-item label="标签：">
                <el-input
                  v-model.number="numberValidateForm.remark"
                  style="width: 300px"
                  size="large"
                  type="text"
                  placeholder="请输入标签"
                  autocomplete="off"
                />
              </el-form-item> -->
              <div class="elform">
                <el-form-item
                  :label="$t('Administration.TemplateName')"
                  prop="postName"
                  :rules="[{ required: true, message: $t('Administration.Pleasename') }]"
                >
                  <el-input
                    v-model="numberValidateForm.postName"
                    style="width: 300px"
                    size="large"
                    type="text"
                    :placeholder="$t('Administration.Pleasename')"
                    autocomplete="off"
                  />
                </el-form-item>
                <el-button type="primary" @click="addNewRow">{{ $t("Administration.AddLine") }}</el-button>
              </div>
              <div class="elform"></div>
              <el-table :data="tableData" border style="width: 100%">
                <el-table-column prop="startTime" :label="$t('Administration.Startingperiod')">
                  <template #default="scope">
                    <!-- <el-input v-model="scope.row.startTime" @change="handleEdit(scope.$index, scope.row)"></el-input> -->
                    <el-time-select
                      v-model="scope.row.startTime"
                      start="00:00"
                      step="00:30"
                      end="24:00"
                      :placeholder="$t('Administration.Selectstart')"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="endTime" :label="$t('Administration.Endperiod')">
                  <template #default="scope">
                    <!-- <el-input v-model="scope.row.endTime" @change="handleEdit(scope.$index, scope.row)"></el-input> -->
                    <el-time-select
                      v-model="scope.row.endTime"
                      start="00:00"
                      step="00:30"
                      end="24:00"
                      :placeholder="$t('Administration.Endperiod')"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="periodType" :label="$t('Administration.peakvalue')">
                  <template #default="scope">
                    <!-- <el-input v-model="scope.row.periodType" @change="handleEdit(scope.$index, scope.row)"></el-input> -->
                    <el-select
                      v-model="scope.row.periodType"
                      collapse-tags
                      :placeholder="$t('Administration.ChooseJianfeng')"
                      popper-class="custom-header"
                      :max-collapse-tags="1"
                      size="large"
                    >
                      <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="buyPrice" :label="$t('Administration.Endperiod')">
                  <template #default="scope">
                    <el-input v-model="scope.row.buyPrice" type="number"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="salePrice" :label="$t('Administration.Sellingelectricity')">
                  <template #default="scope">
                    <el-input v-model="scope.row.salePrice" type="number"></el-input>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('Administration.Actions')" width="80">
                  <template #default="scope">
                    <div @click="handleEdit(scope.$index)">{{ $t("Administration.delete") }}</div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <el-divider />
            <el-form-item class="bottom">
              <el-button type="primary" @click="submitForm(formRef)">{{ $t("Administration.save") }}</el-button>
              <el-button @click="resetForm(formRef)">{{ $t("Administration.close") }}</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>
<!--    -->
<script setup lang="ts">
import { insertschedule, selectscheduletariffidURL, electricityupdateURL } from "@/api/home/Multisite";
import { FormInstance } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { nextTick } from "vue";
import { ElMessage } from "element-plus";

const router = useRouter();
const route = useRoute();

const formRef = ref<FormInstance>();
const supertype = ref(route.query.type);
const options = ref([
  {
    value: 1,
    label: "尖"
  },
  {
    value: 2,
    label: "峰"
  },
  {
    value: 3,
    label: "平"
  },
  {
    value: 4,
    label: "谷"
  }
]);
const numberValidateForm = reactive({
  postName: ""
});

const submitForm = (formEl: FormInstance | undefined) => {
  console.log(tableData);
  if (!formEl) return;
  // formEl.validate(async valid => {
  //   if (valid) {
  //     if (!validateData()) return;
  //     if (route.query.type == "模板新增") {
  //       const { data } = await insertschedule(tableData, numberValidateForm.postName);
  //       console.log(data);
  //       router.push({ path: "/Administration/index", query: { id: "模板管理" } });
  //     } else {
  //       const { data } = await electricityupdateURL(numberValidateForm.postName, scheduleVOS.value.data[0].id, tableData);
  //       console.log(data);
  //       router.push({ path: "/Administration/index", query: { id: "模板管理" } });
  //     }
  //   } else {
  //     console.log("error submit!");
  //     return false;
  //   }
  // });
  formEl.validate(async valid => {
    if (valid) {
      if (!validateData()) return;

      try {
        let responseData;

        if (route.query.type === "模板新增") {
          responseData = await insertschedule(tableData, numberValidateForm.postName);
        } else {
          responseData = await electricityupdateURL(numberValidateForm.postName, scheduleVOS.value.data[0].id, tableData);
        }

        console.log(responseData.data);
        ElMessage.success("操作成功"); // User feedback for success
        router.push({ path: "/Administration/index", query: { id: "模板管理" } }); // Consolidated navigation
      } catch (error) {
        console.error("Submission error:", error);
        ElMessage.error("提交失败，请重试！"); // Inform the user about submission failure
      }
    } else {
      console.log("Validation failed!");
      ElMessage.warning("请检查表单填写是否正确！"); // Inform the user about validation failure
    }
  });
};
const validateData = () => {
  if (tableData.length == 0) {
    ElMessage({ type: "error", message: `请填写电价模板表格` });
    return false;
  }
  for (const row of tableData) {
    if (
      row.startTime === undefined ||
      row.endTime === undefined ||
      row.periodType == "" ||
      row.buyPrice == "" ||
      row.salePrice == ""
    ) {
      // message.error("所有字段都必须填写");
      ElMessage({ type: "error", message: `所有字段都必须填写` });

      return false;
    }
  }
  return true;
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  router.push({ path: "/Administration/index", query: { id: "模板管理" } });
};

interface TableData {
  startTime: string;
  endTime: string;
  periodType: string;
  buyPrice: string;
  salePrice: string;
  id: string;
}
const tableData = reactive<TableData[]>([]);
// 新增行
const addNewRow = () => {
  const newRow = ref<TableData>({
    startTime: "",
    endTime: "",
    periodType: "",
    buyPrice: "",
    salePrice: "",
    id: ""
  });
  tableData.push(newRow.value);

  nextTick(() => {
    const tableBody = document.querySelector(".el-table__body-wrapper");
    if (tableBody) {
      tableBody.scrollTop = tableBody.scrollHeight;
    }
  });
};
const handleEdit = (index: number) => {
  // 处理编辑逻辑，例如更新数据源或发送请求
  tableData.splice(index, 1);
};
// 回显电价
const scheduleVOS = ref();
const getghuedit = async () => {
  const { data } = await selectscheduletariffidURL(route.query.id);
  console.log(data);
  scheduleVOS.value = data;
  numberValidateForm.postName = scheduleVOS.value.data[0].name;
  // tableData = scheduleVOS.value.scheduleVOS;
  for (let index = 0; index < scheduleVOS.value.scheduleVOS.length; index++) {
    tableData.push(scheduleVOS.value.scheduleVOS[index]);
  }
};
onMounted(() => {
  if (route.query.type == "电价编辑") {
    getghuedit();
  }
});
</script>
<style scoped lang="scss">
@import "./addition.scss";
</style>
<!-- -->
