import {
  MyButtons,
  MyFormItems,
  MyModalFormProps,
  MyPageContainer,
} from '@/common';
import { defaultMenu } from '@/common/utils/wxCustomerConfig';
import { Apis } from '@/gen/Apis';
import { CaretDownOutlined, LeftOutlined } from '@ant-design/icons';
import { BetaSchemaForm, ProCard } from '@ant-design/pro-components';
import { useNavigate, useSearchParams } from '@umijs/max';
import { Card, Col, Flex, Form, message, Row, Space, Tag } from 'antd';
import { useEffect, useState } from 'react';
import './style.scss';

interface FormData {
  logo: { url: string }[];
  color: string;
  pageColor: string;
  pageColorValue?: string[];
  admin_logo?: { url: string }[];
  menu?: typeof defaultMenu;
}

export default function Index({ title = '小程序页面配置' }) {
  const [form] = Form.useForm<FormData>();
  const navigate = useNavigate();
  const [menuIndex, setMenuIndex] = useState<number>(0);
  const [getShowData, setShowData] = useState<any>({});
  const [searchParams] = useSearchParams();
  const [formValues, setFormValues] = useState<FormData>({
    logo: [],
    admin_logo: [],
    color: '#1890ff',
    menu: defaultMenu,
    // pageColor: `linear-gradient(180deg,rgba(255, 255, 255, 0.44) 0%,rgba(255, 255, 255, 0) 100%),linear-gradient(146deg,#d3d7ff 0%,rgba(255, 255, 255, 0) 37%),linear-gradient(194deg,#dffff3 0%,#f8f8f8 30%)`,
    pageColor: `linear-gradient(180deg, rgba(208, 229, 255, 0.44) 0%, #f7f7f7 100%, rgba(255, 255, 255, 0) 100%), linear-gradient(145deg, #D3D7FF 3%, rgba(255, 255, 255, 0) 49%), linear-gradient(222deg, #84FFD8 0%, #F7F7F7 67%)`,
  });
  const GET_DEFAULT_COLOR = [
    {
      color: '#d3d7ff',
      percent: 0,
    },
    {
      color: '#dffff3',
      percent: 100,
    },
  ];
  // 处理表单值变化，用于实时预览
  const handleValuesChange = (row: FormData) => {
    console.log('row', row);
    let data: ApiTypes.Company.CompanyConfigs.Store = {
      companies_id: Number(searchParams.get('id')) || 0,
      config_key: 'Theme',
      config_value: {
        color: formValues?.color,
        pageColor: formValues?.pageColor,
        logo: row?.logo || formValues?.logo,
        pageColorValue: formValues?.pageColorValue,
        admin_logo: row?.admin_logo,
        menu: row?.menu?.length ? row?.menu : defaultMenu,
      },
    };

    console.log(data);
    if (getShowData?.id) {
      Apis.Company.CompanyConfigs.Update({
        ...data,
        id: getShowData?.id || 0,
      }).then(() => {
        message.success('保存成功');
      });
    } else {
      Apis.Company.CompanyConfigs.Store(data).then(() => {
        message.success('保存成功');
      });
    }
  };

  useEffect(() => {
    if (searchParams.get('id')) {
      Apis.Company.CompanyConfigs.GetDetail({
        companies_id: searchParams.get('id') ?? 0,
        config_key: 'Theme',
      }).then((res: any) => {
        console.log('res', res);
        let cssStrColor =
          res?.data?.config_value?.pageColorValue?.[0] || '#d3d7ff';
        let cssEndColor =
          res?.data?.config_value?.pageColorValue?.[1] || '#dffff3';
        setShowData(res?.data);
        let newCss = `linear-gradient(180deg,rgba(208, 229, 255, 0.44) 0%,#f7f7f7 100%,rgba(255, 255, 255, 0) 100%),linear-gradient(145deg, ${cssStrColor} 3%,rgba(255, 255, 255, 0) 49%),linear-gradient(222deg, ${cssEndColor} 0%,#F7F7F7 67%)`;
        setFormValues({
          ...res?.data?.config_value,
          pageColor: newCss,
          menu: res?.data?.config_value?.menu || defaultMenu,
        });
        console.log('newCss', newCss);
        form.setFieldsValue({
          ...res?.data?.config_value,
          menu: res?.data?.config_value?.menu || defaultMenu,
          pageColorOtherValue: [
            {
              color: cssStrColor || '',
              percent: 0,
            },
            {
              color: cssEndColor || '',
              percent: 100,
            },
          ],
        });
        console.log('res', res);
      });
    }
  }, [searchParams.get('id')]);

  return (
    <MyPageContainer
      title={title}
      enableTabs={true}
      tabKey="company-set-page-info"
      tabLabel={title}
    >
      <div className="page-config-container">
        <Row gutter={[24, 0]}>
          {/* 左侧表单区域 */}
          <Col span={12}>
            <Card
              title={
                <Space>
                  <MyButtons.Default
                    title=""
                    icon={<LeftOutlined />}
                    onClick={() => navigate(-1)}
                  />
                  页面配置
                </Space>
              }
              className="form-card"
            >
              <BetaSchemaForm<ApiTypes.Company.CompanyConfigs.Store>
                {...MyModalFormProps.props}
                title={title}
                // 基础表单
                layoutType="Form"
                width="800px"
                wrapperCol={{ span: 24 }}
                labelAlign="left"
                form={form}
                submitter={{
                  render: () => {
                    return [
                      <div
                        key="submitter"
                        style={{
                          display: 'flex',
                          paddingTop: '50px',
                          justifyContent: 'flex-end',
                        }}
                      >
                        <MyButtons.Default
                          key="TemporaryStorage"
                          size="middle"
                          type="primary"
                          onClick={() => {
                            handleValuesChange(form.getFieldsValue());
                          }}
                          title="保存"
                        />
                      </div>,
                    ];
                  },
                }}
                onFinish={async () => {
                  // onSave(values);
                }}
                columns={[
                  MyFormItems.UploadImages({
                    key: 'logo',
                    title: (
                      <div>
                        机构小程序Logo
                        <span style={{ fontSize: '12px', color: '#999' }}>
                          (请上传正方形，建议：480*480，png格式的Logo)
                        </span>
                      </div>
                    ),
                    max: 1,
                    colProps: { span: 24 },
                    fieldProps: {
                      onChange: (val: { url: string }[]) => {
                        console.log('val', val);
                        form.setFieldValue('logo', val || []);
                        setFormValues({ ...formValues, logo: val || [] });
                      },
                    },
                  }),
                  MyFormItems.UploadImages({
                    key: 'admin_logo',
                    title: (
                      <div>
                        机构后台Logo
                        <span style={{ fontSize: '12px', color: '#999' }}>
                          (请上传长方形横版，jpg，png格式的Logo)
                        </span>
                      </div>
                    ),
                    max: 1,
                    colProps: { span: 24 },
                  }),
                  {
                    title: (
                      <div>
                        品牌主色配置
                        <span style={{ fontSize: '12px', color: '#999' }}>
                          (设置主品牌色，将应用于按钮、链接等交互组件)
                        </span>
                      </div>
                    ),
                    colProps: { span: 24 },
                    valueType: 'color',
                    key: 'color',
                    fieldProps: {
                      showText: true,
                      defaultValue: formValues?.color || '#1890ff',
                      format: 'rgb',
                      onChange: (value: any, css: string) => {
                        console.log('value', value, css);
                        setFormValues({ ...formValues, color: css });
                      },
                    },
                  },
                  {
                    title: (
                      <div>
                        全局渐变色配置
                        <span style={{ fontSize: '12px', color: '#999' }}>
                          (设置全局渐变色，将应用于页面背景等元素)
                        </span>
                      </div>
                    ),
                    key: 'pageColorOtherValue',
                    colProps: { span: 24 },
                    valueType: 'color',
                    fieldProps: {
                      defaultValue: GET_DEFAULT_COLOR,
                      mode: 'gradient',
                      arrow: true,
                      color: 'toRgb',
                      format: 'rgb',
                      showText: true,
                      onChange: (value: any, css: any) => {
                        console.log('value', value, css);
                        let cssStrColor = value?.colors
                          ? value?.colors?.[0]?.color?.metaColor
                          : value;
                        let cssEndColor = value?.colors
                          ? value?.colors?.[1]?.color?.metaColor
                          : value;
                        // let newCss = `linear-gradient(180deg,rgba(255, 255, 255, 0.44) 0%,rgba(255, 255, 255, 0) 100%),linear-gradient(146deg, rgba(${cssStrColor?.r}, ${cssStrColor?.g}, ${cssStrColor?.b},${cssStrColor?.a}) 0%, rgba(255, 255, 255, 0) 37%),linear-gradient(194deg, rgba(${cssEndColor?.r}, ${cssEndColor?.g}, ${cssEndColor?.b},${cssEndColor?.a}) 0%, #f8f8f8 30%)`;
                        let newCss = `linear-gradient(180deg, rgba(208, 229, 255, 0.44) 50%, #f7f7f7 100%, rgba(255, 255, 255, 0) 100%), linear-gradient(145deg, rgba(${cssStrColor?.r}, ${cssStrColor?.g}, ${cssStrColor?.b},${cssStrColor?.a}) 3%, rgba(255, 255, 255, 0) 49%), linear-gradient(222deg,  rgba(${cssEndColor?.r}, ${cssEndColor?.g}, ${cssEndColor?.b},${cssEndColor?.a}) 0%, #F7F7F7 67%)`;
                        setFormValues({
                          ...formValues,
                          pageColor: newCss,
                          pageColorValue: [
                            `rgba(${cssStrColor?.r}, ${cssStrColor?.g}, ${cssStrColor?.b},${cssStrColor?.a})`,
                            `rgba(${cssEndColor?.r}, ${cssEndColor?.g}, ${cssEndColor?.b},${cssEndColor?.a})`,
                          ],
                        });
                      },
                    },
                  },
                  {
                    valueType: 'divider',
                    fieldProps: {
                      orientation: 'left',
                      children: '首屏底部菜单图标',
                    },
                  },
                  {
                    valueType: 'formList',
                    dataIndex: 'menu',
                    fieldProps: {
                      copyIconProps: false,
                      deleteIconProps: false,
                      creatorButtonProps: false,
                    },
                    formItemProps: {
                      onChange: () => {
                        let formMenuValues = form.getFieldsValue();
                        setFormValues({
                          ...formValues,
                          menu: formMenuValues?.menu,
                        });
                      },
                      style: {
                        borderRadius: '6px',
                        marginBottom: 0,
                      },
                      itemRender: (
                        { listDom, action }: any,
                        { index }: { index: number },
                      ) => {
                        return (
                          <ProCard
                            bordered
                            style={{ marginBlockEnd: 10 }}
                            title={`菜单设置`}
                            size="small"
                            headerBordered
                            extra={
                              <Space>
                                <div
                                  style={{ fontSize: '12px', color: '#666' }}
                                >
                                  请上传正方形图标，建议81*81起的菜单图标
                                </div>
                                {/* {index ? (
                                  <div
                                    onClick={() => {
                                      // 确认删除操作
                                      // 获取当前表单值
                                      const formValues = form.getFieldsValue();
                                      // 检查menu数组是否存在
                                      if (
                                        formValues?.menu &&
                                        Array.isArray(formValues.menu)
                                      ) {
                                        // 创建新的menu数组，删除指定下标项
                                        const newMenu = formValues.menu.filter(
                                          (_, i) => i !== index,
                                        );
                                        // 更新表单值
                                        setFormValues({
                                          ...formValues,
                                          menu: newMenu,
                                        });
                                        form.setFieldsValue({
                                          ...formValues,
                                          menu: newMenu,
                                        });
                                      }
                                    }}
                                    style={{
                                      cursor: 'pointer',
                                      padding: '4px',
                                      borderRadius: '4px',
                                    }}
                                  >
                                    <DeleteFilled />
                                  </div>
                                ) : (
                                  ''
                                )} */}
                              </Space>
                            }
                          >
                            {listDom}
                          </ProCard>
                        );
                      },
                    },
                    columns: [
                      {
                        valueType: 'group',
                        colProps: { span: 24 },
                        columns: [
                          {
                            title: '菜单名称',
                            key: 'text',
                            colProps: { span: 4 },
                          },
                          {
                            title: '跳转链接',
                            key: 'pagePath',
                            colProps: { span: 8 },
                          },
                          MyFormItems.UploadImages({
                            key: 'iconPath',
                            title: '默认图标',
                            max: 1,
                            colProps: { span: 4 },
                          }),
                          MyFormItems.UploadImages({
                            key: 'selectedIconPath',
                            title: '选中图标',
                            max: 1,
                            colProps: { span: 4 },
                          }),
                        ],
                      },
                    ],
                  },
                ]}
              />
            </Card>
          </Col>
          {/* 右侧手机预览区域 */}
          <Col span={12}>
            <Card title="实时预览" className="preview-card">
              <div className="phone-frame">
                <div className="phone-screen">
                  {/* 手机顶部状态栏 */}
                  <div className="phone-status-bar">
                    <div className="status-left">9:41</div>
                    <div className="status-right">信号 电池</div>
                  </div>
                  {/* 页面内容 */}
                  <div
                    className="phone-content"
                    style={{
                      background: formValues?.pageColor,
                      backgroundRepeat: 'no-repeat',
                    }}
                  >
                    <div className="page-title">
                      {formValues?.logo?.[0] && (
                        <img
                          src={formValues?.logo?.[0]?.url}
                          width="24"
                          height="24"
                          style={{ marginRight: 8 }}
                          alt=""
                        />
                      )}
                      某小区1栋1单元2102 <CaretDownOutlined />
                    </div>

                    <div className="tab-content">
                      <Flex vertical gap="large">
                        <Flex gap="small" wrap>
                          <div
                            className="phone-button"
                            style={{
                              backgroundColor: formValues?.color,
                            }}
                          >
                            按钮
                          </div>
                          <div
                            className="phone-button"
                            style={{
                              border: `1px solid ${formValues?.color}`,
                              color: formValues?.color,
                            }}
                          >
                            按钮
                          </div>
                          <div
                            className="phone-button"
                            style={{
                              color: formValues?.color,
                            }}
                          >
                            按钮
                          </div>
                        </Flex>
                        <Flex gap="small" wrap>
                          <Tag color={formValues?.color}>标签</Tag>
                          <Tag color={formValues?.color}>标签</Tag>
                          <Tag color={formValues?.color}>标签</Tag>
                        </Flex>
                        <div className="tabs-content">
                          <div
                            className="tab-item"
                            style={{
                              backgroundColor: formValues?.color,
                              color: '#fff',
                            }}
                          >
                            tab 1
                          </div>
                          <div className="tab-item">tab 2</div>
                          <div className="tab-item">tab 3</div>
                        </div>
                        <div className="tabs-content">
                          <div
                            className="tab-item"
                            style={{
                              borderBottom: `5px solid ${formValues?.color}`,
                            }}
                          >
                            tab 1
                          </div>
                          <div className="tab-item">tab 2</div>
                          <div className="tab-item">tab 3</div>
                        </div>
                      </Flex>
                    </div>
                  </div>
                  <div className="menu-content">
                    {formValues?.menu?.map((item: any, index: number) => (
                      <div
                        key={`item_${index}`}
                        className="item"
                        onClick={() => {
                          setMenuIndex(index);
                        }}
                      >
                        <img
                          src={
                            index === menuIndex
                              ? item?.selectedIconPath?.[0]?.url
                              : item?.iconPath?.[0]?.url
                          }
                          width="28"
                          height="28"
                          alt=""
                        />
                        <div>{item?.text}</div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </Card>
          </Col>
        </Row>
      </div>
    </MyPageContainer>
  );
}
