<template>
  <div class="p-2">
    <!-- 任务信息展示 -->
    <el-card v-if="currentTaskId" shadow="hover" class="mb-[10px]">
      <div class="flex items-center">
        <el-tag type="primary" size="large">当前任务: {{ currentTaskName || '未指定任务' }}</el-tag>
        <el-button v-if="route.query.taskId" link type="primary" icon="Back" @click="handleBack" class="ml-4">返回任务列表</el-button>
      </div>
    </el-card>

    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item v-if="!currentTaskId" label="所属任务" prop="taskId">
              <el-select v-model="queryParams.taskId" placeholder="请选择所属任务" clearable filterable @change="handleTaskChange">
                <el-option v-for="task in taskOptions" :key="task.id" :label="task.taskName" :value="task.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="步骤名称" prop="stepName">
              <el-input v-model="queryParams.stepName" placeholder="请输入步骤名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['inspection:step:add']" type="primary" plain icon="Plus" :disabled="!queryParams.taskId" @click="handleAdd()">新增根步骤</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        ref="stepTableRef"
        v-loading="loading"
        :data="stepList"
        row-key="id"
        border
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column label="步骤名称" align="left" prop="stepName" :show-overflow-tooltip="true" width="250" />
        <el-table-column label="步骤内容" align="left" prop="stepContent" :show-overflow-tooltip="true" />
        <el-table-column label="关联点位" align="center" prop="pointName" :show-overflow-tooltip="true" width="150" />
        <el-table-column label="排序" align="center" prop="orderNum" width="80" />
        <el-table-column label="语音播报" align="center" prop="needVoiceRead" width="90">
          <template #default="scope">
            <el-tag v-if="scope.row.needVoiceRead === '1'" type="success" size="small">是</el-tag>
            <el-tag v-else type="info" size="small">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="AI识别" align="center" prop="needAi" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.needAi === '1'" type="warning" size="small">是</el-tag>
            <el-tag v-else type="info" size="small">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="需要操作" align="center" prop="isOperation" width="90">
          <template #default="scope">
            <el-tag v-if="scope.row.isOperation === '1'" type="danger" size="small">是</el-tag>
            <el-tag v-else type="info" size="small">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="新增子步骤" placement="top">
              <el-button v-hasPermi="['inspection:step:add']" link type="primary" icon="Plus" @click="handleAdd(scope.row)" />
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['inspection:step:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['inspection:step:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改巡检步骤对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="900px" append-to-body>
      <el-form ref="stepFormRef" :model="form" :rules="rules" label-width="120px">
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属任务" prop="taskId">
              <el-select v-model="form.taskId" placeholder="请选择所属任务" disabled style="width: 100%">
                <el-option v-for="task in taskOptions" :key="task.id" :label="task.taskName" :value="task.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="父步骤" prop="parentId">
              <el-tree-select
                v-model="form.parentId"
                :data="stepTreeOptions"
                :props="{ value: 'id', label: 'stepName', children: 'children' } as any"
                value-key="id"
                placeholder="请选择父步骤(0为根节点)"
                check-strictly
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="步骤名称" prop="stepName">
              <el-input v-model="form.stepName" placeholder="请输入步骤名称" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序号" prop="orderNum">
              <el-input-number v-model="form.orderNum" :min="0" :max="9999" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="步骤内容" prop="stepContent">
          <el-input v-model="form.stepContent" type="textarea" :rows="3" placeholder="请输入步骤内容" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关联点位" prop="pointId">
              <el-select v-model="form.pointId" placeholder="请选择关联点位" clearable filterable style="width: 100%">
                <el-option v-for="point in pointOptions" :key="point.id" :label="point.pointName" :value="point.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="内容语音" prop="contentVoice">
              <AudioUpload v-model="form.contentVoice" :file-size="10" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 语音配置 -->
        <el-divider content-position="left">语音配置</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="语音播报" prop="needVoiceRead">
              <el-switch v-model="form.needVoiceRead" active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="需要复述" prop="needVoiceRephrase">
              <el-switch v-model="form.needVoiceRephrase" active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="语音确认" prop="needVoiceConfirm">
              <el-switch v-model="form.needVoiceConfirm" active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.needVoiceRephrase === '1'" :gutter="20">
          <el-col :span="16">
            <el-form-item label="复述内容" prop="rephraseContent">
              <el-input v-model="form.rephraseContent" placeholder="请输入复述内容" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="复述语音" prop="rephraseVoice">
              <AudioUpload v-model="form.rephraseVoice" :file-size="10" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.needVoiceConfirm === '1'" :gutter="20">
          <el-col :span="12">
            <el-form-item label="确认内容" prop="confirmContent">
              <el-input v-model="form.confirmContent" placeholder="请输入确认内容" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="确认关键词" prop="confirmWord">
              <el-input v-model="form.confirmWord" placeholder="关键词" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="确认语音" prop="confirmVoice">
              <AudioUpload v-model="form.confirmVoice" :file-size="10" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- AI配置 -->
        <el-divider content-position="left">AI配置</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="需要AI识别" prop="needAi">
              <el-switch v-model="form.needAi" active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="需要操作" prop="isOperation">
              <el-switch v-model="form.isOperation" active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.needAi === '1'" :gutter="20">
          <el-col :span="12">
            <el-form-item label="AI目标名称" prop="aiTargetName">
              <el-input v-model="form.aiTargetName" placeholder="请输入AI识别目标名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="form.needAi === '1'" label="AI配置数据" prop="aiData">
          <el-input
            v-model="aiDataStr"
            type="textarea"
            :rows="5"
            placeholder='请输入AI配置JSON格式，例如: {"modelName": "yolov8", "confidence": 0.8, "classes": ["红灯", "绿灯"]}'
          />
          <div v-if="jsonError" class="el-form-item__error">{{ jsonError }}</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ArStep" lang="ts">
import { listArStep, getArStep, delArStep, addArStep, updateArStep, getArStepTree } from '@/api/inspection/step';
import { ArStepVO, ArStepQuery, ArStepForm } from '@/api/inspection/step/types';
import { listArTask } from '@/api/inspection/task';
import { ArTaskVO } from '@/api/inspection/task/types';
import { listArPoint } from '@/api/inspection/point';
import { ArPointVO } from '@/api/inspection/point/types';
import AudioUpload from '@/components/AudioUpload/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();

const stepList = ref<ArStepVO[]>([]);
const taskOptions = ref<ArTaskVO[]>([]);
const pointOptions = ref<ArPointVO[]>([]);
const stepTreeOptions = ref<any[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);
const currentTaskId = ref<string | number | undefined>(undefined);
const currentTaskName = ref<string | undefined>(undefined);
const aiDataStr = ref('');
const jsonError = ref('');

const queryFormRef = ref<ElFormInstance>();
const stepFormRef = ref<ElFormInstance>();
const stepTableRef = ref<ElTableInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ArStepForm = {
  id: undefined,
  taskId: undefined,
  parentId: 0,
  stepName: undefined,
  stepContent: undefined,
  contentVoice: undefined,
  orderNum: 0,
  pointId: undefined,
  needVoiceRead: '0',
  needVoiceRephrase: '0',
  rephraseContent: undefined,
  rephraseVoice: undefined,
  needVoiceConfirm: '0',
  confirmContent: undefined,
  confirmVoice: undefined,
  confirmWord: undefined,
  needAi: '0',
  aiTargetName: undefined,
  aiData: undefined,
  isOperation: '0'
};

const data = reactive<PageData<ArStepForm, ArStepQuery>>({
  form: { ...initFormData },
  queryParams: {
    taskId: undefined,
    parentId: undefined,
    stepName: undefined,
    pointId: undefined
  },
  rules: {
    taskId: [{ required: true, message: '所属任务不能为空', trigger: 'change' }],
    stepName: [{ required: true, message: '步骤名称不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 从路由参数初始化任务ID */
onMounted(() => {
  if (route.query.taskId) {
    currentTaskId.value = route.query.taskId as string;
    currentTaskName.value = route.query.taskName as string;
    queryParams.value.taskId = currentTaskId.value;
  }
  getTaskOptions();
  getPointOptions();
  if (queryParams.value.taskId) {
    getList();
  }
});

/** 返回任务列表 */
const handleBack = () => {
  router.back();
};

/** 查询任务选项 */
const getTaskOptions = async () => {
  const res = await listArTask({ pageNum: 1, pageSize: 1000, status: '0' });
  taskOptions.value = res.rows;
};

/** 查询点位选项 */
const getPointOptions = async () => {
  const res = await listArPoint({ pageNum: 1, pageSize: 1000 });
  pointOptions.value = res.rows;
};

/** 查询步骤下拉树结构 */
const getStepTreeselect = async () => {
  if (!queryParams.value.taskId) {
    stepTreeOptions.value = [];
    return;
  }
  const res = await getArStepTree(queryParams.value.taskId);
  stepTreeOptions.value = [];
  const data: any = { id: 0, stepName: '根节点', children: [] };
  data.children = res.data || [];
  stepTreeOptions.value.push(data);
};

/** 验证并解析JSON */
const parseAiData = () => {
  jsonError.value = '';
  if (!aiDataStr.value || aiDataStr.value.trim() === '') {
    form.value.aiData = undefined;
    return true;
  }
  try {
    form.value.aiData = JSON.parse(aiDataStr.value);
    return true;
  } catch (e) {
    jsonError.value = 'JSON格式不正确';
    return false;
  }
};

/** 查询巡检步骤树形列表 */
const getList = async () => {
  if (!queryParams.value.taskId) {
    proxy?.$modal.msgWarning('请先选择任务');
    return;
  }
  loading.value = true;
  const res = await getArStepTree(queryParams.value.taskId);
  stepList.value = res.data || [];
  loading.value = false;
};

/** 任务改变事件 */
const handleTaskChange = () => {
  getList();
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  aiDataStr.value = '';
  jsonError.value = '';
  stepFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = async (row?: ArStepVO) => {
  reset();
  await getStepTreeselect();
  form.value.taskId = queryParams.value.taskId;
  if (row && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = row ? '添加子步骤' : '添加根步骤';
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(stepList.value, isExpandAll.value);
};

/** 展开/折叠操作 */
const toggleExpandAll = (data: ArStepVO[], status: boolean) => {
  data.forEach((item) => {
    stepTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row: ArStepVO) => {
  reset();
  await getStepTreeselect();
  const res = await getArStep(row.id);
  Object.assign(form.value, res.data);
  // 格式化JSON显示
  if (form.value.aiData) {
    aiDataStr.value = JSON.stringify(form.value.aiData, null, 2);
  }
  dialog.visible = true;
  dialog.title = '修改巡检步骤';
};

/** 提交按钮 */
const submitForm = () => {
  stepFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      // 验证JSON格式
      if (form.value.needAi === '1' && !parseAiData()) {
        return;
      }
      buttonLoading.value = true;
      if (form.value.id) {
        await updateArStep(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addArStep(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: ArStepVO) => {
  await proxy?.$modal.confirm('是否确认删除步骤"' + row.stepName + '"？注意:将级联删除所有子步骤!');
  loading.value = true;
  await delArStep(row.id).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};
</script>
