<template>
  <ele-modal
    title="隐患台账"
    :visible.sync="visible"
    width="70%"
    :close-on-click-modal="false"
    :maxable="true"
    custom-class="hazard-dialog"
    append-to-body
  >
    <div class="hazard-management">
      <el-card shadow="never" class="hazard-card">
        <!-- 列表视图 -->
        <div class="list-view">
          <ele-pro-table
            ref="table"
            row-key="id"
            :columns="columns"
            :datasource="datasource"
            :deedPage="false"
            height="350px"
          >
            <template v-slot:toolbar>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-plus"
                @click="handleAdd"
                >新增</el-button
              >
            </template>

            <template v-slot:level="{ row }">
              <el-tag
                :type="getLevelType(row.level)"
                size="small"
                effect="dark"
              >
                {{ getLevelLabel(row.level) }}
              </el-tag>
            </template>
            <template v-slot:title="{ row }">
              <el-link
                type="primary"
                :underline="false"
                @click="handleView(row)"
              >
                {{ row.title }}
              </el-link>
            </template>
            <template v-slot:status="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>

            <template v-slot:category="{ row }">
              {{ getCategoryLabel(row.category) }}
            </template>
          </ele-pro-table>
        </div>

        <!-- 新增/编辑/查看弹窗 -->
        <hazard-dialog ref="hazardDialogRef" @reload="handleReload" />

        <!-- 设备列表弹窗 -->
        <ele-modal
          title="选择设备"
          :visible.sync="deviceVisible"
          width="60%"
          :close-on-click-modal="false"
          append-to-body
          :maxable="true"
        >
          <ele-pro-table
            ref="deviceTable"
            :pageSizes="[10, 20, 50]"
            :columns="deviceColumns"
            :datasource="deviceDatasource"
            highlight-current-row
            @current-change="handleDeviceChange"
          />
          <div slot="footer">
            <el-button @click="deviceVisible = false">取消</el-button>
            <el-button type="primary" @click="handleDeviceConfirm"
              >确定</el-button
            >
          </div>
        </ele-modal>
      </el-card>
    </div>
  </ele-modal>
</template>

<script>
  import HazardDialog from './hazardDialog.vue';
  import dictMixins from '@/mixins/dictMixins';
  import { getList } from '@/api/hazardManagement/index.js';
  import { getWordOrderDetail } from '@/api/maintenance/patrol_maintenance';
  import { getAssetInfo } from '@/api/ledgerAssets';
  import { getWorkOrderDetail } from '@/api/maintenance/repair';
  export default {
    components: {
      HazardDialog
    },
    mixins: [dictMixins],
    props: { sourceType: '' },
    data() {
      return {
        exportParams: {},
        selectedDevice: null,
        row: null,
        visible: false,
        deviceVisible: false,
        deviceColumns: [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center'
          },
          {
            prop: 'substance.codeNumber',
            label: '设备编号',
            align: 'center',
            minWidth: 140,
            formatter: (row) => row.substance?.codeNumber || ''
          },
          {
            prop: 'substance.code',
            label: '设备编码',
            align: 'center',
            minWidth: 140,
            formatter: (row) => row.substance?.code || ''
          },
          {
            prop: 'substance.name',
            label: '设备名称',
            align: 'center',
            minWidth: 140,
            formatter: (row) => row.substance?.name || ''
          },
          {
            prop: 'substance.positionNames',
            label: '设备位置',
            align: 'center',
            minWidth: 180,
            formatter: (row) => row.substance?.positionNames || ''
          }
        ],
        // 隐患状态选项
        statusOptions: [
          // { value: 0, label: '待确认' },
          { value: 1, label: '待整改' },
          { value: 2, label: '整改中' },
          { value: 3, label: '待验收' },
          { value: 4, label: '已验收' },
          { value: 'CLOSED', label: '已关闭' }
        ],
        levelOptions: [
          { value: 4, label: '轻微' },
          { value: 3, label: '一般' },
          { value: 2, label: '较大' },
          { value: 1, label: '重大' }
        ],
        chkTypeList: [
          { value: 1, label: '巡点检' },
          { value: 2, label: '设备保养' },
          { value: 3, label: '设备维修' },
          { value: 5, label: '量具送检' }
        ],
        categoryOptions: [
          { value: 1, label: '设备设施' },
          { value: 2, label: '作业环境' },
          { value: 3, label: '人员行为' },
          { value: 4, label: '管理缺陷' },
          { value: 5, label: '其他' }
        ],

        // 表格列配置
        columns: [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center'
          },
          {
            prop: 'code',
            label: '隐患编号',
            align: 'center',
            minWidth: 140,
            showOverflowTooltip: true
          },
          {
            prop: 'title',
            slot: 'title',
            label: '隐患名称',
            align: 'center',
            minWidth: 180,
            showOverflowTooltip: true
          },
          {
            prop: 'level',
            label: '隐患等级',
            align: 'center',
            minWidth: 100,
            slot: 'level'
          },
          {
            prop: 'status',
            label: '隐患状态',
            align: 'center',
            minWidth: 100,
            slot: 'status'
          },
          {
            prop: 'category',
            label: '隐患类别',
            align: 'center',
            minWidth: 100,
            slot: 'category'
          },
          {
            prop: 'deviceName',
            label: '设备名称',
            align: 'center',
            minWidth: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'deviceLocation',
            label: '设备位置',
            align: 'center',
            minWidth: 180,
            showOverflowTooltip: true
          },
          {
            prop: 'areaName',
            label: '区域名称',
            align: 'center',
            minWidth: 180,
            showOverflowTooltip: true
          },
          {
            prop: 'foundTime',
            label: '发现时间',
            align: 'center',
            minWidth: 160,
            showOverflowTooltip: true
          },
          {
            prop: 'foundUserName',
            label: '发现人',
            align: 'center',
            minWidth: 100,
            showOverflowTooltip: true
          },
          {
            prop: 'fixUserName',
            label: '整改责任人',
            align: 'center',
            minWidth: 100,
            showOverflowTooltip: true
          },
          {
            prop: 'fixDeadline',
            label: '计划整改时限',
            align: 'center',
            minWidth: 160,
            showOverflowTooltip: true
          },
          {
            prop: 'verifyResult',
            label: '验收结果',
            align: 'center',
            minWidth: 100,
            formatter: (row) => {
              const resultMap = {
                1: '合格',
                2: '不合格',
                3: '部分合格'
              };
              return resultMap[row.verifyResult] || '-';
            }
          }
        ]
      };
    },

    computed: {},

    methods: {
      // 获取隐患等级标签类型
      getLevelType(level) {
        const typeMap = {
          1: 'danger',
          2: 'warning',
          3: 'primary',
          4: 'success'
        };
        return typeMap[level] || 'info';
      },

      // 获取隐患等级显示文本
      getLevelLabel(level) {
        const item = this.levelOptions.find((opt) => opt.value == level);
        return item ? item.label : level;
      },

      // 获取隐患状态标签类型
      getStatusType(status) {
        const typeMap = {
          0: 'info',
          1: 'warning',
          2: 'primary',
          3: 'warning',
          4: 'success',
          CLOSED: ''
        };
        return typeMap[status] || 'info';
      },

      // 获取隐患状态显示文本
      getStatusLabel(status) {
        const item = this.statusOptions.find((opt) => opt.value == status);
        return item ? item.label : status;
      },

      // 获取隐患类别显示文本
      getCategoryLabel(category) {
        const item = this.categoryOptions.find((opt) => opt.value == category);
        return item ? item.label : category;
      },

      handleDeviceChange(row) {
        this.selectedDevice = row;
      },

      emitResult(device) {
        const data = {
          sourceCode: this.row.code,
          sourceId: this.row.id,
          sourceName: this.row.planName,
          sourceType: this.sourceType,
          deviceList: device
        };
        this.$refs.hazardDialogRef.open('add', data);
        // this.visible = false;
      },
      // 新增
      async handleAdd() {
        try {
          this.loading = true;
          let detail = null;
          if (this.sourceType == 3) {
            detail = await getWorkOrderDetail(this.row.code);
            let deviceData = await getAssetInfo(
              detail.repairRequestResponse.deviceId
            );
            this.emitResult({
              substance: {
                id: deviceData.id,
                name: deviceData.name,
                codeNumber: deviceData.codeNumber,
                positionNames:
                  deviceData.deviceLocationName +
                  '-' +
                  deviceData.deviceDetailAddress
              }
            });
          } else {
            detail = await getWordOrderDetail(this.row.id);
            this.loading = false;
            const list = detail?.deviceList || [];
            if (list.length === 0) {
              this.$message.warning('该工单暂无设备信息');
              return;
            }
            if (list.length === 1) {
              this.emitResult(list[0]);
            } else {
              this.deviceList = list;
              this.deviceVisible = true;
              this.$nextTick(() => {
                this.$refs.deviceTable.reload({ page: 1 });
              });
            }
          }
        } catch (e) {
          this.loading = false;
          this.$message.error(e.message || '获取详情失败');
        }
      },
      // 查看
      handleView(row) {
        this.$refs.hazardDialogRef.open('view', row);
      },
      open(row) {
        this.row = row;
        this.$nextTick(() => {
          this.handleReload();
        });
        this.visible = true;
      },
      deviceDatasource() {
        return Promise.resolve({
          list: this.deviceList,
          count: this.deviceList.length
        });
      },
      handleDeviceConfirm() {
        if (!this.selectedDevice) {
          this.$message.warning('请选择一个设备');
          return;
        }
        this.emitResult(this.selectedDevice);
        this.deviceVisible = false;
      },
      // 刷新表格
      handleReload() {
        this.$refs.table.reload({ page: 1 });
      },
      // 表格数据源
      async datasource({ page, limit, where }) {
        const body = {
          ...where,
          pageNum: page,
          sourceId: this.row.id,
          size: limit
        };
        // TODO: 替换为实际API调用
        return await getList(body);
      }
    }
  };
</script>

<style lang="scss" scoped></style>
