import React, { useEffect, useState } from 'react';
import { Descriptions, Form, Input, InputNumber, message, Modal, Select, Space } from 'antd';
import { UserScoreDetailsListType } from '@/api/interface/pointManageType';
import { PointManageAPI } from '@/api';
import { maxLength9, noSpaceFront } from '@/utils/validateUtils';

// 列表的类型
type DetailType = (ReturnType<UserScoreDetailsListType> extends Promise<infer T>
  ? T
  : never)['result']['list'];
// 传参类型
interface propType {
  title: string;
  open: boolean;
  closed: any;
  data?: DetailType;
}

export const DistributionModal: React.FC<propType> = (props) => {
  DistributionModal.defaultProps = {
    data: undefined,
  };
  // 参数
  const { title, open, closed, data } = props;
  /// 表单钩子
  const [form] = Form.useForm();
  // 流通方式选择
  const [circulateId, setCirculateId] = useState<number>();
  // 流通方式列表
  const [circulateIdList, setCirculateIdList] = useState<{ label: string; value: number }[]>();
  // 关闭弹窗
  const handleCancel = () => {
    form.resetFields();
    setCirculateId(undefined);
    closed();
  };
  // 提交弹窗
  const handleOk = () => {
    form
      .validateFields()
      .then(async (values) => {
        if (Number(values.score) === 0) {
          return message.warning('积分数值不能为0');
        }
        if (values.orderNo) {
          // 从订单列表查询订单
          const res = await PointManageAPI.GetOrderInfoByOrderNo({
            orderNo: values.orderNo,
          });
          if (res && res.code === '200') {
            const { id } = res.result;
            if (!id) {
              return message.warning('订单编号不存在');
            }
            await handleSubmit({
              ...values,
              orderId: id,
            });
          }
        } else {
          await handleSubmit(values);
        }
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交数据
  const handleSubmit = async (values: any) => {
    const res = await PointManageAPI.OrderScoreRelease({
      circulateId: values.circulateId,
      mallUserId: data?.mallUserId as number,
      orderNo: values.orderNo,
      orderId: values.orderId,
      score: Number(`${values.symbol}${values.score}`),
    });
    if (res && res.code === '200') {
      message.success('操作成功');
      handleCancel();
    } else {
      message.warning(res.message);
    }
  };
  // 获取流通数据列表
  const getListCirculateInfo = async () => {
    const res = await PointManageAPI.ListCirculateInfo({});
    if (res && res.code === '200') {
      setCirculateIdList(
        res.result
          .map((i) => {
            return { label: i.type, value: i.id };
          })
          .filter((i) => [5, 7].includes(i.value)),
      );
    }
  };
  // 流通方式点击事件
  const handleCirculateId = (e: number) => {
    setCirculateId(e);
  };
  // 组件加载
  useEffect(() => {
    if (!open) return;
    (async () => {
      await getListCirculateInfo();
    })();
  }, [open]);
  return (
    <Modal
      open={open}
      title={title}
      onCancel={handleCancel}
      onOk={handleOk}
      destroyOnClose
      width={400}
    >
      <Form
        name='addForm'
        form={form}
        labelAlign='right'
        labelCol={{ span: 8 }}
        // layout="inline"
      >
        <Form.Item label='发放积分数值' required>
          <Space.Compact style={{ width: '100%' }}>
            <Form.Item name='symbol' noStyle initialValue='+'>
              <Select>
                <Select.Option value='+'>+</Select.Option>
                <Select.Option value='-'>-</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item
              name='score'
              noStyle
              rules={[{ required: true, message: '请输入发放积分数值' }]}
            >
              <Input
                style={{ width: '250%' }}
                placeholder='请输入发放积分数值'
                onInput={maxLength9}
              />
            </Form.Item>
          </Space.Compact>
        </Form.Item>
        <Form.Item
          label='流通方式'
          name='circulateId'
          rules={[{ required: true, message: '请选择流通方式' }]}
        >
          <Select
            placeholder='请选择流通方式'
            options={circulateIdList}
            allowClear
            value={circulateId}
            onChange={handleCirculateId}
          />
        </Form.Item>
        {circulateId === 5 && (
          <Form.Item
            label='订单编号'
            name='orderNo'
            rules={[{ required: true, message: '请输入订单编号' }]}
          >
            <Input placeholder='请输入订单编号' maxLength={20} allowClear onInput={noSpaceFront} />
          </Form.Item>
        )}
      </Form>
    </Modal>
  );
};
