<template>
  <div class="global-variable">
    <div class="condition">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="风场名称:">
          <el-input
            v-model="formInline.fieldName"
            placeholder="请输入风场名称"
            size="small"
          ></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>
          <el-button type="primary" @click="onSubmit" size="small"
            >查询</el-button
          >
          <el-button @click="reset" size="small">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="list-page">
      <div class="newly">
        <el-button @click="upfile" size="small">导入</el-button>
        <el-button type="primary" @click="newnuedialog" size="small"
          >新增</el-button
        >
      </div>

      <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="100"
        >
          <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
          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="操作"
          min-width="200"
        >
          <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="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="空气密度:" 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="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 class="row">
            <div class="condition">
              <el-form-item label="测风塔:" prop="anemometerTowerRelationDtos">
                <el-select
                  v-model="form.anemometerTowerRelationDtos"
                  multiple
                  collapse-tags
                  placeholder="请选择"
                  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>
        </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
        >
      </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>
  </div>
</template>

<script>
import {
  WindFieldListPage,
  createWindField,
  delWindFieldById,
  findAllProvince,
  getAllWindCompany,
  getAnemometerTowerByField,
  getAnemometerTowerNameList,
  getCitiesByPId,
  getWindFieldVo,
  updateWindFieldStateById,
  windEngineGrouPage,
  windFieldDto,
  getAllTemplate,
  delWindFieldResource,
} 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";

export default {
  components: {
    WindsiteMessage,
    windsitemachine,
    windsitetower,
    windsiteup,
    windsitetolead,
    selecttree,
  },
  data() {
    return {
      treeval: "",
      tableData: [],
      formInline: {
        fieldName: "",
        timeQuantum: [],
        pageNum: 1,
        pageSize: 10,
        totalSize: 0,
      },
      startDate: "",
      endDate: "",
      parentOpt: [],
      form: {
        anemometerTowerRelationDtos: [],
        areaCode: "",
        cityId: "",
        cityName: "",
        density: "",
        elevationHeight: "",
        fieldName: "",
        latitude: "",
        longitude: "",
        provinceId: "",
        provinceName: "",
        ratedCapacityNumber: "",
        companyCode: "",
      },
      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.validateNumberTwo, trigger: "blur" },
        ],
        provinceName: [
          { required: true, message: "请选择所在省", trigger: "change" },
        ],
        cityName: [
          { required: true, message: "请选择所在市", trigger: "change" },
        ],
        longitude: [
          { required: true, message: "请输入经度", trigger: "blur" },
          { validator: this.validateNumberthree, trigger: "blur" },
        ],
        latitude: [
          { required: true, message: "请输入纬度", trigger: "blur" },
          { validator: this.validateNumberthree, 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: {},
    };
  },
  created() {
    this.onSubmit();
    this.postsheng();
    this.relevanceunit();
    this.TowerNameList();
    this.getAllTemplate();
  },
  methods: {
    handleClose(value, dialogName) {
      this[dialogName] = value;
      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);
    },
    // 查询
    onSubmit() {
      let paramsData = {
        fieldName: this.formInline?.fieldName || undefined,
        beginTime: this.startDate || undefined,
        endTime: this.endDate || undefined,
        pageNum: this.formInline.pageNum || 1,
        pageSize: 10,
      };
      WindFieldListPage(paramsData).then((res) => {
        this.tableData = res.data.list;
        this.formInline.totalSize = res.data.totalSize;
      });
    },
    //分页数据切换
    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) {
      console.log(this.form.anemometerTowerRelationDtos);
      this.processData(this.form.anemometerTowerRelationDtos);
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$message.error("表单验证失败!");
          return false;
        }

        // 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);

        // 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) => {});
      });
    },
    // 重置
    reset() {
      this.formInline.fieldName = "";
      this.formInline.timeQuantum = "";
      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;
      });
    },

    // 编辑

    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 numberRegex = /^\d{1,3}(\.\d{1,3})?$/;
      if (!value) {
        callback(new Error("该项不能为空"));
      } else if (!numberRegex.test(value)) {
        callback(
          new Error("该项必须为不超过三位数且小数点后不超过三位数的数字")
        );
      } else {
        callback();
      }
    },
    validateNumberTwo(rule, value, callback) {
      const numberRegex = /^\d{1,4}(\.\d{1,2})?$/;
      if (!value) {
        callback(new Error("该项不能为空"));
      } else if (!numberRegex.test(value)) {
        callback(new Error("该项必须为不超过四位数且小数点后不超两位数的数字"));
      } else {
        callback();
      }
    },
    validateNumberthree(rule, value, callback) {
      const numberRegex = /^\d{1,3}(\.\d{1,5})?$/;
      if (!value) {
        callback(new Error("该项不能为空"));
      } else if (!numberRegex.test(value)) {
        callback(new Error("该项必须为不超过三位数且小数点后不超五位数的数字"));
      } else {
        callback();
      }
    },
  },
};
</script>

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

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

  .condition {
    width: 50%;

    .el-select {
      width: 260px;
    }

    .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;
}
</style>
