/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-09-14 11:32:17
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/pubDicTypeMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

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

import { createFromIconfontCN } from '@ant-design/icons';
import {
  ActionType,
  ProFormDependency,
  ProFormInstance,
  ProFormText,
  ProFormSelect,
} from '@ant-design/pro-components';
import { ModalForm, ProFormDigit } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, Popover, Switch, Tooltip } from 'antd';
import { useEffect, useRef, useState } from 'react';

import 'moment/locale/zh-cn';

import {
  addData,
  delData,
  editData,
  getApportionmentLevelListNoPage,
  getResponsibilityCenterList,
  getResponsibilityTypeReq,
  getStandardShareLevelReq,
} from './service';

import './style.less';

import { renameChildListToChildren } from '@/utils/tooljs';

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

let selectableLevelList: any[] = [];
let currentRow: any = undefined;

export const searchTree = (tree: any[], searchTerm: string) => {
  const searchTermLower = searchTerm.toLowerCase();

  function searchNode(node: any) {
    const matchedChildren: any[] = [];

    if (node.children && node.children.length > 0) {
      node.children.forEach((child: any) => {
        const matchedChild = searchNode(child);
        if (matchedChild) {
          matchedChildren.push(matchedChild);
        }
      });
    }

    if (
      node.responsibilityName.toLowerCase().includes(searchTermLower) ||
      (node.responsibilityCode &&
        node.responsibilityCode.toLowerCase().includes(searchTermLower))
    ) {
      return {
        ...node,
        children: matchedChildren.length > 0 ? matchedChildren : node.children,
      };
    } else if (matchedChildren.length > 0) {
      return {
        ...node,
        children: matchedChildren,
      };
    }

    return null;
  }

  return tree
    .map((rootNode) => searchNode(rootNode))
    .filter((node) => node !== null);
};

export default function ResponsibilityCenter() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >();
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const tableRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const columns: ProColumns[] = [
    {
      title: '责任中心名称',
      dataIndex: 'responsibilityName',
      ellipsis: true,
      width: 200,
      fixed: 'left',
      renderText(_, record) {
        const { isDefault, responsibilityName, isGatherCenter } = record;
        // return isDefault == 1 ? <Tag>{`${responsibilityName}(是)`}</Tag> : responsibilityName
        return isDefault == 1 || isGatherCenter == 1 ? (
          isGatherCenter == 1 ? (
            <Popover content="汇总中心">
              {responsibilityName}{' '}
              <img
                style={{ width: 14, height: 14, position: 'relative', left: 6 }}
                src={require('../../../../../static/huizong.png')}
              />
            </Popover>
          ) : (
            <>
              {responsibilityName}
              <img
                style={{
                  width: 14,
                  height: 14,
                  position: 'relative',
                  top: -1,
                  left: 6,
                }}
                src={require('../../../../../static/moren.png')}
              />
            </>
          )
        ) : (
          responsibilityName
        );
      },
    },
    {
      title: '责任中心编码',
      ellipsis: true,
      dataIndex: 'responsibilityCode',
    },
    // {
    //     title: '是否汇总中心',
    //     dataIndex: 'isGatherCenter',
    //     renderText(_, record) {
    //         return <>{_ == 1 ? '是' : '否'}</>
    //     },
    // },
    {
      title: '责任类型',
      ellipsis: true,
      dataIndex: 'responsibilityType',
      renderText(num, record) {
        if (record.isGatherCenter != 1) {
          return num == 1
            ? '收益中心'
            : num == 2
            ? '成本(费用)中心'
            : '半收益中心';
        } else {
          return '-';
        }
      },
    },
    {
      title: '分摊级别',
      ellipsis: true,
      dataIndex: 'shareLevel',
      renderText(num, record) {
        if (record.isGatherCenter != 1) {
          return num;
        } else {
          return '-';
        }
      },
    },
    {
      title: '分摊级别名称',
      ellipsis: true,
      dataIndex: 'shareName',
      renderText(name, record) {
        if (record.isGatherCenter != 1) {
          return name;
        } else {
          return '-';
        }
      },
    },
    {
      title: '标准分级',
      ellipsis: true,
      dataIndex: 'standardShareLevelName',
      renderText(name, record) {
        if (record.isGatherCenter != 1) {
          return name;
        } else {
          return '-';
        }
      },
    },
    {
      title: '责任中心类型',
      ellipsis: true,
      dataIndex: 'typeName',
      renderText(name, record) {
        if (record.isGatherCenter != 1) {
          return name;
        } else {
          return '-';
        }
      },
    },
    {
      title: '序号',
      ellipsis: true,
      dataIndex: 'sort',
    },
    {
      title: () => (
        <>
          启用
          <Tooltip title="停用的责任中心在科室损益计算界面及科室损益报表里不显示">
            <IconFont
              style={{
                paddingLeft: 6,
                fontSize: 16,
                position: 'relative',
                top: 1,
              }}
              type="iconshuoming"
            />
          </Tooltip>
        </>
      ),
      dataIndex: 'status',
      fixed: 'right',
      width: 90,
      renderText(number, record) {
        const { isGatherCenter } = record;
        return isGatherCenter != 1 ? (
          <Switch
            checked={number}
            size="small"
            onChange={(bool) => {
              updateTable({ ...record, status: bool ? 1 : 0 }, 'EDIT');
            }}
          />
        ) : (
          <></>
        );
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 120,
      fixed: 'right',
      valueType: 'option',
      render: (_: any, record: any) => {
        const { isGatherCenter } = record;
        return isGatherCenter == 1
          ? [
              <UpDataActBtn key={'act'} record={record} type="ADDCHILD" />,
              <UpDataActBtn key={'act1'} record={record} type="EDIT" />,
              <Popconfirm
                title="是否确认删除？"
                key="del"
                onConfirm={() => delTableData(record)}
              >
                <a>删除</a>
              </Popconfirm>,
            ]
          : [
              <UpDataActBtn key={'act2'} record={record} type="EDIT" />,
              <Popconfirm
                title="是否确认删除？"
                key="del"
                onConfirm={() => delTableData(record)}
              >
                <a>删除</a>
              </Popconfirm>,
            ];
      },
    },
  ];

  const getTableData = async (params: any) => {
    const { filter } = params;
    const resp = await getResponsibilityCenterList({ ...params });
    if (resp) {
      let data = [];

      if (filter) {
        const result = searchTree(
          renameChildListToChildren(resp.list, 'child'),
          filter,
        );
        data = result;
      } else {
        data = renameChildListToChildren(resp.list, 'child');
      }

      return {
        data: data,
        success: true,
        total: resp.totalCount,
        pageSize: resp.pageSize,
        totalPage: resp.totalPage,
      };
    }
    return [];
  };

  const delTableData = async (record: any) => {
    const resp = await delData(record.id);
    if (resp) {
      message.success('操作成功！');
      tableRef.current?.reload();
      // message.success('操作成功!');
    }
  };

  const updateTable = async (
    formVal: any,
    type: 'EDIT' | 'ADD' | 'ADDCHILD',
  ) => {
    if (type == 'ADD' || type == 'ADDCHILD') {
      let id = 0;
      type == 'ADDCHILD' && (id = formVal.id);

      const { isDefault = 0, selectedSharelevel } = formVal;

      const result = {
        responsibilityType: 1,
        ...formVal,
        shareName: selectedSharelevel ? selectedSharelevel.shareName : '',
        shareId: selectedSharelevel ? selectedSharelevel.id : 0,
        shareLevel: selectedSharelevel ? selectedSharelevel.leverSort : 0,
        isDefault,
        id,
        selectedSharelevel: null,
      };

      const resp = await addData(result);
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }
    if (type == 'EDIT') {
      try {
        const {
          responsibilityLevel = 0,
          selectedSharelevel,
          shareId,
        } = formVal;
        let body = {};
        if (!selectedSharelevel) {
          //没有修改分摊层级
          body = { responsibilityType: 1, ...formVal };
        }

        if (
          Object.prototype.toString.call(selectedSharelevel) ==
          '[object Object]'
        ) {
          //修改了分摊层级
          //  console.log('修改了分摊层级');
          body = {
            responsibilityType: 1,
            ...formVal,
            shareId: selectedSharelevel.id,
            shareName: selectedSharelevel.shareName,
            shareLevel: selectedSharelevel.leverSort,
            selectedSharelevel: null,
          };
        }

        const resp = await editData({ ...body });
        if (resp) {
          tableRef.current?.reload();
          message.success('操作成功！');
        }
      } catch (error) {
        console.log({ error });
      }
    }
    return true;
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD' | 'ADDCHILD';
  }) => {
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}责任中心`}
        width={350}
        formRef={formRef}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
              }
            : { selectedSharelevel: 0, sort: 0 }
        }
        trigger={
          type == 'EDIT' ? (
            <a key="edit">编辑</a>
          ) : type == 'ADDCHILD' ? (
            <a className="add">添加</a>
          ) : (
            <span className="add">新增</span>
          )
        }
        onFinish={(val) => {
          return updateTable(
            type == 'EDIT'
              ? { ...record, ...val }
              : type == 'ADDCHILD'
              ? { ...val, id: record.id }
              : { ...val },
            type,
          );
        }}
        modalProps={{ destroyOnClose: true }}
        colProps={{ span: 24 }}
        grid
      >
        <ProFormText name="selectedSharelevel" hidden />
        <ProFormSelect
          disabled={type == 'EDIT'}
          rules={[
            {
              required: true,
              message: '请选择是否为汇总中心',
            },
          ]}
          options={[
            {
              value: 1,
              label: '是',
            },
            {
              value: 2,
              label: '否',
            },
          ]}
          name="isGatherCenter"
          label="是否汇总中心"
        />

        <ProFormText
          label="责任中心名"
          rules={[
            {
              required: true,
              message: '责任中心名是必填项',
            },
          ]}
          name="responsibilityName"
        />
        <ProFormText
          label="责任中心编码"
          rules={[
            {
              required: true,
              message: '责任中心编码是必填项',
            },
          ]}
          name="responsibilityCode"
        />

        <ProFormDependency name={['isGatherCenter']}>
          {({ isGatherCenter }) => {
            return isGatherCenter == 2 ? (
              <ProFormSelect
                rules={[
                  {
                    required: true,
                    message: '请选择是否默认责任中心',
                  },
                ]}
                options={[
                  {
                    value: 1,
                    label: '是',
                  },
                  {
                    value: 0,
                    label: '否',
                  },
                ]}
                width="sm"
                name="isDefault"
                label="是否默认责任中心"
              />
            ) : (
              <></>
            );
          }}
        </ProFormDependency>

        <ProFormDependency name={['isGatherCenter']}>
          {({ isGatherCenter }) => {
            return (
              isGatherCenter != 1 && (
                <>
                  <ProFormSelect
                    rules={[
                      {
                        required: true,
                        message: '请选择责任类别',
                      },
                    ]}
                    options={[
                      {
                        value: 1,
                        label: '收益中心',
                      },
                      {
                        value: 2,
                        label: '成本(费用)中心',
                      },
                      {
                        value: 3,
                        label: '半收益中心',
                      },
                    ]}
                    name="responsibilityType"
                    label="选择责任类别"
                  />
                  <ProFormSelect
                    rules={[
                      {
                        required: true,
                        message: '请选择分摊级别',
                      },
                    ]}
                    fieldProps={{
                      onChange: (val) => {
                        const needItem = selectableLevelList.filter(
                          (item: any) => item.leverSort == val,
                        );
                        console.log({ needItem });
                        if (formRef.current) {
                          formRef.current.setFieldsValue({
                            selectedSharelevel: needItem[0],
                          });
                        }
                      },
                    }}
                    request={async () => {
                      const resp = await getApportionmentLevelListNoPage();
                      if (resp) {
                        selectableLevelList = resp.list;
                        return resp.list.map((item: any) => ({
                          label: `级别${item.leverSort}-${item.shareName}`,
                          value: item.leverSort,
                        }));
                      } else {
                        return [];
                      }
                    }}
                    name="shareLevel"
                    label="选择分摊级别"
                  />
                  <ProFormSelect
                    rules={[
                      {
                        required: true,
                        message: '请选择标准分级',
                      },
                    ]}
                    request={async () => {
                      const resp = await getStandardShareLevelReq();
                      if (resp) {
                        return resp.map((a: any) => ({
                          label: a.name,
                          value: a.code,
                        }));
                      }
                      return [];
                    }}
                    name="standardShareLevel"
                    label="标准分级"
                  />
                  <ProFormSelect
                    rules={[
                      {
                        required: true,
                        message: '请选择责任中心类型',
                      },
                    ]}
                    request={async () => {
                      const resp = await getResponsibilityTypeReq();
                      if (resp) {
                        return resp.map((a: any) => ({
                          label: a.name,
                          value: a.code,
                        }));
                      }
                      return [];
                    }}
                    name="type"
                    label="责任中心类型"
                  />
                </>
              )
            );
          }}
        </ProFormDependency>
        <ProFormDigit
          label="顺序号"
          rules={[
            {
              required: true,
              message: '顺序号是必填项',
            },
          ]}
          name="sort"
        />
      </ModalForm>
    );
  };

  const tableDataSearchHandle = (paramName: string) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      [`${paramName}`]: tableDataSearchKeywords,
    });
  };

  useEffect(() => {}, []);

  return (
    <KCIMPagecontainer className="ResponsibilityCenter" title={false}>
      <div className="toolBar">
        <div className="filter">
          <div className="filterItem">
            <span className="label" style={{ whiteSpace: 'nowrap' }}>
              {' '}
              检索：
            </span>
            <Input
              placeholder={'责任中心编码/名称'}
              allowClear
              autoComplete="off"
              suffix={
                <IconFont
                  type="iconsousuo"
                  style={{ color: '#99A6BF' }}
                  onClick={() => tableDataSearchHandle('filter')}
                />
              }
              onChange={(e) => {
                set_tableDataSearchKeywords(e.target.value);
                if (e.target.value.length == 0) {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    filter: '',
                  });
                }
              }}
              onPressEnter={(e) => {
                set_tableDataFilterParams({
                  ...tableDataFilterParams,
                  filter: (e.target as HTMLInputElement).value,
                });
              }}
            />
          </div>
        </div>
        <div className="btnGroup">
          <UpDataActBtn record type="ADD" />
        </div>
      </div>

      <div style={{ marginTop: 16 }}>
        <KCIMTable
          columns={columns as ProColumns[]}
          scroll={{ x: 1500, y: 'calc(100vh - 232px)' }}
          actionRef={tableRef}
          rowKey="responsibilityCode"
          params={tableDataFilterParams}
          request={(params) => getTableData(params)}
        />
      </div>
    </KCIMPagecontainer>
  );
}
