import { Form, Input, message, Modal, Radio, Select } from "antd";
import React, { useEffect, useState } from "react";
import { debounce } from "lodash";
import { PointManageAPI } from "@/api";

// 传参类型
interface propType {
  title: string;
  open: boolean;
  closed: any;
  data?: any;
  push: any;
  orderData?: any;
}

const DivideAddEditModal: React.FC<propType> = (props: propType) => {
  // 组件默认值
  DivideAddEditModal.defaultProps = {
    data: null,
    orderData: null,
  };
  // 参数
  const { title, open, closed, data, orderData, push } = props;
  // 表单钩子
  const [form] = Form.useForm();
  // 分成方式
  const [divideMethod, setDivideMethod] = React.useState(0);
  // 用户列表
  const [mallUserList, setMallUserList] = React.useState<
    {
      value: number;
      label: string;
      uid: string;
      userName: string;
    }[]
  >([]);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 关闭弹窗
  const handleCancel = () => {
    form.resetFields();
    setMallUserList([]);
    setPagination({
      total: 0,
      pageSize: 10,
      current: 1,
      totalPage: 0,
    });
    closed();
  };
  // 获取分成用户
  const getListKBTMallUser = async (value = {}) => {
    const res = await PointManageAPI.MallUserBySearchKey({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
    });
    if (res && res.code === "200") {
      const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
      const arr = list?.map((i) => ({
        value: i.id,
        label: `${i.userName || i.nickName}(${i.uid}) ${i.phoneNum}`,
        uid: i.uid,
        userName: i.userName || i.nickName,
      }));
      setMallUserList([...mallUserList, ...arr]);
      setPagination({
        total: totalCount,
        current: pageNo,
        pageSize,
        totalPage,
      });
    } else {
      message.warning(res.message);
    }
  };
  // 滚动翻页(防抖)
  const handlePopupScroll = debounce(async (e) => {
    if (pagination.totalPage <= pagination.current) return;
    await getListKBTMallUser({ pageNo: pagination.current + 1 });
    // console.log("handlePopupScroll -->", e.target.scrollTop);
  }, 500);
  // 校验数据
  const handleOk = () => {
    form
      .validateFields()
      .then(async (values) => {
        // 处理数据并准备提交数据
        await handleSubmit({
          ...values,
          proportionRate: Number(values.proportionRate) / 100,
        });
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交数据
  const handleSubmit = async (values: any) => {
    const res = await PointManageAPI.CalculateOrderBonusVO({
      ...data,
      ...values,
      orderId: orderData.orderId,
      orderNO: orderData.orderNo,
      uid: mallUserList.find((i) => i.value === values.mallUserId)?.uid || "",
      userName:
        mallUserList.find((i) => i.value === values.mallUserId)?.userName || "",
      ruleType: 1,
    });
    if (res && res.code === "200") {
      push({
        ...data,
        ...res?.result,
      });
      message.success(data?.id ? "修改成功" : "添加成功").then();
      handleCancel();
    }
  };
  // componentDidMount
  useEffect(() => {
    if (!open) return;
    (async () => {
      await getListKBTMallUser();
    })();
    if (!data) return;
    form.setFieldsValue({
      ...data,
      proportionRate: (Number(data.proportionRate) * 100).toFixed(1),
    });
    setDivideMethod(data.proportionMode);
  }, [open]);
  return (
    <Modal
      open={open}
      title={title}
      onCancel={handleCancel}
      onOk={handleOk}
      destroyOnClose
    >
      <Form
        name="addForm"
        form={form}
        labelAlign="right"
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 10 }}
      >
        <Form.Item
          label="其它分成对象"
          name="proportionObjName"
          rules={[{ required: true, message: "请输入其它分成对象" }]}
        >
          <Input placeholder="请输入其它分成对象" maxLength={20} />
        </Form.Item>
        <Form.Item
          label="分成方式"
          name="proportionMode"
          rules={[{ required: true, message: "请选择分成方式" }]}
          initialValue={divideMethod}
        >
          <Radio.Group
            options={[
              { label: "分成比例", value: 0 },
              { label: "差价分成", value: 1, disabled: true },
            ]}
            onChange={({ target: { value } }) => setDivideMethod(value)}
          />
        </Form.Item>
        {divideMethod === 0 && (
          <>
            <Form.Item
              label="分成参数"
              name="proportionRate"
              rules={[
                { required: true, message: "请输入分成额度百分比" },
                // 只能输入0.1到100.0的一位小数,不能大于100.0
                {
                  pattern: /^(100(\.0)?|[1-9]?\d(\.\d)?)$/,
                  message: "只能输入0.1到100.0的一位小数",
                },
              ]}
            >
              <Input
                placeholder="请输入分成额度百分比"
                maxLength={20}
                type="number"
                suffix="%"
              />
            </Form.Item>
            <div style={{ margin: "0 0 10px 60px" }}>
              说明：分成比例基数以订单金额减去相关渠道利润的得数为基准
            </div>
          </>
        )}
        <Form.Item
          label="分成用户"
          name="mallUserId"
          rules={[{ required: true, message: "请选择分成用户" }]}
          wrapperCol={{ span: 14 }}
        >
          <Select
            placeholder="请选择分成用户"
            options={mallUserList}
            allowClear
            showSearch
            filterOption={(input, option) =>
              (option?.label ?? "").toLowerCase().includes(input.toLowerCase())
            }
            optionFilterProp="label"
            onPopupScroll={handlePopupScroll}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default DivideAddEditModal;
