<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="关联规则" prop="ruleObjId">
        <el-select v-model="queryParams.ruleObjId" placeholder="请选择关联规则" clearable filterable style="width: 260px">
          <el-option v-for="item in recordAlarmRuleList" :key="item.objId" :label="item.ruleName" :value="item.objId" />
        </el-select>
      </el-form-item>
      <el-form-item label="步骤顺序" prop="stepSequence">
        <el-input-number v-model="queryParams.stepSequence" :min="1" :precision="0" controls-position="right" style="width: 180px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @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="small" @click="handleAdd" v-hasPermi="['ems/base:emsAlarmActionStep:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="small" :disabled="single" @click="handleUpdate" v-hasPermi="['ems/base:emsAlarmActionStep:edit']">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ems/base:emsAlarmActionStep:remove']"
        >
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="small" @click="handleExport" v-hasPermi="['ems/base:emsAlarmActionStep:export']">
          导出
        </el-button>
      </el-col>
      <right-toolbar v-model:show-search="showSearch" :columns="columns" @query-table="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="emsAlarmActionStepList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column v-if="columns[0].visible" label="序号" type="index" width="60" align="center" />
      <el-table-column v-if="columns[1].visible" label="关联规则" align="center" min-width="220" show-overflow-tooltip>
        <template #default="scope">
          {{ resolveRuleName(scope.row.ruleObjId) }}
        </template>
      </el-table-column>
      <el-table-column v-if="columns[2].visible" label="步骤顺序" align="center" prop="stepSequence" width="120" />
      <el-table-column v-if="columns[3].visible" label="步骤描述" align="center" prop="description" min-width="260" show-overflow-tooltip />
      <el-table-column v-if="columns[4].visible" label="备注" align="center" prop="remark" min-width="220" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
        <template #default="scope">
          <el-button size="small" type="text" @click="handlePreview(scope.row)">预览</el-button>
          <el-button size="small" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['ems/base:emsAlarmActionStep:edit']">修改</el-button>
          <el-button size="small" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['ems/base:emsAlarmActionStep:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <el-dialog :title="title" v-model="open" width="560px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="96px">
        <el-form-item label="关联规则" prop="ruleObjId">
          <el-select v-model="form.ruleObjId" placeholder="请选择关联规则" filterable style="width: 100%">
            <el-option v-for="item in recordAlarmRuleList" :key="item.objId" :label="item.ruleName" :value="item.objId" />
          </el-select>
        </el-form-item>
        <el-form-item label="步骤顺序" prop="stepSequence">
          <el-input-number v-model="form.stepSequence" :min="1" :precision="0" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="步骤描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入步骤描述" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="previewOpen" :title="previewTitle" width="820px" append-to-body>
      <el-empty v-if="!previewSteps.length" description="当前规则暂无图文 SOP" />
      <div v-else class="preview-steps">
        <article v-for="step in previewSteps" :key="step.objId || step.stepSequence" class="preview-step-card">
          <div class="preview-step-sequence">步骤 {{ step.stepSequence || '-' }}</div>
          <div class="preview-step-desc">{{ step.description || '-' }}</div>
          <div v-if="step.remark" class="preview-step-remark">{{ step.remark }}</div>
          <div v-if="step.stepImages?.length" class="preview-step-images">
            <button
              v-for="image in step.stepImages"
              :key="image.objId || image.imageSequence"
              type="button"
              class="preview-step-image"
              @click="previewImage(image.imageUrl)"
            >
              <img :src="resolveImageUrl(image.imageUrl)" :alt="image.description || 'SOP 图片'" />
              <span>{{ image.description || `图片 ${image.imageSequence || ''}` }}</span>
            </button>
          </div>
        </article>
      </div>
    </el-dialog>

    <el-dialog v-model="imagePreviewVisible" title="SOP 参考图" width="760px" append-to-body>
      <div class="image-preview-container">
        <img :src="previewImageUrl" alt="SOP 参考图预览" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  listEmsAlarmActionStep,
  getEmsAlarmActionStep,
  getEmsAlarmActionStepsByRuleId,
  delEmsAlarmActionStep,
  addEmsAlarmActionStep,
  updateEmsAlarmActionStep
} from '@/api/ems/base/emsAlarmActionStep';
import { getEmsRecordAlarmRuleList } from '@/api/ems/record/recordAlarmRule';
import type { EmsAlarmActionStepVO, EmsRecordAlarmRuleVO } from '@/api/ems/types';

defineOptions({
  name: 'EmsAlarmActionStep'
} as any);

const { proxy } = getCurrentInstance() as any;

const formRef = ref<any>();
const queryFormRef = ref<any>();

const columns = ref<FieldOption[]>([
  { key: 0, label: '序号', visible: true, children: [] },
  { key: 1, label: '关联规则', visible: true, children: [] },
  { key: 2, label: '步骤顺序', visible: true, children: [] },
  { key: 3, label: '步骤描述', visible: true, children: [] },
  { key: 4, label: '备注', visible: true, children: [] }
]);

const createFormData = () => ({
  objId: null,
  ruleObjId: null,
  stepSequence: 1,
  description: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  remark: null
});

const state = reactive({
  loading: true,
  ids: [],
  recordAlarmRuleList: [] as EmsRecordAlarmRuleVO[],
  single: true,
  multiple: true,
  showSearch: true,
  total: 0,
  emsAlarmActionStepList: [] as EmsAlarmActionStepVO[],
  title: '',
  open: false,
  previewOpen: false,
  previewTitle: '',
  previewSteps: [] as EmsAlarmActionStepVO[],
  previewImageUrl: '',
  imagePreviewVisible: false,
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    ruleObjId: null,
    stepSequence: null,
    description: null
  },
  form: createFormData(),
  rules: {
    ruleObjId: [{ required: true, message: '关联规则不能为空', trigger: 'change' }],
    stepSequence: [{ required: true, message: '步骤顺序不能为空', trigger: 'blur' }],
    description: [{ required: true, message: '步骤描述不能为空', trigger: 'blur' }]
  }
} as any);

const { emsAlarmActionStepList, form, ids, imagePreviewVisible, loading, multiple, open, previewImageUrl, previewOpen, previewSteps, previewTitle, queryParams, recordAlarmRuleList, rules, showSearch, single, title, total } = toRefs(state);

const resolveRuleName = (ruleObjId?: string | number) =>
  recordAlarmRuleList.value.find((item) => item.objId === ruleObjId)?.ruleName || (ruleObjId ? String(ruleObjId) : '-');

const resolveImageUrl = (imageUrl?: string | null) => {
  if (!imageUrl) {
    return '';
  }
  if (/^https?:\/\//.test(imageUrl)) {
    return imageUrl;
  }
  return `${window.location.origin}${imageUrl}`;
};

const previewImage = (imageUrl?: string | null) => {
  if (!imageUrl) {
    return;
  }
  previewImageUrl.value = resolveImageUrl(imageUrl);
  imagePreviewVisible.value = true;
};

const getList = () => {
  loading.value = true;
  listEmsAlarmActionStep(queryParams.value).then((response) => {
    emsAlarmActionStepList.value = response.rows ?? [];
    total.value = response.total ?? 0;
    loading.value = false;
  });
};

const loadRuleOptions = () => {
  getEmsRecordAlarmRuleList().then((response) => {
    recordAlarmRuleList.value = (response.data ?? response.rows ?? []) as EmsRecordAlarmRuleVO[];
  });
};

const cancel = () => {
  open.value = false;
  reset();
};

const reset = () => {
  form.value = createFormData();
  formRef.value?.resetFields();
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.objId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  reset();
  open.value = true;
  title.value = '添加报警规则具体措施步骤';
};

const handleUpdate = (row) => {
  reset();
  const objId = row?.objId || ids.value[0];
  if (!objId) {
    return;
  }
  getEmsAlarmActionStep(objId).then((response) => {
    form.value = {
      ...createFormData(),
      ...(response.data ?? {})
    };
    open.value = true;
    title.value = '修改报警规则具体措施步骤';
  });
};

const handlePreview = async (row?: EmsAlarmActionStepVO) => {
  const ruleObjId = row?.ruleObjId;
  if (!ruleObjId) {
    proxy?.$modal.msgWarning('当前步骤缺少关联规则，无法加载图文 SOP');
    return;
  }
  const response = await getEmsAlarmActionStepsByRuleId(ruleObjId as any);
  previewSteps.value = ((response as any).data ?? []) as EmsAlarmActionStepVO[];
  previewTitle.value = `图文 SOP - ${resolveRuleName(ruleObjId)}`;
  previewOpen.value = true;
};

const submitForm = () => {
  formRef.value?.validate((valid) => {
    if (!valid) {
      return;
    }
    if (form.value.objId != null) {
      updateEmsAlarmActionStep(form.value).then(() => {
        proxy?.$modal.msgSuccess('修改成功');
        open.value = false;
        getList();
      });
      return;
    }
    addEmsAlarmActionStep(form.value).then(() => {
      proxy?.$modal.msgSuccess('新增成功');
      open.value = false;
      getList();
    });
  });
};

const handleDelete = (row) => {
  const objIds = row?.objId || ids.value;
  proxy?.$modal
    .confirm('是否确认删除报警规则具体措施步骤编号为"' + objIds + '"的数据项？')
    .then(function () {
      return delEmsAlarmActionStep(objIds);
    })
    .then(() => {
      getList();
      proxy?.$modal.msgSuccess('删除成功');
    })
    .catch(() => {});
};

const handleExport = () => {
  proxy?.download(
    'ems/base/emsAlarmActionStep/export',
    {
      ...queryParams.value
    },
    `emsAlarmActionStep_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
  loadRuleOptions();
});
</script>

<style scoped>
.preview-steps {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.preview-step-card {
  background: linear-gradient(180deg, rgba(248, 250, 255, 0.95), rgba(255, 255, 255, 0.98));
  border: 1px solid rgba(205, 215, 238, 0.78);
  border-radius: 16px;
  padding: 16px;
}

.preview-step-sequence {
  color: #5263c4;
  font-size: 12px;
  letter-spacing: 0.12em;
}

.preview-step-desc {
  font-size: 15px;
  font-weight: 600;
  line-height: 1.7;
  margin-top: 8px;
}

.preview-step-remark {
  color: var(--el-text-color-secondary);
  font-size: 13px;
  line-height: 1.7;
  margin-top: 8px;
}

.preview-step-images {
  display: grid;
  gap: 10px;
  grid-template-columns: repeat(auto-fill, minmax(132px, 1fr));
  margin-top: 12px;
}

.preview-step-image {
  background: #fff;
  border: 1px solid rgba(205, 215, 238, 0.84);
  border-radius: 12px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 8px;
  text-align: left;
}

.preview-step-image img {
  border-radius: 8px;
  height: 96px;
  object-fit: cover;
  width: 100%;
}

.preview-step-image span {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  line-height: 1.5;
}

.image-preview-container {
  align-items: center;
  display: flex;
  justify-content: center;
  min-height: 320px;
}

.image-preview-container img {
  max-height: 70vh;
  max-width: 100%;
}
</style>
