<script setup lang="ts">
import { h, reactive, ref, watch } from 'vue';
import { NButton, NSwitch, useMessage } from 'naive-ui';
import {
  type RuleTemplateCreateParams,
  createRuleTemplate,
  deleteRuleTemplate,
  getRuleTemplateDetail,
  getRuleTemplateList,
  updateRuleTemplate
} from '@/service/api/ruleTemplate';

defineOptions({
  name: 'ContractReviewSettings'
});

const message = useMessage();

// 模板列表
const templates = ref<
  Array<{
    id: number;
    templateName: string;
    status: 0 | 1; // 0 启用 1 停用
    createTime?: string;
  }>
>([]);

// 批量选择
const checkedRowKeys = ref<number[]>([]);

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  pageSizes: [10, 20, 30, 50]
});

// 搜索参数
const searchParams = reactive({
  templateName: ''
});

// 当前步骤
const currentStep = ref(1);

// 是否是编辑模式
const isEditMode = ref(false);
const editingId = ref<number | null>(null);

// 新模板信息
const newTemplate = reactive({
  templateName: '',
  status: 0,
  standpoint: '甲方'
});

// 模板详情
const templateDetail = reactive({
  templateName: '',
  reviewRules: {
    template_name: '',
    standpoint: '甲方',
    rules: [{ name: '', context: '' }]
  },
  reviewElements: {
    template_name: '',
    standpoint: '甲方',
    rules: [{ name: '', context: '' }]
  }
});

// 立场选项
const standpointOptions = [
  { label: '甲方', value: '甲方' },
  { label: '乙方', value: '乙方' }
];

// 对话框控制
const showAddModal = ref(false);
const showDetailModal = ref(false);
const loading = ref(false);

// 重置表单数据
const resetFormData = () => {
  // 重置编辑状态
  isEditMode.value = false;
  editingId.value = null;

  // 重置步骤
  currentStep.value = 1;

  // 重置模板基本信息
  newTemplate.templateName = '';
  newTemplate.status = 0;
  newTemplate.standpoint = '甲方';

  // 重置模板详情
  templateDetail.templateName = '';
  templateDetail.reviewRules = {
    template_name: '',
    standpoint: '甲方',
    rules: [{ name: '', context: '' }]
  };
  templateDetail.reviewElements = {
    template_name: '',
    standpoint: '甲方',
    rules: [{ name: '', context: '' }]
  };
};

// 监听对话框关闭，重置表单
watch(showAddModal, newVal => {
  if (!newVal) {
    resetFormData();
  }
});

// 获取模板列表
const fetchTemplates = async () => {
  loading.value = true;
  try {
    // 构建API请求参数
    const params = {
      pageNum: pagination.page,
      pageSize: pagination.pageSize,
      templateName: searchParams.templateName
    };

    // 调用API接口
    const res = await getRuleTemplateList(params);

    // 更新模板列表和分页信息
    if (res && res.data && !res.error) {
      templates.value = res.data.data || [];
      pagination.itemCount = res.data.total || 0;
    }
  } catch (error) {
    message.error('获取模板列表失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 处理分页变化
const handlePageChange = (page: number) => {
  pagination.page = page;
  fetchTemplates();
};

// 处理每页条数变化
const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  pagination.page = 1;
  fetchTemplates();
};

// 处理搜索
const handleSearch = () => {
  pagination.page = 1;
  fetchTemplates();
};

// 重置搜索
const resetSearch = () => {
  searchParams.templateName = '';
  pagination.page = 1;
  fetchTemplates();
};

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return '-';
  const date = new Date(dateTimeStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 获取模板详情
const fetchTemplateDetail = async (id: number) => {
  try {
    const res = await getRuleTemplateDetail(id);
    if (res && res.data && !res.error) {
      templateDetail.templateName = res.data.templateName;
      templateDetail.reviewRules = JSON.parse(res.data.reviewRuleJson);
      templateDetail.reviewElements = JSON.parse(res.data.reviewElementJson);

      showDetailModal.value = true;
    }
  } catch (error) {
    message.error('获取模板详情失败');
    console.error(error);
  }
};

// 添加规则模板第一步
const nextStep = () => {
  if (!newTemplate.templateName.trim()) {
    message.error('模板名称不能为空');
    return;
  }

  templateDetail.templateName = newTemplate.templateName;
  templateDetail.reviewRules.template_name = newTemplate.templateName;
  templateDetail.reviewElements.template_name = newTemplate.templateName;
  templateDetail.reviewRules.standpoint = newTemplate.standpoint;
  templateDetail.reviewElements.standpoint = newTemplate.standpoint;

  currentStep.value = 2;
};

// 返回第一步
const prevStep = () => {
  currentStep.value = 1;
};

// 添加规则点
const addRuleItem = (type: 'reviewRules' | 'reviewElements') => {
  templateDetail[type].rules.push({
    name: '',
    context: ''
  });
};

// 删除规则点
const removeRuleItem = (type: 'reviewRules' | 'reviewElements', index: number) => {
  templateDetail[type].rules.splice(index, 1);
};

// 编辑模板
const editTemplate = async (template: { id: number; templateName: string; status: 0 | 1 }) => {
  try {
    resetFormData(); // 先重置表单，确保没有旧数据

    isEditMode.value = true;
    editingId.value = template.id;

    const res = await getRuleTemplateDetail(template.id);
    if (res && res.data) {
      newTemplate.templateName = res.data.templateName;
      newTemplate.status = res.data.status;
      // 回显standpoint，优先reviewRules，否则reviewElements
      const reviewRules = JSON.parse(res.data.reviewRuleJson);
      const reviewElements = JSON.parse(res.data.reviewElementJson);
      newTemplate.standpoint = reviewRules.standpoint || reviewElements.standpoint || '甲方';

      templateDetail.templateName = res.data.templateName;
      templateDetail.reviewRules = reviewRules;
      templateDetail.reviewElements = reviewElements;

      showAddModal.value = true;
      currentStep.value = 1;
    }
  } catch (error) {
    message.error('获取模板详情失败');
    console.error(error);
  }
};

// 保存模板
const saveTemplate = async () => {
  // 校验规则和要素是否为空
  if (
    templateDetail.reviewRules.rules.some(rule => !rule.name || !rule.context) ||
    templateDetail.reviewElements.rules.some(rule => !rule.name || !rule.context)
  ) {
    message.error('规则名称和描述不能为空');
    return;
  }

  try {
    const params = {
      templateName: templateDetail.templateName,
      reviewRuleJson: JSON.stringify(templateDetail.reviewRules),
      reviewElementJson: JSON.stringify(templateDetail.reviewElements),
      status: newTemplate.status
    } as RuleTemplateCreateParams;

    if (isEditMode.value && editingId.value !== null) {
      // 更新模板
      const res = await updateRuleTemplate({
        ...params,
        id: editingId.value
      });
      if (!res.error) message.success('更新成功');
    } else {
      // 创建模板
      const res = await createRuleTemplate(params);
      if (!res.error) message.success('创建成功');
    }

    showAddModal.value = false;
    // 重置表单数据 - 不需要在这里调用，因为watch会处理

    // 刷新列表
    fetchTemplates();
  } catch (error) {
    message.error(isEditMode.value ? '更新失败' : '保存失败');
    console.error(error);
  }
};

// 打开添加模板对话框
const openAddModal = () => {
  resetFormData(); // 确保表单数据被重置
  showAddModal.value = true;
};

// 删除模板
const deleteTemplate = async (id: number) => {
  try {
    window.$dialog?.warning({
      title: '确认删除',
      content: '确定要删除此模板吗？删除后不可恢复！',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        const res = await deleteRuleTemplate(String(id));
        if (!res.error) {
          message.success('删除成功');
          fetchTemplates();
        }
      }
    });
  } catch (error) {
    message.error('删除失败');
    console.error(error);
  }
};

// 切换模板启用状态
// const toggleTemplateStatus = async (template: { id: number; templateName?: string; status: 0 | 1 }) => {
//   const { error } = await updateRuleTemplate({
//     id: template.id,
//     templateName: template.templateName || '',
//     reviewRuleJson: '', // 保持原值
//     reviewElementJson: '', // 保持原值
//     status: template.status
//   });
//   if (!error) {
//     message.success(template.status ? '已启用' : '已禁用');
//   } else {
//     message.error('状态更新失败');
//     // 恢复原来的状态
//     template.status = !template.status;
//   }
// };

// 批量删除模板
const batchDeleteTemplates = async () => {
  if (checkedRowKeys.value.length === 0) {
    message.warning('请选择要删除的模板');
    return;
  }

  try {
    window.$dialog?.warning({
      title: '确认批量删除',
      content: `确定要删除选中的 ${checkedRowKeys.value.length} 个模板吗？删除后不可恢复！`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        const res = await deleteRuleTemplate(checkedRowKeys.value.join(','));
        if (!res.error) {
          message.success('批量删除成功');
          checkedRowKeys.value = [];
          fetchTemplates();
        }
      }
    });
  } catch (error) {
    message.error('批量删除失败');
    console.error(error);
  }
};

// 初始化
fetchTemplates();
</script>

<template>
  <div class="h-full w-full p-16px">
    <NCard title="合同审查规则设置" class="h-full">
      <template #header-extra>
        <NSpace>
          <NButton type="primary" @click="openAddModal">添加规则模板</NButton>
          <NButton type="error" :disabled="checkedRowKeys.length === 0" @click="batchDeleteTemplates">批量删除</NButton>
        </NSpace>
      </template>

      <!-- 搜索区域 -->
      <div class="mb-16px">
        <NGrid :cols="24" :x-gap="16">
          <NGridItem :span="6">
            <NInput v-model:value="searchParams.templateName" placeholder="请输入模板名称" clearable />
          </NGridItem>
          <NGridItem :span="6">
            <NSpace>
              <NButton type="primary" @click="handleSearch">查询</NButton>
              <NButton @click="resetSearch">重置</NButton>
            </NSpace>
          </NGridItem>
        </NGrid>
      </div>

      <div class="h-full flex-col">
        <div v-if="templates.length === 0 && !loading" class="h-full flex-center">
          <NEmpty description="暂无规则模板">
            <template #extra>
              <NButton type="primary" @click="openAddModal">添加规则模板</NButton>
            </template>
          </NEmpty>
        </div>

        <NSpin :show="loading">
          <NDataTable
            v-if="templates.length > 0"
            v-model:checked-row-keys="checkedRowKeys"
            :columns="[
              { type: 'selection' },
              { title: '模板名称', key: 'templateName' },
              {
                title: '创建时间',
                key: 'createTime',
                render(row) {
                  return formatDateTime(row.createTime);
                }
              },
              {
                title: '操作',
                key: 'actions',
                render(row) {
                  return h('div', { class: 'flex gap-8px' }, [
                    h(
                      NButton,
                      {
                        type: 'info',
                        size: 'small',
                        onClick: () => fetchTemplateDetail(row.id)
                      },
                      { default: () => '查看' }
                    ),
                    h(
                      NButton,
                      {
                        type: 'primary',
                        size: 'small',
                        onClick: () => editTemplate(row)
                      },
                      { default: () => '编辑' }
                    ),
                    h(
                      NButton,
                      {
                        type: 'error',
                        size: 'small',
                        onClick: () => deleteTemplate(row.id)
                      },
                      { default: () => '删除' }
                    )
                  ]);
                }
              }
            ]"
            :data="templates"
            :pagination="pagination"
            :loading="loading"
            :row-key="row => row.id"
            @update:page="handlePageChange"
            @update:page-size="handlePageSizeChange"
          />
        </NSpin>
      </div>
    </NCard>

    <!-- 添加/编辑模板对话框 -->
    <NModal
      v-model:show="showAddModal"
      preset="card"
      class="max-h-800px w-700px of-y-auto"
      :title="`${isEditMode ? '编辑' : '添加'}规则模板 - 第${currentStep}步`"
      @close="resetFormData"
    >
      <!-- 步骤1：创建模板名称 -->
      <div v-if="currentStep === 1" class="flex flex-col gap-16px">
        <div>
          <div class="mb-6px">模板名称</div>
          <NInput v-model:value="newTemplate.templateName" placeholder="请输入模板名称" />
        </div>
        <div>
          <div class="mb-6px">审查立场</div>
          <NSelect v-model:value="newTemplate.standpoint" :options="standpointOptions" />
        </div>
        <div class="flex items-center">
          <span class="mr-16px">启用模板</span>
          <NSwitch v-model:value="newTemplate.status" :checked-value="0" :unchecked-value="1" />
        </div>

        <div class="mt-16px flex justify-end gap-12px">
          <NButton @click="showAddModal = false">取消</NButton>
          <NButton type="primary" @click="nextStep">下一步</NButton>
        </div>
      </div>

      <!-- 步骤2：配置审查要素和审查规则 -->
      <div v-else class="flex flex-col gap-16px">
        <NTabs type="line" animated>
          <NTabPane name="reviewRules" tab="审查规则">
            <div class="py-16px">
              <div class="mb-16px">
                <div class="mb-6px">规则名称</div>
                <NInput v-model:value="templateDetail.reviewRules.template_name" placeholder="请输入规则名称" />
              </div>

              <div class="mb-16px">
                <div class="mb-6px">审查立场</div>
                <NSelect v-model:value="templateDetail.reviewRules.standpoint" :options="standpointOptions" />
              </div>

              <div class="mb-16px flex items-center justify-between">
                <div class="text-16px font-bold">规则配置</div>
              </div>

              <div
                v-for="(rule, index) in templateDetail.reviewRules.rules"
                :key="index"
                class="mb-16px border rounded p-16px"
              >
                <div class="flex justify-between">
                  <div class="text-14px font-bold">规则点 {{ index + 1 }}</div>
                  <NButton
                    v-if="templateDetail.reviewRules.rules.length > 1"
                    size="tiny"
                    quaternary
                    type="error"
                    @click="removeRuleItem('reviewRules', index)"
                  >
                    删除
                  </NButton>
                </div>

                <div class="mt-8px">
                  <div class="mb-6px">规则名称</div>
                  <NInput v-model:value="rule.name" placeholder="请输入规则名称" />
                </div>

                <div class="mt-12px">
                  <div class="mb-6px">规则补充</div>
                  <NInput
                    v-model:value="rule.context"
                    type="textarea"
                    placeholder="请输入规则补充描述"
                    :autosize="{ minRows: 3, maxRows: 6 }"
                  />
                </div>
              </div>

              <NButton size="small" @click="addRuleItem('reviewRules')">
                <div class="flex-center">
                  <div class="i-ep-plus mr-4px" />
                  添加规则点
                </div>
              </NButton>
            </div>
          </NTabPane>

          <NTabPane name="reviewElements" tab="审查要素">
            <div class="py-16px">
              <div class="mb-16px">
                <div class="mb-6px">要素名称</div>
                <NInput v-model:value="templateDetail.reviewElements.template_name" placeholder="请输入要素名称" />
              </div>

              <div class="mb-16px">
                <div class="mb-6px">审查立场</div>
                <NSelect v-model:value="templateDetail.reviewElements.standpoint" :options="standpointOptions" />
              </div>

              <div class="mb-16px flex items-center justify-between">
                <div class="text-16px font-bold">要素配置</div>
              </div>

              <div
                v-for="(rule, index) in templateDetail.reviewElements.rules"
                :key="index"
                class="mb-16px border rounded p-16px"
              >
                <div class="flex justify-between">
                  <div class="text-14px font-bold">要素 {{ index + 1 }}</div>
                  <NButton
                    v-if="templateDetail.reviewElements.rules.length > 1"
                    size="tiny"
                    quaternary
                    type="error"
                    @click="removeRuleItem('reviewElements', index)"
                  >
                    删除
                  </NButton>
                </div>

                <div class="mt-8px">
                  <div class="mb-6px">要素名称</div>
                  <NInput v-model:value="rule.name" placeholder="请输入要素名称" />
                </div>

                <div class="mt-12px">
                  <div class="mb-6px">要素描述</div>
                  <NInput
                    v-model:value="rule.context"
                    type="textarea"
                    placeholder="请输入要素描述"
                    :autosize="{ minRows: 3, maxRows: 6 }"
                  />
                </div>
              </div>

              <NButton size="small" @click="addRuleItem('reviewElements')">
                <div class="flex-center">
                  <div class="i-ep-plus mr-4px" />
                  添加要素
                </div>
              </NButton>
            </div>
          </NTabPane>
        </NTabs>

        <div class="mt-16px flex justify-end gap-12px">
          <NButton @click="prevStep">上一步</NButton>
          <NButton @click="showAddModal = false">取消</NButton>
          <NButton type="primary" @click="saveTemplate">{{ isEditMode ? '更新' : '保存' }}</NButton>
        </div>
      </div>
    </NModal>

    <!-- 查看模板详情对话框 -->
    <NModal
      v-model:show="showDetailModal"
      preset="card"
      style="width: 700px"
      :title="`模板详情 - ${templateDetail.templateName}`"
    >
      <NTabs type="line" animated>
        <NTabPane name="reviewRules" tab="审查规则">
          <div class="py-16px">
            <div class="mb-16px">
              <div class="text-14px font-bold">规则名称</div>
              <div class="mt-4px">{{ templateDetail.reviewRules.template_name }}</div>
            </div>

            <div class="mb-16px">
              <div class="text-14px font-bold">审查立场</div>
              <div class="mt-4px">{{ templateDetail.reviewRules.standpoint }}</div>
            </div>

            <div class="mb-8px text-16px font-bold">规则列表</div>
            <div
              v-for="(rule, index) in templateDetail.reviewRules.rules"
              :key="index"
              class="mb-16px border rounded p-16px"
            >
              <div class="text-16px font-bold">{{ rule.name }}</div>
              <div class="mt-8px text-14px">{{ rule.context }}</div>
            </div>
          </div>
        </NTabPane>

        <NTabPane name="reviewElements" tab="审查要素">
          <div class="py-16px">
            <div class="mb-16px">
              <div class="text-14px font-bold">要素名称</div>
              <div class="mt-4px">{{ templateDetail.reviewElements.template_name }}</div>
            </div>

            <div class="mb-16px">
              <div class="text-14px font-bold">审查立场</div>
              <div class="mt-4px">{{ templateDetail.reviewElements.standpoint }}</div>
            </div>

            <div class="mb-8px text-16px font-bold">要素列表</div>
            <div
              v-for="(rule, index) in templateDetail.reviewElements.rules"
              :key="index"
              class="mb-16px border rounded p-16px"
            >
              <div class="text-16px font-bold">{{ rule.name }}</div>
              <div class="mt-8px text-14px">{{ rule.context }}</div>
            </div>
          </div>
        </NTabPane>
      </NTabs>
    </NModal>
  </div>
</template>

<style lang="scss" scoped>
.rules-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 8px 0;
}
</style>
