//新建售后

import {
  BetaSchemaForm,
  type EditableFormInstance,
  EditableProTable,
  ProCard,
  type ProColumns,
  ProForm,
  type ProFormColumnsType,
  ProFormDependency,
  ProFormDigit,
  ProFormRadio,
  ProFormTextArea,
} from '@ant-design/pro-components';
import {
  Badge,
  Button,
  Divider,
  Empty,
  Form,
  type FormInstance,
  Input,
  InputNumber,
  Space,
  Spin,
  Statistic,
  Table,
  Typography,
} from 'antd';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import EditableProTableCom from '@/components/EditableProTable';
import CommonModal from '@/components/ModalCom/CommonModal';
import UploadImages from '@/components/Upload/UploadImages';
import styles from './createSales.module.less';

const { Title, Text } = Typography;

interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
}
const originData = Array.from({ length: 100 }).map<DataType>((_, i) => ({
  key: i.toString(),
  name: `Edward ${i}`,
  age: 32,
  address: `London Park no. ${i}`,
}));

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};
const CreateSalesModal = () => {
  const [loading, setLoading] = useState(false);
  const formRefSales = useRef<FormInstance>(null);
  const formRef = useRef<FormInstance>(null);

  const [open, setOpen] = useState<boolean>(false);
  const handleOk = useCallback(async () => {
    try {
      setLoading(true);
      const values1 = formRef.current?.getFieldsValue();
      const values2 = formRefSales.current?.getFieldsValue();

      console.log({ ...values1, values2 });
    } finally {
      setLoading(false);
    }
  }, [open]);

  const onOpen = useCallback(
    (flag: boolean) => {
      setOpen(flag);
    },
    [open],
  );
  const salesColumns: ProFormColumnsType[] = [
    {
      title: '售后类型',
      dataIndex: 'cancelReason',
      valueType: 'radioButton',
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
      fieldProps: {
        options: [{ value: '仅退款', label: '仅退款' }],
      },
    },
    {
      title: '退款类型',
      dataIndex: 'cancelRemark',
      valueType: 'radioButton',
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
      fieldProps: {
        options: [
          { value: '整单退款（通用）', label: '整单退款' },
          { value: '选项二', label: '商品退款' },
          { value: '选项三', label: '扩展服务退款' },
          { value: '服务附加费退款', label: '服务附加费退款' },
          { value: '选项五', label: '退运费' },
          { value: '其他', label: '其他' },
        ],
      },
    },
    // {
    //   title: "",
    //   dependencies: ["cancelRemark"],
    //   dataIndex: "cancelRemark1",
    //   valueType: "textarea",
    //   formItemProps: {
    //     rules: [
    //       {
    //         required: true,
    //       },
    //     ],
    //   },
    //   fieldProps: {
    //     placeholder: "请输入",
    //   },
    //   renderFormItem: (schema, config, form) => {
    //     const grade = form.getFieldValue("cancelRemark");
    //     if (grade === "其他") {
    //       return <Input.TextArea placeholder="请输入" rows={4} />;
    //     }
    //     if (grade === "服务附加费退款") {
    //       return (
    //         <Form.Item>
    //           <ExtendRefunds />
    //         </Form.Item>
    //       );
    //     }
    //     return <></>;
    //   },
    // },
  ];
  const applyColumns: ProFormColumnsType[] = [
    {
      title: '售后类型',
      dataIndex: 'cancelReason1',
      valueType: 'radio',
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
      fieldProps: {
        options: [
          { value: '用户主动取消', label: '用户主动取消' },
          { value: '选项二', label: '选项二' },
          { value: '选项三', label: '选项三' },
          { value: '选项四', label: '选项四' },
          { value: '选项五', label: '选项五' },
          { value: '选项六', label: '选项六' },
          { value: '选项七', label: '选项七' },
        ],
        style: {
          display: 'flex',
          flexDirection: 'column',
          gap: '8px',
          marginTop: '6px',
          background: '#f0f0f0',
          padding: '8px',
          borderRadius: '8px',
        },
      },
    },
    {
      title: '问题描述',
      dataIndex: 'cancelRemark22',
      valueType: 'textarea',
    },
    {
      title: '问题凭证',
      dataIndex: 'cancelRemark23',
      formItemProps: {
        extra: '请上传问题凭证，支持.jpg .png 格式，最多 4 张。',
      },
      renderFormItem: () => {
        return <UploadImages multiple={true} maxCount={4} />;
      },
    },

    {
      title: '商家备注',
      dataIndex: 'cancelRemark2311',
      valueType: 'textarea',
    },
  ];

  return (
    <>
      <Button onClick={() => onOpen(true)}>新建售后</Button>
      <CommonModal
        title="新建售后单"
        open={true}
        onOk={handleOk}
        onCancel={() => onOpen(false)}
        confirmLoading={loading}
      >
        <Space
          direction="vertical"
          style={{ width: '100%' }}
          size={16}
          className={styles.sales}
        >
          <ProCard.Group direction="row">
            <ProCard layout="center">
              <Statistic title="实付金额" value={1000} precision={2} />
            </ProCard>
            <ProCard layout="center">
              <Statistic title="累计退款金额" value={200} precision={2} />
            </ProCard>
            <ProCard layout="center">
              <Statistic title="可退款金额" value={800} precision={2} />
            </ProCard>
          </ProCard.Group>
          <ProCard title="售后选项">
            <ProForm
              formRef={formRefSales}
              layout="horizontal"
              submitter={false}
              labelCol={{ style: { width: '80px' } }}
              labelAlign="right"
            >
              <ProFormRadio.Group
                name="cancelReason"
                label="售后类型"
                rules={[{ required: true, message: '请选择售后类型' }]}
                options={[{ value: '仅退款', label: '仅退款' }]}
                radioType="button"
              />

              <ProFormRadio.Group
                name="cancelRemark"
                label="退款类型"
                rules={[{ required: true, message: '请选择退款类型' }]}
                options={[
                  { value: '整单退款（通用）', label: '整单退款' },
                  { value: '选项二', label: '商品退款' },
                  { value: '选项三', label: '扩展服务退款' },
                  { value: '服务附加费退款', label: '服务附加费退款' },
                  { value: '选项五', label: '退运费' },
                  { value: '其他', label: '其他' },
                ]}
                radioType="button"
              />

              <ConditionalFields />
            </ProForm>
          </ProCard>

          <ProCard title="申请信息（通用表单样式，根据当前订单状态调用不同的申请原因表单）">
            <BetaSchemaForm
              layoutType="Form"
              formRef={formRef}
              columns={applyColumns || []}
              layout="horizontal"
              submitter={false}
              labelCol={{ style: { width: '80px' } }}
              labelAlign="right"
            />
          </ProCard>
          <ProCard split="vertical" headerBordered title="预估退款明细">
            <ProCard
              colSpan={'50%'}
              headerBordered
              title="预估退款明细"
              size="small"
            >
              <Space align="center" style={{ marginBottom: 16 }}>
                <div>
                  <Text type="danger">最高退款金额</Text>
                  <Text type="secondary">（不含虚拟资产）</Text>
                </div>
                <ProFormDigit
                  name="input-number"
                  min={1}
                  max={10}
                  fieldProps={{
                    precision: 0,
                    prefix: '￥',
                    style: { width: '100px', margin: 0 },
                  }}
                />
              </Space>
              <div>
                <Text type="secondary">
                  退款金额上限 <Text type="danger">¥700</Text>
                  ，金额不支持修改，优惠券、积分、余额等虚拟资产不支持修改，虚拟资产将随退款而原路退回，具体金额以实际情况为准。
                </Text>
              </div>
              <Divider />
              <Title level={5}>预估退款项</Title>
              <Space direction="vertical" size={8} style={{ width: '100%' }}>
                <Badge
                  status="processing"
                  style={{ width: '100%' }}
                  text={
                    <div
                      style={{
                        display: 'inline-flex',
                        justifyContent: 'space-between',
                        width: '90%',
                      }}
                    >
                      <Text>商品/服务</Text>
                      <Text>合计¥500</Text>
                    </div>
                  }
                />
                <Badge
                  status="processing"
                  style={{ width: '100%' }}
                  text={
                    <div
                      style={{
                        display: 'inline-flex',
                        justifyContent: 'space-between',
                        width: '90%',
                      }}
                    >
                      <Text>增值/扩展服务</Text>
                      <Text>合计¥500</Text>
                    </div>
                  }
                />
                <Badge
                  status="processing"
                  style={{ width: '100%' }}
                  text={
                    <div
                      style={{
                        display: 'inline-flex',
                        justifyContent: 'space-between',
                        width: '90%',
                      }}
                    >
                      <Text>运费</Text>
                      <Text>合计¥500</Text>
                    </div>
                  }
                />
              </Space>
            </ProCard>
            <ProCard
              size="small"
              headerBordered
              title="预估退款至"
              colSpan={'50%'}
            >
              <Title level={5}>
                预估退款项
                <Text type="secondary">（退款方式：原支付方式返还）</Text>
              </Title>
              <Space direction="vertical" size={8} style={{ width: '100%' }}>
                <Badge
                  status="processing"
                  style={{ width: '100%' }}
                  text={
                    <div
                      style={{
                        display: 'inline-flex',
                        justifyContent: 'space-between',
                        width: '90%',
                      }}
                    >
                      <Text>
                        微信支付
                        <Text type="secondary">（建设银行 尾号1626）</Text>
                      </Text>
                      <Text>¥500</Text>
                    </div>
                  }
                />
                <Badge
                  status="processing"
                  style={{ width: '100%' }}
                  text={
                    <div
                      style={{
                        display: 'inline-flex',
                        justifyContent: 'space-between',
                        width: '90%',
                      }}
                    >
                      <Text>
                        钱包余额
                        <Text type="secondary">（个人钱包 编号1090）</Text>
                      </Text>
                      <Text>¥500</Text>
                    </div>
                  }
                />
                <Badge
                  status="processing"
                  style={{ width: '100%' }}
                  text={
                    <div
                      style={{
                        display: 'inline-flex',
                        justifyContent: 'space-between',
                        width: '90%',
                      }}
                    >
                      <Text>宠豆豆(积分)</Text>
                      <Text>¥500</Text>
                    </div>
                  }
                />
                <Badge
                  status="processing"
                  style={{ width: '100%' }}
                  text={
                    <div
                      style={{
                        display: 'inline-flex',
                        justifyContent: 'space-between',
                        width: '90%',
                      }}
                    >
                      <Text>红包</Text>
                      <Text>¥500</Text>
                    </div>
                  }
                />
              </Space>
              <Divider />
              <Title level={5}>预估扣除项</Title>
              <Text type="secondary">
                如果后续有设计退款时扣除比例的设定才会存在此字段。目前暂时不做这个业务逻辑，仅为布局占位。
              </Text>
              <Space direction="vertical" size={8} style={{ width: '100%' }}>
                <Badge
                  status="processing"
                  style={{ width: '100%' }}
                  text={
                    <div
                      style={{
                        display: 'inline-flex',
                        justifyContent: 'space-between',
                        width: '90%',
                      }}
                    >
                      <Text>
                        违约金
                        <Text type="secondary">（服务开始前60分钟内退款）</Text>
                      </Text>
                      <Text>¥500</Text>
                    </div>
                  }
                />
              </Space>
            </ProCard>
          </ProCard>
        </Space>
      </CommonModal>
    </>
  );
};
type DataSourceType = {
  id: React.Key;
  prod?: string;
  num?: number;
  state?: string;
  created_at?: number;
  children?: DataSourceType[];
};

const columnsSale: ProColumns<DataSourceType>[] = [
  {
    title: '商品',
    dataIndex: 'prod',
    editable: () => false,
  },
  {
    title: '退款信息',
    key: 'refund',
    editable: () => false,
    dataIndex: 'state',
  },
  {
    title: '退款数量',
    dataIndex: 'num',
    valueType: 'digit',
    editable: () => true,
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入退款数量',
        },
      ],
    },
  },
];

const defaultData: DataSourceType[] = new Array(20).fill(1).map((_, index) => {
  return {
    id: (Date.now() + index).toString(),
    prod: `活动名称${index}`,
    num: index,
    state: 'open',
    created_at: 1590486176000,
  };
});

const ExtendRefunds = (props: {
  onChange?: (value: readonly DataSourceType[]) => void;
}) => {
  const [data, setData] = useState<readonly DataSourceType[]>([]);
  const [loading, setLoading] = useState(true);
  const editorFormRef = useRef<EditableFormInstance<DataSourceType>>(null);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [formformSales] = Form.useForm();
  const [formExtend] = Form.useForm();
  const [formServeExtFee] = Form.useForm();
  const [formShippingFee] = Form.useForm();
  const fetchData = async () => {
    await waitTime();
    setData(defaultData);
    setLoading(false);
  };

  useEffect(() => {
    fetchData();
  }, []);
  useEffect(() => {
    props.onChange?.(data);
  }, [data, props.onChange]);

  useEffect(() => {
    setEditableRowKeys(data!.map((item) => item.id));
  }, [data]);
  console.log(editableKeys);
  return (
    <EditableProTable
      value={defaultData}
      columns={columnsSale}
      rowKey="id"
      recordCreatorProps={false}
      editable={{
        // form: formformSales,
        editableKeys: editableKeys,
        onChange: setEditableRowKeys,
        onValuesChange: (record, recordList) => {
          setData(recordList);
        },
      }}
    />
    // <EditableProTableCom<DataSourceType>
    //   columns={columnsSale}
    //   value={defaultData}
    //   rowKey="id"
    //   rowSelection={{
    //     selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
    //   }}
    //   editable={{
    //     form: formformSales,
    //     editableKeys: editableKeys,
    //     onChange: setEditableRowKeys,
    //     onValuesChange: (record, recordList) => {
    //       setData(recordList);
    //     },
    //   }}
    // />
  );
};
// const ExtendRefunds = (props: {
//   onChange?: (value: readonly DataSourceType[]) => void;
// }) => {
//   const [data, setData] = useState<readonly DataSourceType[]>([]);
//   const [loading, setLoading] = useState(true);
//   const editorFormRef = useRef<EditableFormInstance<DataSourceType>>(null);
//   const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
//   const [formformSales] = Form.useForm();
//   const [formExtend] = Form.useForm();
//   const [formServeExtFee] = Form.useForm();
//   const [formShippingFee] = Form.useForm();

//   const fetchData = async () => {
//     await waitTime();
//     setData(defaultData);
//     setLoading(false);
//   };

//   useEffect(() => {
//     fetchData();
//   }, []);
//   useEffect(() => {
//     props.onChange?.(data);
//   }, [data]);

//   useEffect(() => {
//     setEditableRowKeys(data!.map((item) => item.id));
//     console.log(data);
//   }, [data]);

//   const renderContent = useCallback(() => {
//     // if (data.length === 0 && !loading) {
//     //   return (
//     //     <div>
//     //     <Empty
//     //       description="订单无此退款项/类型"
//     //       style={{
//     //         background: "#fff",
//     //         padding: "16px",
//     //         margin: 0,
//     //         borderRadius: "4px",
//     //       }}
//     //     />
//     //   </div>);
//     // }
//     return (
//       <Spin spinning={loading} >
//         <EditableProTable<DataSourceType>
//           columns={columnsSale}
//           rowKey="id"
//           rowSelection={{
//             selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
//           }}
//           value={data}
//           editable={{
//             form: formformSales,
//             editableKeys: data.map((item) => item.id),
//             onChange: setEditableRowKeys,
//             onValuesChange: (record, recordList) => {
//               setData(recordList);
//             },
//           }}
//         />
//         {/* <EditableProTableCom<DataSourceType>
//               columns={columnsSale}
//               rowKey="id"
//               value={data}
//               key={"sale"}
//               // onChange={onTableChange}
//               rowSelection={{
//                 selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
//               }}
//               editable={{
//                 form: formformSales,
//                 editableKeys: data.map((item) => item.id),
//                 onChange: setEditableRowKeys,
//                 // onValuesChange: (record, recordList) => {
//                 //   setData(recordList);
//                 // },
//               }}
//             />
//           </ProCard>
//           <ProCard title="退款项">
//             <EditableProTableCom<DataSourceType>
//               columns={columnsSale}
//               rowKey="id"
//               value={data}
//               // onChange={onTableChange}
//               rowSelection={{
//                 selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
//               }}
//               key={"sale1"}
//               editable={{
//                 form: formExtend,
//                 editableKeys,
//                 onChange: setEditableRowKeys,
//                 // onValuesChange: (record, recordList) => {
//                 //   setData(recordList);
//                 // },
//               }}
//             />
//           </ProCard>
//           <ProCard>
//             <EditableProTableCom<DataSourceType>
//               columns={columns}
//               rowKey="id"
//               value={data}
//               // onChange={onTableChange}
//               rowSelection={{
//                 selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
//               }}
//               key={"sale2"}
//               editable={{
//                 form: formServeExtFee,
//                 editableKeys,
//                 onChange: setEditableRowKeys,
//                 // onValuesChange: (record, recordList) => {
//                 //   setData(recordList);
//                 // },
//               }}
//             />
//           </ProCard>
//           <ProCard>
//             <EditableProTableCom<DataSourceType>
//               columns={columns}
//               rowKey="id"
//               value={data}
//               key={"sale4"}
//               onChange={onTableChange}
//               rowSelection={{
//                 selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
//               }}
//               editable={{
//                 form: formShippingFee,
//                 editableKeys,
//                 onChange: setEditableRowKeys,
//                 // onValuesChange: (record, recordList) => {
//                 //   setData(recordList);
//                 // },
//               }}
//             />
//           </ProCard> */}
//       </Spin>
//     );
//   }, [loading, data]);
//   return <div key="salcessw"> {renderContent()}</div>;
// };

export default CreateSalesModal;

const ConditionalFields: React.FC = () => {
  const cancelRemark = Form.useWatch('cancelRemark', { preserve: true });

  if (cancelRemark === '其他') {
    return (
      <ProFormTextArea
        name="cancelRemarkText"
        label=""
        placeholder="请输入"
        rules={[{ required: true, message: '请输入内容' }]}
        fieldProps={{
          rows: 4,
        }}
      />
    );
  }

  if (cancelRemark === '服务附加费退款') {
    return (
      <ProForm.Item name="extendRefunds" label="">
        <ExtendRefunds />
      </ProForm.Item>
    );
  }

  return null;
};
