<template>
  <div class="global-variable" v-loading="loading">
    <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="80"
        >
          <template slot-scope="{ row }">
            {{ row.state == 1 ? "启用" : "停用" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          align="center"
          label="创建时间"
          min-width="160"
        >
        </el-table-column>
        <el-table-column
          prop="transition"
          align="center"
          fixed="right"
          label="操作"
          min-width="150"
        >
          <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="520px"
      @close="resetForm"
    >
      <el-form
        :model="dynamicValidateForm"
        ref="dynamicValidateForm"
        label-width="100px"
        class="demo-dynamic"
        :rules="rules"
      >
        <el-form-item prop="anemometerName" label="测风塔名称">
          <el-input v-model="dynamicValidateForm.anemometerName"></el-input>
        </el-form-item>
        <el-form-item prop="longitude" label="经度">
          <el-input v-model="dynamicValidateForm.longitude"></el-input>
        </el-form-item>
        <el-form-item prop="latitude" label="纬度">
          <el-input v-model="dynamicValidateForm.latitude"></el-input>
        </el-form-item>
        <el-form-item
          v-for="(
            tower, index
          ) in dynamicValidateForm.anemometerTowerHeightDtoList"
          :label="'测风塔高度' + (index + 1)"
          :key="index"
          :prop="'anemometerTowerHeightDtoList.' + index + '.anemometerHeight'"
          :rules="[
            { required: true, message: '请输入测风塔高度', trigger: 'blur' },
            { validator: validateUniqueHeight, trigger: 'blur' },
          ]"
        >
          <el-input v-model="tower.anemometerHeight"></el-input>
          <el-button v-if="index > 0" @click.prevent="removeTower(index)"
            >删除</el-button
          >
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('dynamicValidateForm')"
            >提交</el-button
          >
          <el-button @click="addDomain">新增测风塔高度</el-button>
        </el-form-item>
      </el-form>
    </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 {
      loading: false,
      tableData: [],
      formInline: {
        anemometerName: "",
        timeQuantum: [],
        pageNum: 1,
        pageSize: 10,
        totalSize: 0,
      },
      startDate: "",
      endDate: "",
      // 新增测风塔信息

      dynamicValidateForm: {
        anemometerTowerHeightDtoList: [
          {
            anemometerHeight: "",
          },
        ],
        anemometertower: "",
        longitude: "",
        latitude: "",
      },

      anemometerTowerHeightDtoList: [
        {
          anemometerHeight: "",
        },
      ],
      errors: [],
      hightower: [],
      cftList: [],
      // 新增信息
      nuedialog: false,
      unusualdialog: false,
      title: "",
      isEdit: false,
      detail: {},
      rules: {
        anemometerName: [
          { required: true, message: "请输入测风塔名称", trigger: "blur" },
        ],
        longitude: [
          { required: true, message: "请输入经度", trigger: "blur" },
          { validator: this.validateNumber, trigger: "blur" },
        ],
        latitude: [
          { required: true, message: "请输入纬度", trigger: "blur" },
          { validator: this.validateNumber, trigger: "blur" },
        ],
      },
    };
  },
  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 || 1,
        pageSize: this.formInline.pageSize,
      };
      this.loading = true;
      getAnemometerTowerPage(paramsData)
        .then((res) => {
          this.tableData = res.data.list;
          this.formInline.totalSize = res.data.totalSize;
          this.loading = false;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 重置
    reset() {
      this.formInline.anemometerName = "";
      this.formInline.timeQuantum = [];
      this.endDate = "";
      this.startDate = "";
      this.onSubmit();
    },
    // 重置
    resetForm() {
      this.dynamicValidateForm.anemometerName = "";
      Object.assign(
        this.$data.dynamicValidateForm,
        this.$options.data().dynamicValidateForm
      );
    },
    //打开新增
    newnuedialog() {
      this.nuedialog = true;
      this.title = "新增";
    },

    // 查看详情
    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;
      this.nuedialog = 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.$set(
          this.dynamicValidateForm,
          "anemometerName",
          item.anemometerName
        );
        this.$set(this.dynamicValidateForm, "latitude", item.latitude);
        this.$set(this.dynamicValidateForm, "longitude", item.longitude);
        this.$set(
          this.dynamicValidateForm,
          "anemometerTowerHeightDtoList",
          this.cftList
        );
      });
    },

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

    // 修改的
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$message.error("请填写必填项");
          return;
        }

        let paramsData = {
          anemometerName: this.dynamicValidateForm.anemometerName,
          latitude: this.dynamicValidateForm.latitude,
          longitude: this.dynamicValidateForm.longitude,
        };

        let API;
        if (!this.isEdit) {
          paramsData.anemometerTowerHeightDtoList =
            this.dynamicValidateForm.anemometerTowerHeightDtoList;
          API = createAnemometerTower(paramsData);
        } else {
          paramsData.anemometerTowerHeightListDtos =
            this.dynamicValidateForm.anemometerTowerHeightDtoList;
          paramsData.anemometerCode = this.detail.anemometerCode;
          API = updateAnemometerTower(paramsData);
        }

        API.then((res) => {
          this.nuedialog = false;
          if (this.isEdit) {
            this.isEdit = false;
            this.$message.success("编辑成功");
          } else {
            this.$message.success("新增成功");
          }
          this.onSubmit();
        }).catch((error) => {});
      });
    },
    // xz
    addDomain() {
      this.dynamicValidateForm.anemometerTowerHeightDtoList.push({
        anemometerHeight: "",
      });
    },
    // 删除
    removeTower(index) {
      this.dynamicValidateForm.anemometerTowerHeightDtoList.splice(index, 1);
    },

    // 数字验证
    validateNumber(rule, value, callback) {
      const numberRegex = /^\d{1,3}(\.\d{1,8})?$/; // 匹配不超过四位数且小数点后不超过二位数的数字
      if (!value) {
        callback(new Error("该项不能为空"));
      } else if (!numberRegex.test(value)) {
        callback(
          new Error("该项必须为不超过三位数且小数点后不超过八位数的数字")
        );
      } else {
        callback();
      }
    },
    validateUniqueHeight(rule, value, callback) {
      const heights = this.dynamicValidateForm.anemometerTowerHeightDtoList.map(
        (tower) => tower.anemometerHeight
      );

      const isDuplicate =
        heights.filter((height) => height === value).length > 1;

      const isInvalidLength = value && value.toString().length > 3;

      if (isDuplicate) {
        callback(new Error("输入的测风塔高度不能重复"));
      } else if (isInvalidLength) {
        callback(new Error("测风塔高度不能超过三位数"));
      } else {
        callback();
      }
    },
  },
};
</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;
    }
  }
}

.demo-dynamic {
  .el-input {
    width: 300px;
    margin-right: 10px;
  }
  .el-form-item {
    margin-bottom: 20px;
  }
}
</style>
