<!--
 * @Author: your name
 * @Date: 2024-05-27 09:23:37
 * @LastEditTime: 2024-07-05 16:03:11
 * @LastEditors: bogon
 * @Description: In User Settings Edit
 * @FilePath: /performance-test/src/views/performance/batchMag.vue
-->
<template>
  <div class="global-variable" v-loading="loading">
    <div class="condition">
      <el-form
        :inline="true"
        ref="ruleForm"
        :model="formInline"
        class="demo-form-inline"
        :rules="rules"
      >
        <el-form-item label="风场名称:" prop="fieldName">
          <el-input
            size="small"
            v-model="formInline.fieldName"
            placeholder="请输入风场名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态:" prop="batchState" size="small">
          <el-select v-model="formInline.batchState" placeholder="请选择状态">
            <el-option label="启用" value="1"></el-option>
            <el-option label="停用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分析时间">
          <el-date-picker
            size="small"
            v-model="formInline.picker"
            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('ruleForm')" size="small">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="list-page">
      <div class="newly">
        <el-button
          v-hasPermi="['performance:batchMag:add']"
          type="primary"
          @click="newnuedialog"
          size="small"
          >新增</el-button
        >
      </div>
      <el-table
        v-loading="loading"
        class="center-align-table"
        :data="tableData"
        border
        :cell-style="rowStyle"
      >
        <el-table-column align="center" label="批次名称" prop="batchName">
        </el-table-column>
        <!-- <el-table-column align="center" label="批次编号" prop="batchCode">
        </el-table-column> -->
        <el-table-column prop="fieldName" align="center" label="关联风场">
        </el-table-column>
        <el-table-column
          prop="batchState"
          align="center"
          label="状态"
          width="100"
        >
          <template slot-scope="scope">
            <span>
              {{
                scope.row.batchState == 0
                  ? "禁用"
                  : scope.row.batchState == 1
                  ? "启用"
                  : "/"
              }}</span
            >
          </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="操作"
          width="200"
        >
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['performance:batchMag:edit']"
              @click="compile(scope.row)"
              type="text"
              size="small"
              >编辑</el-button
            >
            <el-button
              v-hasPermi="['performance:batchMag:editState']"
              v-if="scope.row.batchState == 0"
              @click="setState(1, scope.row)"
              type="text"
              size="small"
              >启用</el-button
            >
            <el-button
              v-else
              v-hasPermi="['performance:batchMag:editState']"
              style="color: #666"
              @click="setState(0, scope.row)"
              type="text"
              size="small"
              >禁用</el-button
            >

            <el-button
              style="color: #f00"
              @click="deleted(scope.row)"
              v-hasPermi="['performance:batchMag:delete']"
              type="text"
              size="small"
              :disabled="scope.row.batchState == 1"
              >删除</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="500px"
      :before-close="handleCloses"
    >
      <div v-loading="loadingView" class="views">
        <el-form
          :model="ruleForm"
          :rules="addUserRules"
          ref="addUserForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="关联风场:" prop="fieldCode">
            <el-select
              :disabled="title === '编辑'"
              v-model="ruleForm.fieldCode"
              placeholder="请选择关联风场"
              style="width: 100%"
            >
              <el-option
                :label="item.fieldName"
                v-for="item in fieldCodeList"
                :value="item.codeNumber"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="批次名称"
            prop="batchName"
            v-if="title === '编辑'"
          >
            <el-input
              v-model="ruleForm.batchName"
              placeholder="请输入批次名称"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancel('addUserForm')" size="small"
            >取 消</el-button
          >
          <el-button
            type="primary"
            @click="submitForm('addUserForm')"
            size="small"
            >确 定</el-button
          >
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getBatchMagList,
  addFieldBatch,
  updateFieldBatch,
  queryCodeNum,
  onOrOffFieldBatch,
  deleteFieldBatch,
  createBatchName,
} from "@/api/performance.js";
export default {
  data() {
    return {
      loadingView: false,
      loading: false, //数据加载中
      rules: {
        fieldCode: { trigger: "change" },
        batchState: { trigger: "blur" },
      },
      startDate: "",
      endDate: "",
      fieldCodeList: [],
      formInline: {
        fieldName: undefined,
        batchState: undefined,
        picker: [],
        pageNum: 1,
        pageSize: 10,
        totalSize: 0,
      },
      tableData: [],
      // 新增编辑表单
      ruleForm: {
        fieldCode: null,
        batchName: null,
        batchCode: null,
      },
      addUserRules: {
        batchCode: {
          required: true,
          message: "请选择关联风场",
          trigger: "change",
        },
        batchName: [
          { required: true, message: "请输入批次名称", trigger: "blur" },
        ],
      },
      //修改密码
      editUserPassword: {
        oldPWD: "",
        newPWD: "",
        userId: "",
      },

      nuedialog: false,
      title: "",
    };
  },
  created() {
    this.getTableList();
    this.getQueryCodeNumList();
  },

  methods: {
    handleCloses(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    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 getQueryCodeNumList() {
      this.loading = true;
      try {
        const result = await queryCodeNum();
        this.fieldCodeList = result.data.fieldCodeList;
        this.loading = false;
      } catch (error) {
        console.error(error);
        this.loading = false;
      }
    },
    //分页数据切换
    handleCurrentChange(val) {
      this.formInline.pageNum = val;
      this.getTableList();
    },
    //修改状态
    setState(state, row) {
      //启用接口
      this.loading = true;
      onOrOffFieldBatch({ batchCode: row.batchCode, batchState: state })
        .then((res) => {
          this.$message({
            message: res.msg,
            type: "success",
          });
          this.loading = false;
          this.getTableList();
        })
        .catch((error) => {
          this.loading = false;
        });
    },
    async getTableList() {
      try {
        this.loading = true;
        const result = await getBatchMagList({
          ...this.formInline,
          picker: undefined,
          startTime: this.startDate || undefined,
          endTime: this.endDate || undefined,
          totalSize: undefined,
        });
        this.tableData = result.data.list;
        this.formInline.totalSize = result.data.totalSize;
        this.loading = false;
      } catch (error) {
        this.$message({
          type: "error",
          message: "请检查是否连接网络",
        });
      }
    },

    rowStyle() {
      return "text-align:center";
    },
    // 查询
    onSubmit() {
      this.getTableList();
    },
    // 重置
    reset(formName) {
      this.formInline.picker = [];
      this.startDate = undefined;
      this.endDate = undefined;
      this.$refs[formName].resetFields();
      this.getTableList();
    },

    // 新增,编辑确定
    submitForm(formName) {
      // this.loading = true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loadingView = true;
          switch (this.title) {
            case "新增":
              const obj = this.fieldCodeList.find(
                (item) => item.codeNumber === this.ruleForm.fieldCode
              );
              const form = new FormData();
              form.append("fieldName", obj.fieldName);
              createBatchName(form).then((results) => {
                addFieldBatch({
                  ...this.ruleForm,
                  batchName: results.data,
                  batchCode: undefined,
                })
                  .then((res) => {
                    this.$message({
                      type: "success",
                      message: res.msg,
                    });
                    // this.loading = false;
                    this.getTableList();
                    this.nuedialog = false;
                    this.loadingView = false;
                  })
                  .catch(() => {
                    this.loadingView = false;
                    // this.loading = false;
                  });
              });

              break;
            case "编辑":
              updateFieldBatch({ ...this.ruleForm, fieldCode: undefined })
                .then((res) => {
                  this.$message({
                    type: "success",
                    message: res.msg,
                  });
                  this.getTableList();
                  this.nuedialog = false;
                  this.loadingView = false;
                })
                .catch(() => {
                  this.loadingView = false;
                });

              break;
          }
          // this.nuedialog = false;
        } else {
          return false;
        }
      });
    },
    //点击取消
    cancel(formName) {
      this.$refs[formName] && this.$refs[formName].resetFields();
      this.ruleForm = {
        fieldCode: null,
        batchCode: null,
        batchName: null,
      };
      this.nuedialog = false;
      this.loadingView = false;
    },
    // 编辑 回显数据
    async compile(row) {
      try {
        // 直接替换整个对象，以确保 Vue 的响应式系统能够检测到变化
        this.ruleForm = {
          fieldCode: row.fieldCode,
          batchCode: row.batchCode,
          batchName: row.batchName,
        };
        this.nuedialog = true;
        this.title = "编辑";
      } catch (error) {
        this.$message.error("获取用户信息失败");
      }
    },
    // 删除
    deleted(row) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          deleteFieldBatch({ batchCode: row.batchCode })
            .then((res) => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.loading = false;
              this.getTableList();
            })
            .catch(() => {
              this.loading = false;
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 新增
    newnuedialog() {
      this.cancel("addUserForm");
      this.ruleForm = {
        batchCode: "",
        batchName: "",
        fieldCode: "",
      };
      this.nuedialog = true;
      this.title = "新增";
    },
  },
};
</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;
    }

    span {
      line-height: 40px;

      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;
}
.demo-ruleForm {
  .el-form-item {
    margin-bottom: 25px;
  }
}
</style>
