<template>
  <div class="global-variable" v-loading="loading">
    <div
      class="condition"
      style="display: flex; justify-content: space-between"
    >
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="风场名称:">
          <el-input
            v-model="formInline.fieldName"
            placeholder="请输入风场名称"
            size="small"
            class="search-input"
          ></el-input>
        </el-form-item>
        <el-form-item label="选择日期:" size="small">
          <el-date-picker
            v-model="formInline.timeQuantum"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="onDateChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所属公司:">
          <el-input
            v-model="formInline.windCompany"
            placeholder="所属公司"
            size="small"
            class="search-input"
          ></el-input>
        </el-form-item>

        <el-form-item label="所在省:">
          <el-select
            v-model="form.shengfeng"
            placeholder="请选择"
            value-key="areaId"
            @change="handleProvinceChange"
            size="small"
            class="search-input"
          >
            <el-option
              v-for="item in provinceNameOptions"
              :key="item.areaId"
              :label="item.province"
              :value="item.areaId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit" size="small"
            >查询</el-button
          >
          <el-button @click="reset" size="small">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="newly">
        <el-button @click="upfile" size="small">导入</el-button>
        <el-button @click="newnuedialog" size="small">新增</el-button>
      </div>
    </div>
    <div class="list-page">
      <el-table
        class="center-align-table"
        :data="tableData"
        border
        :cell-style="rowStyle"
      >
        <el-table-column align="center" fixed prop="" label="风场名称">
          <template slot-scope="scope">
            <el-button
              @click="particulars(scope.row)"
              type="text"
              size="small"
              >{{ scope.row.fieldName }}</el-button
            >
          </template>
        </el-table-column>

        <el-table-column prop="windCompany" align="center" label="所属公司">
        </el-table-column>
        <el-table-column
          prop="windCompany"
          align="center"
          label="风机数量"
          min-width="80"
        >
          <template slot-scope="scope">
            <el-button @click="ONdraught(scope.row)" type="text" size="small">{{
              scope.row.wegNumber
            }}</el-button>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="abnormal"
          label="测风塔"
          min-width="70"
        >
          <template slot-scope="scope">
            <el-button
              @click="ONanemometer(scope.row)"
              type="text"
              size="small"
              >{{ scope.row.atrNumber }}</el-button
            >
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="contractNumber"
          label="合同功率曲线数"
          min-width="100"
        >
          <template slot-scope="scope">
            <el-button @click="ONcurve(scope.row)" type="text" size="small">{{
              scope.row.contractNumber
            }}</el-button>
          </template>
        </el-table-column>

        <el-table-column
          prop="provinceName"
          align="center"
          min-width="100"
          label="所在省/市/自治区"
        >
        </el-table-column>
        <el-table-column
          prop="cityName"
          align="center"
          min-width="100"
          label="所在市"
        >
        </el-table-column>

        <el-table-column
          prop="createTime"
          align="center"
          label="创建时间"
          min-width="160"
        >
        </el-table-column>

        <el-table-column
          prop="state"
          align="center"
          label="状态"
          min-width="80"
        >
          <template slot-scope="{ row }">
            {{ row.state == 1 ? "启用" : "停用" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="transition"
          align="center"
          fixed="right"
          label="操作"
          width="220"
        >
          <template slot-scope="scope">
            <el-button @click="compile(scope.row)" type="text" size="small"
              >编辑</el-button
            >
            <el-button @click="uploading(scope.row)" type="text" size="small"
              >上传</el-button
            >
            <el-button
              v-if="scope.row.state == 0"
              @click="start(scope.row, 1)"
              type="text"
              size="small"
              >启用</el-button
            >
            <el-button
              v-else
              style="color: #666"
              @click="start(scope.row, 0)"
              type="text"
              size="small"
              >停用</el-button
            >
            <el-button
              style="color: #f00"
              @click="batch(scope.row)"
              type="text"
              size="small"
              >批量更改</el-button
            >

            <el-button
              style="color: #f00"
              @click="deleted(scope.row)"
              type="text"
              size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="formInline.pageNum"
          layout="total, prev, pager, next"
          :page-size="formInline.pageSize"
          :total="formInline.totalSize"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 弹出层 -->

    <!-- 新增 -->
    <el-dialog
      :title="title"
      :visible.sync="nuedialog"
      width="1000px"
      @close="handleClose"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <div class="general">
          <div class="row">
            <div class="condition">
              <el-form-item label="风场名称:" prop="fieldName">
                <el-input v-model="form.fieldName"></el-input>
              </el-form-item>
            </div>
            <div class="condition">
              <el-form-item label="空气密度kg/m³:" prop="density">
                <el-input v-model="form.density"></el-input>
              </el-form-item>
            </div>
          </div>
          <div class="row">
            <div class="condition">
              <el-form-item label="所属公司:" prop="companyCode">
                <selecttree
                  placeholder="请选择所属公司"
                  :list="parentOpt"
                  v-model="form.companyCode"
                  @change="parentChange"
                >
                </selecttree>
              </el-form-item>
            </div>
            <div class="condition">
              <el-form-item label="海拔高度/米:" prop="elevationHeight">
                <el-input v-model="form.elevationHeight"></el-input>
              </el-form-item>
            </div>
          </div>
          <div class="row">
            <div class="condition">
              <el-form-item label="所在省:" prop="provinceName">
                <el-select
                  v-model="form.provinceName"
                  placeholder="请选择"
                  value-key="areaId"
                  @change="fetchCities"
                >
                  <el-option
                    v-for="item in provinceNameOptions"
                    :key="item.areaId"
                    :label="item.province"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <div class="condition">
              <el-form-item label="所在市:" prop="cityName">
                <el-select
                  v-model="form.cityName"
                  placeholder="请选择"
                  value-key="areaId"
                >
                  <el-option
                    v-for="item in cityNameOptions"
                    :key="item.areaId"
                    :label="item.city"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
          </div>

          <div class="row">
            <div class="condition">
              <el-form-item label="测风塔:" prop="anemometerTowerRelationDtos">
                <el-select
                  v-model="form.anemometerTowerRelationDtos"
                  multiple
                  collapse-tags
                  placeholder="请选择"
                  @focus="logClick"
                  value-key="anemometerCode"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.anemometerCode"
                    :label="item.anemometerName"
                    :value="item.anemometerCode"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <div class="condition">
              <el-form-item label="经纬度类型:">
                <el-select
                  v-model="SFMvalue"
                  placeholder="请选择"
                  @change="handleSFMChange"
                >
                  <el-option
                    v-for="item in SFMoptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
          </div>

          <div class="row">
            <div class="condition">
              <el-form-item label="经度:" prop="longitude">
                <el-input v-model="form.longitude"></el-input>
              </el-form-item>
            </div>
            <div class="condition">
              <el-form-item label="纬度:" prop="latitude">
                <el-input v-model="form.latitude"></el-input>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>

      <div class="bianji" v-show="listedfiles">
        <el-table :data="filetableData" style="width: 100%">
          <el-table-column prop="fileName" label="文件名"> </el-table-column>
          <el-table-column prop="type" label="文件类型"> </el-table-column>

          <el-table-column fixed="right" label="操作" width="120">
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="deleteRow(scope.row)"
                type="text"
                size="small"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose(false, 'nuedialog')" size="small"
          >取 消</el-button
        >
        <el-button type="primary" @click="newly('formRef')" size="small"
          >确 定</el-button
        >
        <el-button type="primary" size="small" @click="createMachine"
          >创建机型</el-button
        >
      </span>
    </el-dialog>

    <!-- 风场详情 -->
    <WindsiteMessage
      :unusualdialog="unusualdialog"
      :unusualdialogdata="unusualdialogdata"
      @handleClose="handleClose"
    >
    </WindsiteMessage>
    <!-- 测风塔 -->
    <windsitemachine
      :anemometerdialog="anemometerdialog"
      :anemometerData="anemometerData"
      @handleClose="handleClose"
    >
    </windsitemachine>
    <!-- 风机数量 -->
    <windsitetower
      :draught="draught"
      :draughtData="draughtData"
      @handleClose="handleClose"
    ></windsitetower>
    <!-- 上传 -->
    <windsiteup
      :uploadingPOP="uploadingPOP"
      :rowdata="rowdata"
      :AllTemplateurlDR="AllTemplateurlDR"
      @handleClose="handleClose"
    ></windsiteup>
    <!-- 导入 -->
    <windsitetolead
      :parentOptdata="parentOptdata"
      :AllTemplateurl="AllTemplateurl"
      :tolead="tolead"
      @handleClose="handleClose"
      @onSubmit="onSubmit"
    ></windsitetolead>

    <!-- 功率曲线 -->

    <el-dialog
      title="批量修改"
      :visible.sync="drawer"
      width="85%"
      :before-close="batchhandleClose"
    >
      <div class="batchclass">
        <div
          class="batch-processing"
          v-for="(item, index) in batchList"
          :key="index"
        >
          <p>
            风机名称:
            <span>
              <el-input v-model="item.engineName" size="small"></el-input
            ></span>
          </p>
          <p>
            海拔高度:
            <span>
              <el-input v-model="item.hubHeight" size="small"></el-input
            ></span>
          </p>
          <p>
            额定容量:
            <span>
              <el-input v-model="item.ratedCapacity" size="small"></el-input
            ></span>
          </p>
          <p>
            经度:
            <span>
              <el-input v-model="item.longitude" size="small"></el-input
            ></span>
          </p>
          <p>
            维度:
            <span>
              <el-input v-model="item.latitude" size="small"></el-input
            ></span>
          </p>
        </div>
      </div>
      <div style="height: 30px; text-align: right; margin-top: 10px">
        <el-button
          class="batch-submit"
          type="primary"
          size="small"
          @click="ONbatch"
          >提交</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      title="合同功率曲线"
      :visible.sync="curve"
      :before-close="GBhandleClose"
      width="40%"
    >
      <el-table :data="curvelist" style="width: 100%">
        <el-table-column type="index" width="50"> </el-table-column>

        <el-table-column prop="machineTypeCode" label="机型名称" width="">
        </el-table-column>
        <el-table-column prop="createTime" label="上传时间" width="">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small"
              >删除</el-button
            >
            <el-button @click="XZClick(scope.row)" type="text" size="small"
              >下载</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  WindFieldListPage,
  createWindField,
  delWindFieldById,
  findAllProvince,
  getAllWindCompany,
  getAnemometerTowerByField,
  getAnemometerTowerNameList,
  getCitiesByPId,
  getWindFieldVo,
  updateWindFieldStateById,
  windEngineGrouPage,
  windFieldDto,
  getAllTemplate,
  delWindFieldResource,
  getWindEngineGroupListByFieldCode,
  bathUpdateWindEngineGroup,
  getWindFieldContractByFieldCode,
  delWindFieldContractById,
} from "@/api/ledger.js";
import selecttree from "../../components/selecttree";
import WindsiteMessage from "./component/windsiteMessage.vue";
import windsitemachine from "./component/windsitemachine.vue";
import windsitetolead from "./component/windsitetolead.vue";
import windsitetower from "./component/windsitetower.vue";
import windsiteup from "./component/windsiteup.vue";
import { log } from "plotly.js-dist";

export default {
  components: {
    WindsiteMessage,
    windsitemachine,
    windsitetower,
    windsiteup,
    windsitetolead,
    selecttree,
  },
  data() {
    return {
      loading: false,
      treeval: "",
      tableData: [],
      formInline: {
        fieldName: "",
        timeQuantum: [],
        pageNum: 1,
        pageSize: 10,
        totalSize: 0,
        windCompany: "",
        shengfeng: "",
      },
      startDate: "",
      endDate: "",
      parentOpt: [],
      form: {
        anemometerTowerRelationDtos: [],
        areaCode: "",
        cityId: "",
        cityName: "",
        density: "",
        elevationHeight: "",
        fieldName: "",
        latitude: "",
        longitude: "",
        provinceId: "",
        provinceName: "",
        ratedCapacityNumber: "",
        companyCode: "",
      },
      SFMoptions: [
        {
          label: "十进制形式",
          value: "1",
        },
        {
          label: "度分秒形式",
          value: "2",
        },
      ],
      SFMvalue: "",
      rules: {
        fieldName: [
          { required: true, message: "请输入风场名称", trigger: "blur" },
        ],
        density: [
          { required: true, message: "请输入空气密度", trigger: "blur" },
          { validator: this.validateNumber, trigger: "blur" },
        ],
        companyCode: [
          { required: true, message: "请选择所属公司", trigger: "change" },
        ],
        elevationHeight: [
          { required: true, message: "请输入海拔高度", trigger: "blur" },
          { validator: this.validateNumber, trigger: "blur" },
        ],
        provinceName: [
          { required: true, message: "请选择所在省", trigger: "change" },
        ],
        cityName: [
          { required: true, message: "请选择所在市", trigger: "change" },
        ],
        longitude: [
          { required: true, message: "请输入经度", trigger: "blur" },
          { validator: this.validateNumber, trigger: "blur" },
        ],
        latitude: [
          { required: true, message: "请输入纬度", trigger: "blur" },
          { validator: this.validateNumber, trigger: "blur" },
        ],
        // anemometerTowerRelationDtos: [
        //   { required: true, message: "请选择测风塔", trigger: "change" },
        // ],
      },
      provinceNameOptions: [],
      cityNameOptions: [],
      options: [],
      filetableData: [],
      anemometerData: [],
      draughtData: {},
      unusualdialogdata: {},
      parentOptdata: [],
      AllTemplateurl: {},
      AllTemplateurlDR: {},
      rowdata: {},
      listedfiles: false,
      nuedialog: false,
      unusualdialog: false,
      tolead: false,
      draught: false,
      anemometerdialog: false,
      uploadingPOP: false,
      newform: {
        unit: "",
        province: "",
        city: "",
        descr: "",
      },
      isEdit: false,
      title: "新增",
      detail: {},
      drawer: false,
      batchVal1: "",
      batchVal2: "",
      batchVal3: "",
      batchVal4: "",
      batchVal5: "",
      batchList: [],
      curve: false,
      curvelist: [],
      shengID: "",
    };
  },
  created() {
    this.onSubmit();
    this.postsheng();
    this.relevanceunit();
    this.TowerNameList();
    this.getAllTemplate();
  },
  methods: {
    logClick() {
      this.TowerNameList();
    },
    handleClose(value, dialogName) {
      this[dialogName] = value;
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      // this.$refs.formRef.resetFields();
      this.form = Object.assign({}, this.$options.data().form);
    },

    // 列表居中展示
    rowStyle() {
      return "text-align:center";
    },
    getAllTemplate() {
      getAllTemplate().then((res) => {
        this.AllTemplateurl = res.data;
        this.AllTemplateurlDR = res.data;
      });
    },

    // 时间转换
    onDateChange(date) {
      if (Array.isArray(date)) {
        this.startDate = this.$formatDate(date[0]);
        this.endDate = this.$formatDate(date[1]);
        if (this.endDate < this.startDate) {
          this.endDate = this.startDate;
        }
      } else {
        this.startDate = null;
        this.endDate = null;
      }
    },
    // 省
    async postsheng() {
      try {
        const res = await findAllProvince();
        this.provinceNameOptions = res.data;
      } catch (error) {
        console.error("Error fetching province data:", error);
      }
    },

    // 市
    fetchCities(item, city) {
      console.log(item, this.newform.province);
      this.newform.province = item;
      this.form.province = item;
      this.form.cityName = "";
      let data = {
        provinceId: item.areaId,
      };
      getCitiesByPId(data).then((res) => {
        this.cityNameOptions = res.data;
      });
      if (city) {
        this.newform.city = Object.assign(
          {},
          { areaId: city.areaId, city: city.city }
        );
      }
    },
    // 测风塔
    TowerNameList() {
      getAnemometerTowerNameList().then((res) => {
        this.options = res.data;
      });
    },

    // 关联风场
    async relevanceunit() {
      try {
        const res = await getAllWindCompany();
        this.parentOpt = res.data;
        this.parentOptdata = res.data;
      } catch (error) {
        console.error("Error fetching wind company data:", error);
      }
    },

    parentChange(data) {
      //data为当前选中对象
      console.log(data);
    },
    // 查询
    handleProvinceChange(value) {
      this.shengID = value;
    },
    onSubmit() {
      let paramsData = {
        fieldName: this.formInline?.fieldName || undefined,
        beginTime: this.startDate || undefined,
        endTime: this.endDate || undefined,
        pageNum: this.formInline.pageNum || 1,
        companyName: this.formInline.windCompany,
        provinceId: this.shengID, // 这里就是你获取到的值
        pageSize: 10,
      };
      console.log(this.formInline.shengfeng, "shengfeng");

      this.loading = true;

      WindFieldListPage(paramsData)
        .then((res) => {
          this.tableData = res.data.list;
          this.formInline.totalSize = res.data.totalSize;
          this.loading = false;
        })
        .catch((error) => {
          this.loading = false;
          console.error(error);
        });
    },
    //分页数据切换
    handleCurrentChange(val) {
      this.formInline.pageNum = val;
      this.onSubmit();
    },
    // 停用
    start(row, type) {
      let objectval = {
        fieldCode: row.fieldCode,
        state: type === 0 ? 0 : 1,
      };
      updateWindFieldStateById(objectval).then((res) => {
        this.$message({
          message: "状态已更新成功",
          type: "success",
        });
        // this.$message(`${type === 1 ? '状态已更新成功' : '状态已更新成功'}`);
        row.state = type === 1 ? 0 : 1;
        this.onSubmit();
      });
    },
    processData(data) {
      console.log(data);
      if (!data) {
        console.error("Data is undefined");
        return;
      }
      return data.map((code) => ({
        towerCode: code,
      }));
    },

    // 新增提交
    newly(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$message.error("表单验证失败!");
          return false;
        }

        // 判断是否需要转换经纬度
        if (this.SFMvalue === "2") {
          // 转换经度和纬度
          const longitudeDecimal = this.$convertDMSToDecimal(
            this.form.longitude
          );
          const latitudeDecimal = this.$convertDMSToDecimal(this.form.latitude);
          console.log(longitudeDecimal, latitudeDecimal, "...........");

          // 检查转换是否成功
          if (longitudeDecimal !== null) {
            this.form.longitude = longitudeDecimal;
          } else {
            this.$message.error("经度格式不正确!");
            return;
          }

          if (latitudeDecimal !== null) {
            this.form.latitude = latitudeDecimal;
          } else {
            this.$message.error("纬度格式不正确!");
            return;
          }
        }

        // Prepare the params object
        const params = JSON.parse(JSON.stringify(this.form));
        params.anemometerTowerRelationDtos = this.processData(
          this.form.anemometerTowerRelationDtos
        );
        params.cityName = this.form.cityName.city;
        params.cityId = this.form.cityName.areaId;
        params.provinceName = this.form.provinceName.province;
        params.provinceId = this.form.provinceName.areaId;
        params.areaCode = this.form.cityName.areaCode;
        if (this.isEdit) {
          params.fieldCode = this.detail.fieldCode;
        }
        console.log(this.form, params);
        // return;

        // Determine which API to call
        const API = this.isEdit
          ? windFieldDto(params)
          : createWindField(params);

        // Execute the API call
        API.then((res) => {
          // Adjust based on your API response
          this.$message.success(this.isEdit ? "编辑成功" : "新增成功");
          this.onSubmit();
          this.isEdit = false;
          this.nuedialog = false;
        }).catch((error) => {});
      });
    },

    handleSFMChange(newValue) {
      this.form.longitude = "";
      this.form.latitude = "";
    },

    // 重置
    reset() {
      this.formInline.fieldName = "";
      this.formInline.timeQuantum = "";
      this.shengID = "";
      this.startDate = "";
      this.endDate = "";
      this.form.shengfeng = "";
      this.onSubmit();
    },
    //导入提交
    UPsubmit() {
      this.tolead = false;
    },

    //查看详情
    particulars(row) {
      getWindFieldVo({
        fieldCode: row.fieldCode,
      }).then((res) => {
        this.unusualdialogdata = res.data;
        this.unusualdialog = true;
      });
    },
    //风机详情
    ONdraught(row) {
      this.draughtData = row;
      this.draught = true;
    },
    //测风塔详情
    ONanemometer(row) {
      getAnemometerTowerByField({
        fieldCode: row.fieldCode,
      }).then((res) => {
        this.anemometerData = res.data;
        this.anemometerdialog = true;
      });
    },
    // 合同曲线数
    ONcurve(row) {
      this.curve = true;
      getWindFieldContractByFieldCode({ fieldCode: row.fieldCode }).then(
        (res) => {
          this.curvelist = res.data;
        }
      );
    },
    handleClick(row) {
      delWindFieldContractById({ windFieldContractId: row.id })
        .then((res) => {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.curvelist = this.curvelist.filter((item) => item.id !== row.id);
        })
        .catch((error) => {});
    },
    // 下载附件
    XZClick(row) {
      const link = document.createElement("a");
      link.href = row.contractSource;
      link.download = ""; // 可以设置默认下载文件名
      link.target = "_blank"; // 新窗口打开
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    GBhandleClose() {
      this.curve = false;
      this.onSubmit();
    },
    // 编辑

    compile(row) {
      getWindFieldVo({
        fieldCode: row.fieldCode,
      })
        .then((res) => {
          this.filetableData = res.data.windFieldResourceVos;
          const item = JSON.parse(JSON.stringify(res.data));
          this.detail = item;

          Object.keys(this.form).forEach((key) => {
            this.form[key] = item[key];
          });

          this.form.anemometerTowerRelationDtos = item.anemometerTowerByFieldVos
            ? item.anemometerTowerByFieldVos.map(
                (element) => element.anemometerCode
              )
            : [];
          this.detail = row;
          this.nuedialog = true;
          this.listedfiles = true;
          this.title = "编辑";
          this.isEdit = true;
        })
        .catch((error) => {
          console.error("Error fetching wind field data:", error);
        });
    },

    // 上传附件
    uploading(row) {
      this.uploadingPOP = true;
      this.rowdata = row;
    },

    // 删除
    deleted(row) {
      console.log(row, "row");
      if (row.state == "1") {
        this.$message({
          type: "error",
          message: "该项处于启用状态，无法删除！",
        });
        return;
      }
      this.$confirm("此操作将永久删除该文件，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delWindFieldById({ fieldCode: row.fieldCode })
            .then((res) => {
              if (res.code === -1) {
                // Assuming -1 indicates success, adjust according to actual API response
                this.$message({
                  type: "error",
                  message: "删除失败！",
                });
              } else {
                this.$message({
                  type: "success",
                  message: "删除成功！",
                });
                this.onSubmit();
              }
            })
            .catch((error) => {});
        })
        .catch(() => {
          // 取消删除
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 删除附件
    deleteRow(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delWindFieldResource({ id: row.id }).then((res) => {
            const index = this.filetableData.indexOf(row);
            if (index !== -1) {
              this.filetableData.splice(index, 1);
            }
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 导入
    upfile() {
      this.tolead = true;
    },
    // 新增
    newnuedialog() {
      this.nuedialog = true;
      this.listedfiles = false;
      this.title = "新增";
    },
    // 数字验证
    validateNumber(rule, value, callback) {
      const { regex, errorMessage } = this.getValidationConfig(rule.field);
      if (!value) {
        callback(new Error("该项不能为空"));
      } else if (!regex.test(value)) {
        callback(new Error(errorMessage));
      } else {
        callback();
      }
    },
    getValidationConfig(fieldName) {
      switch (fieldName) {
        case "density":
          return {
            regex: /^\d{1,3}(\.\d{1,3})?$/,
            errorMessage: "该项必须为不超过三位数且小数点后不超过三位数的数字",
          };
        case "elevationHeight":
          return {
            regex: /^\d{1,4}(\.\d{1,2})?$/,
            errorMessage: "该项必须为不超过四位数且小数点后不超两位数的数字",
          };
        case "longitude":
        case "latitude":
          return {
            regex: /^[+-]?\d+(\.\d+)?$|^[+-]?\d{1,3}°\d{1,2}′\d{1,2}″$/,
            errorMessage:
              "请输入有效的经纬度格式，可以是度分秒格式（如：91°06′00″）或十进制格式（如：116.39138889）",
          };
        default:
          return {
            regex: /^[^\u4e00-\u9fa5]+$/,
            errorMessage: "请输入有效数字，不能包含汉字或其他非法字符",
          };
      }
    },

    batch(row) {
      if (row.wegNumber != 0) {
        getWindEngineGroupListByFieldCode({ fieldCode: row.fieldCode }).then(
          (res) => {
            this.batchList = res.data;
          }
        );
        this.drawer = true;
      } else {
        this.$message({
          message: "暂无风机无法批量更改",
          type: "warning",
        });
      }
    },
    ONbatch() {
      bathUpdateWindEngineGroup({
        windEngineGroupUpdateDtoList: this.batchList,
      })
        .then((res) => {
          this.drawer = false;
          this.$message({
            title: "成功",
            message: "风机组信息更新成功",
            type: "success",
          });
        })
        .catch((error) => {});
    },
    batchhandleClose(done) {
      this.batchList = [];
      done();
    },
    createMachine() {
      // this.$router.push({
      //   path: "/home/Ledger/milltype?id=192",
      // });
      window.open("/home/Ledger/milltype?id=192", "_blank");
    },
  },
};
</script>

<style lang="scss" scoped>
.general {
  display: flex;
  flex-direction: column;

  .row {
    display: flex;
    justify-content: space-between;
  }

  .condition {
    width: 50%;

    .el-select {
      width: 360px;
    }

    .el-form-item {
      margin-bottom: 22px;
    }
  }
}

.UPcondition {
  display: flex;

  p {
    width: 74px;
    text-align: right;
    line-height: 40px;
  }

  .el-select {
    width: 100%;
    margin-bottom: 20px;
  }

  .el-input {
    margin-bottom: 20px;
  }
}

.model-center {
  color: #666;
  line-height: 40px;
  height: 40px;
  font-size: 14px;
}
.batchclass {
  max-height: 550px;
  overflow: hidden;
  overflow-y: auto;
  position: relative;
}
.batch-processing {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  p {
    .el-input {
      width: 200px;
    }
  }
}

.batch-name {
  margin-left: 20px;
  .el-input {
    width: 200px;
  }
}

::v-deep .el-date-editor--daterange.el-input__inner {
  width: 260px;
}
.bianji {
  margin-top: 10px;
}
::v-deep .el-dialog__footer {
  text-align: center;
}
</style>
