import {Button, GetProps, Popover, Typography, Tabs, message} from "antd";
import React, {FC} from "react";
import {useNode} from '@craftjs/core';
import {useStateData} from '@jeoshi-design/rex-design.hooks.core';
import {ProCard, ProForm, ProFormDependency, ProFormSwitch, ProFormList, ProFormRadio, ProFormSelect, ProFormText, ProFormDigit} from "@ant-design/pro-components";
import styled from 'styled-components';
import {Table} from "./table";
import {ActionButtonsSettings} from "../action-buttons";

type TProps = GetProps<typeof Table>;


export const TableSettings: FC = () => {

  const [form] = ProForm.useForm();
  const {state, update} = useStateData(() => ({
    popoverStatus: {} as Record<string, boolean>,
  }))
  const {actions: {setProp}, ...dataProps} = useNode<TProps>((node) => ({
    ...node.data.props
  }));

  const change = (values: TProps) => {
    // console.log(values);
    setProp((props: TProps) => {
      Object.keys(values).forEach((key) => {
        const typedKey = key as keyof TProps;
        // eslint-disable-next-line no-param-reassign
        props[typedKey] = values[typedKey] as never;
      })
    })
  };

  const columnConfigFn = (name = 'fieldsConfig', level = 0) => {
    const commonProFormListProps: GetProps<typeof ProFormList> = {
      name,
      creatorButtonProps: {
        creatorButtonText: '添加列',
        position: "bottom",
        style: {marginTop: 10}
      },
      creatorRecord: {
        title: '',
        dataIndex: '',
        fixed: undefined,
        width: 100,
      },
    };

    return (
      <ProFormList
        {...commonProFormListProps}
        itemRender={({listDom, action}, {index}) => {
          return (
            <ProFormDependency name={['title']}>
              {(data) => {
                const noChildren = level > 0;
                const key = `items-popover-${name}-${index}`;

                const boxContent = (node: JSX.Element) => {
                  if (noChildren) {
                    return <>{node}</>
                  }

                  return (
                    <Popover
                      key={key}
                      open={!!state.popoverStatus[key]}
                      content={<>{columnConfigFn('children', level + 1)}</>}
                      arrow={false}
                      trigger="click"
                      placement="left"
                      fresh
                      styles={{
                        body: {
                          width: '500px',
                          maxHeight: '50vh',
                          overflow: 'auto'
                        }
                      }}
                      onOpenChange={(val) => {
                        state.popoverStatus[key] = false;
                        update();
                      }}
                    >
                      {node}
                    </Popover>
                  )
                };

                return boxContent(
                  <ProCard
                    title={(
                      <>
                        <span>{data.title ? data.title : `第${index + 1}列`}</span>
                        {
                          noChildren
                            ? <></>
                            : (
                              <Button
                                type="link"
                                style={{fontSize: 10, paddingLeft: 2, verticalAlign: 'baseline'}}
                                onClick={(e) => {
                                  e.stopPropagation();
                                  state.popoverStatus[key] = true;
                                  update();
                                }}
                              >
                                (点击编辑二级表头)
                              </Button>
                            )
                        }
                      </>
                    )}
                    size="small"
                    key={key}
                    collapsible
                    defaultCollapsed
                    extra={action}
                    style={{
                      borderBottom: '1px solid #ddd',
                      borderRadius: 0,
                      background: 'rgb(241 241 241 / 20%)'
                    }}
                    headStyle={{
                      padding: 10,
                    }}
                  >
                    {listDom}
                  </ProCard>
                );
              }}
            </ProFormDependency>
          );
        }}
      >
        <ProFormText
          name='title'
          label='列标题'
          required
          rules={[{required: true, message: '请输入列标题'}]}
        />
        <ProFormText
          name='dataIndex'
          label='索引值'
        />
        <ProFormText
          name='width'
          label='宽度'
          getValueFromEvent={(e) => {
            const {value} = e.target;
            if (value === '' || value === undefined || value === null) return value;
            return Number.isNaN(+value) ? value : +value;
          }}
        />
        <ProFormRadio.Group
          name='align'
          label='对齐方式'
          options={[
            {label: '左', value: 'left', },
            {label: '右', value: 'right', },
            {label: '居中', value: 'center', },
          ]}
        />
        <ProFormRadio.Group
          name='fixed'
          label='固定列'
          options={[
            {label: '左', value: 'left', },
            {label: '右', value: 'right', },
            {label: '不设置', value: undefined, },
          ]}
        />
      </ProFormList>
    )
  }

  return (
    <ProForm
      initialValues={dataProps as TProps}
      layout="horizontal"
      size="small"
      form={form}
      style={{padding: 16}}
      onFinish={(values) => {change(values)}}
      submitter={{
        render: (props, doms) => {
          return [];
        },
      }}
    >
      <Typography.Title level={3} style={{marginTop: 0}}>Table Settings</Typography.Title>
      <Tabs
        defaultActiveKey="1"
        tabPosition="top"
        style={{}}
        tabBarExtraContent={{
          right: (
            <Button
              htmlType="submit"
              type="primary"
              key="edit"
              onClick={() => {
                form.validateFields().catch(() => {
                  message.warning('配置设置失败,请注意');
                })
              }}
            >
              提交
            </Button>
          )
        }}
        items={[
          {
            key: '1',
            label: '属性',
            children: (
              <>
                <ProFormSelect
                  key="defaultPageSize"
                  name="defaultPageSize"
                  label="默认条数"
                  options={[
                    {label: '20', value: 20},
                    {label: '50', value: 50},
                    {label: '100', value: 100},
                  ]}
                />
                <ProFormSwitch
                  key="hidePagination"
                  name="hidePagination"
                  label="隐藏分页"
                />
                <ProFormText
                  key="api"
                  name="api"
                  label="请求地址"
                  placeholder="/listApi"
                />
                <ProFormSwitch
                  key="showFakeDataSource"
                  name="showFakeDataSource"
                  label="显示假数据"
                />
              </>
            )
          },
          {
            key: '2',
            label: '操作按钮配置',
            children: (
              <>
                <ProFormText
                  name={['actionConfig', 'columnConfig', 'title']}
                  label='列标题'
                  placeholder='请输入'
                />
                <ProFormText
                  name={['actionConfig', 'columnConfig', 'width']}
                  label='宽度'
                  getValueFromEvent={(e) => {
                    const {value} = e.target;
                    if (value === '' || value === undefined || value === null) return value;
                    return Number.isNaN(+value) ? value : +value;
                  }}
                />
                <ProFormRadio.Group
                  name={['actionConfig', 'columnConfig', 'align']}
                  label='对齐方式'
                  options={[
                    {label: '左', value: 'left', },
                    {label: '右', value: 'right', },
                    {label: '居中', value: 'center', },
                  ]}
                />
                <ActionButtonsSettings isRenderContent rootKey="actionButtonItems" />
              </>
            )
          },
          {
            key: '3',
            label: '列配置',
            children: (
              <>
                {columnConfigFn()}
              </>
            )
          },
        ]}
      />
    </ProForm>
  )
}

export const tableDefaultProps: TProps = {
  defaultPageSize: 50,
  fieldsConfig: [
    {
      "title": "基础信息",
      "dataIndex": "spu_info",
      "key": "spu_info",
      "width": 270
    },
    {
      "title": "图片",
      "dataIndex": "goods_image",
      "key": "image",
      "width": 50
    },
    {
      "title": "属性",
      "dataIndex": "goods_name",
      "key": "title",
    },
  ],
  api: '/listData',
  actionButtonItems: [
    {
      type: 'button_items',
      items: [
        {label: 'confirm', value: '3', buttonProps: {type: 'primary'}},
        {label: 'modal', value: '4', action: 'modal'},
      ],
    },
  ],
  actionConfig: {
    columnConfig: {
      width: 280,
      align: 'center',
    },
  },
};

const RulesDiv = styled.div`
  .ant-pro-form-list-container {
    display: flex;
    gap: 10px;
  }

  .ant-form-item {
    flex: 1;
    margin-bottom: 0;
  }
`;

const CustomTabsStyle = styled.div<{height: string}>`
  .ant-tabs-tabpane {
    max-height: ${(props) => props.height};
    overflow: auto;
  }
`;
