<template>
  <div class="p-2 erpNativeList">
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container">
      <a-form ref="formRef" @keyup.enter="searchQuery" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :lg="3" :md="6" :sm="8">
            <a-form-item label="年份" name="year">
              <JDictSelectTag v-model:value="queryParam.year" dictCode="super_year" placeholder="请选择年份" allow-clear @change="searchQuery" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="8" :sm="12">
            <a-form-item label="事项名称" name="title">
              <JInput v-model:value="queryParam.title" type="like" placeholder="请输入事项名称" allow-clear trim />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="8" :sm="12">
            <a-form-item label="会议决议" name="content">
              <JInput v-model:value="queryParam.content" type="like" placeholder="请输入会议决议" allow-clear trim />
            </a-form-item>
          </a-col>
<!--          <a-col :lg="6" :md="8" :sm="12">-->
<!--            <a-form-item label="事项目录编码" name="matterCode">-->
<!--              <JInput v-model:value="queryParam.matterCode" type="like" placeholder="请输入事项目录编码" allow-clear trim />-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :lg="6" :md="6" :sm="8">
            <a-form-item label="完成状态" name="bpmStatus">
              <JDictSelectTag v-model:value="queryParam.bpmStatus" dictCode="super_status" placeholder="请选择完成状态" allow-clear @change="searchQuery" />
            </a-form-item>
          </a-col>
          <a-col :lg="3" :md="8" :sm="12">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery">查询</a-button>
              <a-button preIcon="ant-design:reload-outlined" style="margin-left: 8px" @click="searchReset">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="content">
      <!--引用表格-->
      <BasicTable @register="registerTable" :expandedRowKeys="expandedRowKeys" @expand="handleExpand">
        <!--插槽:table标题-->
        <template #tableTitle>
          <a-button type="primary" v-auth="actionAuth.add"  @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
          <a-button type="primary" v-auth="actionAuth.exportXls"  preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
<!--          <j-upload-button type="primary"  v-auth="actionAuth.importExcel" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>-->
<!--          <a-dropdown v-if="selectedRowKeys.length > 0">-->
<!--            <template #overlay>-->
<!--              <a-menu>-->
<!--                <a-menu-item key="1" @click="batchHandleDelete">-->
<!--                  <Icon icon="ant-design:delete-outlined"></Icon>-->
<!--                  删除-->
<!--                </a-menu-item>-->
<!--              </a-menu>-->
<!--            </template>-->
<!--            <a-button v-auth="actionAuth.deleteBatch">-->
<!--              批量操作-->
<!--              <Icon icon="mdi:chevron-down"></Icon>-->
<!--            </a-button>-->
<!--          </a-dropdown>-->
          <!-- 高级查询 -->
          <super-query :config="superQueryConfig" @search="handleSuperQuery" />
        </template>
        <!--操作栏-->
        <template #action="{ record }">
          <TableAction stopButtonPropagation :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
        </template>
        <!--字段回显插槽-->
        <template v-slot:bodyCell="{ column, record, index, text }">
        </template>
        <!--嵌套子表-->
        <template #expandedRowRender="{ record }">
          <div class="feedback-expand-table">
            <div class="feedback-expand-header">
              <div class="feedback-expand-title">
                <span class="feedback-expand-icon">
                  <Icon icon="ant-design:message-outlined" />
                </span>
                <span>反馈信息</span>
                <a-tag class="feedback-expand-count" color="processing">
                  {{ getFeedbackTableLoading(record) ? '加载中' : `${getFeedbackCount(record)} 条` }}
                </a-tag>
              </div>
              <div class="feedback-expand-desc">当前事项的责任部门反馈记录</div>
            </div>
            <BasicTable
              class="feedback-inner-table"
              bordered
              size="small"
              rowKey="id"
              :canResize="false"
              :showIndexColumn="false"
              :showActionColumn="false"
              :showTableSetting="false"
              :clickToRowSelect="false"
              :columns="feedbackExpandColumns"
              :dataSource="getFeedbackTableData(record)"
              :loading="getFeedbackTableLoading(record)"
              :pagination="false"
              :scroll="{ x: 1220 }"
            >
              <template #feedbackAttachments="{ record: feedbackRecord }">
                <SUploadFile
                  v-if="feedbackRecord.id"
                  class="feedback-attachment-list"
                  :bussiness-id="feedbackRecord.id"
                  :disabled="true"
                  :multiple="true"
                />
                <span v-else>-</span>
              </template>
            </BasicTable>
          </div>
        </template>
      </BasicTable>
    </div>
    <!-- 表单区域 -->
    <BgPartymatterModal ref="registerModal" @success="handleSuccess" />
      <!-- 审批记录 -->
      <BpmPictureModal @register="registerBpmModal" />
    <FlowScheduleStartModalForBG ref="flowScheduleModalRef" @confirm="handleFlowScheduleConfirm" />
    <BusinessProcessListModal ref="businessProcessListModalRef" />
  </div>
</template>

<script lang="ts" name="bgpartymatter-bgPartymatter" setup>
  import { reactive, ref } from 'vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import type { BasicColumn } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { useModal } from '/@/components/Modal';
  import { dateUtil } from '/@/utils/dateUtil';
  import { startProcessSchedules } from '/@/api/common/api';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JInput from '/@/components/Form/src/jeecg/components/JInput.vue';
  import Icon from '/@/components/Icon/index';
  import BgPartymatterModal from './components/BgPartymatterModal.vue';
  import BusinessProcessListModal from '/src/components/semri/process/BusinessProcessListModal.vue';
  import FlowScheduleStartModalForBG from '/src/components/semri/process/FlowScheduleStartModalForBG.vue';
  import SUploadFile from '/@/components/semri/fileComponent/SUploadFile.vue';
  import { columns, superQuerySchema, bgPartymatterFeedbackColumns } from './BgPartymatter.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, bgPartymatterFeedbackList, saveOrUpdate } from './BgPartymatter.api';

  const props = withDefaults(
    defineProps<{
      meetingType?: string;
      ledgerTitle?: string;
      flowName?: string;
      permissionPrefix?: string;
    }>(),
    {
      meetingType: 'party',
      ledgerTitle: '党委会',
      flowName: '党委会决议事项督办',
      permissionPrefix: 'bgpartymatter:bg_partymatter',
    }
  );

  const FLOW_CODE = 'dev_task_task_001';
  const BUSINESS_TABLE_NAME = 'bg_partymatter';
  const FORM_URL = 'bg/bgpartymatter/components/BgPartymatterBPMForm';
  const actionAuth = {
    add: `${props.permissionPrefix}:add`,
    edit: `${props.permissionPrefix}:edit`,
    delete: `${props.permissionPrefix}:delete`,
    deleteBatch: `${props.permissionPrefix}:deleteBatch`,
    exportXls: `${props.permissionPrefix}:exportXls`,
    importExcel: `${props.permissionPrefix}:importExcel`,
  };

  const [registerBpmModal, { openModal: bpmPicModal }] = useModal();
  const formRef = ref();
  const registerModal = ref();
  const flowScheduleModalRef = ref();
  const businessProcessListModalRef = ref();
  const queryParam = reactive<any>({});
  const expandedRowKeys = ref<Array<string | number>>([]);
  const feedbackTableData = reactive<Record<string, Recordable[]>>({});
  const feedbackTableLoading = reactive<Record<string, boolean>>({});

  interface DeptOption {
    label: string;
    value: string;
  }
  //注册table数据
  const feedbackExpandColumns: BasicColumn[] = [
    ...bgPartymatterFeedbackColumns,
    {
      title: '附件下载',
      dataIndex: 'id',
      key: 'attachments',
      align: 'left',
      width: 340,
      slots: { customRender: 'feedbackAttachments' },
    },
  ];

  const { tableContext, onExportXls, onImportXls } = useListPage({
    tableProps:{
      title: props.ledgerTitle,
      api: list,
      columns,
      canResize: true,
      resizeHeightOffset: 56,
      useSearchForm: false,
      expandRowByClick: true,
      clickToRowSelect: true,
      rowSelection: {type: 'radio'},
      actionColumn: {
        width: 120,
        fixed:'right'
      },
      beforeFetch: async (params) => {
        return Object.assign(params, getLedgerQueryParams());
      },
      pagination: {
        current: 1,
        pageSize: 12,
        pageSizeOptions: ['12', '24', '36'],
      },
    },
    exportConfig: {
      name: props.ledgerTitle,
      url: getExportUrl,
      params: getLedgerQueryParams,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });

  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  /**
   * 判断查询值是否为空。
   * JInput 的 like 查询在输入为空时可能会生成 `**`，这里也按空值处理，避免传给后端形成无效模糊查询。
   */
  function isEmptyQueryValue(value) {
    return value === undefined || value === null || value === '' || value === '**' || (Array.isArray(value) && value.length === 0);
  }

  /**
   * 字符串查询值统一去除前后空格，非字符串值保持原样。
   */
  function getTrimmedQueryValue(value) {
    return typeof value === 'string' ? value.trim() : value;
  }

  /**
   * 生成最终提交给列表接口的查询参数。
   * 会过滤空值、纯空值以及 JInput 空模糊值，保留 JInput 已生成好的 like 查询格式。
   */
  function getQueryParams() {
    const params: Recordable = {};
    Object.keys(queryParam).forEach((key) => {
      const value = getTrimmedQueryValue(queryParam[key]);
      if (!isEmptyQueryValue(value)) {
        params[key] = value;
      }
    });
    return params;
  }

  /**
   * 台账入口固定追加会议类型，避免党委会和所务会共表后数据串台。
   */
  function getLedgerQueryParams() {
    return {
      ...getQueryParams(),
      meetingType: props.meetingType,
    };
  }

  /**
   * 清空查询条件。
   * 通过删除 reactive 对象中的字段，让查询表单和实际请求参数都恢复为空。
   */
  function clearQueryParams() {
    Object.keys(queryParam).forEach((key) => {
      delete queryParam[key];
    });
  }

  function getFeedbackKey(record: Recordable) {
    return String(record?.id ?? '');
  }

  function getFeedbackTableData(record: Recordable) {
    return feedbackTableData[getFeedbackKey(record)] || [];
  }

  function getFeedbackCount(record: Recordable) {
    return getFeedbackTableData(record).length;
  }

  function getFeedbackTableLoading(record: Recordable) {
    return !!feedbackTableLoading[getFeedbackKey(record)];
  }

  function clearFeedbackTableData() {
    Object.keys(feedbackTableData).forEach((key) => {
      delete feedbackTableData[key];
    });
    Object.keys(feedbackTableLoading).forEach((key) => {
      delete feedbackTableLoading[key];
    });
  }

  function resetFeedbackExpand() {
    expandedRowKeys.value = [];
    clearFeedbackTableData();
  }

  async function loadFeedbackTableData(mainId: string | number) {
    const key = String(mainId);
    feedbackTableLoading[key] = true;
    try {
      const res = await bgPartymatterFeedbackList({
        mainId,
        pageNo: 1,
        pageSize: 9999,
        column: 'createTime',
        order: 'desc',
      });
      feedbackTableData[key] = Array.isArray(res) ? res : res?.records || [];
    } finally {
      feedbackTableLoading[key] = false;
    }
  }

  async function handleExpand(expanded: boolean, record: Recordable) {
    const mainId = record?.id;
    expandedRowKeys.value = [];
    if (!expanded || mainId === undefined || mainId === null || mainId === '') {
      return;
    }
    expandedRowKeys.value = [mainId];
    await loadFeedbackTableData(mainId);
  }

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    searchQuery();
  }

  function searchQuery() {
    resetFeedbackExpand();
    reload({ page: 1 });
  }

  /**
   * 新增事件
   */
  function handleAdd() {
    registerModal.value.disableSubmit = false;
    registerModal.value.add({ meetingType: props.meetingType });
  }

  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
     registerModal.value.disableSubmit = false;
     registerModal.value.edit(record);
  }

  /**
   * 详情事件
   */
  function handleDetail(record: Recordable) {
    registerModal.value.disableSubmit = true;
    registerModal.value.edit(record);
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({id: record.id}, handleSuccess);
  }

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ids: selectedRowKeys.value},handleSuccess);
  }

  /**
   * 成功回调
   */
  function handleSuccess() {
    selectedRowKeys.value = [];
    resetFeedbackExpand();
    reload();
  }

  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
        auth: actionAuth.edit
      },
    ];
  }

  /**
   * 下拉操作栏
   */
  function getDropDownAction(record){
    let dropDownAction = [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      }, {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft'
        },
        auth: actionAuth.delete
      },
      // {
      //   label: '审批进度',
      //   onClick: handlePreviewPic.bind(null, record),
      //   ifShow: !!record.bpmStatus && record.bpmStatus !== '1',
      // },
      {
        label: '查询督办流程',
        onClick: handleQueryProcess.bind(null, record),
      },
    ];

    if (record.bpmStatus == '1' || !record.bpmStatus) {
      dropDownAction.push({
        label: '发起督办流程',
        onClick: handleProcess.bind(null, record),
      });
    }
    if (record.bpmStatus == '2' || !record.bpmStatus) {
      dropDownAction.push({
        label: '再次督办',
        onClick: handleProcess.bind(null, record),
      });
    }

    return dropDownAction;
  }

  function handleProcess(record) {
    flowScheduleModalRef.value?.open({
      title: '发起流程',
      taskTitle: record?.title,
      payload: { record },
      deptOptions: getResponsibleDeptOptions(record),
      showSuoleaderFields: true,
      isNeedAppro: record?.isNeedAppro,
      supDeptleaderid: record?.supDeptleaderid,
      showDeadlineField: true,
      deadline: record?.deadline,
      showUrgencyLevelField: true,
      urgencyLevel: record?.urgencyLevel,
    });
  }

  function splitDeptValue(value) {
    if (Array.isArray(value)) {
      return value.map((item) => String(item || '').trim()).filter(Boolean);
    }
    return String(value || '')
      .split(/[,\uFF0C]/)
      .map((item) => item.trim())
      .filter(Boolean);
  }

  function getResponsibleDeptOptions(record): DeptOption[] {
    const optionMap = new Map<string, DeptOption>();
    [
      {
        ids: splitDeptValue(record?.responDeptid),
        names: splitDeptValue(record?.responDeptid_dictText || record?.responDeptname),
      },
      {
        ids: splitDeptValue(record?.assistDeptid),
        names: splitDeptValue(record?.assistDeptid_dictText || record?.assistDeptname),
      },
    ].forEach(({ ids, names }) => {
      ids.forEach((deptId, index) => {
        if (optionMap.has(deptId)) {
          return;
        }
        optionMap.set(deptId, {
          value: deptId,
          label: names[index] || deptId,
        });
      });
    });
    return Array.from(optionMap.values());
  }

  function getResponsibleDeptIds(record) {
    return getResponsibleDeptOptions(record)
      .map((item) => item.value)
      .join(',');
  }

  function getNextSuperviseCount(value) {
    const count = Number(value || 0);
    return Number.isFinite(count) ? count + 1 : 1;
  }

  function handleQueryProcess(record) {
    businessProcessListModalRef.value?.open({
      title: '流程列表',
      businessId: record.id,
      columns:''
      // 默认使用 BusinessProcessListModal 内部列配置
    });
  }

  async function handleFlowScheduleConfirm({ payload, options }) {
    const record = payload?.record || {};
    const formatDate = (value, format) => {
      return value ? dateUtil(value).format(format) : undefined;
    };
    const formatDeadlineDateTime = (value) => {
      const deadlineDate = formatDate(value, 'YYYY-MM-DD');
      return deadlineDate ? `${deadlineDate} 00:00:00` : undefined;
    };
    const nextSuperviseCount = getNextSuperviseCount(record.superviseCount);
    const selectedTitle = options.title || record.title || '';
    const selectedDeadline = options.deadline || record.deadline;
    const selectedUrgencyLevel = options.urgencyLevel ?? record.urgencyLevel ?? '0';
    const defaultDeptIds = getResponsibleDeptIds(record);
    const currentMeetingType = record.meetingType || props.meetingType;
    const flowJsonData = {
      ...record,
      meetingType: currentMeetingType,
      isNeedAppro: options.isNeedAppro ?? record.isNeedAppro ?? '',
      supDeptleaderid: options.supDeptleaderid ?? record.supDeptleaderid ?? '',
      superviseCount: nextSuperviseCount,
      // 用户可在发起前确认本次督办标题，仅影响本次流程数据，不回写台账标题。
      title: selectedTitle,
      deadline: selectedDeadline,
      // 发起流程时允许临时调整急件标记，仅写入流程变量和流程中间表。
      urgencyLevel: selectedUrgencyLevel,
    };

    const params = {
      intervalType: options.intervalType,
      startCount: options.startCount,
      taskTask: {
        //重复督办字段
        triggerType: options.triggerType,
        startTime: options.intervalStartTime,
        //流程相关字段
        flowCode: FLOW_CODE,
        formUrl: FORM_URL,
        flowName: props.flowName,
        jsonData: flowJsonData,
        //台账相关字段
        businessTablename: BUSINESS_TABLE_NAME,
        businessId: record.id,
        title: selectedTitle,
        content: record.content,
        urgencyLevel: selectedUrgencyLevel,
        deptId: options.deptId || defaultDeptIds,
        deptLeaderId: record.responDeptid,
        requireFinishDate: formatDate(selectedDeadline, 'YYYY-MM-DD'),
        deadline: formatDeadlineDateTime(selectedDeadline),
      },
    };

    await startProcessSchedules(params);
    await saveOrUpdate({ id: record.id, bpmStatus: '2', superviseCount: nextSuperviseCount, meetingType: currentMeetingType }, true);
    handleSuccess();
  }

  async function handlePreviewPic(record) {
    bpmPicModal(true, {
      flowCode: FLOW_CODE,
      dataId: record.id,
    });
  }
  /* ----------------------以下为原生查询需要添加的-------------------------- */
  const toggleSearchStatus = ref<boolean>(false);
  const labelCol = reactive({
    xs:24,
    sm:4,
    xl:6,
    xxl:4
  });
  const wrapperCol = reactive({
    xs: 24,
    sm: 20,
  });

  /**
   * 重置
   */
  function searchReset() {
    formRef.value?.resetFields();
    clearQueryParams();
    selectedRowKeys.value = [];
    resetFeedbackExpand();
    //刷新数据
    reload({ page: 1 });
  }


  /**
   * form点击事件(以逗号分割)
   * @param key
   * @param value
   */
  function handleFormJoinChange(key, value) {
    if (typeof value != 'string') {
      queryParam[key] = value.join(',');
    }
  }
</script>

<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    padding: 0;
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust{
      min-width: 100px !important;
    }
    .query-group-split-cust{
      width: 30px;
      display: inline-block;
      text-align: center;
    }

    .ant-form-item:not(.ant-form-item-with-help) {
      margin-bottom: 16px;
      height: 32px;
    }

    :deep(.ant-picker),
    :deep(.ant-input-number) {
      width: 100%;
    }
  }

  .erpNativeList {
    height: 100%;

    .content {
      background-color: #fff;
      // 内容区高度由表格自适应撑开，避免覆盖页面底部 footer。
      height: auto;
    }

    .feedback-expand-table {
      margin: 4px 10px 12px 42px;
      padding: 12px 14px 14px;
      background: #f6fbff;
      border: 1px solid #d6e8ff;
      border-left: 4px solid #1677ff;
      border-radius: 6px;
      box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.72);

      .feedback-expand-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 12px;
        margin-bottom: 10px;
      }

      .feedback-expand-title {
        display: inline-flex;
        align-items: center;
        min-width: 0;
        color: #1f2937;
        font-size: 14px;
        font-weight: 600;
        line-height: 24px;
      }

      .feedback-expand-icon {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 24px;
        height: 24px;
        margin-right: 8px;
        color: #1677ff;
        background: #e6f4ff;
        border-radius: 50%;
      }

      .feedback-expand-count {
        margin-left: 10px;
      }

      .feedback-expand-desc {
        color: #64748b;
        font-size: 13px;
        line-height: 22px;
        white-space: nowrap;
      }

      :deep(.jeecg-basic-table) {
        background: #fff;
      }

      :deep(.feedback-inner-table .ant-table-wrapper) {
        padding: 0;
        border-radius: 4px;
      }

      :deep(.feedback-inner-table .ant-table-thead > tr > th) {
        background: #eef6ff;
        color: #334155;
        font-weight: 600;
      }

      :deep(.feedback-inner-table .ant-table-tbody > tr > td) {
        background: #fff;
      }

      :deep(.feedback-inner-table .ant-table-tbody > tr:hover > td) {
        background: #f8fbff;
      }

      .feedback-attachment-list {
        min-width: 300px;

        :deep(.file-list-wrapper) {
          min-height: 0 !important;
          padding: 4px 8px !important;
        }

        :deep(.ant-spin-nested-loading),
        :deep(.ant-spin-container) {
          min-height: 0 !important;
          line-height: 20px;
        }

        :deep(.file-list-header) {
          margin-bottom: 6px;
          padding-bottom: 6px;
        }

        :deep(.file-list .file-item) {
          padding: 8px;
          margin-bottom: 6px;
        }

        :deep(.ant-empty) {
          margin: 0 !important;
          display: flex;
          align-items: center;
          min-height: 20px;
          text-align: left;
        }

        :deep(.ant-empty-image) {
          display: none !important;
        }

        :deep(.ant-empty-description) {
          color: #94a3b8;
          font-size: 12px;
          line-height: 20px;
        }
      }
    }
  }
</style>
