<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="物料编码" prop="materialCode">
        <el-input v-model="queryParams.materialCode" placeholder="请输入物料编码" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="材质" prop="wlMaterial">
        <el-input
          v-model="queryParams.wlMaterial"
          placeholder="请输入材质"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预计可用量" prop="requiredStock">
        <el-input v-model="queryParams.requiredStock" placeholder="请输入所需库存" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="即时库存" prop="currentStock">
        <el-input v-model="queryParams.currentStock" placeholder="请输入当前库存" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="触发时间" prop="triggerTime">
        <el-date-picker clearable v-model="queryParams.triggerTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择触发时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否符合要求" prop="safeStatus">
        <el-select v-model="queryParams.safeStatus" placeholder="请选择" clearable>
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="分组" prop="wlMaterial">
        <el-select v-model="queryParams.wlMaterial" placeholder="请选择" clearable>
          <el-option label="30S" value="30S" />
          <el-option label="30D" value="30D" />
          <el-option label="35E" value="35E" />
          <el-option label="40S" value="40S" />
          <el-option label="35R" value="35R" />
          <el-option label="40R" value="40R" />
          <el-option label="40C" value="40C" />
          <el-option label="60R" value="60R" />
          <el-option label="80R" value="80R" />
          <el-option label="通用" value="通用" />
          <el-option label="行程检测" value="行程检测" />
          <el-option label="行程检测白模具三" value="行程检测白模具三" />
          <el-option label="行程检测灰模具三" value="行程检测灰模具三" />
          <el-option label="行程检测模具四" value="行程检测模具四" />
          <el-option label="行程检测模具五" value="行程检测模具五" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:stockData:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:stockData:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:stockData:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:stockData:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="generateDoc"
          v-hasPermi="['system:stockData:generateDoc']">生成安全库存单据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stockDataList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--      <el-table-column label="主键ID" align="center" prop="id" v-if="true"/>-->
      <el-table-column label="物料编码" align="center" prop="materialCode">
        <template slot-scope="scope">
          <span :style="{
            color: scope.row.availableStock < scope.row.minsafetyStock ? 'red' : 'inherit',
            fontWeight: 'bold'
          }">
            {{ scope.row.materialCode }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="物料名称" align="center" prop="materialName" />
      <el-table-column label="材质 " align="center" width="200" prop="documentType" />
      <el-table-column label="预计可用量" align="center" prop="currentStock" />
<!--      <el-table-column label="即时库存" align="center" prop="currentStock" />-->

      <el-table-column label="用料清单未领料数量" align="center" prop="availableStock" />
      <el-table-column label="即时库存" align="center" prop="secAvbqty" />


      <el-table-column label="生产订单未入库数量" align="center" prop="productionQty" />
      <el-table-column label="采购订单未入库数量" align="center" prop="purchaseQty" />
      <el-table-column label="最大安全库存" align="center" prop="maxsafetyStock" />
      <el-table-column label="最低安全库存" align="center" prop="minsafetyStock" />
      <el-table-column label="分组" align="center" prop="wlMaterial" />
      <el-table-column label="是否符合安全库存要求" align="center" prop="safeStatus">
      <template slot-scope="scope">
        <dict-tag :options="dict.type.safe_status" :value="scope.row.safeStatus"></dict-tag>
      </template>
      </el-table-column>
      <el-table-column label="触发时间" align="center" prop="triggerTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.triggerTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:stockData:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:stockData:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改安全库存单据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物料编码" prop="materialCode">
          <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="所需库存" prop="requiredStock">
          <el-input v-model="form.requiredStock" placeholder="请输入所需库存" />
        </el-form-item>
        <el-form-item label="当前库存" prop="currentStock">
          <el-input v-model="form.currentStock" placeholder="请输入当前库存" />
        </el-form-item>
        <el-form-item label="触发时间" prop="triggerTime">
          <el-date-picker clearable v-model="form.triggerTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择触发时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-progress :percentage="percentage"></el-progress>
    <div class="log-container">
      <ul ref="list" class="log-list">
        <li v-for="(item, index) in list" :key="index" :class="['log-item', getLogClass(item.message)]">
          <span class="log-timestamp">{{ item.timestamp }}</span>
          <span class="log-message">{{ item.message }}</span>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>

import {
  listStockData,
  getStockData,
  delStockData,
  addStockData,
  updateStockData,
  generateDoc,
  logs,
} from "@/api/system/stockData";
import dict from "@/utils/dict";
import DictData from "@/components/DictData";
DictData.install();
export default {
  dicts: ['safe_status'],
  name: "StockData",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 安全库存单据表格数据
      stockDataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialCode: undefined,
        materialName: undefined,
        requiredStock: undefined,
        currentStock: undefined,
        triggerTime: undefined,
        documentType: undefined,
        wlMaterial: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "主键ID不能为空", trigger: "blur" }
        ],
        materialCode: [
          { required: true, message: "物料编码不能为空", trigger: "blur" }
        ],
        materialName: [
          { required: true, message: "物料名称不能为空", trigger: "blur" }
        ],
        requiredStock: [
          { required: true, message: "所需库存不能为空", trigger: "blur" }
        ],
        currentStock: [
          { required: true, message: "当前库存不能为空", trigger: "blur" }
        ],
        triggerTime: [
          { required: true, message: "触发时间不能为空", trigger: "blur" }
        ],
        documentType: [
          { required: true, message: "单据类型 (1: 最高库存单, 0: 最低库存单)不能为空", trigger: "change" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ],
        updateBy: [
          { required: true, message: "更新人不能为空", trigger: "blur" }
        ]
      },
      percentage: 0,
      list: [],
      lastLogIndex: 0,
      timer: null // 存储定时器的引用
    };
  },
  created() {
    this.getList();
  },
  methods: {
    dict,
    /** 查询安全库存单据列表 */
    getList() {
      this.loading = true;
      listStockData(this.queryParams).then(response => {
        this.stockDataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        materialCode: undefined,
        materialName: undefined,
        requiredStock: undefined,
        currentStock: undefined,
        triggerTime: undefined,
        documentType: undefined,
        createTime: undefined,
        safeStatus: undefined,
        wlMaterial: undefined,
        updateTime: undefined,
        createBy: undefined,
        updateBy: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加安全库存单据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getStockData(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改安全库存单据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateStockData(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addStockData(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除安全库存单据编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delStockData(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/stockData/export', {
        ...this.queryParams
      }, `stockData_${new Date().getTime()}.xlsx`)
    },
    updateProgress() {
      if (this.percentage < 100) {
        this.percentage++;
        this.scrollToBottom();
      } else {
        this.percentage = 100;
      }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const list = this.$refs.list;
        list.scrollTop = list.scrollHeight;
      });
    },
    generateDoc() {
      this.loading = true;
      this.percentage = 0;
      this.list = [];
      this.timer = setInterval(this.updateProgress, 1000);

      this.fetchLogs(); // 启动日志获取

      generateDoc().then(response => {
        this.loading = false;
        clearInterval(this.timer);
        this.percentage = 100;

        if (response.code === 200) {
          const stockDataList = response.data;
          this.list.push('生成安全库存单据成功！');
        } else {
          this.$message.error('生成安全库存单据失败，请稍后再试');
          this.list.push('生成安全库存单据失败');
        }
        this.refreshPage();
      })
        .catch((error) => {
          this.loading = false;
          clearInterval(this.timer);
          this.$message.error('请求失败，请检查网络连接');
          this.list.push('请求失败，请检查网络连接');
          this.refreshPage();
        });
    },
    fetchLogs() {
      this.timer = setInterval(() => {
        console.log('请求日志接口');
        logs(this.lastLogIndex)
          .then(response => {
            console.log('完整响应:', response);
            if (Array.isArray(response)) {
              const newLogs = response.map(message => ({
                timestamp: this.formatTimestamp(new Date()),
                message: message
              }));
              this.list = this.list.concat(newLogs);
              console.log('更新后的 list:', this.list);
              this.lastLogIndex += response.length;
            } else {
              console.error('返回的数据格式不正确:', response);
            }
            this.scrollToBottom();
          })
          .catch(error => {
            console.error('获取日志失败:', error);
          });
      }, 5000);
    },
    formatTimestamp(date) {
      const year = date.getFullYear();
      const month = this.padZero(date.getMonth() + 1);
      const day = this.padZero(date.getDate());
      const hours = this.padZero(date.getHours());
      const minutes = this.padZero(date.getMinutes());
      const seconds = this.padZero(date.getSeconds());
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    padZero(num) {
      return num < 10 ? '0' + num : num;
    },
    mounted() {
      // 这里可以添加其他初始化逻辑
      this.fetchLogs();
    },
    beforeDestroy() {
      clearInterval(this.timer);
    },
    getLogClass(message) {
      if (message.includes('错误') || message.includes('失败')) {
        return 'log-error';
      } else if (message.includes('成功')) {
        return 'log-success';
      } else {
        return 'log-info';
      }
    }
  }
};
</script>

<style scoped>
.log-container {
  height: 300px;
  overflow-y: auto;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 10px;
  margin-top: 20px;
}

.log-list {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.log-item {
  margin-bottom: 10px;
}

.log-timestamp {
  color: #999;
  font-size: 12px;
  margin-right: 10px;
}

.log-message {
  font-size: 14px;
}

.log-error {
  color: red;
}

.log-success {
  color: green;
}

.log-info {
  color: blue;
}
</style>
