/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-09-09 10:54:09
 * @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,
  ProFormDigit,
} from '@ant-design/pro-components';
import { ModalForm, ProFormCascader } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, Form, Select } from 'antd';
import { Key, useEffect, useRef, useState } from 'react';

import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';

import {
  addData,
  delData,
  editData,
  getAccountList,
  getIdleCostTableList,
  getIdleResponsibleList,
  getShareParamList,
} from './service';

import './style.less';
import { getAccountingSubjectList } from '../../accountingAccountSet/accountingSubMana/service';
import { getCostshareparamList } from '../costAllocationParamsSet/service';

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

function filterTree(trees: any[]) {
  // 递归筛选函数
  function filterNode(node: any) {
    // 如果是叶子节点，直接根据条件返回节点或null
    if (!node.children || node.children.length === 0) {
      return node.isBaseCost === 1 ? { ...node } : null;
    }

    // 对于非叶子节点，先递归筛选子节点
    const filteredChildren = node.children
      .map(filterNode)
      .filter((child: any) => child !== null);

    // 如果子节点中有被保留的，或者当前节点自身满足条件，保留当前节点
    // 注意这里的改变：我们不再检查非叶子节点是否直接满足条件，而是基于其子节点是否被保留
    if (filteredChildren.length > 0) {
      return { ...node, children: filteredChildren };
    } else {
      // 如果没有子节点被保留，且当前节点不满足条件，返回null
      return null;
    }
  }

  // 遍历树结构集合并应用筛选函数
  return trees.map(filterNode).filter((root) => root !== null);
}

export default function IdleCostSetting() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >({ accountType: 1 });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const tableRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [currentRow, setCurrentRow] = useState<any | undefined>(undefined);
  const [selectableLevelList, setSelectableLevelList] = useState<any[]>([]); //可选的分摊层级列表

  const columns: ProColumns[] = [
    {
      title: '闲置成本项目',
      dataIndex: 'freeAccountName',
    },
    {
      title: '设备成本项目',
      dataIndex: 'accountName',
    },
    {
      title: '可检查时间参数',
      dataIndex: 'canParamName',
    },
    {
      title: '实际检查时间参数',
      dataIndex: 'actualParamName',
    },
    {
      title: '归属责任中心',
      dataIndex: 'freeResponsibilityName',
    },
    {
      title: '操作',
      key: 'option',
      width: 90,
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <UpDataActBtn key={'act'} record={record} type="EDIT" />,
          <Popconfirm
            title="是否确认删除？"
            key="del"
            onConfirm={() => delTableData(record)}
          >
            <a>删除</a>
          </Popconfirm>,
        ];
      },
    },
  ];

  const getTableData = async (params: any) => {
    const resp = await getIdleCostTableList({ ...params });
    if (resp) {
      return {
        data: resp,
        success: true,
        // total: resp.totalCount,
        // pageSize: resp.pageSize,
        // totalPage: resp.totalPage,
      };
    }
    return [];
  };

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

  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') => {
    const {
      freeAccount = [],
      account,
      canParam,
      actualParam,
      freeResponsibility,
    } = formVal;
    const result = {
      freeAccountCode: freeAccount.accountingCode,
      freeAccountName: freeAccount.accountingName,
      accountCode: account.accountingCode,
      accountName: account.accountingName,
      canParamCode: canParam.shareParamCode,
      canParamName: canParam.shareParamName,
      actualParamCode: actualParam.shareParamCode,
      actualParamName: actualParam.shareParamName,
      freeResponsibilityName: freeResponsibility.responsibilityName,
      freeResponsibilityCode: freeResponsibility.responsibilityCode,
    };

    if (type == 'ADD') {
      const resp = await addData(result);
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }
    if (type == 'EDIT') {
      try {
        const { id } = formVal;
        const resp = await editData({ ...result, id });
        if (resp) {
          tableRef.current?.reload();
          message.success('操作成功！');
        }
      } catch (error) {
        console.log({ error });
      }
    }
    return true;
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD';
  }) => {
    setCurrentRow(record);
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}闲置成本对应`}
        width={350}
        formRef={formRef}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
                freeAccount: record.freeAccountCode,
                account: record.accountCode,
                canParam: record.canParamCode,
                actualParam: record.actualParamCode,
                freeResponsibility: record.freeResponsibilityCode,
              }
            : {}
        }
        trigger={
          type == 'EDIT' ? (
            <a key="edit">编辑</a>
          ) : (
            <span className="add">新增</span>
          )
        }
        onFinish={(val) => {
          return updateTable(
            type == 'EDIT' ? { ...record, ...val } : { ...val },
            type,
          );
        }}
        modalProps={{ destroyOnClose: true }}
        colProps={{ span: 24 }}
        grid
      >
        {/* <ProFormText name='freeAccount' hidden />
                <ProFormText name='account' hidden /> */}
        {/* <ProFormCascader
                    rules={[
                        {
                            required: true,
                            message: '请选择闲置成本项目',
                        },
                    ]}
                    request={async ()=>{
                         const resp = await getAccountList({accountType: 2,pageSize:500,current:1});
                         return filterTree(resp.list)
                    }}

                    fieldProps={{
                        // searchValue:'accountingName',
                        showSearch:true,
                        fieldNames:{label:'accountingName',value:'accountingCode',children:'children'},
                        onChange:(value:any, selectedOptions:any)=>{
                            formRef.current?.setFieldValue('freeAccount',selectedOptions)
                        }
                    }}
                    name='freeCostItem'
                    label="闲置成本项目"
                />
                <ProFormCascader
                    rules={[
                        {
                            required: true,
                            message: '请选择设备成本项目',
                        },
                    ]}
                    request={async ()=>{
                         const resp = await getAccountingSubjectList({accountType: 2,pageSize:500,current:1});
                         return filterTree(resp.list)
                    }}
                
                    fieldProps={{
                        showSearch:true,
                        fieldNames:{label:'accountingName',value:'accountingCode',children:'children'},
                        onChange:(value:any, selectedOptions:any)=>{
                            formRef.current?.setFieldValue('account',selectedOptions)
                        }
                    }}
                    name='equipmentCostItem'
                    label="设备成本项目"
                /> */}
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '请选择闲置成本项目',
            },
          ]}
          request={async () => {
            const resp = await getAccountList({ pageSize: 500, current: 1 });
            return resp;
          }}
          fieldProps={{
            labelInValue: true,
            showSearch: true,
            fieldNames: { label: 'accountingName', value: 'accountingCode' },
          }}
          name="freeAccount"
          label="闲置成本项目"
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '请选择设备成本项目',
            },
          ]}
          request={async () => {
            const resp = await getAccountList({ pageSize: 500, current: 1 });
            return resp;
          }}
          fieldProps={{
            labelInValue: true,
            showSearch: true,
            fieldNames: { label: 'accountingName', value: 'accountingCode' },
          }}
          name="account"
          label="设备成本项目"
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '请选择可检查时间参数',
            },
          ]}
          request={async () => {
            const resp = await getShareParamList({ pageSize: 500, current: 1 });
            return resp;
          }}
          fieldProps={{
            labelInValue: true,
            showSearch: true,
            fieldNames: { label: 'shareParamName', value: 'shareParamCode' },
          }}
          name="canParam"
          label="可检查时间参数"
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '请选择实际检查时间参数',
            },
          ]}
          request={async () => {
            const resp = await getShareParamList({ pageSize: 500, current: 1 });
            return resp;
          }}
          fieldProps={{
            labelInValue: true,
            showSearch: true,
            fieldNames: { label: 'shareParamName', value: 'shareParamCode' },
          }}
          name="actualParam"
          label="实际检查时间参数"
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '请选择归属责任中心',
            },
          ]}
          request={async () => {
            const resp = await getIdleResponsibleList({
              pageSize: 500,
              current: 1,
            });
            return resp;
          }}
          fieldProps={{
            labelInValue: true,
            showSearch: true,
            fieldNames: {
              label: 'responsibilityName',
              value: 'responsibilityCode',
            },
          }}
          name="freeResponsibility"
          label="归属责任中心"
        />
      </ModalForm>
    );
  };

  return (
    <KCIMPagecontainer className="IdleCostSetting" 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>
        <KCIMTable
          scroll={{ y: `calc(100vh - 234px)` }}
          columns={columns as ProColumns[]}
          actionRef={tableRef}
          rowKey="id"
          params={tableDataFilterParams}
          request={(params) => getTableData(params)}
        />
      </div>
    </KCIMPagecontainer>
  );
}
