<template>
  <div>
      <!-- 查询表单 -->
      <el-form :inline="true" :model="queryForm" ref="queryForm" label-width="80px">
        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker v-model="queryForm.startDate" type="date" placeholder="选择开始时间" value-format="yyyy-MM-dd"
            :clearable="true"></el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker v-model="queryForm.endDate" type="date" placeholder="选择结束时间" value-format="yyyy-MM-dd"
            :clearable="true"></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery" :loading="btnLoading">
            <i class="el-icon-search"></i> 查询
          </el-button>
          <el-button @click="handleReset">
            <i class="el-icon-refresh"></i> 重置
          </el-button>
          <!-- <el-button type="success" @click="handleAdd">
            <i class="el-icon-plus"></i> 新增
          </el-button> -->
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table v-loading="tableLoading" :data="tableData" border style="width: 100%; margin-top: 20px;"
        @row-click="handleRowClick" highlight-current-row>
        <el-table-column prop="coilid" label="钢卷号" width="120" align="center"></el-table-column>
        <el-table-column prop="stopType" label="停机类型" width="120" align="center"></el-table-column>
        <el-table-column prop="remark" label="停机原因" min-width="200"></el-table-column>
        <el-table-column prop="shift" label="班" width="80" align="center"></el-table-column>
        <el-table-column prop="crew" label="组" width="80" align="center"></el-table-column>
        <el-table-column prop="area" label="区域" width="100" align="center"></el-table-column>
        <el-table-column prop="seton" label="设备" width="100" align="center"></el-table-column>
        <el-table-column prop="startDate" label="开始时间" width="180" align="center"></el-table-column>
        <el-table-column prop="endDate" label="结束时间" width="180" align="center"></el-table-column>
        <el-table-column prop="duration" label="停机时长(分)" width="120" align="center"></el-table-column>
        <el-table-column prop="insdate" label="更新时间" width="180" align="center"></el-table-column>
        
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)" icon="el-icon-edit">
              编辑
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)" icon="el-icon-delete"
              :loading="scope.row.deleteLoading">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    <!-- 编辑/新增弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%" :close-on-click-modal="false">
      <el-form :model="formData" ref="formData" label-width="80px" :rules="formRules">
        <el-form-item label="停机ID" prop="stopid" v-if="formData.stopid">
          <el-input v-model="formData.stopid" disabled></el-input>
        </el-form-item>

        <el-form-item label="钢卷号" prop="coilid">
          <el-input v-model="formData.coilid" placeholder="请输入钢卷号"></el-input>
        </el-form-item>

        <el-form-item label="班" prop="shift">
          <el-select v-model="formData.shift" placeholder="请选择班次" clearable>
            <el-option label="早班" value="早班"></el-option>
            <el-option label="中班" value="中班"></el-option>
            <el-option label="晚班" value="晚班"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="组" prop="crew">
          <el-input v-model="formData.crew" placeholder="请输入组号"></el-input>
        </el-form-item>

        <el-form-item label="区域" prop="area">
          <el-input v-model="formData.area" placeholder="请输入区域"></el-input>
        </el-form-item>

        <el-form-item label="机组" prop="unit">
          <el-input v-model="formData.unit" placeholder="请输入机组"></el-input>
        </el-form-item>

        <el-form-item label="设备" prop="seton">
          <el-input v-model="formData.seton" placeholder="请输入设备"></el-input>
        </el-form-item>

        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker v-model="formData.startDate" type="datetime" placeholder="选择开始时间"
            value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker v-model="formData.endDate" type="datetime" placeholder="选择结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        </el-form-item>

        <el-form-item label="停机类型" prop="stopType">
          <el-select v-model="formData.stopType" placeholder="请选择停机类型" clearable>
            <el-option label="计划停机" value="计划停机"></el-option>
            <el-option label="故障停机" value="故障停机"></el-option>
            <el-option label="维护停机" value="维护停机"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="停机原因" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入停机原因" type="textarea" rows="4"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saveLoading">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import createFetch from '@/api/l2/stop'

export default {
  name: 'StoppageManagement',
  props: {
    baseURL: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fetchApi: {},
      // 查询表单数据
      queryForm: {
        // 只保留年月日YYYY-mm-dd
        startDate: '2023-08-13',
        endDate: '2025-08-20'
      },
      // 表格数据
      tableData: [],
      // 加载状态
      tableLoading: false,
      btnLoading: false,
      // 弹窗状态
      dialogVisible: false,
      dialogTitle: '新增停机记录',
      // 表单数据
      formData: {
        stopid: '',
        coilid: '',
        shift: '',
        crew: '',
        area: '',
        unit: '',
        seton: '',
        startDate: '',
        endDate: '',
        duration: 0,
        insdate: '',
        stopType: '',
        remark: ''
      },
      // 表单验证规则
      formRules: {
        startDate: [
          { required: true, message: '请选择开始时间', trigger: 'blur' }
        ],
        endDate: [
          { required: true, message: '请选择结束时间', trigger: 'blur' }
        ],
        seton: [
          { required: true, message: '请输入设备', trigger: 'blur' }
        ]
      },
      // 保存按钮加载状态
      saveLoading: false,
      // 当前操作的行数据
      currentRow: {}
    };
  },
  created() {
    // 页面加载时默认查询一次
    this.fetchApi = createFetch(this.baseURL)
    this.getStoppageList();
  },
  methods: {
    // 获取停机记录列表
    getStoppageList() {
      this.tableLoading = true;
      this.fetchApi.listStoppage(this.queryForm)
        .then(response => {
          this.tableLoading = false;
          this.btnLoading = false;
          this.tableData = response.data.map(item => ({
            ...item,
            deleteLoading: false
          }));
        })
        .catch(error => {
          this.tableLoading = false;
          this.btnLoading = false;
          console.error('获取数据失败:', error);
          this.$message.error('获取数据失败，请稍后重试');
        });
    },

    // 处理查询
    handleQuery() {
      // 验证开始时间不能晚于结束时间
      if (this.queryForm.startDate && this.queryForm.endDate &&
        new Date(this.queryForm.startDate) > new Date(this.queryForm.endDate)) {
        this.$message.warning('开始时间不能晚于结束时间');
        return;
      }

      this.btnLoading = true;
      this.getStoppageList();
    },

    // 处理重置
    handleReset() {
      this.$refs.queryForm.resetFields();
      this.getStoppageList();
    },

    // 行点击事件
    handleRowClick(row) {
      this.currentRow = row;
    },

    // 新增
    handleAdd() {
      this.dialogTitle = '新增停机记录';
      this.formData = {
        stopid: '',
        coilid: '',
        shift: '',
        crew: '',
        area: '',
        unit: '',
        seton: '',
        startDate: '',
        endDate: '',
        duration: 0,
        insdate: '',
        stopType: '',
        remark: ''
      };
      this.dialogVisible = true;
    },

    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑停机记录';
      this.formData = { ...row };
      this.dialogVisible = true;
    },

    // 删除
    handleDelete(row) {
      this.$confirm(`确定要删除ID为 ${row.stopid} 的停机记录吗？`, '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        // 设置当前行的删除按钮为加载状态
        row.deleteLoading = true;

        this.fetchApi.deleteStoppage(row.stopid)
          .then(response => {
            row.deleteLoading = false;

            if (response.code === 200) {
              this.$message.success('删除成功');
              // 重新查询数据
              this.getStoppageList();
            } else {
              this.$message.error(response.msg || '删除失败');
            }
          })
          .catch(error => {
            row.deleteLoading = false;
            console.error('删除失败:', error);
            this.$message.error('删除失败，请稍后重试');
          });
      }).catch(() => {
        // 用户取消删除
        this.$message.info('已取消删除');
      });
    },

    // 保存
    handleSave() {
      this.$refs.formData.validate(valid => {
        if (valid) {
          // 验证开始时间不能晚于结束时间
          if (new Date(this.formData.startDate) > new Date(this.formData.endDate)) {
            this.$message.warning('开始时间不能晚于结束时间');
            return;
          }

          // 计算停机时长(分钟)
          const start = new Date(this.formData.startDate).getTime();
          const end = new Date(this.formData.endDate).getTime();
          this.formData.duration = Math.round((end - start) / (1000 * 60) * 10) / 10;

          // 设置当前时间为更新时间
          const now = new Date();
          this.formData.insdate = now.toISOString().slice(0, 19).replace('T', ' ');

          this.saveLoading = true;

          // 调用更新接口
          this.fetchApi.updateStoppage(this.formData)
            .then(response => {
              this.saveLoading = false;

              if (response.code === 200) {
                this.$message.success('保存成功');
                this.dialogVisible = false;
                // 重新查询数据
                this.getStoppageList();
              } else {
                this.$message.error(response.msg || '保存失败');
              }
            })
            .catch(error => {
              this.saveLoading = false;
              console.error('保存失败:', error);
              this.$message.error('保存失败，请稍后重试');
            });
        }
      });
    }
  }
};
</script>

<style scoped>
.no-data {
  margin-top: 50px;
  text-align: center;
}
 
::v-deep .el-form-item {
  margin-bottom: 15px;
}
</style>
