<template>
  <a-drawer
    placement="right"
    v-model:visible="innerVisible"
    :get-container="true"
    width="100%"
    :title="props.project?.name"
    :mask="true"
    @close="handleClose()"
    :style="{ position: 'absolute', paddingTop: '0px', margin: '0px' }"
    @open="handleShowReport"
  >
    <a-row style="height: calc(100vh - 95px)" :gutter="10">
      <a-col :span="24 - rightWidth" style="height: 100%">
        <a-card
          :bodyStyle="{ height: 'calc(100% - 67px)', padding: '0px', overflow: 'hidden' }"
          :headStyle="{ padding: '0 16px', background: '#F0F0F0' }"
          :bordered="false"
        >
          <template #title>
            <div class="card-header-container">
              <a-input-search
                v-model:value="searchValue"
                placeholder="输入关键词搜索全表"
                style="width: 300px"
                @search="handleSearch"
                allowClear
                @change="handleSearchChange"
              />
            </div>
          </template>
          <template #extra>
            <vxe-button @click="openReportConfigModal" status="primary" mode="text">报告配置</vxe-button>
            <vxe-button @click="openCateModal" status="primary" mode="text">模板配置</vxe-button>
            <vxe-button @click="problemClassify(1)" status="primary" mode="text">现状归纳</vxe-button>
            <vxe-button @click="problemClassify(2)" status="primary" mode="text">问题归纳</vxe-button>
            <vxe-button @click="toggleFullscreen('left')" status="primary" mode="text" icon="vxe-icon-fullscreen" />
            <vxe-button @click="openCustomEvent" status="primary" mode="text" icon="vxe-icon-custom-column" />
            <!-- <vxe-button type="link" @click="handelHideLeft">
            <menuUnfoldOutlined v-if="rightWidth==12" class="trigger" />
            <MenuFoldOutlined v-else class="trigger" />
          </vxe-button> -->
          </template>
          <vxe-grid ref="refCheckTable" v-bind="gridOptions" style="height: 100%" :data="tableDatas">
            <template #action="{ row }">
              <vxe-button mode="text" @click="handleEditRow(row)">编辑/查看</vxe-button>
            </template>
          </vxe-grid>
        </a-card>
      </a-col>
      <a-col :span="rightWidth" style="height: 100%">
        <a-card
          title="分类列表"
          :bodyStyle="{ height: 'calc(100% - 67px)', padding: '0px' }"
          :headStyle="{ padding: '0 16px', background: '#F0F0F0' }"
          :bordered="false"
        >
          <template #extra>
            <vxe-button status="primary" mode="text" @click="problemClassify(1)">现状归纳</vxe-button>
            <vxe-button status="primary" mode="text" @click="problemClassify(2)">问题归纳</vxe-button>
            <vxe-button status="primary" mode="text" @click="handleFormSubmit">保存</vxe-button>
            <vxe-button status="primary" mode="text" @click="handleReload">刷新</vxe-button>
            <vxe-button status="danger" mode="text" @click="handleDelete">删除</vxe-button>
            <vxe-button @click="handleCreateDocReport" status="primary" mode="text">生成报告</vxe-button>
            <vxe-button @click="toggleFullscreen('right')" status="primary" mode="text" icon="vxe-icon-fullscreen" />
            <!-- <vxe-button type="link" @click="handelHideRight">
              <menuUnfoldOutlined v-if="rightWidth==12" class="trigger" />
              <MenuFoldOutlined v-else class="trigger" />
            </vxe-button> -->
          </template>
          <a-collapse v-model:activeKey="activeKey" accordion style="height: 100%; overflow-y: auto" :bordered="false" @change="handleCollapseChange">
            <a-collapse-panel
              v-for="card in allReport"
              :key="card.id"
              :header="`类别:${card.tp == 1 ? '现状' : '问题' || ''}&nbsp;|&nbsp;分组标题：${card.viewpoint || ''}`"
              @click="handlePanelClick(card)"
            >
              <BasicForm @register="registerForm" ref="basicFormRef" style="padding: 20px" />
            </a-collapse-panel>
          </a-collapse>
        </a-card>
      </a-col>
    </a-row>
  </a-drawer>
  <ProjectItemModal @register="registerItemModal" @success="reloadData" />
  <ProjectCategoriesModal @register="registerModal" />
  <ProjectReportConfigModal @register="registerReportConfigModal" />
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, watch, defineProps, defineEmits, onMounted, nextTick } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useForm, BasicForm, FormSchema } from '/@/components/Form';
  import { useModal } from '/@/components/Modal';
  import { message } from 'ant-design-vue';
  import type { VxeTablePropTypes } from 'vxe-table';
  import { MenuUnfoldOutlined, MenuFoldOutlined } from '@ant-design/icons-vue';
  import ProjectItemModal from './ProjectItemModal.vue';
  import ProjectCategoriesModal from './ProjectCategoriesModal.vue';
  import { getFileAccessHttpUrl } from '/@/utils/common/compUtils';
  import ProjectReportConfigModal from './ProjectReportConfigModal.vue';

  import { saveOrUpdate, listAll, createDocReport, deleteOne } from '../AuditProjectProblem.api';
  const [registerModal, { openModal }] = useModal();
  const [registerItemModal, { openModal: openItemModal }] = useModal();
  const [registerReportConfigModal, { openModal: reportConfigOpenModal }] = useModal();
  const currentEditingCard = ref<any>(null);

  const selectedRows = ref([]);
  const basicFormRef = ref();
  const editingCardId = ref<string | null>(null);

  const filterName = ref();
  const allReport = ref([]);
  const tableDatas = ref([]);
  const rightWidth = ref(12);
  const collapsed = ref(false);
  const activeKey = ref();

  const searchValue = ref();

  // Computed dataTitle
  const dataTitle = computed(() => {
    if (activeKey.value === 0 || !activeKey.value) {
      return '未分类数据';
    }

    const currentCard = allReport.value.find((item) => item.id === activeKey.value);
    if (currentCard) {
      return `当前分类: ${currentCard.viewpoint || '无标题'}`;
    }

    return '所有数据';
  });

  const props = defineProps({
    checkData: {
      type: Array,
      required: true,
    },
    project: {
      type: Object,
      required: true,
    },
    visible: {
      type: Boolean,
      required: true,
    },
  });

  const refCheckTable = ref();
  const innerVisible = ref(props.visible);

  watch(
    () => props.visible,
    (newVal) => {
      innerVisible.value = newVal;
      if (newVal) {
        handleShowReport();
      }
    }
  );

  watch(
    () => props.checkData,
    (newVal) => {
      tableDatas.value = newVal;
    },
    { immediate: true }
  );

  const emit = defineEmits(['updateData', 'update:visible']);

  const gridOptions = reactive({
    border: true,
    showOverflow: true,
    loading: false,
    height: '100%',
    scrollY: {
      enabled: true,
      gt: 50,
    },
    checkboxConfig: {
      highlight: true,
      checkStrictly: false,
    },
    columnConfig: {
      useKey: true,
      resizable: true,
    },
    columns: [
      { type: 'checkbox', width: 50, showOverflow: false },
      { field: 'cgrpPath', title: '分组', visible: false, type: 'html' },
      { field: 'content', title: '检查项', type: 'html' },
      { field: 'item', title: '合规条目', visible: false },
      { field: 'tp', title: '检查分类', type: 'html' },
      { field: 'name', title: '检查方法', type: 'html' },
      { field: 'situation', title: '当前现状', type: 'html' },
      { field: 'issues', title: '存在问题', type: 'html' },
      { field: 'action', title: '操作', fixed: 'right', width: 100, slots: { default: 'action' } },
    ],
  });

  const formSchemas = computed<FormSchema[]>(() => [
    {
      label: '分类',
      field: 'tp',
      component: 'Select',
      labelWidth: 150,
      required: true,
      show: true,
      componentProps: {
        type: 'radio',
        options: [
          {
            label: '现状',
            value: 1,
          },
          {
            label: '问题',
            value: 2,
          },
        ],
        onChange: async (tp) => {
          if (tp == 1) {
            await updateFormField(false);
          } else {
            await updateFormField(true);
          }
        },
      },
    },
    {
      label: '分组标题',
      field: 'viewpoint',
      component: 'Input',
      labelWidth: 150,
      required: false,
    },
    {
      label: '所属标题',
      field: 'titleId',
      component: 'JTreeSelect',
      labelWidth: 150,
      componentProps: {
        dict: 'audit_project_report_title,title,id',
        pidField: 'parent_id',
        hasChildField: 'has_child',
        condition: JSON.stringify({ project_id: props.project?.id }),
      },
      required: false,
    },
    {
      label: '风险提示',
      field: 'riskWarning',
      component: 'InputTextArea',
      labelWidth: 150,
      required: false,
      componentProps: {
        showCount: true,
        maxlength: 1024,
        rows: 4,
      },
    },
    {
      label: '改进建议',
      field: 'improvementSuggestion',
      component: 'InputTextArea',
      labelWidth: '150px',
      required: false,
      componentProps: {
        showCount: true,
        maxlength: 1024,
        rows: 4,
      },
    },
    {
      label: '风险等级',
      field: 'riskLevel',
      component: 'Select',
      componentProps: {
        type: 'radio',
        options: [
          {
            label: '低风险',
            value: 1,
          },
          {
            label: '中风险',
            value: 2,
          },
          {
            label: '高风险',
            value: 3,
          },
        ],
      },
    },

    {
      label: '',
      field: 'itemIdList',
      component: 'Input',
      labelWidth: '0',
      required: false,
      ifShow: false,
    },
    {
      label: '',
      field: 'projectId',
      component: 'Input',
      labelWidth: '0',
      required: false,
      ifShow: false,
    },
    {
      label: '',
      field: 'id',
      component: 'Input',
      ifShow: false,
    },
  ]);

  const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue, appendSchemaByField, removeSchemaByFiled, updateSchema }] = useForm({
    showResetButton: false,
    showActionButtonGroup: false,
    schemas: formSchemas,
    onChange: async () => {
      if (activeKey.value && currentEditingCard.value) {
        const formValues = await getFieldsValue();
        // 更新当前编辑的卡片数据
        Object.assign(currentEditingCard.value, formValues);

        // 更新 allReport 中的对应数据
        const index = allReport.value.findIndex((item) => item.id === activeKey.value);
        if (index !== -1) {
          allReport.value[index] = { ...allReport.value[index], ...formValues };
        }
      }
    },
  });

  // Fullscreen toggle function
  const toggleFullscreen = (side: 'left' | 'right') => {
    if (side === 'left') {
      rightWidth.value = rightWidth.value === 0 ? 12 : 0;
    } else {
      rightWidth.value = rightWidth.value === 24 ? 12 : 24;
    }
  };

  const handleClose = () => {
    innerVisible.value = false;
    emit('update:visible', false);
  };

  const problemClassify = async (tp) => {
    await setAllTableDatas();
    await allReport.value.unshift({ tp: tp * 1 });
    activeKey.value = 0;
    handlePanelClick({ tp: tp * 1 });
  };

  function handleEditRow(row) {
    openItemModal(true, {
      isUpdate: true,
      showFooter: true,
      row,
    });
  }
  function openCateModal() {
    openModal(true, {
      isUpdate: false,
      showFooter: true,
      projectId: props.project.id,
    });
  }

  function openReportConfigModal() {
    reportConfigOpenModal(true, {
      isUpdate: false,
      showFooter: true,
      projectId: props.project.id,
    });
  }

  const handlePanelClick = async (card) => {
    await setAllTableDatas(card);
    currentEditingCard.value = card;

    // 重置表单并确保 DOM 更新完成
    //await resetFields();
    await nextTick();

    if (card.itemIdList && card.itemIdList.length > 0) {
      let ownData = props.checkData.filter((record) => card.itemIdList.includes(record.id));
      if (ownData && ownData.length > 0) {
        tableDatas.value = ownData.concat(tableDatas.value);
        const $table = refCheckTable.value;
        if ($table) {
          $table.setCheckboxRow(ownData, true);
        }
      }
    }

    // 确保表单值设置正确
    const formData = {
      ...card,
      projectId: props.project?.id, // 确保 projectId 正确设置
    };
    await setFieldsValue(formData);

    if (card.tp == 1) {
      await updateFormField(false);
    } else {
      await updateFormField(true);
    }
  };

  const handleFormSubmit = async () => {
    try {
      const formValues = await validate();
      const ids = getSelectIds();
      if (ids.length === 0) {
        message.warning('请先选择左侧的数据进行汇总！');
        return;
      }
      if (!formValues.viewpoint) {
        return;
      }
      formValues.projectId = props.project?.id;
      formValues.itemIdList = ids;
      formValues.id = activeKey.value;

      let isUpdate = formValues.id ? true : false;
      const ret = await saveOrUpdate(formValues, isUpdate);

      const updatedCard = ret.result || formValues;
      if (isUpdate) {
        const index = allReport.value.findIndex((item) => item.id === activeKey.value);
        if (index !== -1) {
          allReport.value[index] = updatedCard;
        }
      } else {
        allReport.value.unshift(updatedCard);
        activeKey.value = updatedCard.id;
      }
      await setFieldsValue(updatedCard);
    } catch (error) {
      console.error('保存失败:', error);
    }
  };

  function getSelectIds() {
    let ids = [];
    const $table = refCheckTable.value;
    if ($table) {
      const selRecords = $table.getCheckboxRecords();
      selRecords.forEach(function (ele) {
        if (ele.id) {
          ids.push(ele.id);
        }
      });
    }
    return ids;
  }

  function getSelectDatas() {
    const $table = refCheckTable.value;
    const selRecords = $table?.getCheckboxRecords();
    return selRecords;
  }

  async function getAllReport() {
    const pid = props.project.id;
    allReport.value = await listAll({ projectId: pid });
  }

  const handleDelete = async () => {
    if (!activeKey.value) {
      handleSuccess();
      return;
    }
    await deleteOne({ id: activeKey.value }, handleSuccess);
  };

  const handleSuccess = async () => {
    activeKey.value = 0;
    await handleReload();
  };

  const handleReload = async () => {
    activeKey.value = '';
    tableDatas.value = props.checkData;
    await getAllReport();
  };

  const handleCollapseChange = (key) => {
    activeKey.value = key;
  };

  const handleShowReport = async () => {
    await getAllReport();
  };

  const setAllTableDatas = async (card) => {
    const idsToRemove = new Set();
    allReport.value.forEach((item) => {
      if (item.itemIdList) {
        if (card?.tp == item.tp) {
          item.itemIdList.forEach((id) => idsToRemove.add(id));
        }
      }
    });
    tableDatas.value = props.checkData.filter((record) => !idsToRemove.has(record.id));
  };

  const openCustomEvent = () => {
    const $table = refCheckTable.value;
    if ($table) {
      $table.openCustom();
    }
  };

  const handleSearch = async (value: string) => {
    searchValue.value = value;
    await tableSearch(value);
  };

  const handleSearchChange = async (e: Event) => {
    const value = (e.target as HTMLInputElement).value;
    if (!value) {
      searchValue.value = '';
    }
    await tableSearch(value);
  };

  const tableSearch = async (srhTxt) => {
    const filterSrhTxt = String(srhTxt).trim().toLowerCase();
    if (filterSrhTxt) {
      const filterRE = new RegExp(filterSrhTxt, 'gi');
      const searchProps = ['cgrpPath', 'content', 'item', 'name', 'situation', 'issues'];
      let rest = props.checkData.filter((item) => searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterSrhTxt) > -1));

      tableDatas.value = rest.map((row) => {
        const item = Object.assign({}, row);
        searchProps.forEach((key) => {
          item[key] = String(item[key]).replace(filterRE, (match) => `<span style="color:red">${match}</span>`);
        });
        return item;
      });
    } else {
      tableDatas.value = props.checkData;
    }
  };

  function reloadData(data, row) {
    Object.assign(row, data);
  }

  async function handleCreateDocReport() {
    let pid = props.project.id;
    let cofig = await createDocReport({ projectId: pid });
    let url = getFileAccessHttpUrl(cofig.reportUrl);
    window.open(url);
  }

  // function delField(field) {
  //   removeSchemaByFiled([]);
  // }

  async function updateFormField(isShow) {
    updateSchema({
      field: 'riskLevel',
      show: isShow,
    });

    updateSchema({
      field: 'riskWarning',
      show: isShow,
    });
    updateSchema({
      field: 'improvementSuggestion',
      show: isShow,
    });
  }

  const treeSelectCondition = computed(() => ({
    project_id: props.project?.id || '',
  }));
</script>

<style lang="less" scoped>
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }

  :deep(.ant-card) {
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  :deep(.ant-drawer-body) {
    padding: 0;
    overflow: hidden;
  }

  :deep(.vxe-table--render-wrapper) {
    height: 100% !important;
  }

  /* Fullscreen button style */
  :deep(.vxe-button--fullscreen) {
    margin-right: 8px;
  }

  .card-header-container {
    display: flex;
    align-items: center;
    width: 100%;
    gap: 16px;
  }

  .card-title {
    flex-shrink: 0;
    min-width: 100px;
  }

  /* Search input styles */
  :deep(.ant-input-search) {
    max-width: 400px;
    min-width: 200px;

    .ant-input {
      border-radius: 4px;
      border-color: #d9d9d9;

      &:hover {
        border-color: #40a9ff;
      }

      &:focus {
        border-color: #40a9ff;
        box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
      }
    }

    .ant-input-group-addon {
      background-color: transparent;

      button {
        border-radius: 0 4px 4px 0;
        background-color: #1890ff;
        color: white;
        border-color: #1890ff;

        &:hover {
          background-color: #40a9ff;
          border-color: #40a9ff;
        }
      }
    }
  }
</style>
