<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="ruleName">
        <el-input
          v-model="queryParams.ruleName"
          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="teamCode">
        <el-select v-model="queryParams.teamCode" placeholder="请选择班组" clearable>
          <el-option
            v-for="item in teamMembersList"
            :key="item.teamCode"
            :label="item.teamName"
            :value="item.teamCode"
          />
        </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:andonRule: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:andonRule: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:andonRule:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="andonRuleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="规则名称" align="center" prop="ruleName" v-if="columns[1].visible"/>
      <el-table-column label="呼叫类型编码" align="center" prop="callTypeCode" 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="teamCode" v-if="columns[5].visible"/>
      <el-table-column label="限定触发源类型" align="center" prop="sourceType" v-if="columns[6].visible"/>
      <el-table-column label="确认时限" align="center" prop="ackTimeoutMin" v-if="columns[7].visible"/>
      <el-table-column label="解决时限" align="center" prop="resolveTimeoutMin" v-if="columns[8].visible"/>
      <el-table-column label="默认优先级" align="center" prop="priorityDefault" v-if="columns[9].visible"/>
      <el-table-column label="通知角色" align="center" prop="notifyRoles" v-if="columns[10].visible"/>
      <el-table-column label="通知用户" align="center" prop="notifyUsers" v-if="columns[11].visible">
        <template slot-scope="scope">
          <span>{{ mapUserNames(scope.row.notifyUsers) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="升级链" align="center" prop="escalateLevels" v-if="columns[12].visible"/>
      <el-table-column label="生效开始时间" align="center" prop="effectiveBeginTime" width="180" v-if="columns[13].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.effectiveBeginTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生效结束时间" align="center" prop="effectiveEndTime" width="180" v-if="columns[14].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.effectiveEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否有效" align="center" prop="isFlag" v-if="columns[15].visible"/>
      <el-table-column label="备注" align="center" prop="remark" v-if="columns[16].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:andonRule:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['production:andonRule: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"
    />

    <!-- 添加或修改安灯规则配置对话框（简化版：PDA绑定工位触发安灯） -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-alert
          title="手持PDA绑定工位后，点击安灯按钮将自动匹配此规则并派工给通知用户"
          type="info"
          :closable="false"
          style="margin-bottom: 15px;"
        />
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="form.ruleName" placeholder="请输入规则名称，如：装配工位-设备故障" />
        </el-form-item>
        <el-form-item label="绑定工位" prop="stationCode">
          <el-select v-model="form.stationCode" placeholder="请选择绑定的工位（必填）" filterable style="width: 100%">
            <el-option
              v-for="item in processStationList"
              :key="item.productLineCode"
              :label="item.productLineCode + ' - ' + item.productLineName"
              :value="item.productLineCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="呼叫类型" prop="callTypeCode">
          <el-select v-model="form.callTypeCode" placeholder="请选择呼叫类型">
            <el-option
              v-for="dict in dict.type.andon_call_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="通知用户" prop="notifyUsers">
          <el-select v-model="formNotifyUsersArr" multiple filterable placeholder="请选择派工通知的用户（必填）">
            <el-option
              v-for="u in userOptions"
              :key="u.userId"
              :label="u.nickName || u.userName || String(u.userId)"
              :value="String(u.userId)"
            />
          </el-select>
        </el-form-item>
        <el-divider content-position="left">时限设置（可选）</el-divider>
        <el-form-item label="确认时限" prop="ackTimeoutMin">
          <el-input-number v-model="form.ackTimeoutMin" :min="0" placeholder="分钟" style="width: 100%" />
          <span style="color: #909399; font-size: 12px;">接单确认的时限（分钟）</span>
        </el-form-item>
        <el-form-item label="解决时限" prop="resolveTimeoutMin">
          <el-input-number v-model="form.resolveTimeoutMin" :min="0" placeholder="分钟" style="width: 100%" />
          <span style="color: #909399; font-size: 12px;">问题解决的时限（分钟）</span>
        </el-form-item>
        <el-form-item label="默认优先级" prop="priorityDefault">
          <el-input-number v-model="form.priorityDefault" :min="1" :max="5" style="width: 100%" />
          <span style="color: #909399; font-size: 12px;">1最高，5最低</span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" 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>
  </div>
</template>

<script>
import { listAndonRule, getAndonRule, delAndonRule, addAndonRule, updateAndonRule } from "@/api/production/andonRule";
import { selectUserList } from "@/api/system/user";
import { findProductLineList } from "@/api/base/productLine";
import { listProcessStation } from "@/api/base/processStation";
import { getTeamMemberList } from "@/api/base/teamMembers";
import { getDeviceLedgerList } from "@/api/base/deviceLedger";

export default {
  name: "AndonRule",
  dicts: ['andon_call_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 安灯规则配置表格数据
      andonRuleList: [],
      // 用户下拉选项（不分页）
      userOptions: [],
      // 通知用户多选（用于表单）
      formNotifyUsersArr: [],
      // 默认通知用户（当前仅一个用户时）
      defaultUserId: null,
      // 产线下拉选项
      productLineList: [],
      // 工位/工序下拉选项
      processStationList: [],
      // 班组下拉选项
      teamMembersList: [],
      // 设备下拉选项
      deviceLedgerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleName: null,
        callTypeCode: null,
        productLineCode: null,
        stationCode: null,
        teamCode: null,
        sourceType: null,
        ackTimeoutMin: null,
        resolveTimeoutMin: null,
        priorityDefault: null,
        notifyRoles: null,
        notifyUsers: null,
        escalateLevels: null,
        effectiveBeginTime: null,
        effectiveEndTime: null,
        isFlag: null,
      },
      // 表单参数
      form: {},
      // 表单校验（简化版：工位和通知用户必填）
      rules: {
        ruleName: [
          { required: true, message: "规则名称不能为空", trigger: "blur" }
        ],
        stationCode: [
          { required: true, message: "请选择绑定的工位", trigger: "change" }
        ],
        callTypeCode: [
          { 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: false },
            { key: 4, label: `适用工位/工序编码`, visible: true },
            { key: 5, label: `适用班组编码`, visible: false },
            { key: 6, label: `限定触发源类型`, visible: false },
            { key: 7, label: `确认时限`, visible: true },
            { key: 8, label: `解决时限`, visible: true },
            { key: 9, label: `默认优先级`, visible: true },
            { key: 10, label: `通知角色`, visible: false },
            { key: 11, label: `通知用户`, visible: true },
            { key: 12, label: `升级链`, visible: false },
            { key: 13, label: `生效开始时间`, visible: false },
            { key: 14, label: `生效结束时间`, visible: false },
            { key: 15, label: `是否有效`, visible: false },
            { key: 16, label: `备注`, visible: true },
            { key: 17, label: `创建人`, visible: true },
            { key: 18, label: `创建时间`, visible: true },
            { key: 19, label: `更新人`, visible: false },
            { key: 20, label: `更新时间`, visible: false },
        ]
    };
  },
  created() {
    this.getList();
    // 初始化用户下拉选项（不分页）
    selectUserList({}).then(res => {
      this.userOptions = res.rows || res.data || [];
      if (this.userOptions && this.userOptions.length === 1) {
        this.defaultUserId = this.userOptions[0].userId;
      }
    });
    // 初始化产线、工位、班组、设备下拉选项
    this.loadProductLines();
    this.loadProcessStations();
    this.loadTeamMembers();
    this.loadDeviceLedgers();
  },
  methods: {
    /** 查询安灯规则配置列表 */
    getList() {
      this.loading = true;
      listAndonRule(this.queryParams).then(response => {
        this.andonRuleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ruleId: null,
        ruleName: null,
        callTypeCode: null,
        productLineCode: null,
        stationCode: null,
        teamCode: null,
        sourceType: null,
        ackTimeoutMin: null,
        resolveTimeoutMin: null,
        priorityDefault: null,
        notifyRoles: null,
        notifyUsers: null,
        escalateLevels: null,
        effectiveBeginTime: null,
        effectiveEndTime: 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.ruleId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 设置默认值
      this.form.isFlag = '1'; // 默认有效
      this.form.priorityDefault = 3; // 默认优先级3
      this.form.ackTimeoutMin = 5; // 默认确认5分钟
      this.form.resolveTimeoutMin = 30; // 默认解决30分钟
      this.open = true;
      this.title = "添加安灯规则配置";
      // 单用户场景下默认通知该用户
      if (this.defaultUserId) {
        this.formNotifyUsersArr = [String(this.defaultUserId)];
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ruleId = row.ruleId || this.ids
      getAndonRule(ruleId).then(response => {
        this.form = response.data;
        // 将后端字符串转为多选数组
        this.formNotifyUsersArr = (this.form.notifyUsers ? String(this.form.notifyUsers).split(',').filter(Boolean) : []);
        this.open = true;
        this.title = "修改安灯规则配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const payload = { ...this.form, notifyUsers: (this.formNotifyUsersArr || []).join(',') };
          // 确保必填字段有默认值
          if (!payload.isFlag) payload.isFlag = '1';
          if (!payload.priorityDefault) payload.priorityDefault = 3;
          if (!payload.ackTimeoutMin) payload.ackTimeoutMin = 5;
          if (!payload.resolveTimeoutMin) payload.resolveTimeoutMin = 30;
          if (payload.ruleId != null) {
            updateAndonRule(payload).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAndonRule(payload).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 映射用户ID字符串为姓名展示
    mapUserNames(userIdsStr) {
      if (!userIdsStr) return '';
      const ids = String(userIdsStr).split(',').filter(Boolean);
      const nameMap = new Map(this.userOptions.map(u => [String(u.userId), (u.nickName || u.userName || String(u.userId))]));
      return ids.map(id => nameMap.get(String(id)) || id).join(', ');
    },
    /** 删除按钮操作 */
    handleDelete(row) {listProcessStation 
      const ruleIds = row.ruleId || this.ids;
      this.$modal.confirm('是否确认删除安灯规则配置编号为"' + ruleIds + '"的数据项？').then(function() {
        return delAndonRule(ruleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('production/andonRule/export', {
        ...this.queryParams
      }, `andonRule_${new Date().getTime()}.xlsx`)
    },
    /** 加载产线下拉选项 */
    loadProductLines() {
      findProductLineList({}).then(res => {
        this.productLineList = res.data || res.rows || [];
      }).catch(() => {
        this.productLineList = [];
      });
    },
    /** 加载工位/工序下拉选项 */
    loadProcessStations() {
      findProductLineList({ productLineType: 2 }).then(res => {
        this.processStationList = res.data || res.rows || [];
      }).catch(() => {
        this.processStationList = [];
      });
    },
    /** 加载班组下拉选项 */
    loadTeamMembers() {
      getTeamMemberList({}).then(res => {
        this.teamMembersList = res.data || res.rows || [];
      }).catch(() => {
        this.teamMembersList = [];
      });
    },
    /** 加载设备下拉选项 */
    loadDeviceLedgers() {
      getDeviceLedgerList({}).then(res => {
        this.deviceLedgerList = res.data || res.rows || [];
      }).catch(() => {
        this.deviceLedgerList = [];
      });
    }
  }
};
</script>
