<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.anemometerName"
            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 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="anemometerName"
          label="测风塔名称"
        >
          <template slot-scope="scope">
            <el-button
              @click="particulars(scope.row)"
              type="text"
              size="small"
              >{{ scope.row.anemometerName }}</el-button
            >
          </template>
        </el-table-column>

        <el-table-column
          prop="anemometerCode"
          align="center"
          label="测风塔编号"
        >
        </el-table-column>

        <el-table-column
          prop="longitude"
          align="center"
          label="经度"
          min-width="200"
        >
        </el-table-column>

        <el-table-column
          prop="latitude"
          align="center"
          label="纬度"
          min-width="200"
        >
        </el-table-column>
        <el-table-column
          prop="state"
          align="center"
          label="状态"
          min-width="100"
        >
          <template slot-scope="{ row }">
            {{ row.state == 1 ? "启用" : "停用" }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" align="center" label="创建时间">
        </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
              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="860px"
      @close="resetForm"
    >
      <div class="addition">
        <span @click="addition">
          <SvgIcons
            name="jia"
            class="jia"
            width="20px"
            height="22px"
            color="#222"
          ></SvgIcons>
        </span>
        <span @click="subtraction">
          <SvgIcons
            name="jian"
            class="jian"
            width="20px"
            height="22px"
            color="#222"
          ></SvgIcons>
        </span>
      </div>
      <div class="general">
        <div class="condition">
          <p>测风塔名称：</p>
          <el-input v-model="anemometerName"></el-input>
        </div>
        <div class="condition">
          <p>经度：</p>
          <el-input v-model="latitude"></el-input>
        </div>

        <div class="condition">
          <p>纬度：</p>
          <el-input v-model="longitude"></el-input>
        </div>
        <div
          v-for="(tower, index) in anemometerTowerHeightDtoList || [
            { anemometerHeight: '' },
          ]"
          :key="index"
          class="condition"
        >
          <p>测风塔高度{{ index + 1 }}：</p>
          <el-input
            v-model="tower.anemometerHeight"
            placeholder="请输入测风塔高度"
          ></el-input>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="nuedialog = false" size="small">取 消</el-button>
        <el-button type="primary" @click="newly" size="small">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 测风塔详情 -->
    <el-dialog title="详情" :visible.sync="unusualdialog" width="400px">
      <p>测风塔名称：{{ hightower.anemometerName }}</p>
      <p>测风塔编号：{{ hightower.anemometerCode }}</p>
      <p>经度：{{ hightower.longitude }}</p>
      <p>维度：{{ hightower.latitude }}</p>
      <p>状态: {{ hightower.state === 1 ? "启用" : "停用" }}</p>
      <p v-for="(item, index) in cftList" :key="index">
        测风塔高度：{{ item.anemometerHeight }}米
      </p>
    </el-dialog>
  </div>
</template>

<script>
import {
  createAnemometerTower,
  delAnemometerTower,
  getAnemometerTower,
  getAnemometerTowerPage,
  updateAnemometerTower,
  updateAnemometerTowerState,
} from "@/api/ledger.js";
export default {
  data() {
    return {
      tableData: [],
      formInline: {
        anemometerName: "",
        timeQuantum: [],
        pageNum: 1,
        pageSize: 10,
        totalSize: 0,
      },
      startDate: "",
      endDate: "",
      // 新增测风塔信息
      anemometerName: "",
      latitude: "",
      longitude: "",
      anemometerTowerHeightDtoList: [
        {
          anemometerHeight: "",
        },
      ],
      errors: [],
      hightower: [],
      cftList: [],
      // 新增信息
      nuedialog: false,
      unusualdialog: false,
      title: "",
      isEdit: false,
      detail: {},
    };
  },
  created() {
    this.onSubmit();
  },
  methods: {
    rowStyle() {
      return "text-align:center";
    },
    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;
      }
    },

    // 查询
    onSubmit() {
      let paramsData = {
        anemometerName: this.formInline.anemometerName || undefined,
        beginTime: this.startDate || undefined,
        endTime: this.endDate || undefined,
        pageNum: this.formInline.pageNum,
        pageSize: this.formInline.pageSize,
      };
      getAnemometerTowerPage(paramsData).then((res) => {
        this.tableData = res.data.list;
        this.formInline.totalSize = res.data.totalSize;
      });
    },
    // 重置
    reset() {
      this.formInline.anemometerName = "";
      this.formInline.timeQuantum = [];
      this.endDate = "";
      this.startDate = "";
    },
    // 重置
    resetForm() {
      this.anemometerName = "";
      this.latitude = "";
      this.longitude = "";
      this.anemometerTowerHeightDtoList = [
        {
          anemometerHeight: "",
        },
      ];
    },
    //打开新增
    newnuedialog() {
      this.nuedialog = true;
      this.title = "新增";
    },
    // 新增提交
    newly() {
      const isEmptyAnemometerHeight = this.anemometerTowerHeightDtoList.some(
        (tower) =>
          !tower.anemometerHeight || !tower.anemometerHeight.toString().trim()
      );

      if (isEmptyAnemometerHeight) {
        this.$message({
          message: "测风塔高度不能为空",
          type: "warning",
        });
        return;
      }

      // Other validation checks
      if (!this.anemometerName) {
        this.$message({
          message: "请填写测风塔名称",
          type: "warning",
        });
        return;
      }
      if (!this.latitude) {
        this.$message({
          message: "请填写纬度",
          type: "warning",
        });
        return;
      }
      if (!this.longitude) {
        this.$message({
          message: "请填写经度",
          type: "warning",
        });
        return;
      }
      let paramsData = {
        anemometerName: this.anemometerName,
        latitude: this.latitude,
        longitude: this.longitude,
      };
      if (!this.isEdit) {
        paramsData.anemometerTowerHeightDtoList =
          this.anemometerTowerHeightDtoList;
        createAnemometerTower(paramsData).then((res) => {
          this.nuedialog = false;
          this.$message.success("新增成功");
          this.onSubmit();
        });
      } else {
        paramsData.anemometerTowerHeightListDtos =
          this.anemometerTowerHeightDtoList;
        paramsData.anemometerCode = this.detail.anemometerCode;
        // delete objectval.parentCode
        updateAnemometerTower(paramsData).then((res) => {
          this.isEdit = false;
          this.nuedialog = false;
          this.onSubmit();
          this.$message.success("编辑成功");
        });
      }
      this.resetForm();
    },

    // 查看详情
    particulars(row) {
      getAnemometerTower({ anemometerCode: row.anemometerCode }).then((res) => {
        this.hightower = res.data;
        this.cftList = res.data.list;
      });
      this.unusualdialog = true;
    },
    // 启用/停用
    start(row, type) {
      let objectval = {
        anemometerCode: row.anemometerCode,
        state: type === 0 ? 0 : 1,
      };
      updateAnemometerTowerState(objectval).then((res) => {
        this.$message({
          message: "状态已更新成功",
          type: "success",
        });
        // this.$message(`${type === 1 ? '状态已更新成功' : '状态已更新成功'}`);
        row.state = type === 1 ? 0 : 1;
        this.onSubmit();
      });
    },
    // 删除
    deleted(row) {
      console.log(row, "row");
      if (row.state == "1") {
        this.$message({
          type: "error",
          message: "该项处于启用状态，无法删除！",
        });
        return;
      }
      this.$confirm("此操作将永久删除该文件，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delAnemometerTower({ anemometerCode: row.anemometerCode }).then(
            (res) => {
              this.onSubmit();
              // 执行删除操作
              this.$message({
                type: "success",
                message: "删除成功！",
              });
            }
          );
        })
        .catch(() => {
          // 取消删除
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 编辑
    compile(row) {
      this.title = "编辑";
      this.isEdit = true;
      getAnemometerTower({ anemometerCode: row.anemometerCode }).then((res) => {
        this.hightower = res.data;
        this.cftList = res.data.list;
        const item = JSON.parse(JSON.stringify(res.data));
        this.detail = item;
        this.anemometerName = item.anemometerName;
        this.latitude = item.latitude;
        this.longitude = item.longitude;
        this.anemometerTowerHeightDtoList = this.cftList;
        this.nuedialog = true;
      });
    },

    //分页数据切换
    handleCurrentChange(val) {
      this.formInline.pageNum = val;
      this.onSubmit();
    },

    // 测风塔高度
    addition() {
      this.anemometerTowerHeightDtoList.push({ anemometerHeight: "" });
    },
    subtraction() {
      if (this.anemometerTowerHeightDtoList.length > 1) {
        // Ensure at least one input remains
        this.anemometerTowerHeightDtoList.pop();
      }
    },
  },
};
</script>

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

  .condition {
    width: 50%;
    display: flex;

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

    span {
      line-height: 40px;
      margin-right: 5px;
      padding-left: 20px;
    }

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

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

.attachment {
  display: flex;
  padding-top: 10px;

  p {
    margin-right: 20px;
    color: #409eff;
  }
}

.addition {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.error {
  color: red;
  position: absolute;
  bottom: 85px;
  left: 91px;
  width: 213px !important;
  font-size: 12px;
}

.forinput {
  position: relative;
}
</style>
