/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-09-09 10:42: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 { createFromIconfontCN } from '@ant-design/icons';

import { ActionType } from '@ant-design/pro-components';
import { ProFormSelect } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, Modal } from 'antd';
import { Key, useEffect, useRef, useState } from 'react';

import {
  addChildReportList,
  addData,
  delData,
  editData,
  getReportListTableData,
  getReportListType,
} from './service';

import './style.less';

import '../../../../utils/zhongtaiB';
import React from 'react';
import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import TableTransfer from './transform';
import UpDateActBtn from './UpDateActBtn';

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

let currentEditRow: any = undefined;

const reportColumnMana = () => {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >();

  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');

  const tableRef = useRef<ActionType>();

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

  const columns: ProColumns[] = [
    {
      title: '列代码',
      dataIndex: 'code',
      width: 80,
    },
    {
      title: '列名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '列标题',
      dataIndex: 'headerText',
      ellipsis: true,
    },
    {
      title: '列类型',
      dataIndex: 'typeName',
      ellipsis: true,
      // render:(_:any)=>_ == 1?'指标':'自定义SQL'
    },
    {
      title: '取数类型',
      dataIndex: 'dataSource',
      ellipsis: true,
      //render: (_: any) => _ == 1 ? '指标' : '自定义SQL',
      renderText(num, record, index, action) {
        return num == 1 ? '计算公式' : '自定义SQL';
      },
    },
    {
      title: '取数来源',
      width: 200,
      ellipsis: true,
      render: (_: any, record: any) => {
        if (record.dataSource == 1) return record.formula;
        if (record.dataSource == 2) return record.sql;
      },
    },
    {
      title: '子列',
      width: 200,
      ellipsis: true,
      dataIndex: 'childColumnList',
      render: (_: any, record: any) => {
        if (record.childColumnList) {
          return record.childColumnList.reduce((prev: any, cur: any) => {
            return `${prev.length > 0 ? prev + '|' : prev}${cur.headerText}`;
          }, '');
        }
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 120,
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <a
            key="edit_child"
            onClick={() => {
              currentEditRow = record;
              addReportColumnChild(record);
            }}
          >
            子列
          </a>,
          <UpDateActBtn
            key={'act'}
            record={record}
            type="EDIT"
            tableRef={tableRef}
          />,
          <Popconfirm
            title="是否确认删除？"
            key="del"
            onConfirm={() => delTableData(record)}
          >
            <a>删除</a>
          </Popconfirm>,
        ];
      },
    },
  ];

  const transferTableColumn: ProColumns[] = [
    {
      title: '列名称',
      dataIndex: 'name',
      ellipsis: true,
      // render:(_:any)=>_ == 1?'指标':'自定义SQL'
    },
    {
      title: '列标题',
      dataIndex: 'headerText',
      ellipsis: true,
      // render:(_:any)=>_ == 1?'指标':'自定义SQL'
    },
  ];

  const getTableData = async (params: any) => {
    const resp = await getReportListTableData(params);
    if (resp) {
      return {
        data: resp.list,
        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 tableDataSearchHandle = (paramName: string) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      [`${paramName}`]: tableDataSearchKeywords,
    });
  };

  const onSaveHandle = async (keys: Key[], rows: any[]) => {
    const result = {
      parentCode: currentEditRow.code,
      childColumnList: rows,
    };
    const resp = await addChildReportList(result);
    if (resp) {
      currentEditRow = undefined;
      message.success('操作成功！');
      tableRef.current?.reload();
    }
  };

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

    Modal.confirm({
      title: `选择报表列`,
      icon: <></>,
      width: 750,
      centered: true,
      okText: '确定',
      cancelText: '取消',
      content: (
        <TableTransfer
          ref={ref}
          record={record}
          onSave={onSaveHandle}
          leftColumns={transferTableColumn}
          rightColumns={transferTableColumn}
          dataSource={[]}
        ></TableTransfer>
      ),
      onOk: () => {
        return ref.current && ref.current.save();
      },
    });
  };

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

  return (
    <KCIMPagecontainer className="reportColumnMana" title={false}>
      <div className="toolBar">
        <div className="filter">
          <div className="filterItem">
            <span className="label" style={{ whiteSpace: 'nowrap' }}>
              {' '}
              列类型：
            </span>
            <ProFormSelect
              noStyle
              placeholder={'请选择类型'}
              width={160}
              request={async () => {
                const resp = await getReportListType();
                if (resp) {
                  return resp.map((a: any) => ({
                    label: a.name,
                    value: a.code,
                  }));
                }
                return [];
              }}
              fieldProps={{
                onChange(value, option) {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    columnType: value,
                  });
                },
              }}
            />
          </div>
          <div className="filterItem" style={{ marginLeft: 16 }}>
            <span className="label" style={{ whiteSpace: 'nowrap' }}>
              {' '}
              列标题：
            </span>
            <Input
              placeholder={'请输入'}
              allowClear
              width={160}
              autoComplete="off"
              suffix={
                <IconFont
                  type="iconsousuo"
                  style={{ color: '#99A6BF' }}
                  onClick={() => tableDataSearchHandle('columnName')}
                />
              }
              onChange={(e) => {
                set_tableDataSearchKeywords(e.target.value);
                if (e.target.value.length == 0) {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    columnName: '',
                  });
                }
              }}
              onPressEnter={(e) => {
                set_tableDataFilterParams({
                  ...tableDataFilterParams,
                  columnName: (e.target as HTMLInputElement).value,
                });
              }}
            />
          </div>
        </div>
        <div className="btnGroup">
          <UpDateActBtn record type="ADD" tableRef={tableRef} />
        </div>
      </div>

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

export default reportColumnMana;
