<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="boardCode">
        <el-input
          v-model="queryParams.boardCode"
          placeholder="请输入看板编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="看板名称" prop="boardName">
        <el-input
          v-model="queryParams.boardName"
          placeholder="请输入看板名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="产品线编码" prop="productLineCode">
        <el-select v-model="queryParams.productLineCode" placeholder="请选择产线" clearable>
          <el-option
            v-for="item in productLineList"
            :key="item.productLineCode"
            :label="item.productLineName"
            :value="item.productLineCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工位/工序编码" prop="stationCode">
        <el-select v-model="queryParams.stationCode" placeholder="请选择工位/工序" clearable>
          <el-option
            v-for="item in processStationList"
            :key="item.stationCode"
            :label="item.stationName"
            :value="item.stationCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="刷新间隔" prop="refreshIntervalSec">
        <el-input
          v-model="queryParams.refreshIntervalSec"
          placeholder="请输入刷新间隔"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否有效" prop="isFlag">
        <el-select v-model="queryParams.isFlag" placeholder="请选择是否有效" clearable>
          <el-option label="有效" value="1" />
          <el-option label="无效" value="0" />
        </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="['production:andonBoardConfig: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="['production:andonBoardConfig: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="['production:andonBoardConfig: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="['production:andonBoardConfig:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="andonBoardConfigList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="boardId" v-if="columns[0].visible"/>
      <el-table-column label="看板编码" align="center" prop="boardCode" v-if="columns[1].visible"/>
      <el-table-column label="看板名称" align="center" prop="boardName" v-if="columns[2].visible"/>
      <el-table-column label="产品线编码" align="center" prop="productLineCode" v-if="columns[3].visible"/>
      <el-table-column label="工位/工序编码" align="center" prop="stationCode" v-if="columns[4].visible"/>
      <el-table-column label="看板展示字段配置" align="center" prop="displayFields" v-if="columns[5].visible"/>
      <el-table-column label="刷新间隔" align="center" prop="refreshIntervalSec" v-if="columns[6].visible"/>
      <el-table-column label="是否有效" align="center" prop="isFlag" v-if="columns[7].visible">
        <template slot-scope="scope">
          <span>{{ scope.row.isFlag === '1' ? '有效' : '无效' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" v-if="columns[8].visible"/>
      <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="['production:andonBoardConfig:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['production:andonBoardConfig: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="boardCode">
          <el-input v-model="form.boardCode" placeholder="请输入看板编码" />
        </el-form-item>
        <el-form-item label="看板名称" prop="boardName">
          <el-input v-model="form.boardName" placeholder="请输入看板名称" />
        </el-form-item>
        <el-form-item label="产品线编码" prop="productLineCode"  label-width="120px">
          <el-select v-model="form.productLineCode" placeholder="请选择产线" clearable>
            <el-option
              v-for="item in productLineList"
              :key="item.productLineCode"
              :label="item.productLineName"
              :value="item.productLineCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工位/工序编码" prop="stationCode"  label-width="120px">
          <el-select v-model="form.stationCode" placeholder="请选择工位/工序" clearable>
            <el-option
              v-for="item in processStationList"
              :key="item.stationCode"
              :label="item.stationName"
              :value="item.stationCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="展示字段配置" prop="displayFields"  label-width="120px">
          <el-input type="textarea" v-model="form.displayFields" placeholder="请输入展示字段配置" :rows="3" />
          <div style="margin-top: 6px;">
            <el-button type="info" size="mini" plain @click="helpVisible = true">操作说明</el-button>
          </div>
        </el-form-item>
        <el-form-item label="刷新间隔" prop="refreshIntervalSec">
          <el-input v-model="form.refreshIntervalSec" placeholder="请输入刷新间隔" />
        </el-form-item>
        <el-form-item label="是否有效" prop="isFlag">
          <el-radio-group v-model="form.isFlag">
            <el-radio label="1">有效</el-radio>
            <el-radio label="0">无效</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 展示字段配置操作说明 -->
    <el-dialog title="展示字段配置说明" :visible.sync="helpVisible" width="640px" append-to-body>
      <div class="help-block">
        <p><strong>作用：</strong>控制大屏进行中/已关闭列表显示哪些列、顺序与标题，可单独设置列宽与对齐。</p>
        <p><strong>写法示例：</strong></p>
        <ol>
          <li>逗号分隔字符串（两张表共用同列）<br><code>callCode,stationCode,eventStatus,priority,createTime</code></li>
          <li>JSON 数组（可带 label/width/align）<br><pre style="margin:4px 0;">[
  "callCode",
  { "field": "eventStatus", "label": "状态", "align": "center" }
]</pre></li>
          <li>JSON 对象区分进行中/已关闭<br><pre style="margin:4px 0;">{
  "activeFields": ["callCode","priority"],
  "closedFields": ["callCode","responseEndTime","resolution"]
}</pre></li>
        </ol>
        <p><strong>可用字段：</strong></p>
        <div class="field-tags">
          <ul style="padding-left: 18px; margin: 6px 0;">
            <li v-for="f in availableFields" :key="f.field" style="margin: 2px 0;">
              <code>{{ f.field }}</code> - {{ f.label }}
            </li>
          </ul>
        </div>
        <p style="margin-top: 8px; color: #888;">未填写或格式错误时会回退默认列，label/width/align 未设置则自动使用字段默认标题。</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="helpVisible = false">知道了</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listAndonBoardConfig, getAndonBoardConfig, delAndonBoardConfig, addAndonBoardConfig, updateAndonBoardConfig } from "@/api/production/andonBoardConfig";
import { findProductLineList } from "@/api/base/productLine";
import { listProcessStation } from "@/api/base/processStation";

export default {
  name: "AndonBoardConfig",
  dicts: [],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 安灯看板配置表格数据
      andonBoardConfigList: [],
      // 产线下拉选项
      productLineList: [],
      // 工位/工序下拉选项
      processStationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 操作说明弹层
      helpVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        boardCode: null,
        boardName: null,
        productLineCode: null,
        stationCode: null,
        displayFields: null,
        refreshIntervalSec: null,
        isFlag: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        boardCode: [
          { required: true, message: "看板编码不能为空", trigger: "blur" }
        ],
        boardName: [
          { required: true, message: "看板名称不能为空", trigger: "blur" }
        ],
        isFlag: [
          { required: true, message: "是否有效不能为空", trigger: "change" }
        ],
      },
      columns: [
            { key: 0, label: `主键ID`, visible: false },
            { key: 1, label: `看板编码`, visible: true },
            { key: 2, label: `看板名称`, visible: true },
            { key: 3, label: `产品线编码`, visible: true },
            { key: 4, label: `工位/工序编码`, visible: true },
            { key: 5, label: `看板展示字段配置`, visible: true },
            { key: 6, label: `刷新间隔`, visible: true },
            { key: 7, label: `是否有效`, visible: true },
            { key: 8, label: `备注`, visible: true },
            { key: 9, label: `创建人`, visible: true },
            { key: 10, label: `创建时间`, visible: true },
            { key: 11, label: `更新人`, visible: true },
            { key: 12, label: `更新时间`, visible: true },
        ]
      ,
      // 可用字段列表（与大屏展示字段映射一致）
      availableFields: [
        { field: "index", label: "序号（前端行号）" },
        { field: "eventId", label: "事件ID" },
        { field: "callCode", label: "呼叫单号" },
        { field: "callTypeCode", label: "呼叫类型" },
        { field: "sourceType", label: "触发源类型（工位/设备/报警/手动）" },
        { field: "sourceRefId", label: "触发源编码" },
        { field: "productLineCode", label: "产线编码" },
        { field: "stationCode", label: "工位/工序编码" },
        { field: "teamCode", label: "班组编码" },
        { field: "orderCode", label: "工单号" },
        { field: "materialCode", label: "物料编码" },
        { field: "deviceCode", label: "设备编码" },
        { field: "priority", label: "优先级" },
        { field: "eventStatus", label: "状态（待处理/处理中/已解决/已取消）" },
        { field: "description", label: "呼叫描述" },
        { field: "ackBy", label: "确认人" },
        { field: "ackTime", label: "确认时间" },
        { field: "responseStartTime", label: "开始处理时间" },
        { field: "responseEndTime", label: "完成时间" },
        { field: "resolution", label: "解决措施" },
        { field: "cancelReason", label: "取消原因" },
        { field: "escalateLevel", label: "升级级别" },
        { field: "escalateTime", label: "升级时间" },
        { field: "ackDeadline", label: "确认截止时间" },
        { field: "resolveDeadline", label: "解决截止时间" },
        { field: "createTime", label: "创建时间" },
        { field: "updateTime", label: "更新时间" }
      ]
    };
  },
  created() {
    this.getList();
    // 初始化产线、工位下拉选项
    this.loadProductLines();
    this.loadProcessStations();
  },
  methods: {
    /** 查询安灯看板配置列表 */
    getList() {
      this.loading = true;
      listAndonBoardConfig(this.queryParams).then(response => {
        this.andonBoardConfigList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        boardId: null,
        boardCode: null,
        boardName: null,
        productLineCode: null,
        stationCode: null,
        displayFields: null,
        refreshIntervalSec: null,
        isFlag: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.boardId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.isFlag = '1'; // 默认有效
      this.open = true;
      this.title = "添加安灯看板配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const boardId = row.boardId || this.ids
      getAndonBoardConfig(boardId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改安灯看板配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.boardId != null) {
            updateAndonBoardConfig(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAndonBoardConfig(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const boardIds = row.boardId || this.ids;
      this.$modal.confirm('是否确认删除安灯看板配置编号为"' + boardIds + '"的数据项？').then(function() {
        return delAndonBoardConfig(boardIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('production/andonBoardConfig/export', {
        ...this.queryParams
      }, `andonBoardConfig_${new Date().getTime()}.xlsx`)
    },
    /** 加载产线下拉选项 */
    loadProductLines() {
      findProductLineList({}).then(res => {
        this.productLineList = res.data || res.rows || [];
      }).catch(() => {
        this.productLineList = [];
      });
    },
    /** 加载工位/工序下拉选项 */
    loadProcessStations() {
      listProcessStation({}).then(res => {
        this.processStationList = res.data || res.rows || [];
      }).catch(() => {
        this.processStationList = [];
      });
    }
  }
};
</script>
