/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-02-06 15:59:31
 * @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,
  ProFormTextArea,
  ProFormTreeSelect,
} from '@ant-design/pro-components';
import { ModalForm } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, Tag, Tabs } from 'antd';
import { Key, SetStateAction, useEffect, useRef, useState } from 'react';

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

import {
  addData,
  copyParamsList,
  delData,
  editData,
  getCostshareparamConnectList,
  getResponsibilityCenterSelecterList,
  saveParamsList,
} from './service';

import './style.less';
import { getAccountingSubjectList } from '../../accountingAccountSet/accountingSubMana/service';
import { getChilds } from '@/utils/tooljs';
import EditTableModal from './editTableModal';
import TableSelecter from './tableSelector';

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

export default function AllocationParamsMap() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >(undefined);
  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([]); //可选的分摊层级列表
  const [tabs, set_tabs] = useState<any[]>([]);
  const [accountType, set_accountType] = useState<Key>(1);

  const [selectedResponsibilityId, setSelectedResponsibilityId] =
    useState(null);
  const [selectedResponsibility, setSelectedResponsibility] = useState(null);

  const [editTableVisible, set_editTableVisible] = useState(false);
  const [tableSelecterVisible, set_tableSelecterVisible] = useState(false);

  const columns: ProColumns[] = [
    {
      title: '分摊级别',
      width: 80,
      ellipsis: true,
      dataIndex: 'shareLevel',
    },
    {
      title: '责任中心编码',
      ellipsis: true,
      width: 120,
      dataIndex: 'responsibilityCode',
    },
    {
      title: '责任中心名',
      ellipsis: true,
      width: 120,
      dataIndex: 'responsibilityName',
    },
    {
      title: '分摊参数',
      ellipsis: true,
      dataIndex: 'shareParamMap',
    },
    {
      title: '会计科目名称',
      ellipsis: true,
      dataIndex: 'accountingNames',
    },
    {
      title: '会计科目编码',
      ellipsis: true,
      dataIndex: 'accountingCodes',
    },
    {
      title: '别名',
      ellipsis: true,
      width: 100,
      dataIndex: 'alias',
    },
    {
      title: '备注',
      ellipsis: true,
      width: 200,
      dataIndex: 'costNode',
    },
    {
      title: '操作',
      key: 'option',
      width: 200,
      fixed: 'right',
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <a
            key="copy"
            onClick={() => {
              set_tableSelecterVisible(true);
              setCurrentRow(record);
            }}
          >
            复制
          </a>,
          <UpDataActBtn key={'act'} record={record} type="EDIT" />,
          <Popconfirm
            title="是否确认删除？"
            key="del"
            onConfirm={() => delTableData(record)}
          >
            <a>删除</a>
          </Popconfirm>,
          <a
            key="share"
            onClick={() => {
              set_editTableVisible(true);
              setCurrentRow(record);
            }}
          >
            分摊参数
          </a>,
        ];
      },
    },
  ];

  const getTableData = async (params: any) => {
    const resp = await getCostshareparamConnectList({ ...params });
    if (resp) {
      return {
        data: resp.list,
        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') => {
    console.log({ formVal });
    try {
      const result = {
        responsibilityId: formVal.responsibilityId,
        accountingIds: formVal.accountingIds.join(','),
        isShareCost: formVal.isShareCost,
        alias: formVal.alias,
        costNode: formVal.costNode,
        responsibilityName: formVal.responsibility
          ? formVal.responsibility.responsibilityName
          : formVal.responsibilityName,
        shareLevel: formVal.responsibility
          ? formVal.responsibility.shareLevel
          : formVal.shareLevel,
        responsibilityCode: formVal.responsibility
          ? formVal.responsibility.responsibilityCode
          : formVal.responsibilityCode,
      };

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

    return true;
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD';
  }) => {
    const [ifDisable, setIfDisable] = useState(false);
    const [needDisableIds, set_needDisableIds] = useState<any[]>([]);

    let accountingIds: Key[] = record.accountingIdList
      ? record.accountingIdList.map((a: string) => Number(a))
      : [];

    useEffect(() => {
      if (type == 'EDIT' && needDisableIds.length > 0) {
        if (needDisableIds.includes(record.responsibilityId)) {
          setIfDisable(false);
        } else {
          setIfDisable(true);
        }
      }
    }, [needDisableIds]);

    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}成本分摊参数对应`}
        width={350}
        formRef={formRef}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
                accountings: record.accountingIdList
                  ? record.accountingIdList.map((a: string) => Number(a))
                  : [],
              }
            : {}
        }
        trigger={
          type == 'EDIT' ? (
            <a key="edit">编辑</a>
          ) : (
            <span className="add">新增</span>
          )
        }
        onFinish={(val) => {
          return updateTable(
            type == 'EDIT'
              ? { ...record, ...val, accountingIds }
              : { ...val, accountingIds },
            type,
          );
        }}
        modalProps={{ destroyOnClose: true }}
        colProps={{ span: 24 }}
        grid
      >
        <ProFormText name="responsibility" hidden />
        <ProFormText name="responsibility" hidden />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '请选择责任中心',
            },
          ]}
          fieldProps={{
            showSearch: true,
            onChange: async (val, option: any) => {
              const {} = option;
              const resp = await getResponsibilityCenterSelecterList();

              if (resp) {
                const selected = resp.filter((item: any) => item.id == val);
                if (selected[0]) {
                  formRef.current?.setFieldValue('responsibility', selected[0]);
                }
              }

              if (needDisableIds.includes(val)) {
                setIfDisable(false);
              } else {
                setIfDisable(true);
              }
            },
          }}
          request={async () => {
            const resp = await getResponsibilityCenterSelecterList();
            // const resp = [
            //     {
            //         calcType: 1,
            //         id: 401,
            //         responsibilityCode: "B0100",
            //         responsibilityId: 401,
            //         responsibilityName: "公共费用",
            //         shareId: 59,
            //         shareLevel: 1,
            //         shareName: "公共费用",
            //     }
            // ]
            if (resp) {
              let tempArr: any[] = [];
              const result = resp.map((item: any) => {
                if (item.calcType == 1) {
                  tempArr.push(item.id);
                }
                return {
                  label: item.responsibilityName,
                  value: item.id,
                };
              });
              set_needDisableIds((prevIds) => {
                if (
                  prevIds.length === tempArr.length &&
                  prevIds.every((id, index) => id === tempArr[index])
                ) {
                  return prevIds; // 保持原来的引用，不触发更新
                }
                return tempArr;
              });
              return result;
            }
            return [];
          }}
          name="responsibilityId"
          label="请选择责任中心"
        />
        <ProFormTreeSelect
          disabled={ifDisable}
          allowClear
          rules={[
            {
              required: ifDisable ? false : true,
              message: '请选择会计科目',
            },
          ]}
          request={async () => {
            const resp = await getAccountingSubjectList({
              accountType: 2,
              pageSize: 500,
              current: 1,
            });

            if (resp) {
              return resp.list;
            }
            return [];
          }}
          fieldProps={{
            showSearch: true,
            multiple: true,
            maxTagCount: 'responsive',
            maxTagPlaceholder: '...',
            treeCheckable: true,
            treeNodeFilterProp: 'accountingName',
            showCheckedStrategy: 'SHOW_CHILD',
            fieldNames: {
              label: 'accountingName',
              value: 'id',
            },
            onChange(value, labelList, extra) {
              // console.log({value,labelList,extra});
              accountingIds = value;
            },
            // onSelect: (value, opt) => {
            //     console.log({ value, opt });
            //     // console.log(getChilds(opt,'children'));
            //     if (opt.children && opt.children.length > 0) {
            //         const childs = getChilds(opt, 'children');
            //         const ids = childs.map((a) => a.id);
            //         accountingIds = ids;
            //     }
            // }
          }}
          name="accountings"
          label="选择会计科目"
        />
        <ProFormSelect
          disabled={ifDisable}
          rules={[
            {
              required: ifDisable ? false : true,
              message: '请选择',
            },
          ]}
          request={async () => [
            { label: '不包含分摊成本', value: 0 },
            { label: '包含分摊成本', value: 1 },
          ]}
          name="isShareCost"
          label="是否包含分摊成本"
        />
        <ProFormText name="alias" label="别名" />
        <ProFormTextArea
          name="costNode"
          label="备注"
          placeholder="请输入备注"
        />
      </ModalForm>
    );
  };

  const shareParamsSetCommit = async (rows: any[]) => {
    const resp = await saveParamsList({
      id: currentRow.id,
      shareParamProportionVOList: rows,
    });
    if (resp) {
      set_editTableVisible(false);
      message.success('操作成功！');
      tableRef.current?.reload();
    }
  };

  const tableSelecterCommit = async (keys: Key[], rows: any) => {
    const { id } = currentRow;
    const resp = await copyParamsList({ id, responsibilityIds: keys });
    if (resp) {
      set_tableSelecterVisible(false);
      message.success('操作成功！');
      tableRef.current?.reload();
    }
  };

  return (
    <KCIMPagecontainer className="AllocationParamsMap" title={false}>
      <EditTableModal
        onVisibleChange={(bool) => set_editTableVisible(bool)}
        title="分摊参数设置"
        rowKey={'id'}
        record={currentRow}
        open={editTableVisible}
        onFinish={(rows) => shareParamsSetCommit(rows)}
      />
      <TableSelecter
        onVisibleChange={(bool) => set_tableSelecterVisible(bool)}
        title="选择复制目标"
        rowKey={'id'}
        defaultSelectedKeys={[]}
        record={currentRow}
        open={tableSelecterVisible}
        onFinish={(keys, rows) => tableSelecterCommit(keys, rows)}
      />
      <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('name')}
                />
              }
              onChange={(e) => {
                set_tableDataSearchKeywords(e.target.value);
                if (e.target.value.length == 0) {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    name: '',
                  });
                }
              }}
              onPressEnter={(e) => {
                set_tableDataFilterParams({
                  ...tableDataFilterParams,
                  name: (e.target as HTMLInputElement).value,
                });
              }}
            />
          </div>
        </div>
        <div className="btnGroup">
          <UpDataActBtn record type="ADD" />
        </div>
      </div>

      <div>
        <KCIMTable
          scroll={{ x: 2000, y: `calc(100vh - 234px)` }}
          columns={columns as ProColumns[]}
          actionRef={tableRef}
          rowKey="id"
          params={tableDataFilterParams}
          request={(params) => getTableData(params)}
        />
      </div>
    </KCIMPagecontainer>
  );
}
