/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2025-04-16 10:09:18
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-07-09 18:55:02
 * @FilePath: /pfmBackMana/src/pages/checkConditionMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

/*
 * @Description: 条件管理页面
 */

import { createFromIconfontCN } from '@ant-design/icons';
import {
  ActionType,
  ProColumns,
  ProFormInstance,
} from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormRadio,
  ProFormTreeSelect,
} from '@ant-design/pro-form';
import { Button, Empty, Input, message, Popconfirm, Tabs, Tooltip } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

import {
  addCondition,
  delCondition,
  editCondition,
  getConditionDeptClassList,
  getConditionList,
  saveConditionDeptClass,
} from './service';

import './style.less';

import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';

const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

// 定义表单样式
const formItemLayout = {
  style: { marginBottom: '8px' },
};

export default function CheckConditionMana() {
  const [tableDataFilterParams, setTableDataFilterParams] = useState<
    any | undefined
  >();
  const [tableDataSearchKeywords, setTableDataSearchKeywords] =
    useState<string>('');
  const tableRef = useRef<ActionType>();
  const [activeTab, setActiveTab] = useState('系统追踪');

  // 分类相关状态
  const [classifyModalVisible, setClassifyModalVisible] = useState(false);
  const [classifyRecord, setClassifyRecord] = useState<any>(null);
  const [classifyList, setClassifyList] = useState<any[]>([]);
  const [classifyLoading, setClassifyLoading] = useState(false);
  const [selectedClassifyIds, setSelectedClassifyIds] = useState<React.Key[]>(
    [],
  );



  // 条件列表数据，用于子项选择
  const [conditionOptions, setConditionOptions] = useState<any[]>([]);

  // 选项卡项目
  const tabItems = [
    { label: '系统追踪', key: '系统追踪' },
    { label: '个案追踪', key: '个案追踪' },
  ];

  // 诊别选项
  const typeOptions = [
    { label: '门诊', value: 1 },
    { label: '急诊', value: 2 },
  ];

  // 是否选项
  const yesNoOptions = [
    { label: '否', value: 0 },
    { label: '是', value: 1 },
  ];

  // 选择类型选项
  const multipleOptions = [
    { label: '不选', value: 0 },
    { label: '单选', value: 1 },
    { label: '多选', value: 2 },
  ];

  // 系统追踪表格列定义
  const systemColumns: ProColumns[] = [
    {
      title: '条件名称',
      dataIndex: 'name',
    },
    {
      title: '诊别',
      dataIndex: 'depType',
      width: 100,
      valueEnum: {
        1: { text: '门诊' },
        2: { text: '急诊' },
      },
    },
    {
      title: '自查督查',
      dataIndex: 'checkType',
      width: 100,
      valueEnum: {
        0: { text: '否' },
        1: { text: '是' },
      },
    },
    {
      title: '顺序号',
      dataIndex: 'sortNo',
      width: 80,
    },
    {
      title: '单位分类',
      dataIndex: 'deptClassList',
      render: (_, record) => {
        if (record.deptClassList && record.deptClassList.length > 0) {
          return record.deptClassList
            .map((item: any) => item.deptClassName)
            .join(', ');
        }
        return '-';
      },
    },
    {
      title: '说明',
      dataIndex: 'description',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'option',
      width: 180,
      valueType: 'option',
      render: (_: any, record: any) => {
        // 判断是否有子项
        const hasChildren = record.children && record.children.length > 0;
        // 判断是否已选择单位分类
        const hasDeptClass =
          record.deptClassList && record.deptClassList.length > 0;

        return (
          <div className="operationBtns">
            {hasChildren ? (
              <Tooltip title="已添加子项，不可设置单位分类">
                <span className="disabled-btn">分类</span>
              </Tooltip>
            ) : (
              <a onClick={() => handleClassify(record)}>分类</a>
            )}

            {hasDeptClass ? (
              <Tooltip title="已选单位分类，不可添加子项">
                <span className="disabled-btn">添加</span>
              </Tooltip>
            ) : (
              <UpDataActBtn 
                record={null} 
                type="ADD" 
                parentRecord={{
                  id: record.id,
                  name: record.name,
                  hasChildren: record.children && record.children.length > 0,
                }}
                triggerText="添加"
              />
            )}

            <UpDataActBtn record={record} type="EDIT" />
            <Popconfirm
              title={`确定要删除该条件吗?${hasChildren ? '（包括所有子项）' : ''}`}
              onConfirm={() => handleDelete(record.id, record)}
              okText="确定"
              cancelText="取消"
            >
              <a>删除</a>
            </Popconfirm>
          </div>
        );
      },
    },
  ];

  // 个案追踪表格列定义
  const caseColumns: ProColumns[] = [
    {
      title: '条件名称',
      dataIndex: 'name',
    },
    {
      title: '条件设置',
      dataIndex: 'code',
      width: 120,
      render: (text: any, record: any) => {
        const tags = [];

        // 添加初显标签
        if (record.initialize === 1) {
          tags.push(
            <span key="initialize" className="tag-gray">
              初显
            </span>,
          );
        }

        // 添加选择类型标签
        if (record.multiple === 1) {
          tags.push(
            <span key="multiple" className="tag-blue">
              单选
            </span>,
          );
        } else if (record.multiple === 2) {
          tags.push(
            <span key="multiple" className="tag-blue">
              多选
            </span>,
          );
        }

        // 添加必填标签
        if (record.required === 1) {
          tags.push(
            <span key="required" className="tag-red">
              必填
            </span>,
          );
        }

        return <div style={{ marginTop: '4px' }}>{tags}</div>;
      },
    },
    {
      title: '序列号',
      dataIndex: 'sortNo',
      width: 80,
    },
    {
      title: '子项',
      dataIndex: 'children',
      width: 80,
      render: (_, record) => {
        if (record.children && record.children.length > 0) {
          return record.children.length;
        }
        return '-';
      },
    },
    {
      title: '单位分类',
      dataIndex: 'deptClassList',
      width: 150,
      render: (_, record) => {
        if (record.deptClassList && record.deptClassList.length > 0) {
          return record.deptClassList
            .map((item: any) => item.deptClassName)
            .join(', ');
        }
        return '-';
      },
    },
    {
      title: '说明',
      dataIndex: 'description',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'option',
      width: 180,
      valueType: 'option',
      render: (_: any, record: any) => {
        // 判断是否有子项
        const hasChildren = record.children && record.children.length > 0;
        // 判断是否已选择单位分类
        const hasDeptClass =
          record.deptClassList && record.deptClassList.length > 0;

        return (
          <div className="operationBtns">
            {hasChildren ? (
              <Tooltip title="已添加子项，不可设置单位分类">
                <span className="disabled-btn">分类</span>
              </Tooltip>
            ) : (
              <a onClick={() => handleClassify(record)}>分类</a>
            )}

            {hasDeptClass ? (
              <Tooltip title="已选单位分类，不可添加子项">
                <span className="disabled-btn">添加</span>
              </Tooltip>
            ) : (
              <UpDataActBtn 
                record={null} 
                type="ADD" 
                parentRecord={{
                  id: record.id,
                  name: record.name,
                  hasChildren: record.children && record.children.length > 0,
                }}
                triggerText="添加"
              />
            )}

            <UpDataActBtn record={record} type="EDIT" />
            <Popconfirm
              title={`确定要删除该条件吗?${hasChildren ? '（包括所有子项）' : ''}`}
              onConfirm={() => handleDelete(record.id, record)}
              okText="确定"
              cancelText="取消"
            >
              <a>删除</a>
            </Popconfirm>
          </div>
        );
      },
    },
  ];

  // 获取表格数据
  const getTableData = async (params: any) => {
    // 根据当前选项卡设置conditionType
    const conditionType = activeTab === '系统追踪' ? 1 : 0;
    const resp = await getConditionList({
      ...params,
      conditionType,
      filter: tableDataSearchKeywords || undefined,
    });
    if (resp) {
      return {
        data: resp,
        success: true,
      };
    }
    return { data: [], success: false };
  };

  // 处理分类
  const handleClassify = async (record: any) => {
    // 先重置状态
    setClassifyRecord(record);
    setSelectedClassifyIds([]);
    setClassifyList([]);
    setClassifyModalVisible(true);
    setClassifyLoading(true);

    try {
      const resp = await getConditionDeptClassList({
        filterConditionId: record.id,
      });

      if (resp) {
        // 先设置数据源
        setClassifyList(resp.itemList || []);
        
        // 然后设置选中项，确保数据类型正确
        const selectedIds = (resp.mapIdList || []).map((id: any) => String(id));
        
        // 使用 setTimeout 确保数据渲染完成后再设置选中状态
        setTimeout(() => {
          setSelectedClassifyIds(selectedIds);
        }, 100);
      }
    } catch (error) {
      console.error('获取分类列表失败:', error);
      message.error('获取分类列表失败');
    } finally {
      setClassifyLoading(false);
    }
  };

  // 处理分类保存
  const handleClassifySave = async () => {
    if (!classifyRecord) return;

    try {
      const resp = await saveConditionDeptClass({
        id: classifyRecord.id,
        mapIdList: selectedClassifyIds,
      });

      if (resp) {
        message.success('保存成功');
        setClassifyModalVisible(false);
        tableRef.current?.reload();
      }
    } catch (error) {
      console.error('保存分类失败:', error);
      message.error('保存分类失败');
    }
  };



  // 收集所有子项ID的递归函数
  const collectAllChildrenIds = (record: any): string[] => {
    let ids: string[] = [record.id];
    
    if (record.children && record.children.length > 0) {
      record.children.forEach((child: any) => {
        ids = ids.concat(collectAllChildrenIds(child));
      });
    }
    
    return ids;
  };

  // 处理删除
  const handleDelete = async (recordId: string, record?: any) => {
    // 如果有完整的record对象，收集所有需要删除的ID
    let idsToDelete: string[] = [recordId];
    
    if (record && record.children && record.children.length > 0) {
      idsToDelete = collectAllChildrenIds(record);
    }
    
    // 如果有子项，传递数组；否则传递单个ID
    const resp = await delCondition(idsToDelete.length > 1 ? idsToDelete : recordId);
    if (resp) {
      const deletedCount = idsToDelete.length;
      message.success(`删除成功！${deletedCount > 1 ? `(包括${deletedCount - 1}个子项)` : ''}`);
      tableRef.current?.reload();
    }
  };

  // 获取条件列表用于子项选择
  const getConditionOptionsForSubItem = async () => {
    const conditionType = activeTab === '系统追踪' ? 1 : 0;
    const resp = await getConditionList({ conditionType });
    if (resp) {
      setConditionOptions(resp);
    }
  };



  // 编辑/新增按钮组件
  const UpDataActBtn = ({
    record,
    type,
    parentRecord = null,
    triggerText,
  }: {
    record: any;
    type: 'EDIT' | 'ADD';
    parentRecord?: any;
    triggerText?: string;
  }) => {
    const formRef = useRef<ProFormInstance<any>>();

    // 系统追踪表单
    const renderSystemForm = () => (
      <>
        <ProFormText
          name="name"
          label="条件名称："
          placeholder="请输入"
          rules={[{ required: true, message: '条件名称不能为空!' }]}
          {...formItemLayout}
        />
        <ProFormRadio.Group
          name="depType"
          label="诊别："
          options={[
            { label: '门诊', value: 1 },
            { label: '急诊', value: 2 },
          ]}
          rules={[{ required: true, message: '请选择诊别!' }]}
          {...formItemLayout}
        />
        <ProFormRadio.Group
          name="checkType"
          label="自查督查："
          options={[
            { label: '否', value: 0 },
            { label: '是', value: 1 },
          ]}
          rules={[{ required: true, message: '请选择是否自查督查!' }]}
          {...formItemLayout}
        />
        <ProFormDigit
          name="sortNo"
          label="序号："
          placeholder="请输入"
          min={1}
          rules={[{ required: true, message: '请输入序号!' }]}
          {...formItemLayout}
        />
        <ProFormTextArea
          name="description"
          label="说明："
          placeholder="请输入"
          {...formItemLayout}
        />
      </>
    );

    // 个案追踪表单
    const renderCaseForm = () => (
      <>
        <ProFormText
          name="name"
          label="条件名称："
          placeholder="请输入"
          rules={[{ required: true, message: '条件名称不能为空!' }]}
          {...formItemLayout}
        />
        <ProFormRadio.Group
          name="required"
          label="必填："
          options={[
            { label: '否', value: 0 },
            { label: '是', value: 1 },
          ]}
          rules={[{ required: true, message: '请选择是否必填!' }]}
          {...formItemLayout}
        />
        <ProFormRadio.Group
          name="multiple"
          label="选择类型："
          options={[
            { label: '不选', value: 0 },
            { label: '单选', value: 1 },
            { label: '多选', value: 2 },
          ]}
          rules={[{ required: true, message: '请选择选择类型!' }]}
          {...formItemLayout}
        />
        <ProFormRadio.Group
          name="initialize"
          label="初显："
          options={[
            { label: '否', value: 0 },
            { label: '是', value: 1 },
          ]}
          rules={[{ required: true, message: '请选择是否初显!' }]}
          {...formItemLayout}
        />
        <ProFormTreeSelect
          name="subOptionId"
          label="子项："
          placeholder="请选择"
          allowClear
          fieldProps={{
            onFocus: () => {
              // 在获取焦点时加载数据，避免影响弹窗状态
              if (conditionOptions.length === 0) {
                getConditionOptionsForSubItem();
              }
            },
            showSearch: true,
            treeData: conditionOptions,
            fieldNames: { label: 'name', value: 'id', children: 'children' },
            dropdownStyle: { maxHeight: 400, overflow: 'auto' },
          }}
          {...formItemLayout}
        />
        <ProFormDigit
          name="sortNo"
          label="序号："
          placeholder="请输入"
          min={1}
          rules={[{ required: true, message: '请输入序号!' }]}
          {...formItemLayout}
        />
        <ProFormTextArea
          name="description"
          label="说明："
          placeholder="请输入"
          {...formItemLayout}
        />
        <ProFormDigit name="depType" hidden initialValue={1} />
        <ProFormDigit name="checkType" hidden initialValue={0} />
        <ProFormDigit name="subOptions" hidden initialValue={0} />
        <ProFormDigit name="parentId" hidden initialValue={0} />
        <ProFormText name="parentName" hidden initialValue="" />
      </>
    );

    return (
      <ModalForm
        title={`${
          type === 'EDIT' 
            ? '编辑' 
            : parentRecord 
            ? `添加子${activeTab === '系统追踪' ? '系统' : '个案'}条件 (${parentRecord.name})`
            : '新增'
        }${
          activeTab === '系统追踪' ? '系统条件' : '个案条件'
        }`}
        width={352}
        initialValues={
          type === 'EDIT'
            ? (() => {
                // 编辑时处理 subOptionId，如果为 0 则不设置该字段（显示为空）
                const editValues = { ...record };
                if (editValues.subOptionId === 0) {
                  delete editValues.subOptionId;
                }
                return editValues;
              })()
            : activeTab === '系统追踪'
            ? { depType: 1, checkType: 0, sortNo: 1 }
            : {
                required: 0,
                multiple: 0,
                initialize: 0,
                checkType: 0,
                sortNo: 1,
                parentId: parentRecord?.id || 0,
                parentName: parentRecord?.name || '',
                subOptions: parentRecord?.hasChildren ? 1 : 0,
                subOptionId: undefined, // 新增时默认为 undefined，不显示 0
                description: '',
                depType: 1,
              }
        }
        trigger={
          type === 'EDIT' ? (
            <a>修改</a>
          ) : triggerText ? (
            <a>{triggerText}</a>
          ) : (
            <span className="add">新增</span>
          )
        }
        onFinish={async (val: any) => {

          
          const conditionType = activeTab === '系统追踪' ? 1 : 0;
          
          // 准备表单数据
          let submitData = {
            ...val,
            conditionType,
          };
          
          // 个案追踪的子项逻辑处理（新增和编辑都需要）
          if (activeTab === '个案追踪') {
            // 处理子选项逻辑
            if (submitData.subOptionId && submitData.subOptionId !== 0) {
              // 如果选择了子项，设置subOptions为1
              submitData.subOptions = 1;
            } else {
              // 如果没有选择子项或清空了子项，重置相关字段
              submitData.subOptionId = 0;
              submitData.subOptions = 0;
            }
          }
          
          // 编辑时只传递需要的字段，避免传递多余字段
          if (type === 'EDIT') {
            // 编辑时：添加id，保持原有的父级关系
            submitData = {
              id: record.id,
              ...submitData,
              // 如果是个案追踪，需要保持原有的父级关系
              ...(activeTab === '个案追踪' && {
                parentId: record.parentId || 0,
                parentName: record.parentName || '',
              })
            };
          }

          
          // 直接调用接口，不走updateTable
          if (type === 'ADD') {
            // 如果是系统追踪，补充 parentId 和 parentName 字段
            if (activeTab === '系统追踪') {
              submitData = {
                ...submitData,
                parentId: parentRecord ? parentRecord.id : 0, // 有父级记录时使用父级id，否则为0
                parentName: parentRecord ? parentRecord.name : '', // 有父级记录时使用父级名称，否则为空
              };
            }
            const resp = await addCondition(submitData);
            if (resp) {
              tableRef.current?.reload();
              message.success('添加成功！');
            }
            return true;
          }
          if (type === 'EDIT') {
            const resp = await editCondition(submitData);
            if (resp) {
              tableRef.current?.reload();
              message.success('编辑成功！');
            }
            return true;
          }
        }}
        formRef={formRef}
        modalProps={{ destroyOnClose: true }}
        colProps={{ span: 24 }}
        grid
      >
        {activeTab === '系统追踪' ? renderSystemForm() : renderCaseForm()}
      </ModalForm>
    );
  };

  // 处理搜索
  const tableDataSearchHandle = () => {
    tableRef.current?.reload();
  };

  // 处理选项卡切换
  const handleTabChange = (key: string) => {
    setActiveTab(key);
    // 重置搜索条件
    setTableDataSearchKeywords('');
    setTableDataFilterParams({});
    // 切换选项卡后，重新加载数据
    tableRef.current?.reload();
  };

  // 组件初始化时预加载条件选项
  useEffect(() => {
    if (activeTab === '个案追踪') {
      getConditionOptionsForSubItem();
    }
  }, [activeTab]);

  // 自定义空状态
  const customizeRenderEmpty = () => (
    <div style={{ textAlign: 'center', padding: '50px 0' }}>
      <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
    </div>
  );

  // 渲染系统追踪内容
  const renderSystemTabContent = () => {
    return (
      <>
        <div className="toolBar">
          <div className="filter">
            <div className="filterItem" style={{ marginRight: 16, width: 250 }}>
              <span className="label">检索：</span>
              <Input
                placeholder="请输入条件名称"
                allowClear
                suffix={
                  <IconFont
                    type="iconsousuo"
                    style={{ color: '#99A6BF', cursor: 'pointer' }}
                    onClick={() => tableDataSearchHandle()}
                  />
                }
                onChange={(e) => {
                  setTableDataSearchKeywords(e.target.value);
                  if (e.target.value.length === 0) {
                    tableRef.current?.reload();
                  }
                }}
                onPressEnter={() => tableDataSearchHandle()}
              />
            </div>
          </div>
          <div className="btnGroup">
            <UpDataActBtn type="ADD" record={null} />
          </div>
        </div>

        <KCIMTable
          actionRef={tableRef}
          columns={systemColumns}
          request={getTableData}
          rowKey="id"
          search={false}
          locale={{ emptyText: customizeRenderEmpty() }}
          scroll={{ y: 'calc(100vh - 272px)' }}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
          }}
          expandable={{
            childrenColumnName: 'children',
            defaultExpandAllRows: true,
          }}
        />
      </>
    );
  };

  // 渲染个案追踪内容
  const renderCaseTrackingContent = () => {
    return (
      <>
        <div className="toolBar">
          <div className="filter">
            <div className="filterItem" style={{ marginRight: 16, width: 250 }}>
              <span className="label">检索：</span>
              <Input
                placeholder="请输入条件名称"
                allowClear
                suffix={
                  <IconFont
                    type="iconsousuo"
                    style={{ color: '#99A6BF', cursor: 'pointer' }}
                    onClick={() => tableDataSearchHandle()}
                  />
                }
                onChange={(e) => {
                  setTableDataSearchKeywords(e.target.value);
                  if (e.target.value.length === 0) {
                    tableRef.current?.reload();
                  }
                }}
                onPressEnter={() => tableDataSearchHandle()}
              />
            </div>
          </div>
          <div className="btnGroup">
            <UpDataActBtn type="ADD" record={null} />
          </div>
        </div>

        <KCIMTable
          actionRef={tableRef}
          columns={caseColumns}
          request={getTableData}
          rowKey="id"
          search={false}
          locale={{ emptyText: customizeRenderEmpty() }}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
          }}
          scroll={{ y: 'calc(100vh - 272px)' }}
          expandable={{
            childrenColumnName: 'children',
            defaultExpandAllRows: true,
          }}
        />
      </>
    );
  };



  return (
    <KCIMPagecontainer className="checkConditionMana" title={false}>
      <div
        style={{
          padding: '16px',
          background: '#fff',
          borderRadius: '4px',
          paddingTop: 0,
        }}
      >
        <Tabs
          activeKey={activeTab}
          items={tabItems}
          onChange={handleTabChange}
          className="condition-tabs"
        />

        {activeTab === '系统追踪'
          ? renderSystemTabContent()
          : renderCaseTrackingContent()}



        {/* 分类选择弹窗 */}
        <ModalForm
          className="TableSelecter"
          title={`选择单位分类 (${classifyRecord?.name || ''})`}
          width={352}
          submitter={{
            render: false,
          }}
          open={classifyModalVisible}
          modalProps={{
            closable: false,
          }}
        >
       
          <div>
            <Input
              placeholder="请输入"
              allowClear
              suffix={
                <IconFont style={{ color: '#99A6BF' }} type="iconsousuo" />
              }
              style={{ marginBottom: 8 }}
              onChange={(e) => {
                if (e.target.value.length === 0) {
                  // 重置搜索
                  if (classifyRecord) {
                    handleClassify(classifyRecord);
                  }
                } else {
                  // 本地搜索
                  const filteredList = classifyList.filter(
                    (item) => item.name.indexOf(e.target.value) !== -1,
                  );
                  setClassifyList(filteredList);
                }
              }}
            />

            <KCIMTable
              columns={[
                {
                  title: '单位分类名称',
                  dataIndex: 'name',
                  key: 'name',
                },
                {
                  title: '角色名称',
                  dataIndex: 'depTypeName',
                  key: 'depTypeName',
                },
              ]}
              options={{
                density: false,
                setting: false,
              }}
              rowKey={(record) => String(record.id)}
              scroll={{ y: 465 }}
              tableAlertRender={false}
              rowSelection={{
                selectedRowKeys: selectedClassifyIds,
                onChange: (newSelectedRowKeys: React.Key[]) => {
                  setSelectedClassifyIds(newSelectedRowKeys);
                },
              }}
              pagination={false}
              dataSource={classifyList}
              loading={classifyLoading}
            />

            <div className="footer">
              <span
                className="cancel"
                onClick={() => setClassifyModalVisible(false)}
              >
                取消
              </span>
              <span className="ok" onClick={handleClassifySave}>
                {`确认(${selectedClassifyIds.length})`}
              </span>
            </div>
          </div>
        </ModalForm>
      </div>
    </KCIMPagecontainer>
  );
}
