<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="personType">
        <el-select
          v-model="queryParams.personType"
          placeholder="请选择人员类型"
          clearable
        >
          <el-option
            v-for="item in personTypeOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="人员姓名" prop="realName">
        <el-input
          v-model="queryParams.realName"
          placeholder="请输入人员姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="定位卡号" prop="cardId">
        <el-input
          v-model="queryParams.cardId"
          placeholder="请输入定位卡号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search1"
          size="mini"
          @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh1" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="infoList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="人员类型" align="center" prop="personTypeName" />
      <el-table-column label="姓名" align="center" prop="realName" />
      <el-table-column label="联系方式" align="center" prop="phone" />
      <el-table-column label="定位卡号" align="center" prop="cardId" />
      <el-table-column label="SOS报警时间" align="center" prop="alarmTime" />
      <el-table-column label="报警地点经纬度" align="center">
        <template slot-scope="scope">
          <div>{{ scope.row.longitude }}</div>
          <div>{{ scope.row.latitude }}</div>
        </template>
      </el-table-column>
      <el-table-column label="报警状态" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="!scope.row.alarmStatus"
            type="primary"
            size="mini"
            icon="el-icon-close-notification"
            @click="handleDispose(scope.row)"
          >
            处置
          </el-button>
          <span v-if="scope.row.alarmStatus">已处置</span>
        </template>
      </el-table-column>
      <el-table-column label="解除原因" align="center" prop="relieveReason">
        <template slot-scope="scope">
          <span>{{
            scope.row.otherReason
              ? scope.row.otherReason
              : scope.row.relieveReason
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="解除人" align="center" prop="relieveBy" />
      <el-table-column label="解除时间" align="center" prop="relieveTime" />
    </el-table>

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

    <!-- 处置弹窗 -->
    <el-dialog
      title="解除报警"
      :visible.sync="disposeDialogVisible"
      width="500px"
    >
      <el-form
        :model="disposeForm"
        ref="disposeFormRef"
        label-width="150px"
        :rules="rules"
      >
        <el-form-item label="选择解除报警原因" prop="reason">
          <div
            v-for="item in reasonOptions"
            :key="item.dictValue"
            class="radio-item"
          >
            <el-radio
              v-model="disposeForm.reason"
              :label="item.dictValue"
              @change="handleReasonChange(item.dictValue)"
            >
              {{ item.dictLabel }}
            </el-radio>
          </div>
        </el-form-item>
        <!-- 当选择其他时显示文本框 -->
        <el-form-item
          v-if="showOtherReason"
          label="其他原因"
          prop="otherReason"
          required
        >
          <el-input
            v-model="disposeForm.otherReason"
            type="textarea"
            :rows="4"
            placeholder="请输入其他解除原因"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="disposeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDispose">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, update } from "@/api/jinrun/alarm";
import { getDict } from "@/api/jinrun/common";

export default {
  name: "Info",
  data() {
    return {
      // 处置弹窗是否显示
      disposeDialogVisible: false,
      // 是否显示其他原因文本框
      showOtherReason: false,
      // 处置表单数据
      disposeForm: {
        realName: "",
        personId: "",
        reason: "",
        otherReason: "",
      },
      // 人员类型下拉列表数据
      personTypeOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 人员信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        personType: "",
        cardId: null,
        realName: null,
      },
      // 表单参数
      form: {
        personType: "",
      },
      // 校验规则
      rules: {
        reason: [
          {
            required: true,
            message: "请选择解除报警原因",
            trigger: "change",
          },
        ],
        otherReason: [
          {
            required: true,
            message: "请输入其他解除原因",
            trigger: "blur",
          },
          {
            min: 1,
            max: 200,
            message: "其他原因长度应在 1 到 200 个字符之间",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getReasonOptions();
    this.getPersonTypeOptions();
  },

  methods: {
    /** 获取人员类型下拉列表数据 */
    getPersonTypeOptions() {
      // 调用数据字典接口
      getDict({ dictType: "person_type" })
        .then((response) => {
          this.personTypeOptions = response.records || [];
        })
        .catch((error) => {
          this.$modal.msgError("获取人员类型数据失败");
          console.error("获取人员类型数据失败:", error);
        });
    },
    /** 提交解除报警 */
    submitDispose() {
      // 表单验证
      this.$refs.disposeFormRef.validate((valid) => {
        if (valid) {
          // 构建提交参数
          const submitData = {
            // personId: this.disposeForm.personId,
            alarmStatus: 1, // 设置为已处置状态
            id: this.disposeForm.id,
            relieveReason: this.disposeForm.reason,
          };
          if (this.disposeForm.reason === 0) {
            submitData.otherReasons = this.disposeForm.otherReason;
          }

          // 调用后端接口
          update(submitData)
            .then((response) => {
              if (response.code === 200) {
                // 成功处理
                this.$modal.msgSuccess("解除报警成功");
                // 关闭弹窗
                this.disposeDialogVisible = false;
                // 刷新数据列表
                this.getList();
              } else {
                // 处理失败
                this.$modal.msgError(response.msg || "解除报警失败");
              }
            })
            .catch((error) => {
              // 处理网络错误等异常情况
              console.error("解除报警失败:", error);
              this.$modal.msgError("服务器错误，请稍后重试");
            });
        } else {
          // 表单验证失败
          return false;
        }
      });
    },
    /** 获取解除原因选项 */
    getReasonOptions() {
      // 调用数据字典接口获取解除原因
      getDict({ dictType: "relieve_reason" })
        .then((response) => {
          this.reasonOptions = response.records || [];
        })
        .catch((error) => {
          this.$modal.msgError("获取解除原因数据失败");
          console.error("获取解除原因数据失败:", error);
        });
    },
    /** 查询人员信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then((response) => {
        this.infoList = response.records;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 处理报警处置 */
    handleDispose(row) {
      // 重置表单
      this.disposeForm = {
        id: row.id,
        reason: "",
        otherReason: "",
      };
      this.showOtherReason = false;
      // 显示弹窗
      this.disposeDialogVisible = true;
    },

    /** 处理原因选择变化 */
    handleReasonChange(reason) {
      // 当选择其他时显示文本框
      this.showOtherReason = reason == 0;
      // 如果不是其他，清空其他原因
      if (!this.showOtherReason) {
        this.disposeForm.otherReason = "";
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        createBy: null,
        createTime: null,
        updateTime: null,
        remark: null,
        personId: null,
        personType: null,
        personTypeName: null,
        staffType: null,
        staffTypeName: null,
        positionIconType: null,
        positionIconTypeName: null,
        realName: null,
        phone: null,
        sex: null,
        birth: null,
        email: null,
        nativePlace: null,
        nation: null,
        maritalStatus: null,
        politicsStatus: null,
        healthStatus: null,
        idType: null,
        idNumber: null,
        personIc: null,
        personCode: null,
        personSource: null,
        company: null,
        companyName: null,
        administratorName: null,
        administratorPhone: null,
        jobNumber: null,
        jobStatus: null,
        hireDate: null,
        hireDateAlias: null,
        dimissionDate: null,
        officePhone: null,
        duty: null,
        professionalTitle: null,
        professionalTitleNumber: null,
        seniority: null,
        experience: null,
        yearPlusExperience: null,
        highestEducation: null,
        highestDegree: null,
        profession: null,
        school: null,
        diplomaNumber: null,
        cengNumber: null,
        accessory: null,
        accessoryList: null,
        contractorId: null,
        contractorName: null,
        receiveLeader: null,
        receivePhone: null,
        gateThrough: null,
        leaveTime: null,
        visitorStatus: null,
        visitTime: null,
        process: null,
        lastUpdateDate: null,
        lastCreateDate: null,
        updateFail: null,
        onlineStatus: null,
        inOutStatus: null,
        cardType: null,
        cardTypeName: null,
        cardId: null,
        icCardId: null,
        cardPower: null,
        personPhoto: null,
        photoSign: null,
        deptName: null,
        reservationEntryStartTime: null,
        reservationEntryEndTime: null,
        reservationVisitingTime: null,
        curUserName: null,
        visitorId: 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.personId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
  },
};
</script>

<style scoped lang="scss">
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50px;
  height: 50px;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 20px;
}
</style>