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

        <el-table-column
          prop="manufacturerCode"
          align="center"
          label="厂商编号"
        >
        </el-table-column>

        <el-table-column
          prop="curvedMotionType"
          align="center"
          label="机型类型"
          min-width="120"
        >
          <template v-slot="scope">
            <!-- 假设 type 为 123 时显示特殊内容 -->
            <span v-if="scope.row.curvedMotionType == '1'">双馈</span>
            <span v-else-if="scope.row.curvedMotionType == '2'">半驱</span>
            <span v-else-if="scope.row.curvedMotionType == '3'">半直曲</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="manufacturerName"
          align="center"
          label="厂商名称"
          min-width="200"
        >
        </el-table-column>

        <el-table-column
          prop="brand"
          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="创建时间"
          min-width="150"
        >
        </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"
      :before-close="handleClose"
      width="800px"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm form-grid"
      >
        <div class="form-row">
          <el-form-item label="收资机型型号:" prop="machineTypeCode">
            <el-input
              v-model="ruleForm.machineTypeCode"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="厂商名称:" prop="manufacturerName">
            <el-input
              v-model="ruleForm.manufacturerName"
              size="small"
            ></el-input>
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="驱动方式:" prop="curvedMotionType">
            <el-select
              v-model="ruleForm.curvedMotionType"
              placeholder="请选择"
              value-key="contentsValue"
              @change="handleSelectChange"
              size="small"
            >
              <el-option
                v-for="item in curvedMotionTypeOptions"
                :key="item.contentsValue"
                :label="item.contentsName"
                :value="item.contentsValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="塔筒高度:" prop="towerHeight">
            <el-input v-model="ruleForm.towerHeight" size="small"></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="叶片长度:" prop="vaneLong">
            <el-input v-model="ruleForm.vaneLong" size="small"></el-input>
          </el-form-item>
          <el-form-item label="叶轮直径:" prop="rotorDiameter">
            <el-input v-model="ruleForm.rotorDiameter" size="small"></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="传动比-转速比:" prop="rotationalSpeedRatio">
            <el-input
              v-model="ruleForm.rotationalSpeedRatio"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="额定风速:" prop="ratedWindSpeed">
            <el-input v-model="ruleForm.ratedWindSpeed" size="small"></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="切入风速:" prop="ratedCutInWindspeed">
            <el-input
              v-model="ruleForm.ratedCutInWindspeed"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="切出风速:" prop="ratedCutOutWindspeed">
            <el-input
              v-model="ruleForm.ratedCutOutWindspeed"
              size="small"
            ></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <!-- <el-form-item label="厂商编号:" prop="manufacturerCode">
            <el-input
              v-model="ruleForm.manufacturerCode"
              size="small"
            ></el-input>
          </el-form-item> -->
          <el-form-item label="品牌名称:" prop="brand">
            <el-input v-model="ruleForm.brand" size="small"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <div class="form-actions">
        <el-button type="primary" @click="submitForm('ruleForm')" size="small"
          >提交</el-button
        >
        <el-button @click="resetForm('ruleForm')" size="small">取消</el-button>
      </div>
    </el-dialog>

    <!-- 机型详情 -->
    <el-dialog title="机型详情" :visible.sync="unusualdialog" width="600px">
      <div class="general">
        <div class="condition">
          <p>收资机型型号:</p>
          <span>{{ particularsdata.machineTypeCode }}</span>
        </div>
        <div class="condition">
          <p>厂商名称:</p>
          <span>{{ particularsdata.manufacturerName }}</span>
        </div>

        <div class="condition">
          <p>厂商编号:</p>
          <span>{{ particularsdata.manufacturerCode }}</span>
        </div>
        <div class="condition">
          <p>品牌名称:</p>
          <span>{{ particularsdata.brand }}</span>
        </div>

        <div class="condition">
          <p>驱动方式:</p>
          <span>
            <span v-if="particularsdata.curvedMotionType === 1">双馈</span>
            <span v-else-if="particularsdata.curvedMotionType === 2">半驱</span>
            <span v-else-if="particularsdata.curvedMotionType === 3"
              >半直曲</span
            ></span
          >
        </div>
        <div class="condition">
          <p>状态:</p>
          <span>{{ particularsdata.state == 1 ? "启用" : "停用" }}</span>
        </div>
        <div class="condition">
          <p>塔筒高度:</p>
          <span>{{ particularsdata.towerHeight }}(米)</span>
        </div>

        <div class="condition">
          <p>叶片长度:</p>
          <span>{{ particularsdata.vaneLong }}(米)</span>
        </div>
        <div class="condition">
          <p>叶轮直径:</p>
          <span>{{ particularsdata.rotorDiameter }}(米)</span>
        </div>
        <div class="condition">
          <p>传动比-转速比:</p>
          <span>{{ particularsdata.rotationalSpeedRatio }}</span>
        </div>
        <div class="condition">
          <p>额定风速:</p>
          <span>{{ particularsdata.ratedWindSpeed }} m/s</span>
        </div>
        <div class="condition">
          <p>切入风速:</p>
          <span>{{ particularsdata.ratedCutInWindspeed }} m/s</span>
        </div>
        <div class="condition">
          <p>切出风速:</p>
          <span>{{ particularsdata.ratedCutOutWindspeed }} m/s</span>
        </div>
      </div>
      <div class="attachment">
        <p class="model-center" @click="downloadfile">下载标准功率曲线附件</p>
      </div>
    </el-dialog>

    <!-- 上传 -->
    <el-dialog title="上传文件" :visible.sync="uploadingPOP" width="400px">
      <el-alert title="请点击模板下载文件附件" type="success" :closable="false">
      </el-alert>
      <p class="model-center" @click="download">模板下载</p>

      <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>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadingPOP = false" size="small">取 消</el-button>
        <el-button type="primary" @click="filesubmit" size="small"
          >提交</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createEngineMill,
  delWindEngineMill,
  getAllTemplate,
  getDictList,
  getWindEngineMillPageVo,
  powerWordCriterionImportData,
  updateWindEngineMill,
  windEngineMillPage,
} from "@/api/ledger.js";

export default {
  data() {
    var validateMachineTypeCode = (rule, value, callback) => {
    const regex = /^[a-zA-Z0-9./\\-]+$/;
    if (!value) {
      callback(new Error('请输入机型型号'));
    } else if (!regex.test(value)) {
      callback(new Error('只能输入数字，字母，小数点，斜杠，横杠'));
    } else {
      callback();
    }};
    return {
      loading: false,
      tableData: [],
      formInline: {
        machineTypeCode: "",
        timeQuantum: [],
        pageNum: 1,
        pageSize: 10,
        totalSize: 0,
      },
      startDate: "",
      endDate: "",
      //新增
      ruleForm: {
        machineTypeCode: "",
        manufacturerName: "",
        brand: "",
        curvedMotionType: "",
        towerHeight: "",
        manufacturerCode: "",
        vaneLong: "",
        rotorDiameter: "",
        rotationalSpeedRatio: "",
        ratedWindSpeed: "",
        ratedCutInWindspeed: "",
        ratedCutOutWindspeed: "",
      },
      curvedMotionTypeOptions: [],
      rules: {
        machineTypeCode: [
        { required: true, message: '请输入机型型号', trigger: 'blur' },
        { validator: validateMachineTypeCode, trigger: 'blur' }
        ],
        manufacturerName: [
          { required: true, message: "请输入厂商名称", trigger: "blur" },
        ],
        manufacturerCode: [
          { required: true, message: "请输入厂商编号", trigger: "blur" },
        ],
        brand: [{ required: true, message: "请输入品牌名称", trigger: "blur" }],
        curvedMotionType: [
          { required: true, message: "请选择驱动方式", trigger: "change" },
        ],
        towerHeight: [
          { required: true, message: "请输入塔筒高度", trigger: "blur" },
          { validator: this.validateNumber, trigger: ["blur", "change"] },
        ],
        rotorDiameter: [
          { required: true, message: "请输入叶轮直径", trigger: "blur" },
          { validator: this.validateNumber, trigger: ["blur", "change"] },
        ],
      },
      particularsdata: [],
      // 新增信息
      superior: "",
      superiorOptions: [],
      altitude: "",
      fileList: [],
      globalFileList: [],
      AllTemplateurl: "",
      rowmillTypeCode: "",

      nuedialog: false,
      unusualdialog: false,
      draught: false,
      uploadingPOP: false,
      title: "新增",
      detail: {},
      isEdit: false,
    };
  },
  created() {
    this.onSubmit();
    this.Modeltype();
  },
  mounted() {
    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;
      }
    },

    // 查询
    onSubmit() {
      let paramsData = {
        machineTypeCode: this.formInline?.machineTypeCode || undefined,
        beginTime: this.startDate || undefined,
        endTime: this.endDate || undefined,
        pageNum: this.formInline.pageNum || 1,
        pageSize: 10,
      };
      this.loading = true;
      windEngineMillPage(paramsData)
        .then((res) => {
          this.tableData = res.data.list;
          this.formInline.totalSize = res.data.totalSize;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          console.error(error);
        });
    },
    // 停用
    start(row, type) {
      let objectval = {
        millTypeCode: row.millTypeCode,
        state: type === 0 ? 0 : 1,
      };
      updateWindEngineMill(objectval).then((res) => {
        this.$message({
          message: "状态已更新成功",
          type: "success",
        });
        // this.$message(`${type === 1 ? '状态已更新成功' : '状态已更新成功'}`);
        row.state = type === 1 ? 0 : 1;
        this.onSubmit();
      });
    },
    Modeltype() {
      getDictList({
        dictType: 1,
      }).then((res) => {
        this.curvedMotionTypeOptions = res.data;
      });
    },
    handleSelectChange(value) {
      console.log("Selected value:", value);
    },
    // 新增提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$message.error("请填写必填项");
          return false;
        }
        let objectdata = {
          machineTypeCode: this.ruleForm.machineTypeCode,
          manufacturerName: this.ruleForm.manufacturerName,
          // manufacturerCode: this.ruleForm.manufacturerCode,
          brand: this.ruleForm.brand,
          curvedMotionType: this.ruleForm.curvedMotionType,
          towerHeight: this.ruleForm.towerHeight,
          vaneLong: this.ruleForm.vaneLong,
          rotorDiameter: this.ruleForm.rotorDiameter,
          rotationalSpeedRatio: this.ruleForm.rotationalSpeedRatio,
          ratedWindSpeed: this.ruleForm.ratedWindSpeed,
          ratedCutInWindspeed: this.ruleForm.ratedCutInWindspeed,
          ratedCutOutWindspeed: this.ruleForm.ratedCutOutWindspeed,
        };

        if (this.isEdit) {
          objectdata.millTypeCode = this.detail.millTypeCode;
        }

      
        const API = !this.isEdit
          ? createEngineMill(objectdata) //新增
          : updateWindEngineMill(objectdata); //编辑
          console.log(this.isEdit,API,'APIAPI');
        API.then((res) => {
          this.nuedialog = false;
          this.onSubmit();
          this.$message.success(this.isEdit ? "编辑成功" : "新增成功");
          this.isEdit = false;
        }).catch((error) => {});
      });
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.nuedialog = false;
      this.isEdit = false;
    },
    handleClose(done) {
      this.$refs.ruleForm.resetFields();
      this.nuedialog = false;
      this.isEdit = false;
      done();
    },

    // 数字验证
    validateNumber(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();
      }
    },

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

    //机型详情
    particulars(row) {
      getWindEngineMillPageVo({ millTypeCode: row.millTypeCode }).then(
        (res) => {
          this.unusualdialog = true;
          this.particularsdata = res.data;
        }
      );
    },
    //分页数据切换
    handleCurrentChange(val) {
      this.formInline.pageNum = val;
      this.onSubmit();
    },

    // 重置
    reset() {
      this.formInline.machineTypeCode = "";
      this.formInline.timeQuantum = "";
      this.onSubmit();
    },

    // 新增
    newly() {
      this.nuedialog = false;
    },

    // 编辑
    compile(row) {
      getWindEngineMillPageVo({ millTypeCode: row.millTypeCode }).then(
        (res) => {
          const item = JSON.parse(JSON.stringify(res.data));
          this.detail = item;
          Object.keys(this.ruleForm).forEach((key) => {
            this.ruleForm[key] = item[key];
          });
          console.log(res);
        }
      );
      this.title = "编辑";
      this.nuedialog = true;
      this.isEdit = true;
    },
    // 上传附件
    uploading(row) {
      this.rowmillTypeCode = row.millTypeCode;

      this.uploadingPOP = true;
    },
    // 附件提交
    filesubmit() {
      console.log(this.globalFileList);
      let filedata = {
        millTypeCode: this.rowmillTypeCode,
        file: this.globalFileList,
      };
      powerWordCriterionImportData(filedata).then((res) => {
        console.log(res);
        this.uploadingPOP = false;
        this.$message.success("上传成功");
      });
    },

    // 删除附件
    deleteRow(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 新增
    newnuedialog() {
      this.nuedialog = true;
      this.title = "新增";
    },
    // 下载模板
    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");
      }
    },
    getAllTemplate() {
      getAllTemplate().then((res) => {
        this.AllTemplateurl = res.data.bzPower;
      });
    },
    // 下载附件
    downloadfile() {
      if (this.particularsdata.powerCriterionUrl) {
        const link = document.createElement("a");
        link.href = this.particularsdata.powerCriterionUrl;
        link.download = ""; // 可以设置默认下载文件名
        link.target = "_blank"; // 新窗口打开
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } else {
        this.$message({
          showClose: true,
          message: "当前未上传附件无法下载，请先上传附件！！！",
          type: "warning",
        });
      }
    },
    // 附件验证
    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;
    },
  },
};
</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: 100%;
      margin-bottom: 20px;
    }

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

.UPcondition {
  display: flex;

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

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

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

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

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

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

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

  .el-form-item__error {
    padding-top: 0;
  }

  .el-select {
    width: 260px;
  }

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

.form-grid {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.form-row {
  display: flex;
  gap: 10px;
}

.form-row .el-form-item {
  flex: 1;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>
