<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="elform">
              <div style="display: flex; align-items: center">
                <el-form-item label="电站名称" prop="powerName" :rules="[{ required: true, message: '请输入电站名称' }]">
                  <el-input
                    v-model="numberValidateForm.powerName"
                    style="width: 300px"
                    size="large"
                    type="text"
                    placeholder="请输入电站名称"
                    autocomplete="off"
                  />
                </el-form-item>
              </div>

              <el-form-item label="绑定设备" prop="emsId" :rules="[{ required: true, message: '请选择绑定设备' }]">
                <el-select
                  multiple
                  v-model="selectemsId"
                  placeholder="请选择绑定设备"
                  size="large"
                  style="width: 300px"
                  @change="onselect"
                >
                  <el-option v-for="item in equipmentdata" :key="item.eid" :label="item.emsDeviceId" :value="item.eid" />
                </el-select>
              </el-form-item>
            </div>
            <div class="elform">
              <el-form-item label="安装人">
                <el-input
                  v-model.number="numberValidateForm.installerName"
                  style="width: 300px"
                  size="large"
                  type="text"
                  placeholder="请输入安装人"
                  autocomplete="off"
                />
              </el-form-item>
              <el-form-item label="安装人联系电话">
                <el-input
                  v-model.number="numberValidateForm.contactPhone"
                  style="width: 300px"
                  size="large"
                  type="text"
                  placeholder="请输入安装人联系电话"
                  autocomplete="off"
                />
              </el-form-item>
            </div>
            <div class="elform">
              <!-- <el-form-item label="电站联系电话">
                <el-input
                  v-model.number="numberValidateForm.stationtelephone"
                  style="width: 300px"
                  size="large"
                  type="text"
                  placeholder="请输入电站联系电话"
                  autocomplete="off"
                />
              </el-form-item> -->
              <el-form-item label="电站地址">
                <el-cascader
                  :props="props"
                  v-model="selectedValue"
                  clearable
                  size="large"
                  :placeholder="selectedValuename"
                  @change="oncascader"
                  @visible-change="handleVisibleChange"
                  style="width: 300px; margin-right: 20px"
                />
              </el-form-item>
              <div class="elform1">
                <el-form-item label="投运时间" prop="operationDate" :rules="[{ required: true, message: '请选择投运时间' }]">
                  <el-date-picker
                    v-model="numberValidateForm.operationDate"
                    type="date"
                    size="large"
                    style="width: 300px"
                    placeholder="请选择投运时间"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :default-value="timedate"
                    :disabled-date="pickerOptions"
                  />
                </el-form-item>
              </div>
            </div>
            <div class="elform">
              <el-form-item label="详细地址" prop="detailedaddress" :rules="[{ required: true, message: '请输入装机功率' }]">
                <el-input
                  v-model="numberValidateForm.detailedaddress"
                  style="width: 300px"
                  size="large"
                  type="text"
                  placeholder="请输入装机功率"
                  autocomplete="off"
                />
              </el-form-item>
              <el-form-item label="装机容量" prop="installedCap" :rules="[{ required: true, message: '请输入装机功率' }]">
                <el-input
                  v-model="numberValidateForm.installedCap"
                  style="width: 300px"
                  size="large"
                  type="text"
                  placeholder="请输入装机容量"
                  autocomplete="off"
                />
              </el-form-item>
            </div>
            <div class="elform">
              <el-form-item label="经度" prop="longitude" :rules="[{ required: true, message: '请输入装机功率' }]">
                <el-input
                  v-model="numberValidateForm.longitude"
                  style="width: 300px"
                  size="large"
                  type="text"
                  placeholder="请输入装机功率"
                  autocomplete="off"
                />
              </el-form-item>

              <el-form-item label="经度" prop="latitude" :rules="[{ required: true, message: '请输入装机功率' }]">
                <el-input
                  v-model="numberValidateForm.latitude"
                  style="width: 300px"
                  size="large"
                  type="text"
                  placeholder="请输入装机容量"
                  autocomplete="off"
                />
              </el-form-item>
            </div>
            <div class="elform">
              <el-form-item label="装机功率" prop="installedPower" :rules="[{ required: true, message: '请输入装机功率' }]">
                <el-input
                  v-model="numberValidateForm.installedPower"
                  style="width: 300px"
                  size="large"
                  type="text"
                  placeholder="请输入装机功率"
                  autocomplete="off"
                />
              </el-form-item>
            </div>
            <!-- <div class="elform">
              <el-form-item label="并网点信息">
                <el-input
                  v-model.number="numberValidateForm.connection"
                  style="width: 300px"
                  size="large"
                  type="text"
                  placeholder="请输入并网点信息"
                  autocomplete="off"
                />
              </el-form-item>
              <el-form-item label="变压器信息">
                <el-input
                  v-model.number="numberValidateForm.transformer"
                  style="width: 300px"
                  size="large"
                  type="text"
                  placeholder="请输入变压器信息"
                  autocomplete="off"
                />
              </el-form-item>
            </div> -->
            <div class="elform">
              <!-- <div>
                <el-form-item label="站点变压器容量">
                  <el-input
                    v-model.number="numberValidateForm.transformercapacity"
                    style="width: 300px"
                    size="large"
                    type="text"
                    placeholder="请输入站点变压器容量"
                    autocomplete="off"
                  />
                </el-form-item>
              </div> -->

              <div class="elform1">
                <el-form-item label="电站图片">
                  <UploadImgs v-model:file-list="absoluteStationPicUr1" width="300px" :limit="9">
                    <template #empty>
                      <el-icon><Picture /></el-icon>
                      <span>请上传电站图片</span>
                    </template>
                    <template #tip>图片类型 __ jpg jpeg png</template>
                  </UploadImgs>
                </el-form-item>
              </div>
            </div>
            <div class="elform">
              <div class="elform1">
                <el-form-item label="电站布局图">
                  <UploadImgs v-model:file-list="layoutPicUr1" width="300px" :limit="9">
                    <template #empty>
                      <el-icon><Picture /></el-icon>
                      <span>请上传电站图片</span>
                    </template>
                    <template #tip>图片类型 __ jpg jpeg png</template>
                  </UploadImgs>
                </el-form-item>
              </div>
            </div>

            <el-divider />
            <el-form-item class="bottom">
              <el-button type="primary" @click="submitForm(formRef)">保存</el-button>
              <el-button @click="resetForm(formRef)">关闭</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>
<!--    -->
<script setup lang="ts">
import {
  updatesingleeditURL,
  editpowerURL,
  selectemssytemALLURL,
  insertpowerURL,
  getlistcountry,
  getliststate,
  getlistcity,
  getlistcounty
} from "@/api/home/Multisite";
import { CascaderOption, CascaderProps, FormInstance } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import UploadImgs from "@/components/Upload/Imgs.vue";
const router = useRouter();
const route = useRoute();

const formRef = ref<FormInstance>();
const supertype = ref(route.query.type);
const selectedValue = ref([44]);
const selectedValuename = ref("请选择地区");
const absoluteStationPicUr1 = ref();
const layoutPicUr1 = ref();
const numberValidateForm = reactive({
  id: "",
  powerName: "", // 电站名称
  url: [], // 图片
  arrangementplan: [],
  // stationtelephone: "", // 电话
  emsId: "", //设备id
  address: "", // 地址
  installerName: "", // 安装人名称
  contactPhone: "", // 安装人电话
  installedPower: "", // 装机功率
  installedCap: "", //装机容量
  // connection: "",
  // transformer: "",
  // transformercapacity: "",
  operationDate: "", // 投运时间
  Category: 0, // 国家id
  provinceCode: 0, // 省id
  cityCode: 0, // 市id
  countyCode: 0, //区id
  longitude: 0, // 经度
  latitude: 0, //维度
  detailedaddress: "" //详细地址
});
const timedate = ref();
const pickerOptions = (time: { getTime: (arg0: Date) => number }) => {
  return time.getTime(new Date()) > Date.now();
};

const submitForm = (formEl: FormInstance | undefined) => {
  numberValidateForm.Category = selectedValue.value[0] ?? 0;
  numberValidateForm.provinceCode = selectedValue.value[1] ?? 0;
  numberValidateForm.cityCode = selectedValue.value[2] ?? 0;
  numberValidateForm.countyCode = selectedValue.value[3] ?? 0;

  if (!formEl) return;
  // formEl.validate(async valid => {
  //   if (valid) {
  //     if (route.query.type == "电站新增") {
  //       // numberValidateForm.emsId;

  //       numberValidateForm.url = absoluteStationPicUr1.value.map((item: { url: any }) => item.url).join(", ");
  //       numberValidateForm.arrangementplan = layoutPicUr1.value.map((item: { url: any }) => item.url).join(", ");
  //       const { data } = await insertpowerURL(numberValidateForm);
  //       console.log(data);
  //     } else {
  //       numberValidateForm.url = absoluteStationPicUr1.value.map((item: { url: any }) => item.url).join(", ");
  //       numberValidateForm.arrangementplan = layoutPicUr1.value.map((item: { url: any }) => item.url).join(", ");
  //       const { data } = await updatesingleeditURL(numberValidateForm);
  //       console.log(data);
  //     }
  //     router.back();
  //   } else {
  //     console.log("error submit!");
  //     return false;
  //   }
  // });
  formEl.validate(async valid => {
    if (valid) {
      // Prepare URL fields only once
      const urls = absoluteStationPicUr1.value.map((item: { url: any }) => item.url).join(", ");
      const arrangements = layoutPicUr1.value.map((item: { url: any }) => item.url).join(", ");

      numberValidateForm.url = urls;
      numberValidateForm.arrangementplan = arrangements;

      try {
        let responseData;

        if (route.query.type === "电站新增") {
          // Add a new power station
          responseData = await insertpowerURL(numberValidateForm);
        } else {
          // Update an existing power station
          responseData = await updatesingleeditURL(numberValidateForm);
        }

        console.log(responseData.data);
        router.back(); // Navigate back after success
      } catch (error) {
        console.error("Submission error:", error);
      }
    } else {
      console.log("Validation failed!");
    }
  });
};
const selectemsId = ref();
const onselect = () => {
  console.log(selectemsId.value);

  numberValidateForm.emsId = selectemsId.value.join();
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  router.push("/powerStation/index");
};
const yonghueditdata = ref();
const getghuedit = async () => {
  const { data } = await editpowerURL(route.query.id, {});
  yonghueditdata.value = data;

  numberValidateForm.id = yonghueditdata.value[0].powerId;
  numberValidateForm.powerName = yonghueditdata.value[0].stationName;
  numberValidateForm.installerName = yonghueditdata.value[0].installerName;
  numberValidateForm.url = yonghueditdata.value[0].url;
  numberValidateForm.arrangementplan = yonghueditdata.value[0].arrangementurl;
  selectemsId.value = [];
  for (let index = 0; index < yonghueditdata.value[0].emsid.length; index++) {
    let a = yonghueditdata.value[0].emsid[index].eid;
    selectemsId.value.push(a);
  }
  numberValidateForm.emsId = selectemsId.value.join();
  // numberValidateForm.address = yonghueditdata.value[0].address;
  numberValidateForm.contactPhone = yonghueditdata.value[0].contactPhone;
  numberValidateForm.installedPower = yonghueditdata.value[0].installedPower;
  numberValidateForm.installedCap = yonghueditdata.value[0].installedCap;
  numberValidateForm.operationDate = yonghueditdata.value[0].operationDate;
  numberValidateForm.longitude = yonghueditdata.value[0].longitude;
  numberValidateForm.latitude = yonghueditdata.value[0].latitude;
  numberValidateForm.detailedaddress = yonghueditdata.value[0].detailedaddress;
  absoluteStationPicUr1.value = [];
  for (let index = 0; index < yonghueditdata.value[0].url.length; index++) {
    absoluteStationPicUr1.value.push({
      url: yonghueditdata.value[0].url[index]
    });
  }

  layoutPicUr1.value = [];
  for (let index = 0; index < yonghueditdata.value[0].arrangementurl.length; index++) {
    layoutPicUr1.value.push({
      url: yonghueditdata.value[0].arrangementurl[index]
    });
  }

  selectedValue.value = [];
  if (yonghueditdata.value[0].citiesname) {
    selectedValuename.value =
      yonghueditdata.value[0].countriesname +
      "/" +
      yonghueditdata.value[0].statesname +
      "/" +
      yonghueditdata.value[0].citiesname +
      "/" +
      yonghueditdata.value[0].regionsname;
  } else {
    selectedValuename.value = "请选择地址";
  }

  // console.log(selectedValue.value);
  grtselectemssytem();
};
// 选择设备编码 ----
const equipmentdata = ref();
const grtselectemssytem = async () => {
  const { data } = await selectemssytemALLURL({});
  let arr = data;
  console.log(arr);
  if (route.query.type == "电站编辑") {
    const emsidArray = yonghueditdata.value[0].emsid as any[];
    const arrArray = arr as any[];
    equipmentdata.value = [...emsidArray, ...arrArray];
  } else {
    const arrArray = arr as any[];
    equipmentdata.value = [...arrArray];
  }

  console.log(equipmentdata.value);
};
// 地区
const countrydata = ref();
const statedata = ref();
const citydata = ref();
const countydata = ref();
// const selectedOptions = ref(44);
const props: CascaderProps = {
  lazy: true,
  checkStrictly: true,
  async lazyLoad(node, resolve) {
    console.log(node);
    console.log(selectedValue.value);
    if (node.level == 0) {
      // node为当前点击的节点，resolve为数据加载完成的回调(必须调用)
      let nodes: CascaderOption[] | undefined = [];
      // 构造查询条件 => 接口入参
      let params = {
        id: node.value // 入参名按照自己的接口来改
      };
      // 请求接口
      let { data } = await getlistcountry(params);
      // console.log(Object.values(data));
      if (data) {
        countrydata.value = data;
        countrydata.value.map((item: { id: any; chineseName: any }) => {
          let obj = {
            value: item.id,
            label: item.chineseName,
            leaf: node.level >= 3 // 当 node.level 层级达到2级时, 就不再请求接口
            // 具体要多少级才不请求接口, 根据层级修改
          };
          nodes?.push(obj);
        });
      }
      //重新加载节点
      resolve(nodes);
    } else if (node.level == 1) {
      // node为当前点击的节点，resolve为数据加载完成的回调(必须调用)
      let nodes: CascaderOption[] | undefined = [];
      // 构造查询条件 => 接口入参
      let params = {
        countryId: node.value // 入参名按照自己的接口来改
      };
      // 请求接口
      let { data } = await getliststate(params);
      if (data) {
        statedata.value = data;
        statedata.value.map((item: { id: any; chineseName: any }) => {
          let obj = {
            value: item.id,
            label: item.chineseName,
            leaf: node.level >= 3 // 当 node.level 层级达到2级时, 就不再请求接口
            // 具体要多少级才不请求接口, 根据层级修改
          };
          nodes?.push(obj);
        });
      }
      //重新加载节点
      resolve(nodes);
    } else if (node.level == 2) {
      // node为当前点击的节点，resolve为数据加载完成的回调(必须调用)
      let nodes: CascaderOption[] | undefined = [];
      // 构造查询条件 => 接口入参
      let params = {
        stateId: node.value // 入参名按照自己的接口来改
      };
      // 请求接口
      let { data } = await getlistcity(params);
      if (data) {
        citydata.value = data;
        citydata.value.map((item: { id: any; chineseName: any }) => {
          let obj = {
            value: item.id,
            label: item.chineseName,
            leaf: node.level >= 3 // 当 node.level 层级达到2级时, 就不再请求接口
            // 具体要多少级才不请求接口, 根据层级修改
          };
          nodes?.push(obj);
        });
      }
      //重新加载节点
      resolve(nodes);
    } else if (node.level == 3) {
      // node为当前点击的节点，resolve为数据加载完成的回调(必须调用)
      let nodes: CascaderOption[] | undefined = [];
      // 构造查询条件 => 接口入参
      let params = {
        cityId: node.value // 入参名按照自己的接口来改
      };
      // 请求接口
      let { data } = await getlistcounty(params);
      countydata.value = data;
      if (data) {
        countydata.value.map((item: { id: any; chineseName: any }) => {
          let obj = {
            value: item.id,
            label: item.chineseName,
            leaf: true // 当 node.level 层级达到2级时, 就不再请求接口
            // 具体要多少级才不请求接口, 根据层级修改
          };
          nodes?.push(obj);
        });
      }
      //重新加载节点
      resolve(nodes);
    }
  }
};
// 中国省市县
const oncascader = async (selectedValues: any) => {
  console.log(selectedValues);
  selectedValue.value = selectedValues;
  console.log(selectedValue.value);
};
const handleVisibleChange = async (visible: any) => {
  if (route.query.type == "电站编辑") {
    if (visible) {
      selectedValue.value = [44];
    } else {
      if (selectedValue.value.length > 2) {
      } else {
        selectedValue.value = [];
        if (yonghueditdata.value[0].citiesname) {
          selectedValuename.value =
            yonghueditdata.value[0].countriesname +
            "/" +
            yonghueditdata.value[0].statesname +
            "/" +
            yonghueditdata.value[0].citiesname +
            "/" +
            yonghueditdata.value[0].regionsname;
        } else {
          selectedValuename.value = "请选择地址";
        }
      }
    }
  }
};

onMounted(() => {
  if (route.query.type == "电站编辑") {
    getghuedit();
  } else {
    grtselectemssytem();
  }
});
</script>
<!--  -->
<style scoped lang="scss">
@import "./addition.scss";
</style>
<!--
    
 -->
