import { Button, Col, Form, Input, Row, Select, Table, Tag } from 'antd';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { useState } from 'react';
import { isEmptyBol, regPriceNumber } from '~/utils/validateUtils';
import EditableCell from '~/components/EditableCell';
import { InterReqType } from '~/api/interface';
import { addMallGoodsType } from '~/api/interface/goodsType';

type EditableTableProps = Parameters<typeof Table>[0];
type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;

//规格表单数据类型
type specificationFormListType = {
  optionList: { label: string; value: string }[];
  id: number;
  name: string;
  addSpecificationValueShow: boolean;
  specificationValueList: { name: string; id: number; specificationName: string }[];
};
//规格表格类型
type skuTableType = Exclude<InterReqType<addMallGoodsType>, undefined>['priceStock'];

const SkuInfo = () => {
  const [form] = Form.useForm<{ [x: string]: string }>();
  //表格数据
  const [tableData, setTableData] = useState<skuTableType>([]);
  //表格-列
  const salePriceValidator = (_rules: any, value: number) => {
    if (!isEmptyBol(value)) {
      if (regPriceNumber(value.toString())) {
        if (value > 99999999 || value < 0) {
          return Promise.reject(new Error('价格最大为99999999且大于0'));
        }
        return Promise.resolve();
      } else {
        return Promise.reject(new Error('为整数且最多保留两位小数'));
      }
    } else {
      return Promise.reject(new Error('请输入销售价'));
    }
  };
  //渠道正则价格校验
  const channelPriceValidator = (_rules: any, value: number) => {
    if (!isEmptyBol(value)) {
      if (regPriceNumber(value.toString())) {
        if (value > 99999999 || value < 0) {
          return Promise.reject(new Error('价格最大为99999999且大于0'));
        }
        return Promise.resolve();
      } else {
        return Promise.reject(new Error('为整数且最多保留两位小数'));
      }
    } else {
      return Promise.resolve();
    }
  };
  //库存正则校验
  const stockPriceValidator = (_rules: any, value: number) => {
    if (!isEmptyBol(value)) {
      if (/^[+]{0,1}(\d+)$/.test(value.toString())) {
        if (value > 99999999 || value < 0) {
          return Promise.reject(new Error('库存最大为99999999且大于0'));
        }
        return Promise.resolve();
      } else {
        return Promise.reject(new Error('请输入正整数'));
      }
    } else {
      return Promise.resolve();
    }
  };
  const defaultColumns: (ColumnTypes[number] & {
    editable?: boolean;
    dataIndex?: string;
    inputType?: string;
    radioOption?: { name: string; id: number }[];
    rules?: any;
    maxLength?: number;
  })[] = [
    {
      title: '商品规格',
      align: 'center',
    },
    {
      title: '图片',
      align: 'center',
      editable: true,
      dataIndex: 'skuImage',
      inputType: 'uploader',
    },
    {
      title: '料号',
      align: 'center',
      editable: true,
      dataIndex: 'skuNo',
      maxLength: 30,
    },
    {
      title: '销售价',
      align: 'center',
      editable: true,
      dataIndex: 'salePrice',
      rules: [{ required: true, validator: salePriceValidator }],
      inputType: 'number',
    },
    {
      title: '渠道价',
      editable: true,
      align: 'center',
      dataIndex: 'channelPrice',
      rules: [{ required: false, validator: channelPriceValidator }],
      inputType: 'number',
    },
    {
      title: '库存',
      editable: true,
      align: 'center',
      dataIndex: 'stock',
      rules: [{ required: false, validator: stockPriceValidator }],
      inputType: 'number',
    },
    {
      title: '操作',
      align: 'center',
      width: '10%',
      render: (_text: string, _record: any, index: number) => <></>,
    },
  ];
  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: any) => ({
        record,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: col.editable,
        radioOption: col.radioOption,
        inputType: col.inputType,
        uploadSuccess: col.inputType === 'uploader' ? uploadSuccess : undefined,
        rules: col.rules,
      }),
    };
  });

  //规格表单数组
  const [specificationFormList, setSpecificationFormList] = useState<specificationFormListType[]>([
    {
      id: Math.random(),
      name: `specification1`,
      optionList: [],
      specificationValueList: [],
      addSpecificationValueShow: false,
    },
  ]);

  //新增规格项目
  const addSpecificationClick = () => {
    setSpecificationFormList([
      ...specificationFormList,
      {
        id: Math.random(),
        name: `specification${specificationFormList.length + 1}`,
        optionList: [],
        specificationValueList: [],
        addSpecificationValueShow: false,
      },
    ]);
  };
  // 删除规格项目
  const deleteSpecificationClick = (index: number) => {
    specificationFormList.splice(index, 1);
    combineSpecificationValue();
    setSpecificationFormList([...specificationFormList]);
  };
  //规格项名称输入完成
  const specificationPressEnter = (e: any, index: number) => {
    specificationFormList[index].optionList = [{ label: e.target.value, value: e.target.value }];
    const obj = Object.create(null);
    obj[specificationFormList[index].name] = e.target.value;
    form.setFieldsValue(obj);
    setSpecificationFormList([...specificationFormList]);
  };
  //规格值添加
  const addSpecificationValueClick = (index: number) => {
    specificationFormList[index].addSpecificationValueShow = true;
    setSpecificationFormList([...specificationFormList]);
  };
  const specificationValuePressEnter = (e: any, index: number) => {
    specificationFormList[index].specificationValueList.push({
      id: Math.random(),
      name: e.target.value,
      specificationName: specificationFormList[index].optionList[0].value,
    });
    combineSpecificationValue();
    setSpecificationFormList(specificationFormList);
    specificationValueCancel(index);
  };
  //规格值添加-取消
  const specificationValueCancel = (index: number) => {
    specificationFormList[index].addSpecificationValueShow = false;
    setSpecificationFormList([...specificationFormList]);
  };
  //规格值-删除
  const specificationValueDelete = (i: number, j: number) => {
    specificationFormList[i].specificationValueList.splice(j, 1);
    combineSpecificationValue();
    setSpecificationFormList([...specificationFormList]);
  };

  //组合数据
  const combineSpecificationValue = () => {
    let combineSpecificationList: any = [];
    const combineList = specificationFormList.reduce((pre: any, cur, currentIndex) => {
      //  首次组合两个数据
      if (currentIndex === 0 && specificationFormList.length > 1) {
        combineSpecificationList = combineEvent(
          cur.specificationValueList,
          specificationFormList[currentIndex + 1].specificationValueList,
        );
        //二维数组拆分为对象
        combineSpecificationList = getCombineObj(combineSpecificationList);
        //  两个数据以上的组合
      } else if (currentIndex < specificationFormList.length - 1) {
        //  上一次的组合作为下一次组合的参数
        combineSpecificationList = combineEvent(
          combineSpecificationList,
          specificationFormList[currentIndex + 1].specificationValueList,
        );
        //二维数组拆分为对象
        combineSpecificationList = getCombineObj(combineSpecificationList);
      }
      pre = combineSpecificationList;
      return pre;
    }, []);
    console.log('组合数据-->', combineList);
    const tableDataList = combineList.reduce((pre: any, cur: any) => {
      pre.push(
        cur.reduce((a: any, b: any, currentIndex: number) => {
          a['name' + (currentIndex + 1)] = b.name;
          a['specificationName' + (currentIndex + 1)] = b.specificationName;
          a['id'] = Math.random();
          return a;
        }, {}),
      );
      return pre;
    }, []);
    console.log('表格数据-->', tableDataList);
    setTableData(tableDataList);
  };

  //组合数据拆分为对象
  const getCombineObj = (combineSpecificationList: any) => {
    return combineSpecificationList.reduce((pre: any, cur: any) => {
      pre.push(
        cur.reduce((a: any, b: any) => {
          if (Array.isArray(b)) {
            a.push(...b);
          } else {
            a.push({ ...b });
          }
          return a;
        }, []),
      );
      return pre;
    }, []);
  };

  const combineEvent = (list1: any, list2: any) => {
    return list1.reduce((pre: any, cur: any) => pre.concat(list2.map((v: any) => [cur, v])), []);
  };

  //规格值上传图片返回
  const uploadSuccess = () => {};

  return (
    <div className='sku-info'>
      <Form wrapperCol={{ span: 5 }} labelCol={{ span: 1 }} form={form}>
        {specificationFormList.map((v, index) => (
          <>
            {/*  规格项*/}
            <Row key={v.id}>
              <Col span={7}>
                <Form.Item
                  label={'规格项' + (index + 1)}
                  wrapperCol={{ span: 18 }}
                  labelCol={{ span: 5 }}
                  name={v.name}
                >
                  <Select
                    placeholder='请输入规格项，按回车键完成'
                    dropdownRender={(menu) => (
                      <>
                        {v.optionList.length ? menu : ''}
                        <Input onPressEnter={(e) => specificationPressEnter(e, index)} />
                      </>
                    )}
                    options={v.optionList}
                  />
                </Form.Item>
              </Col>
              {index ? (
                <Col span={2}>
                  <Button
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => deleteSpecificationClick(index)}
                  >
                    删除
                  </Button>
                </Col>
              ) : (
                ''
              )}
            </Row>
            {/*规格值显示*/}
            {v.specificationValueList.length ? (
              <Row style={{ marginBottom: '10px' }}>
                <Col span={2}></Col>
                <Col span={4}>
                  <div>
                    {v.specificationValueList.map((v, i) => (
                      <Tag key={v.id} closable onClose={() => specificationValueDelete(index, i)}>
                        {v.name}
                      </Tag>
                    ))}
                  </div>
                </Col>
              </Row>
            ) : (
              ''
            )}

            {/*规格值操作*/}
            {v.optionList.length ? (
              <Row>
                <Col span={2}></Col>
                <Col span={4} style={{ marginBottom: '10px' }}>
                  {v.addSpecificationValueShow ? (
                    <Input
                      placeholder='请输入规格值，按回车键完成'
                      onPressEnter={(e) => specificationValuePressEnter(e, index)}
                    />
                  ) : (
                    <Button
                      type='link'
                      danger
                      icon={<PlusOutlined />}
                      onClick={() => addSpecificationValueClick(index)}
                    >
                      添加规格值
                    </Button>
                  )}
                </Col>
                {v.addSpecificationValueShow ? (
                  <Col>
                    <Button
                      type='primary'
                      style={{ marginLeft: '10px' }}
                      onClick={() => specificationValueCancel(index)}
                    >
                      取消
                    </Button>
                  </Col>
                ) : (
                  ''
                )}
              </Row>
            ) : (
              ''
            )}
          </>
        ))}
        <Row>
          <Col span={2}></Col>
          <Col>
            <Button type='primary' icon={<PlusOutlined />} onClick={addSpecificationClick}>
              添加规格
            </Button>
          </Col>
        </Row>
      </Form>
      <Form>
        <Table
          style={{ marginTop: '10px' }}
          rowKey='id'
          columns={columns as ColumnTypes}
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          bordered
          dataSource={tableData}
          pagination={false}
        />
      </Form>
    </div>
  );
};
export default SkuInfo;
