<template>
  <div class="create-report">
    <el-row :gutter="10">
      <el-col :span="6" style="margin-top: 10px; margin-bottom: 10px">
        <dept-tree @deptChange="handleDeptChange" :showQuickGroup="true" />
      </el-col>
      <el-col :span="6" style="margin-top: 10px; margin-bottom: 10px">
        <!-- 月份选择 格式化为 2024-7  -->
        <el-date-picker
          v-model="dateValue"
          type="month"
          format="yyyy-M"
          value-format="yyyy-M"
          placeholder="选择月份"
          @change="handleDateChange"
        >
        </el-date-picker>
      </el-col>
    </el-row>
    <el-row :gutter="10">
      <el-table
        :data="tableData"
        style="width: 100%"
        border
        :max-height="tableHeight"
        v-loading="loading"
      >
        <el-table-column prop="gangqu" label="归属港区" />
        <el-table-column prop="deptName" label="归属企业" />
        <el-table-column prop="sn" label="设备编码" />
        <el-table-column prop="year" label="年份" />
        <el-table-column prop="month" label="月份" />
        <el-table-column prop="avgValue" label="平均值">
          <template slot-scope="scope">
            <div @dblclick="changeAvgValue(scope.$index, scope.row)">
              <span v-show="!scope.row.enable_edit">{{
                scope.row.avgValue
              }} mg/m³</span>

              <el-input
                :ref="'changeAvgValue' + scope.$index"
                @blur="changeAvgValueBlur(scope.$index, scope.row)"
                @keyup.enter.native="$event.target.blur"
                clearable
                v-show="scope.row.enable_edit"
                size="mini"
                v-model="scope.row.avgValue"
                placeholder="请输入内容"
              ></el-input>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="page-ele">
        <el-pagination
          layout="sizes, prev, pager, next, total"
          :total="total"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 40]"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        >
        </el-pagination>
      </div>
    </el-row>
  </div>
</template>

<script>
import {
  getDeviceReportMonthList,
  updateDeviceReportMonth,
} from "@/api/statistics/monthData.js";
import { checkRole } from "@/utils/permission";

export default {
  name: "CreateReport",
  data() {
    return {
      deptId: "",
      dateValue: "",
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      loading: false,
      oldValue: "",
    };
  },
  created() {
    this.initDate();
  },
  computed: {
    tableHeight() {
      return window.innerHeight - 300;
    },
  },
  methods: {
    handleDeptChange(value) {
      this.deptId = value.deptId;
      this.queryData();
    },
    handleDateChange(value) {
      this.queryData();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.queryData();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.queryData();
    },
    initDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      this.dateValue = `${year}-${month}`;
    },
    changeAvgValue(index, row) {
      if (!checkRole(['admin','power'])) return;
      this.$set(row, "enable_edit", true);
      this.oldValue = row.avgValue;
      this.$nextTick(() => {
        this.$refs["changeAvgValue" + index].focus();
      });
    },
    changeAvgValueBlur(index, row) {
      this.$set(row, "enable_edit", false);
      if (row.avgValue === "") {
        this.$message.error("平均值不能为空");
        this.queryData();
        return;
      }
      if (isNaN(row.avgValue)) {
        this.$message.error("平均值必须为数字");
        this.queryData();
        return;
      }
      if (row.avgValue < 0) {
        this.$message.error("平均值不能小于0");
        this.queryData();
        return;
      }
      if (this.oldValue === row.avgValue) {
        return;
      }
      this.$confirm(`是否修改数据?${this.oldValue}→${row.avgValue}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const params = {
            id: row.id,
            avgValue: row.avgValue,
          };
          updateDeviceReportMonth(params)
            .then((res) => {
              if (res.code !== 200) {
                this.$message.error("修改失败");
              } else {
                this.$message({
                  type: "success",
                  message: "修改成功!",
                });
              }
            })
            .catch((error) => {
              console.error(error);
              this.$message.error("修改失败");
            })
            .finally(() => {
              this.queryData();
            });
        })
        .catch(() => {
          row.avgValue = this.oldValue;
          this.$message({
            type: "info",
            message: "取消修改",
          });
        });
    },
    queryData() {
      this.loading = true;
      const params = {
        deptId: this.deptId,
        year: this.dateValue.split("-")[0],
        month: this.dateValue.split("-")[1],
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      getDeviceReportMonthList(params)
        .then((res) => {
          if (res.code === 200) {
            this.tableData = res.rows;
            this.total = res.total;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
};
</script>

<style scoped>
.create-report {
  min-height: 50vh;
}
.page-ele {
  margin-top: 10px;
  text-align: right;
}
</style>
