/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-09-11 15:24: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 } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, Modal, Switch, Tooltip } 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,
  getCostshareparamList,
  setAccountingSub,
} from './service';

import './style.less';
import React from 'react';
import TableTransfer from './transform';
import { getAccountingSubjectList } from '../../accountingAccountSet/accountingSubMana/service';
import { getNodesWithChildren } from '@/utils/tooljs';

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

const transferTableColumn = [
  {
    title: '会计科目编码',
    dataIndex: 'accountingCode',
  },
  {
    title: '会计科目名称',
    dataIndex: 'accountingName',
  },
];

export default function CostAllocationParamsSet() {
  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: 'shareParamName',
    },
    {
      title: '成本分摊参数编号',
      width: 160,
      dataIndex: 'shareParamCode',
      sorter: (a, b) => {
        // 比较字符串数字部分大小
        const codeA = parseInt(a.shareParamCode.slice(1), 10);
        const codeB = parseInt(b.shareParamCode.slice(1), 10);
        return codeA - codeB;
      },
    },
    {
      title: '计算方式',
      dataIndex: 'calcType',
      renderText(text, record) {
        return text == 1 ? '手动填写' : '按对应会计科目计算';
      },
    },
    {
      title: () => (
        <>
          启动
          <Tooltip title="停用的分摊参数在成本分摊报表里不显示">
            <IconFont
              style={{
                paddingLeft: 6,
                fontSize: 16,
                position: 'relative',
                top: 1,
              }}
              type="iconshuoming"
            />
          </Tooltip>
        </>
      ),
      dataIndex: 'status',
      renderText(number, record) {
        return (
          <Switch
            checked={number}
            size="small"
            onChange={(bool) => {
              updateTable({ ...record, status: bool ? 1 : 0 }, 'EDIT');
            }}
          />
        );
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 160,
      valueType: 'option',
      render: (_: any, record: any) => {
        const { calcType } = record;
        return calcType != 1
          ? [
              <UpDataActBtn key={'act'} record={record} type="EDIT" />,
              <Popconfirm
                title="是否确认删除？"
                key="del"
                onConfirm={() => delTableData(record)}
              >
                <a>删除</a>
              </Popconfirm>,
              <a
                key={'bind'}
                onClick={() => {
                  oprnTableTransform(record);
                }}
              >
                会计科目
              </a>,
            ]
          : [
              <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 getCostshareparamList({ ...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') => {
    if (type == 'ADD') {
      const result = { ...formVal };

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

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD';
  }) => {
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}成本分摊参数`}
        width={350}
        formRef={formRef}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
              }
            : {}
        }
        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
          label="成本分摊参数名"
          rules={[
            {
              required: true,
              message: '成本分摊参数名是必填项',
            },
          ]}
          name="shareParamName"
        />
        <ProFormText
          label="成本分摊参数编号"
          rules={[
            {
              required: true,
              message: '成本分摊参数编号是必填项',
            },
          ]}
          name="shareParamCode"
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '请选择计算方式',
            },
          ]}
          options={[
            {
              value: 1,
              label: '手动填写',
            },
            {
              value: 2,
              label: '按对应会计科目计算',
            },
          ]}
          name="calcType"
          label="计算方式"
        />
      </ModalForm>
    );
  };

  const onSaveHandle = async (keys: Key[], rows: any[], record: any) => {
    const { id } = record;
    const resp = await setAccountingSub({
      costShareParamId: id,
      accountIds: keys,
    });
    if (resp) {
      message.success('操作成功！');
      tableRef.current?.reload();
    }
  };

  const oprnTableTransform = (record: any) => {
    const ref = React.createRef<{ save: any }>();

    Modal.confirm({
      title: `选择会计科目`,
      icon: <></>,
      width: 750,
      centered: true,
      okText: '确定',
      cancelText: '取消',
      content: (
        <TableTransfer
          ref={ref}
          keyName="id"
          record={record}
          onSave={(keys, rows) => onSaveHandle(keys, rows, record)}
          leftColumns={transferTableColumn}
          rightColumns={transferTableColumn}
          dataSource={[]}
        ></TableTransfer>
      ),
      onOk: () => {
        return ref.current && ref.current.save();
      },
    });
  };

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