<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.engineName"
            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="engineCode"
          label="系统编号"
        >
          <template slot-scope="scope">
            <el-button
              @click="particulars(scope.row)"
              type="text"
              size="small"
              >{{ scope.row.engineCode }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="engineName" align="center" label="风机名称">
        </el-table-column>

        <el-table-column prop="fieldName" align="center" label="关联风场">
        </el-table-column>
        <el-table-column
          prop="longitude"
          align="center"
          label="经度"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          prop="latitude"
          align="center"
          label="纬度"
          min-width="100"
        >
        </el-table-column>

        <el-table-column
          prop="elevationHeight"
          align="center"
          label="海拔高度/米"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          prop="sightcing"
          align="center"
          label="是否标杆"
          min-width="80"
        >
          <template slot-scope="{ row }">
            {{ row.sightcing == 1 ? "是" : "否" }}
          </template>
        </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="140"
        >
        </el-table-column>

        <el-table-column
          prop="transition"
          align="center"
          fixed="right"
          label="操作"
          min-width="160"
        >
          <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="导入文件"
      :visible.sync="tolead"
      width="400px"
      @close="handleClose"
    >
      <el-alert title="请点击模板下载文件附件" type="success" :closable="false">
      </el-alert>
      <p class="model-center" @click="download">模板下载</p>
      <div class="UPcondition">
        <p>所属风场:</p>
        <el-select
          v-model="subordinate"
          placeholder="请选择"
          value-key="fieldCode"
        >
          <el-option
            v-for="item in subordinatedata"
            :key="item.fieldCode"
            :label="item.fieldName"
            :value="item.fieldCode"
          >
          </el-option>
        </el-select>
      </div>

      <el-upload
        class="upload-demo"
        :file-list="fileList"
        drag
        action
        :multiple="false"
        :before-upload="beforeUpload"
        :limit="1"
        :auto-upload="false"
        :on-change="handleOnChange"
        accept=".xlsx"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          只能上传xlsx文件，且不超过5MB
        </div>
      </el-upload>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose" size="small">取 消</el-button>
        <el-button type="primary" @click="UPsubmit" size="small"
          >提交</el-button
        >
      </span>
    </el-dialog>
    <!-- 新增 -->
    <el-dialog
      :title="title"
      :visible.sync="nuedialog"
      width="1000px"
      @close="resetForm('ruleForm')"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <div class="form-row">
          <el-form-item label="风机名称:" prop="engineName">
            <el-input v-model="ruleForm.engineName" size="small"></el-input>
          </el-form-item>
          <el-form-item label="关联风场:" prop="fieldCode">
            <el-select
              v-model="ruleForm.fieldCode"
              filterable
              placeholder="请选择"
              size="small"
            >
              <el-option
                v-for="item in fieldCodeOptions"
                :key="item.fieldCode"
                :label="item.fieldName"
                :value="item.fieldCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="机型编号:" prop="millTypeCode">
            <el-select
              v-model="ruleForm.millTypeCode"
              placeholder="请选择"
              size="small"
            >
              <el-option
                v-for="item in millTypeCodeOptions"
                :key="item.millTypeCode"
                :label="item.machineTypeCode"
                :value="item.millTypeCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="额定容量:" prop="ratedCapacity">
            <el-input v-model="ruleForm.ratedCapacity" size="small"></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="海拔高度:" prop="elevationHeight">
            <el-input
              v-model="ruleForm.elevationHeight"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="经度:" prop="longitude">
            <el-input v-model="ruleForm.longitude" size="small"></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="纬度:" prop="latitude">
            <el-input v-model="ruleForm.latitude" size="small"></el-input>
          </el-form-item>
          <el-form-item label="轮毂高度:" prop="hubHeight">
            <el-input v-model="ruleForm.hubHeight" size="small"></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="是否标杆:" prop="sightcing">
            <el-select
              v-model="ruleForm.sightcing"
              placeholder="请选择"
              size="small"
            >
              <el-option
                v-for="item in sightcingOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <div class="form-buttons">
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确定</el-button
        >
        <el-button @click="resetForm('ruleForm')">取消</el-button>
      </div>
    </el-dialog>

    <!-- 风机详情 -->
    <el-dialog title="风机详情" :visible.sync="unusualdialog" width="800px">
      <div class="general">
        <div class="condition">
          <p>关联风场:</p>
          <span>{{ particularsdata.fieldCode }}</span>
        </div>
        <div class="condition">
          <p>风机名称:</p>
          <span>{{ particularsdata.engineCode }}</span>
        </div>

        <div class="condition">
          <p>风机名称:</p>
          <span>{{ particularsdata.engineName }}</span>
        </div>
        <div class="condition">
          <p>机型编号:</p>
          <span>{{ particularsdata.millTypeCode }}</span>
        </div>
        <div class="condition">
          <p>额定容量:</p>
          <span>{{ particularsdata.ratedCapacity }}</span> <span>(kW)</span>
        </div>

        <div class="condition">
          <p>海拔高度:</p>
          <span>{{ particularsdata.elevationHeight }}</span> <span>(米)</span>
        </div>
        <div class="condition">
          <p>经度:</p>
          <span>{{ particularsdata.longitude }}°</span>
        </div>

        <div class="condition">
          <p>纬度:</p>
          <span>{{ particularsdata.latitude }}°</span>
        </div>

        <div class="condition">
          <p>轮毂高度:</p>
          <span>{{ particularsdata.hubHeight }}</span> <span>(米)</span>
        </div>
        <div class="condition">
          <p>是否标杆:</p>
          <span>{{ particularsdata.sightcing == 1 ? "是" : "否" }}</span>
        </div>
        <div class="condition">
          <p>状态:</p>
          <span>{{ particularsdata.state == 1 ? "启用" : "停用" }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createWindEngineGroup,
  delWindEngineGroup,
  getWindEngineGroup,
  getWindEngineMillList,
  getWindFieldNames,
  updateStateWindEngineGroup,
  updateWindEngineGroup,
  windEngineGrouPage,
  getAllTemplate,
  windEngineGroupImportData,
} from "@/api/ledger.js";
export default {
  data() {
    return {
      loading: false,
      formInline: {
        fieldCode: "",
        timeQuantum: [],
        pageNum: 1,
        pageSize: 10,
        totalSize: 0,
      },
      startDate: "",
      endDate: "",
      tableData: [],
      particularsdata: [],
      ruleForm: {
        fieldCode: "",
        engineName: "",
        airdensity: "",
        millTypeCode: "",
        ratedCapacity: "",
        elevationHeight: "",
        longitude: "",
        latitude: "",
        hubHeight: "",
        sightcing: "",
      },
      fieldCodeOptions: [],
      millTypeCodeOptions: [],
      sightcingOptions: [
        {
          value: 1,
          label: "是",
        },
        {
          value: 2,
          label: "否",
        },
      ],
      rules: {
        fieldCode: [
          { required: true, message: "请选择关联风场", trigger: "change" },
        ],
        engineName: [
          { required: true, message: "请输入风机名称", trigger: "blur" },
        ],
        millTypeCode: [
          { required: true, message: "请输入机型编号", trigger: "blur" },
        ],
        ratedCapacity: [
          { required: true, message: "请输入额定容量(kW)", trigger: "blur" },
        ],
        longitude: [
          { required: true, message: "请输入经度", trigger: "blur" },
          { validator: this.validateNumber, trigger: "blur" },
        ],
        latitude: [
          { required: true, message: "请输入纬度", trigger: "blur" },
          { validator: this.validateNumber, trigger: "blur" },
        ],
        hubHeight: [
          { required: true, message: "请输入轮毂高度", trigger: "blur" },
          { validator: this.validateNumbertwo, trigger: "blur" },
        ],
        elevationHeight: [
          { required: true, message: "请输入海拔高度", trigger: "blur" },
          { validator: this.validateNumbertwo, trigger: "blur" },
        ],
        sightcing: [
          { required: true, message: "请选择是否标杆", trigger: "change" },
        ],
      },
      subordinatedata: [],
      subordinate: "",
      AllTemplateurl: "",
      // 新增信息
      engineName: "",
      airdensity: "",
      fieldCode: "",

      millTypeCode: "",
      sheng: "",
      shengOptions: [],
      shi: "",
      shiOptions: [],
      elevationHeight: "",
      latitude: "",
      sightcing: "",

      fileList: [],
      globalFileList: [],
      nuedialog: false,
      unusualdialog: false,
      tolead: false,
      isEdit: false,
      title: "",
    };
  },
  created() {
    this.onSubmit();
    this.windsite();
    this.relevancy();
    this.getAllTemplate();
  },
  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;
      }
    },
    //获取模板
    getAllTemplate() {
      getAllTemplate().then((res) => {
        this.AllTemplateurl = res.data.draught;
      });
    },
    // 下载模板
    download() {
      if (this.AllTemplateurl) {
        const link = document.createElement("a");
        link.href = this.AllTemplateurl;
        link.download = ""; // 可以设置默认下载文件名
        link.target = "_blank"; // 新窗口打开
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } else {
        console.error("URL is not set");
      }
    },
    // 数字验证
    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();
      }
    },
    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();
      }
    },
    // 查询
    onSubmit() {
      let paramsData = {
        engineName: this.formInline.engineName || undefined,
        beginTime: this.startDate || undefined,
        endTime: this.endDate || undefined,
        pageNum: this.formInline.pageNum || 1,
        pageSize: 10,
      };
      this.loading = true;
      windEngineGrouPage(paramsData)
        .then((res) => {
          this.tableData = res.data.list;
          this.formInline.totalSize = res.data.totalSize;
          this.loading = false;
        })
        .catch((error) => {
          console.error(error);
        });
    },

    // 停用
    start(row, type) {
      let objectval = {
        engineCode: row.engineCode,
        state: type === 0 ? 0 : 1,
      };
      updateStateWindEngineGroup(objectval).then((res) => {
        this.$message({
          message: "状态已更新成功",
          type: "success",
        });
        // this.$message(`${type === 1 ? '状态已更新成功' : '状态已更新成功'}`);
        row.state = type === 1 ? 0 : 1;
        this.onSubmit();
      });
    },
    //详情
    particulars(row) {
      this.unusualdialog = true;
      getWindEngineGroup({ engineCode: row.engineCode }).then((res) => {
        this.particularsdata = res.data;
      });
    },
    // 确认
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        const objData = {
          fieldCode: this.ruleForm.fieldCode,
          engineName: this.ruleForm.engineName,
          millTypeCode: this.ruleForm.millTypeCode,
          ratedCapacity: this.ruleForm.ratedCapacity,
          elevationHeight: this.ruleForm.elevationHeight,
          longitude: this.ruleForm.longitude,
          latitude: this.ruleForm.latitude,
          hubHeight: this.ruleForm.hubHeight,
          sightcing: this.ruleForm.sightcing,
        };

        if (valid) {
          const API = this.isEdit
            ? updateWindEngineGroup(objData)
            : createWindEngineGroup(objData);

          API.then((res) => {
            if (res.code === -1) {
              this.$message({
                message: "操作成功 操作失败",
                type: " error",
              });
            } else {
              this.$message({
                message: "操作成功",
                type: "success",
              });
            }
            this.nuedialog = false;
            this.onSubmit();
          }).catch((error) => {});
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },

    // 取消
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.nuedialog = false;
    },
    // 获取风场
    windsite() {
      // debugger;
      getWindFieldNames().then((res) => {
        this.fieldCodeOptions = res.data;
        this.subordinatedata = res.data;
      });
    },
    // 获取机型
    async relevancy() {
      try {
        const res = await getWindEngineMillList();
        this.millTypeCodeOptions = res.data;
      } catch (error) {
        console.error("Error fetching wind engine mill list:", error);
      }
    },

    //分页数据切换
    handleCurrentChange(val) {
      this.formInline.pageNum = val;
      this.onSubmit();
    },
    // 重置
    reset() {
      this.formInline.engineName = "";
      this.formInline.timeQuantum = "";
      this.onSubmit();
    },
    //导入提交
    UPsubmit() {
      let filedata = {
        fieldCode: this.subordinate,
        file: this.globalFileList,
      };
      if (filedata.file == "") {
        this.$message({
          message: "请先提交附件",
          type: "warning",
        });
      } else {
        windEngineGroupImportData(filedata)
          .then((res) => {
            console.log(res);
            this.uploadingPOP = false;
            if (res.code === -1) {
              this.$message({
                message: "上传失败",
                type: "error",
              });
            } else {
              this.tolead = false;
              this.$message({
                message: "上传成功",
                type: "success",
              });
              this.onSubmit();
              this.handleClose();
            }
          })
          .catch((error) => {});
      }

      console.log(filedata);
      // this.tolead = false
    },
    // 新增
    newly() {
      this.nuedialog = false;
    },

    // 编辑
    compile(row) {
      getWindEngineGroup({ engineCode: row.engineCode }).then((res) => {
        const item = JSON.parse(JSON.stringify(res.data));
        this.detail = item;
        Object.keys(this.ruleForm).forEach((key) => {
          this.ruleForm[key] = item[key];
        });
      });
      this.nuedialog = true;
      this.title = "编辑";
      this.isEdit = true;
    },

    // 删除
    deleted(row) {
      console.log(row, "row");
      if (row.state == "1") {
        this.$message({
          type: "error",
          message: "该项处于启用状态，无法删除！",
        });
        return;
      }
      this.$confirm("此操作将永久删除该文件，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delWindEngineGroup({ engineCode: row.engineCode }).then((res) => {
            this.onSubmit();
            // 执行删除操作
            this.$message({
              type: "success",
              message: "删除成功！",
            });
          });
        })
        .catch(() => {
          // 取消删除
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 导入
    upfile() {
      this.tolead = true;
    },
    // 新增
    newnuedialog() {
      this.nuedialog = true;
      this.title = "新增";
    },

    // 附件验证
    beforeUpload(fileList) {
      const isXLSX =
        fileList.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      if (!isXLSX) {
        this.$message.error("只能上传xlsx文件");
      }
      const isLt5MB = fileList.size / 1024 / 1024 < 5;
      if (!isLt5MB) {
        this.$message.error("文件大小不能超过5MB");
      }
      console.log(fileList, "fileList");
      return isXLSX && isLt5MB;
    },
    handleOnChange(fileList) {
      console.log(fileList);
      this.globalFileList = fileList.raw;
    },

    handleClose() {
      this.subordinate = "";
      this.fileList = [];
      this.tolead = false;
    },
  },
};
</script>

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

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

    p {
      width: 100px;
      text-align: right;
      line-height: 40px;
      margin-right: 10px;
    }

    span {
      line-height: 40px;
    }

    .el-select {
      width: 260px;
    }

    .el-input {
      width: 260px;
    }
  }
}

.UPcondition {
  display: flex;
  margin-bottom: 10px;

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

  .el-select {
    width: 260px;
  }

  .el-input {
    width: 260px;
  }
}

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

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

.model-center {
  color: #666;
  line-height: 40px;
  height: 40px;
  font-size: 14px;
}

.demo-ruleForm {
  .el-select {
    width: 260px;
  }

  .el-input {
    width: 260px;
  }

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

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

  .el-form-item {
    width: 48%;
  }
}

.form-buttons {
  display: flex;
  justify-content: center;
  width: 100%;
  margin-top: 20px;
  /* optional: adds some space above the buttons */
}

.model-center {
  color: #409eff;
  cursor: pointer;
  line-height: 40px;
  height: 40px;
  font-size: 14px;
}
</style>
