<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 简化搜索：隐藏事件ID输入，建议使用列表直接选择行 -->
      <!--
      <el-form-item label="事件ID" prop="eventId">
        <el-input
          v-model="queryParams.eventId"
          placeholder="请输入事件ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      -->
<!--      <el-form-item label="被分配用户" prop="assigneeUserId">
        <el-select v-model="queryParams.assigneeUserId" placeholder="请选择用户" clearable>
          <el-option
            v-for="u in userOptions"
            :key="u.userId"
            :label="u.nickName || u.userName || String(u.userId)"
            :value="u.userId"
          />
        </el-select>
      </el-form-item>-->
      <!-- 简化搜索：隐藏姓名/角色/班组等次要查询条件 -->
      <!--
      <el-form-item label="被分配用户姓名" prop="assigneeUserName">
        <el-input
          v-model="queryParams.assigneeUserName"
          placeholder="请输入被分配用户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      -->
      <!--
      <el-form-item label="被分配角色编码" prop="assigneeRoleKey">
        <el-input
          v-model="queryParams.assigneeRoleKey"
          placeholder="请输入被分配角色编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      -->
      <!--
      <el-form-item label="被分配班组编码" prop="assigneeTeamCode">
        <el-input
          v-model="queryParams.assigneeTeamCode"
          placeholder="请输入被分配班组编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      -->
<!--      <el-form-item label="分配时间" prop="assignedTime">
        <el-date-picker clearable
          v-model="queryParams.assignedTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择分配时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="接单时间" prop="acceptTime">
        <el-date-picker clearable
          v-model="queryParams.acceptTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择接单时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="完成时间" prop="finishTime">
        <el-date-picker clearable
          v-model="queryParams.finishTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择完成时间">
        </el-date-picker>
      </el-form-item>-->
      <el-form-item label="只看我的" prop="onlyMine">
        <el-switch v-model="onlyMine" @change="handleOnlyMineChange" />
      </el-form-item>
      <el-form-item label="派工状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择派工状态" clearable>
          <el-option
            v-for="dict in dict.type.andon_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="是否有效" prop="isFlag">
        <el-input
          v-model="queryParams.isFlag"
          placeholder="请输入是否有效"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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:andonEventAssignment: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:andonEventAssignment: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:andonEventAssignment: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:andonEventAssignment:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="andonEventAssignmentList" @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
      <el-table-column type="selection" width="55" align="center" />
      <!-- 隐藏主键列，减少干扰 -->
      <el-table-column label="主键ID" align="center" prop="assignmentId" v-if="columns[0].visible"/>
      <el-table-column label="事件ID" align="center" prop="eventId" v-if="columns[1].visible"/>
      <el-table-column label="被分配用户ID" align="center" prop="assigneeUserId" v-if="columns[2].visible"/>
      <el-table-column label="被分配用户姓名" align="center" prop="assigneeUserName" v-if="columns[3].visible"/>
      <el-table-column label="被分配角色编码" align="center" prop="assigneeRoleKey" v-if="columns[4].visible"/>
      <el-table-column label="被分配班组编码" align="center" prop="assigneeTeamCode" v-if="columns[5].visible"/>
      <el-table-column label="分配时间" align="center" prop="assignedTime" width="180" v-if="columns[6].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.assignedTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="接单时间" align="center" prop="acceptTime" width="180" v-if="columns[7].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.acceptTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" align="center" prop="finishTime" width="180" v-if="columns[8].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.finishTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="派工状态" align="center" prop="status" v-if="columns[9].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.andon_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="是否有效" align="center" prop="isFlag" v-if="columns[10].visible"/>
      <el-table-column label="备注" align="center" prop="remark" v-if="columns[11].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:andonEventAssignment:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['production:andonEventAssignment: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">
        <!-- 事件ID改为下拉选择（不分页） -->
        <el-form-item label="事件ID" prop="eventId">
          <el-select v-model="form.eventId" placeholder="请选择事件">
            <el-option
              v-for="evt in eventOptions"
              :key="evt.eventId"
              :label="(evt.callCode || ('事件#' + evt.eventId)) + (evt.stationCode ? (' - ' + evt.stationCode) : '')"
              :value="evt.eventId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="被分配用户" prop="assigneeUserId">
          <el-select v-model="form.assigneeUserId" placeholder="请选择用户" @change="onAssigneeChange">
            <el-option
              v-for="u in userOptions"
              :key="u.userId"
              :label="u.nickName || u.userName || String(u.userId)"
              :value="u.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="被分配用户姓名" prop="assigneeUserName">
          <el-input v-model="form.assigneeUserName" placeholder="请输入被分配用户姓名" />
        </el-form-item>
        <el-form-item label="被分配角色编码" prop="assigneeRoleKey">
          <el-input v-model="form.assigneeRoleKey" placeholder="请输入被分配角色编码" />
        </el-form-item>
        <el-form-item label="被分配班组编码" prop="assigneeTeamCode">
          <el-input v-model="form.assigneeTeamCode" placeholder="请输入被分配班组编码" />
        </el-form-item>
        <el-form-item label="分配时间" prop="assignedTime">
          <el-date-picker clearable
            v-model="form.assignedTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择分配时间">
          </el-date-picker>
        </el-form-item>
        <!-- 接单时间改为只读展示，后端自动维护 -->
        <el-form-item label="接单时间">
          <span>{{ form.acceptTime ? parseTime(form.acceptTime, '{y}-{m}-{d} {h}:{i}:{s}') : '后端自动维护' }}</span>
        </el-form-item>
        <!-- 完成时间改为只读展示，后端自动维护 -->
        <el-form-item label="完成时间">
          <span>{{ form.finishTime ? parseTime(form.finishTime, '{y}-{m}-{d} {h}:{i}:{s}') : '后端自动维护' }}</span>
        </el-form-item>
        <el-form-item label="派工状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择派工状态">
            <el-option
              v-for="dict in dict.type.andon_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否有效" prop="isFlag">
          <el-input v-model="form.isFlag" placeholder="请输入是否有效" />
        </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>
  </div>
</template>

<script>
import { listAndonEventAssignment, getAndonEventAssignment, delAndonEventAssignment, addAndonEventAssignment, updateAndonEventAssignment } from "@/api/production/andonEventAssignment";
import { getAndonEventList } from "@/api/production/andonEvent";
import { selectUserList } from "@/api/system/user";

export default {
  name: "AndonEventAssignment",
  dicts: ['andon_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 安灯派工记录（派工即通知/待办）表格数据
      andonEventAssignmentList: [],
      // 事件下拉选项（不分页）
      eventOptions: [],
      // 用户下拉选项（不分页）
      userOptions: [],
      // 只看我的派工记录（默认开启）
      onlyMine: true,
      // 当前登录用户ID
      currentUserId: null,
      // 默认通知用户（当前仅一个用户时）
      defaultUserId: null,
      defaultUserName: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        eventId: null,
        assigneeUserId: null,
        assigneeUserName: null,
        assigneeRoleKey: null,
        assigneeTeamCode: null,
        assignedTime: null,
        acceptTime: null,
        finishTime: null,
        status: null,
        isFlag: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        eventId: [
          { required: true, message: "事件ID不能为空", trigger: "blur" }
        ],
        isFlag: [
          { required: true, message: "是否有效不能为空", trigger: "blur" }
        ],
      },
      columns: [
            { key: 0, label: `主键ID`, visible: false },
            { key: 1, label: `事件ID`, visible: false },
            { key: 2, label: `被分配用户ID`, visible: false },
            { 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: false },
            { key: 13, label: `创建时间`, visible: false },
            { key: 14, label: `更新人`, visible: false },
            { key: 15, label: `更新时间`, visible: false },
        ]
    };
  },
  created() {
    // 获取当前登录用户ID
    this.currentUserId = this.$store.getters.userId;
    // 默认只查询当前用户的派工记录
    if (this.onlyMine && this.currentUserId) {
      this.queryParams.assigneeUserId = this.currentUserId;
    }
    this.getList();
    // 初始化事件下拉选项（不分页）
    getAndonEventList({ isFlag: '1' }).then(res => {
      this.eventOptions = res.data || res.rows || [];
    });
    // 初始化用户下拉选项（不分页）
    selectUserList({}).then(res => {
      this.userOptions = res.rows || res.data || [];
      if (this.userOptions && this.userOptions.length === 1) {
        const u = this.userOptions[0];
        this.defaultUserId = u.userId;
        this.defaultUserName = u.nickName || u.userName || String(u.userId);
      }
    });
  },
  methods: {
    /** 查询安灯派工记录（派工即通知/待办）列表 */
    getList() {
      this.loading = true;
      listAndonEventAssignment(this.queryParams).then(response => {
        this.andonEventAssignmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 切换“只看我的”开关 */
    handleOnlyMineChange(val) {
      if (val && this.currentUserId) {
        this.queryParams.assigneeUserId = this.currentUserId;
      } else {
        this.queryParams.assigneeUserId = null;
      }
      this.handleQuery();
    },
    /** 表格行样式：未完成的记录高亮显示 */
    tableRowClassName({ row }) {
      // status: 0=待接单, 1=处理中, 2=已完成, 3=已取消
      if (row.status === '0' || row.status === 0) {
        return 'warning-row';  // 待接单 - 高亮警告
      } else if (row.status === '1' || row.status === 1) {
        return 'info-row';     // 处理中
      }
      return '';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        assignmentId: null,
        eventId: null,
        assigneeUserId: this.defaultUserId,
        assigneeUserName: this.defaultUserName,
        assigneeRoleKey: null,
        assigneeTeamCode: null,
        assignedTime: null,
        acceptTime: null,
        finishTime: null,
        status: null,
        isFlag: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    // 选择被分配用户后，自动带出姓名
    onAssigneeChange(val) {
      const u = this.userOptions.find(item => String(item.userId) === String(val));
      this.form.assigneeUserName = u ? (u.nickName || u.userName || String(u.userId)) : null;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.assignmentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加安灯派工记录（派工即通知/待办）";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const assignmentId = row.assignmentId || this.ids
      getAndonEventAssignment(assignmentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改安灯派工记录（派工即通知/待办）";
      });
    },
    /** 提交按钮（不提交接单/完成时间，后端自动维护） */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const payload = { ...this.form };
          delete payload.acceptTime;
          delete payload.finishTime;
          if (payload.assignmentId != null) {
            updateAndonEventAssignment(payload).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAndonEventAssignment(payload).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const assignmentIds = row.assignmentId || this.ids;
      this.$modal.confirm('是否确认删除安灯派工记录（派工即通知/待办）编号为"' + assignmentIds + '"的数据项？').then(function() {
        return delAndonEventAssignment(assignmentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('production/andonEventAssignment/export', {
        ...this.queryParams
      }, `andonEventAssignment_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
/* 待接单记录高亮 - 红色背景 */
::v-deep .el-table .warning-row {
  background-color: #fef0f0 !important;
}
::v-deep .el-table .warning-row:hover > td {
  background-color: #fde2e2 !important;
}
/* 处理中记录 - 蓝色背景 */
::v-deep .el-table .info-row {
  background-color: #f0f9eb !important;
}
::v-deep .el-table .info-row:hover > td {
  background-color: #e1f3d8 !important;
}
</style>
