/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-10-09 14:51:33
 * @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,
  DrawerForm,
  EditableFormInstance,
  EditableProTable,
  ProFormInstance,
  ProFormSelect,
} from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormDigit,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm } from 'antd';
import { useEffect, useRef, useState } from 'react';

import { addData, delData, editData, getData } from './service';

import './style.less';

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

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

type TableDataResponse = {
  data: any[];
  success: boolean;
  total: number;
  pageSize: number;
  totalPage: number;
};

export default function FenyeTemplate() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >();
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const tableRef = useRef<ActionType>();

  const columns: ProColumns[] = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: '模板名称',
      dataIndex: 'name',
    },
    {
      title: '创建时间',
      dataIndex: 'date',
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
    },
    {
      title: '备注说明',
      dataIndex: 'remark',
    },
    {
      title: '操作',
      key: 'option',
      width: 120,
      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,
  ): Promise<TableDataResponse | any[]> => {
    const resp = await getData(params);
    if (resp) {
      if (resp.totalCount == 0 && resp.currPage != 1) {
        return getTableData({ ...params, current: resp.currPage - 1 });
      } else {
        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 updateTable = async (formVal: any, type: 'EDIT' | 'ADD') => {
    const content = formVal.table.map((a: any) => ({}));

    if (type == 'ADD') {
      const result = {
        name: formVal.name,
        content: JSON.stringify(formVal.table),
        remark: formVal.remark,
      };
      const resp = await addData({ ...result });
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }
    if (type == 'EDIT') {
      const result = {
        id: formVal.id,
        name: formVal.name,
        content: JSON.stringify(formVal.table),
        remark: formVal.remark,
      };
      const resp = await editData({ ...result });
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }

    return true;
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD';
  }) => {
    const editableFormRef = useRef<EditableFormInstance>();
    const formRef = useRef<ProFormInstance<any>>();
    const editorFormRef = useRef<EditableFormInstance<any>>();

    const editableColumns: ProColumns[] = [
      {
        title: '标题',
        dataIndex: 'title',
        editable: () => true,
      },
      {
        title: '类型',
        dataIndex: 'filedType',
        editable: () => false,
      },
      {
        title: '是否必填',
        dataIndex: 'required',
        request: async () => [
          {
            value: 1,
            label: '是',
          },
          {
            value: 0,
            label: '否',
          },
        ],
        fieldProps: (_, { rowIndex }) => {
          return {
            onSelect: () => {
              // 每次选中重置参数
              editableFormRef.current?.setRowData?.(rowIndex, { fraction: [] });
            },
          };
        },
        renderText(text) {
          return text ? '是' : '否';
        },
      },
      {
        title: '是否展示信息',
        dataIndex: 'showFiled',
        request: async () => [
          {
            value: 1,
            label: '是',
          },
          {
            value: 0,
            label: '否',
          },
        ],
        fieldProps: (_, { rowIndex }) => {
          return {
            onSelect: () => {
              // 每次选中重置参数
              editableFormRef.current?.setRowData?.(rowIndex, { fraction: [] });
            },
          };
        },
        renderText(text) {
          return text ? '是' : '否';
        },
      },
      {
        title: '操作',
        valueType: 'option',
        render: (text, record, _, action) => [
          <a
            key="editable"
            onClick={() => {
              console.log({ record });
              action?.startEditable?.(record.tempId);
            }}
          >
            编辑
          </a>,
          <a
            key="delete"
            onClick={() => {
              const tableDataSource = formRef.current?.getFieldValue(
                'table',
              ) as any[];
              formRef.current?.setFieldsValue({
                table: tableDataSource.filter(
                  (item) => item.tempId !== record.tempId,
                ),
              });
            }}
          >
            删除
          </a>,
        ],
      },
    ];

    let defaultTableData = JSON.parse(record.content ? record.content : '[]');
    defaultTableData = defaultTableData.map((a: any) => ({
      ...a,
      tempId: (Math.random() * 1000000).toFixed(0),
    }));

    const [tempData, setTempData] = useState<any[]>(defaultTableData);
    // console.log({defaultTableData});

    return (
      <KCIMDrawerForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}模板数据`}
        width={800}
        initialValues={
          type == 'EDIT'
            ? { ...record, table: defaultTableData, filedType: 'Text' }
            : { filedType: 'Text' }
        }
        trigger={
          type == 'EDIT' ? (
            <a key="edit">编辑</a>
          ) : (
            <span className="add">新增</span>
          )
        }
        onFinish={(val: any) => {
          return updateTable(
            type == 'EDIT' ? { ...record, ...val } : { ...val },
            type,
          );
        }}
        formRef={formRef}
        drawerProps={{ destroyOnClose: true }}
        colProps={{ span: 24 }}
        grid
      >
        <ProFormText
          name="name"
          label="模板名称："
          placeholder="请输入"
          width={300}
          rules={[{ required: true, message: '名称不能为空!' }]}
        />
        <ProFormTextArea
          name="remark"
          label="备注说明："
          placeholder="请输入"
        />

        <EditableProTable
          className="pfm-EditableProTable"
          name="table"
          style={{ margin: '0 4px' }}
          rowKey={'tempId'}
          editableFormRef={editorFormRef}
          tableStyle={{ padding: 0 }}
          columns={editableColumns}
          // controlled
          editable={{}}
          recordCreatorProps={{
            record: () => ({
              tempId: (Math.random() * 1000000).toFixed(0),
              filedType: 'Text',
            }),
          }}
        />
      </KCIMDrawerForm>
    );
  };

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

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

  return (
    <KCIMPagecontainer className="FenyeTemplate" title={false}>
      <div className="toolBar">
        <div className="filter">
          <div className="filterItem" style={{ marginRight: 16, width: 205 }}>
            <span className="label" style={{ whiteSpace: 'nowrap' }}>
              {' '}
              检索：
            </span>
            <Input
              placeholder={'请输入模板名称'}
              allowClear
              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[]}
          actionRef={tableRef}
          rowKey="id"
          params={tableDataFilterParams}
          request={(params) => getTableData(params)}
        />
      </div>
    </KCIMPagecontainer>
  );
}
