import {
  MyButtons,
  MyColumns,
  MyModalFormProps,
  MyPageContainer,
  rulesHelper,
} from '@/common';
import { Apis } from '@/gen/Apis';
import { QuestionsTypeEnum } from '@/gen/Enums';
import type { ProColumns } from '@ant-design/pro-components';
import {
  BetaSchemaForm,
  DragSortTable,
  ProCard,
} from '@ant-design/pro-components';
import { useNavigate, useSearchParams } from '@umijs/max';
import { Form, message, Space } from 'antd';
import { useEffect, useState } from 'react';
import MySurveysSelectList from '../modals/SurveysSelectList';
export default function Index({ title = '新增问卷' }) {
  const [data, setShow] = useState<any>({});
  const [dataSource, setDataSource] = useState<ApiTypes.Survey.Surveys.Store[]>(
    [],
  );
  const [form] = Form.useForm();
  const navigate = useNavigate();

  const columns: ProColumns[] = [
    {
      title: '排序',
      dataIndex: 'sort',
      width: 60,
      className: 'drag-visible',
    },
    {
      title: '题目',
      dataIndex: 'title',
    },
    MyColumns.EnumTag({
      title: '类型',
      dataIndex: 'type',
      valueEnum: QuestionsTypeEnum,
    }),
    MyColumns.Boolean({
      dataIndex: 'required',
      title: '是否必答',
      search: false,
    }),
    MyColumns.Option({
      render: (_, item: any, index) => (
        <Space key={index}>
          <MyButtons.Delete
            onConfirm={() => {
              setDataSource(
                dataSource.filter((res: any) => res?.id !== item?.id),
              );
            }}
          />
        </Space>
      ),
    }),
  ];

  const handleDragSortEnd = (
    beforeIndex: number,
    afterIndex: number,
    newDataSource: any,
  ) => {
    console.log(newDataSource, 'newDataSource');
    setDataSource(newDataSource);
  };

  const [searchParams] = useSearchParams();

  const loadShow = () => {
    let paramsId: any = { id: searchParams.get('id') ?? 0 };
    Apis.Survey.Surveys.Show(paramsId).then((res) => {
      res?.data?.questions_with_order?.forEach((k: any) => {
        k.question_id = k?.id;
      });
      setDataSource(res?.data?.questions_with_order || []);
      setShow(res?.data);
      form.setFieldsValue(res?.data); // 编辑赋值
    });
  };

  useEffect(() => {
    loadShow();
  }, [searchParams.get('id')]);

  return (
    <MyPageContainer
      title={
        <Space
          style={{ cursor: 'pointer' }}
          onClick={() => {
            navigate(-1);
          }}
        >
          {/* <LeftCircleOutlined size={34} /> */}
          {title}
        </Space>
      }
      enableTabs={false}
      tabKey="charge-standards-create"
      tabLabel={title}
    >
      <ProCard>
        <div style={{ width: 900, minHeight: '83vh', margin: '0 auto' }}>
          <BetaSchemaForm<ApiTypes.Survey.Surveys.Store>
            {...MyModalFormProps.props}
            title={title}
            // 基础表单
            layoutType="Form"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 24 }}
            labelAlign="left"
            width="900px"
            form={form}
            onFinish={async (values: any) =>
              Apis.Survey.Surveys.Update({
                ...values,
                questions: dataSource,
                id: data?.id,
              })
                .then(() => {
                  navigate(-1);
                  message.success('编辑成功');
                  return true;
                })
                .catch(() => false)
            }
            columns={[
              {
                key: 'name',
                title: '问卷名称',
                colProps: { span: 24 },
                formItemProps: { ...rulesHelper.text },
              },

              {
                key: 'description',
                title: '问卷描述',
                valueType: 'textarea',
                colProps: { span: 24 },
              },
              {
                colProps: { span: 24 },
                renderFormItem: () => {
                  return (
                    <ProCard bordered>
                      <DragSortTable
                        headerTitle="题目列表(拖拽排序)"
                        toolBarRender={() => [
                          <MySurveysSelectList
                            key="select"
                            item={{ list: dataSource }}
                            onChange={(e: any) => {
                              setDataSource(e);
                            }}
                          />,
                        ]}
                        bordered
                        options={false}
                        columns={columns}
                        rowKey="id"
                        search={false}
                        pagination={false}
                        dataSource={dataSource || []}
                        dragSortKey="sort"
                        onDragSortEnd={handleDragSortEnd}
                      />
                    </ProCard>
                  );
                },
              },
              {
                key: 'is_enabled',
                title: '是否启用',
                valueType: 'switch',
                colProps: { span: 24 },
              },
            ]}
          />
        </div>
      </ProCard>
    </MyPageContainer>
  );
}
