import React, { useEffect, useState } from 'react';
import { Button, Form, Input, message, Modal, Select, Switch, Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { PlusOutlined } from '@ant-design/icons';
import DivideAddEditObject from '../divideAddEditObject';
import { AddAndEditBonusRuleType, BonusRuleListQueryType } from '@/api/interface/pointManageType';
import { PointManageAPI } from '@/api';

// 编辑的数据类型
type DataType = (ReturnType<BonusRuleListQueryType> extends Promise<infer T>
  ? T
  : never)['result']['list'][0];
type ReqType = Parameters<AddAndEditBonusRuleType>[0];
// 传参类型
interface propType {
  title: string;
  open: boolean;
  closed: any;
  isEdit: boolean;
  data?: DataType;
}

export const DivideAddEditModal: React.FC<propType> = (props: propType) => {
  // 组件默认值
  DivideAddEditModal.defaultProps = {
    data: { bonusSet: [], id: undefined, ruleName: '' },
  };
  // 参数
  const { title, open, closed, data, isEdit } = props;
  // 表单钩子
  const [form] = Form.useForm();
  // 表格数据
  const [tableData, setTableData] = useState<DataType['bonusSet']>([]);
  // 需要编辑的数据
  const [editData, setEditData] = useState<any>();
  // 添加编辑弹窗
  const [addEditVisible, setAddEditVisible] = useState<boolean>(false);
  // 分成对象列表
  const [propObjCode, setPropObjCode] = useState<{ label: string; value: number }[]>([]);
  // 关闭弹窗
  const handleCancel = () => {
    form.resetFields();
    closed();
  };
  // 删除数据
  const handleDelete = (record: any) => {
    Modal.confirm({
      title: '提示',
      content: '删除后此数据将会丢失，确定删除吗？',
      onOk: () => {
        // 删除数据
        setTableData(tableData.filter((i) => i.id !== record.id));
        message.success('操作成功').then();
      },
    });
  };
  // 获取分成对象列表
  const getListProportionObject = async () => {
    const res = await PointManageAPI.ListProportionObject();
    if (res && res.code === '200') {
      setPropObjCode(
        res.result?.map((i) => {
          return { label: i.name, value: i.code };
        }),
      );
    }
  };
  // 追加列表数据
  const handlePush = (val: DataType['bonusSet'][0]) => {
    // 原来列表中没有的数据就追加，有的话就替换
    if (tableData.some((i) => val?.id === i.id)) {
      setTableData(
        tableData.map((i) => {
          if (i.id === val.id) {
            return val;
          }
          return i;
        }),
      );
    } else {
      setTableData([...tableData, val]);
    }
  };
  // 校验数据
  const handleOk = () => {
    form
      .validateFields()
      .then(async (values) => {
        await handleSubmit({
          ...data,
          ...values,
          bonusSetList: tableData.map((i) => {
            const id = data?.bonusSet?.some((j) => j.id === i.id);
            return id ? i : { ...i, id: null };
          }),
        });
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交数据
  const handleSubmit = async (val: ReqType) => {
    const res = await PointManageAPI.AddAndEditBonusRule(val);
    if (res && res.code === '200') {
      message.success('操作成功').then();
      closed();
    }
  };
  // 通用表格列
  const defaultColumns: ColumnsType<DataType['bonusSet'][0]> = [
    {
      title: '分成对象',
      dataIndex: 'propObjCode',
      align: 'center',
      render: (text) => propObjCode.find((i) => i.value === text)?.label || text,
    },
    {
      title: '分成方式',
      dataIndex: 'proportionMode',
      align: 'center',
      render: (text) => (text === 0 ? '比例分成' : '差价分成'),
    },
    {
      title: '分成参数',
      dataIndex: 'proportionParam',
      align: 'center',
      render: (text, record) =>
        record.proportionMode === 0 ? `${(Number(text) * 100).toFixed(1)}%` || '/' : '/',
    },
    {
      title: '操作',
      dataIndex: 'id',
      align: 'center',
      width: 100,
      render: (text, record) => (
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <Button
            type='link'
            onClick={() => {
              setEditData(record);
              setAddEditVisible(true);
            }}
          >
            编辑
          </Button>
          <Button type='link' onClick={() => handleDelete(record)}>
            删除
          </Button>
        </div>
      ),
    },
  ];
  useEffect(() => {
    if (!open) return;
    (async () => {
      await getListProportionObject();
    })();
    if (!data) return;
    form.setFieldsValue({ ...data, defaultRule: data.defaultRule === 0 });
    setTableData(data.bonusSet);
  }, [open]);
  return (
    <>
      <Modal
        open={open}
        title={title}
        onCancel={handleCancel}
        // onOk={handleOk}
        destroyOnClose
        width={768}
        wrapClassName='divide-setting-modal'
        footer={
          !isEdit ? (
            <>
              <Button onClick={handleCancel}>取消</Button>
              <Button type='primary' onClick={handleOk}>
                确定
              </Button>
            </>
          ) : null
        }
      >
        <Form
          name='addForm'
          form={form}
          labelAlign='right'
          disabled={isEdit}
          // layout="inline"
        >
          <div className='divide-title'>一、基本信息</div>
          <Form.Item
            label='规则名称'
            name='ruleName'
            rules={[{ required: true, message: '请输入规则名称' }]}
            wrapperCol={{ span: 6 }}
          >
            <Input placeholder='请输入规则名称' maxLength={20} allowClear />
          </Form.Item>
          <div className='divide-title'>二、分成设置</div>
          {!isEdit && (
            <Button icon={<PlusOutlined />} type='primary' onClick={() => setAddEditVisible(true)}>
              添加分成对象
            </Button>
          )}
          <Table
            size='small'
            dataSource={tableData}
            columns={!isEdit ? defaultColumns : defaultColumns.slice(0, -1)}
            rowKey='id'
            bordered
            style={{ margin: '10px 0 -40px 0' }}
          />
          <Form.Item
            label='是否默认规则'
            name='defaultRule'
            wrapperCol={{ span: 6 }}
            valuePropName='checked'
            initialValue={false}
          >
            <Switch checkedChildren='是' unCheckedChildren='否' />
          </Form.Item>
        </Form>
      </Modal>
      <DivideAddEditObject
        title={editData ? '编辑分成对象' : '添加分成对象'}
        open={addEditVisible}
        data={editData}
        closed={() => {
          setAddEditVisible(false);
          setEditData(null);
        }}
        state={{ propObjCode }}
        push={handlePush}
        selected={tableData}
      />
    </>
  );
};
