import React, { useEffect, useState } from 'react';
import { Button, Form, message, Modal, Select, Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { PlusOutlined } from '@ant-design/icons';
import DivideAddEditModal from '@/pages/pointManage/divideOrder/comp/divideAddEditModal';
import { PointManageAPI } from '@/api';
import { OrderBonusListByOrderIdType } from '@/api/interface/pointManageType';

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

export const DivideSetting: React.FC<propType> = (props: propType) => {
  // 组件默认值
  DivideSetting.defaultProps = {
    data: null,
  };
  // 参数
  const { title, open, closed, data, isEdit } = props;
  // 表单钩子
  const [form] = Form.useForm();
  // 规则列表
  const [ruleNameList, setRuleNameList] = useState<{ label: string; value: number }[]>([]);
  // 默认表格数据
  const [defaultTableData, setDefaultTableData] = useState<TableType>([]);
  // 扩展表格数据
  const [extendTableData, setExtendTableData] = useState<TableType>([]);
  // 需要编辑的数据
  const [editData, setEditData] = useState<TableType[0]>();
  // 添加编辑弹窗
  const [addEditVisible, setAddEditVisible] = useState<boolean>(false);
  // 关闭弹窗
  const handleCancel = () => {
    form.resetFields();
    setRuleNameList([]);
    setExtendTableData([]);
    setDefaultTableData([]);
    closed();
  };
  // 校验数据
  const handleOk = () => {
    // 编辑状态下直接发放积分
    if (isEdit) {
      return handleConfirm();
    }
    form
      .validateFields()
      .then(async (values) => {
        await handleSubmit();
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 确定发放积分
  const handleConfirm = () => {
    Modal.confirm({
      title: '提示',
      content: '确认一键发放积分给相关用户吗？操作不可逆，请谨慎操作',
      onOk: async () => {
        const res = await PointManageAPI.DistributeMallOrderBonus({
          orderId: data.orderId,
        });
        if (res && res.code === '200') {
          message.success('发放成功').then();
          handleCancel();
        }
      },
    });
  };
  // 删除数据
  const handleDelete = (record: any) => {
    Modal.confirm({
      title: '提示',
      content: '删除后此数据将会丢失，确定删除吗？',
      onOk: () => {
        setExtendTableData(extendTableData?.filter((i) => i.index !== record.index));
        message.success('操作成功').then();
      },
    });
  };
  // 获取分成对象列表
  const getOrderBonusListRule = async () => {
    const res = await PointManageAPI.OrderBonusListRule();
    if (res && res.code === '200') {
      setRuleNameList(
        res.result?.map((i) => {
          return { label: i.ruleName, value: i.id };
        }),
      );
    }
  };
  // 获取订单详情
  const getBonusRuleListQuery = async () => {
    const res = await PointManageAPI.OrderBonusListByOrderId({
      orderId: data?.orderId,
    });
    if (res && res.code === '200') {
      const { bonusRuleDTO, extendList } = res.result;
      // 设置扩展规则数据
      setExtendTableData(extendList?.map((i, j) => ({ ...i, index: j })));
      // 判断是否有默认规则
      if (!bonusRuleDTO?.id) return;
      // 设置规则名称回显
      form.setFieldValue('ruleName', bonusRuleDTO.id);
      // 获取规则列表
      await getOrderBonusBuildMall(bonusRuleDTO.id);
    }
  };
  // 获取订单规则列表
  const getOrderBonusBuildMall = async (proportionRuleId: number) => {
    const res = await PointManageAPI.OrderBonusBuildMall({
      proportionRuleId,
      orderId: data?.orderId,
    });
    if (res && res.code === '200') {
      // 强行设置索引
      setDefaultTableData(res.result.map((i, j) => ({ ...i, index: j })));
    }
  };
  // 追加列表数据
  const handlePush = (val: TableType[0]) => {
    // 原来列表中没有的数据就追加，有的话就替换
    if (extendTableData.some((i) => val?.index === i.index)) {
      setExtendTableData(
        extendTableData.map((i) => {
          if (i.index === val?.index) {
            return val;
          }
          return i;
        }),
      );
    } else {
      setExtendTableData([...extendTableData, val].map((i, j) => ({ ...i, index: j })));
    }
  };
  // 提交数据
  const handleSubmit = async () => {
    const res = await PointManageAPI.UpdateMallOrderBonus([
      ...defaultTableData,
      ...extendTableData,
    ]);
    if (res && res.code === '200') {
      message.success('操作成功').then();
      handleCancel();
    }
  };
  // componentDidMount
  useEffect(() => {
    if (!open) return;
    if (!data) return;
    (async () => {
      await getOrderBonusListRule();
      await getBonusRuleListQuery();
    })();
  }, [open]);
  // 通用表格列
  const defaultColumns: ColumnsType<TableType[0]> = [
    {
      title: '分成对象',
      dataIndex: 'proportionObjName',
      align: 'center',
    },
    {
      title: '分成方式',
      dataIndex: 'proportionMode',
      align: 'center',
      render: (text) => (text === 0 ? '比例分成' : '差额分成'),
    },
    {
      title: '分成参数',
      dataIndex: 'proportionRate',
      align: 'center',
      render: (text, record) =>
        record.proportionMode === 0 ? `${(Number(text) * 100).toFixed(1)}%` || '/' : '/',
    },
    {
      title: '分成用户名称',
      dataIndex: 'userName',
      align: 'center',
    },
    {
      title: '分成用户UID',
      dataIndex: 'uid',
      align: 'center',
    },
    {
      title: '渠道等级',
      dataIndex: 'channelName',
      align: 'center',
      render: (text) => text || '无',
    },
    {
      title: '分成积分数额',
      dataIndex: 'scoreAmount',
      align: 'center',
    },
  ];
  // 扩展表格列
  const extendColumns: ColumnsType<TableType[0]> = [
    {
      title: '其它分成对象',
      dataIndex: 'proportionObjName',
      align: 'center',
    },
    ...defaultColumns.slice(1, 5),
    ...defaultColumns.slice(6),
    {
      title: '操作',
      align: 'center',
      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>
      ),
    },
  ];
  return (
    <>
      <Modal
        open={open}
        title={title}
        onCancel={handleCancel}
        onOk={handleOk}
        destroyOnClose
        width={768}
        wrapClassName='divide-setting-modal'
        okText={!isEdit ? '确定' : '确定一键发放积分'}
      >
        <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 }}
          >
            <Select
              placeholder='请选择规则名称'
              options={ruleNameList}
              allowClear
              onChange={(value) => {
                if (value) {
                  getOrderBonusBuildMall(value).then();
                } else {
                  setDefaultTableData([]);
                }
              }}
            />
          </Form.Item>
          <Table
            size='small'
            dataSource={defaultTableData}
            columns={defaultColumns}
            rowKey='index'
            bordered
            style={{ marginBottom: '-40px' }}
          />
          <div className='divide-title'>二、扩展规则</div>
          {!isEdit && (
            <Button icon={<PlusOutlined />} type='primary' onClick={() => setAddEditVisible(true)}>
              添加分成对象
            </Button>
          )}
          <Table
            size='small'
            dataSource={extendTableData}
            columns={!isEdit ? extendColumns : extendColumns.slice(0, -1)}
            rowKey='index'
            bordered
            style={{ marginTop: '10px' }}
          />
        </Form>
      </Modal>
      <DivideAddEditModal
        title={editData ? '编辑分成对象' : '添加分成对象'}
        open={addEditVisible}
        data={editData}
        orderData={data}
        closed={() => {
          setAddEditVisible(false);
          setEditData(undefined);
        }}
        push={handlePush}
      />
    </>
  );
};
