import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Select, Radio, Button, Table, message, ModalProps } from 'antd';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import type { RadioChangeEvent } from 'antd';

import EditableCell from '~/components/EditableCell';
import { InterDataType } from '~/api/interface';
import { categoryListType } from '~/api/interface/categoryManage';
import { ProduceManageAPI } from '~/api';
import {
  cooperationTagType,
  productListType,
  ProductSpecListType,
} from '~/api/interface/produceManageType';
import { customizeEntity, skuUnitType, specEntity } from '~/api/interface/goodsType';
import { Uploader } from '~/components/uploader';
import ConfigurePriceModal from '../configurePriceModal';

//分类返回类型
type categoryType = InterDataType<categoryListType>['list'];
//产品返回类型
type productType = InterDataType<productListType>['list'];
//产品-规格返回类型
type productSpecType = InterDataType<ProductSpecListType>['list'];
//产品-规格单位返回类型
type unitType = InterDataType<skuUnitType>;
//加盟标签返回类型
type cooperationTagResponseType = InterDataType<cooperationTagType>;

interface selfProps {
  handleCancel: () => void;
  handleOk: (data: specEntity) => void;
  currentDesc: number;
  categoryList: categoryType;
  curtRowData: Partial<specEntity>;
  skuUnitList: unitType;
  goodsType: number;
}

// interface tableRowEntity {
//   goodsTypeId: number;
//   prodOrScheme: any;
//   selectSource: any;
//   skuUnit: any;
// }

const AddOrEditSkuModal: React.FC<ModalProps & selfProps> = ({
  open,
  handleCancel,
  handleOk,
  currentDesc,
  categoryList,
  curtRowData,
  skuUnitList,
  goodsType,
}) => {
  // 弹窗标题
  const [dialogTitle, setDialogTitle] = useState<string>('添加');
  // 规格表单
  const [skuForm] = Form.useForm<any>();
  // 自定义产品表单
  const [selfProduct] = Form.useForm<any>();
  // 是否自定义产品类型
  const [isCustomProd, setIsCustomProd] = useState<boolean>(false);
  //产品列表
  const [productList, setProductList] = useState<productType>([]);
  //产品规格列表
  const [productSpecList, setProductSpecList] = useState<productSpecType>([]);
  // 配置价格弹窗
  const [configurePriceModalShow, setConfigurePriceModalShow] = useState<boolean>(false);
  const [customRowData, setCustomRowData] = useState<Partial<customizeEntity>>({
    id: -1,
    productSpecCPQVO: {},
  });
  const [selfProductData, setSelfProductData] = useState<customizeEntity[]>([
    {
      id: 1,
      specName: '',
      partNo: '',
      specImage: '',
      fileList: [],
      productSpecCPQVO: {},
    },
  ]);
  // 等级标签列表
  const [tagInfoList, setTagInfoList] = useState<cooperationTagResponseType>([]);
  // 自定义id数组
  const [selfIds, setSelfIds] = useState<number[]>([]);
  // 自定义选项表格
  const selfSelectColumns = [
    {
      title: '选项名称',
      align: 'center',
      dataIndex: 'specName',
      editable: true,
    },
    {
      title: '料号',
      align: 'center',
      dataIndex: 'partNo',
      editable: true,
    },
    {
      title: '操作',
      align: 'center',
      width: '220px',
      ellipsis: true,
      render: (_text: string, record: any, i: number) => {
        return (
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Uploader
              fileUpload
              listType='picture-card'
              onChange={(fileList) => selfUploadSuccess(fileList, record, i)}
              defaultFileList={record.fileList}
            >
              <UploadOutlined />
            </Uploader>
            <Button size='small' type='link' onClick={() => configurePriceEvent(record)}>
              配置价格
            </Button>
            {i != 0 ? (
              <Button
                className='delete'
                size='small'
                type='link'
                onClick={() => deleteSelfProduct(record)}
              >
                删除
              </Button>
            ) : (
              ''
            )}
          </div>
        );
      },
    },
  ];
  const mergedColumns = selfSelectColumns.map((col: any) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: any) => ({
        record,
        inputType: col.dataIndex === 'age' ? 'number' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: true,
      }),
    };
  });
  // // 根据产品类型获取产品列表
  const handleProdTypeSelect = (id: number) => {
    getProductList(id);
    skuForm.setFieldsValue({
      skuId: undefined,
      specIds: undefined,
    });
    // getProduct(id);
  };
  //
  // // 根据所属行业获取方案列表
  // const handleIndeTypeSelect = async (id: number) => {
  //   getIndustrySku(id);
  //   skuForm.setFieldsValue({
  //     skuId: undefined,
  //     specIds: undefined,
  //   });
  // };
  //
  // 根据选择产品或行业获取选项来源列表
  const handleProdOrInduSelected = (id: number) => {
    getProductSpecList(id);
  };
  // // 选项来源选中
  const handleSourceSelect = (id: number | string) => {
    const values: any[] = skuForm.getFieldValue('specIds');
    const obj = productSpecList.find((v) => v.id === id);
    if (!obj?.priceList) {
      message.warning('所选规格来源未配置好价格，请配置好SKU价格后重新选择！');
      const index: number = values.findIndex((i: number) => i === id);
      values.splice(index, 1);
    }
    skuForm.setFieldValue('specIds', values);
  };
  // // 规格来源切换
  const skuSourceRadioChange = (e: RadioChangeEvent) => {
    setIsCustomProd(e.target.value === 1);
  };
  // // 清除表单
  const onCancel = () => {
    // 关闭前恢复初始值
    skuForm.resetFields();
    selfProduct.resetFields();
    setSelfProductData([
      {
        id: 1,
        specName: '',
        partNo: '',
        specImage: '',
        fileList: [],
        productSpecCPQVO: {},
      },
    ]);
    setCustomRowData({
      id: -1,
      productSpecCPQVO: {},
    });
    setIsCustomProd(false);
    handleCancel();
  };
  //获取产品列表
  const getProductList = (categoryId: number) => {
    ProduceManageAPI.listPageProductSku({ pageNo: 1, pageSize: 9999, categoryId }).then(
      ({ result }) => {
        setProductList(result.list || []);
      },
    );
  };
  //产品-规格
  const getProductSpecList = (productSkuId: number) => {
    ProduceManageAPI.listPageProductSpec({ pageNo: 1, pageSize: 9999, productSkuId }).then(
      ({ result }) => {
        setProductSpecList(result.list || []);
        if (result.list) {
          const ids: number[] = result.list.reduce((pre: number[], cur) => {
            return cur.priceList || goodsType === 1 ? [...pre, cur.id] : pre;
          }, []);
          skuForm.setFieldValue('specIds', ids.length ? ids : undefined);
        }
      },
    );
  };
  // 添加自定义产品项
  const addSelfSelectItem = () => {
    setSelfProductData([
      ...selfProductData,
      {
        id: selfProductData.length + 1,
        specName: '',
        partNo: '',
        specImage: '',
        fileList: [],
        productSpecCPQVO: {},
      },
    ]);
  };
  // 删除自定义产品
  const deleteSelfProduct = (record: customizeEntity) => {
    const cusObj: customizeEntity | undefined =
      curtRowData.customizeInfo &&
      curtRowData.customizeInfo.find((i: customizeEntity) => i.id === record.id);
    if (cusObj) {
      setSelfIds([...selfIds, cusObj.id]);
    }
    const index: number = selfProductData.findIndex((item: any) => item.id === record.id);
    selfProductData.splice(index, 1);
    setSelfProductData([...selfProductData]);
  };
  //自定义商品上传成功
  const selfUploadSuccess = (
    fileList: {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[],
    record: any,
    index: number,
  ) => {
    record.fileList = [
      {
        uid: `${Math.random()}`,
        status: 'done',
        url: fileList[0].url,
        name: fileList[0].name,
      },
    ];
    record.specImage = fileList[0].url;
    selfProductData.splice(index, 1, record);
    setSelfProductData([...selfProductData]);
  };
  // 配置价格操作
  const configurePriceEvent = (record: customizeEntity) => {
    getTagNameList();
    setConfigurePriceModalShow(true);
    setCustomRowData({ ...record });
  };
  const configurePriceHandleOk = (specPrice: any, leaseTerm?: number) => {
    setConfigurePriceModalShow(false);
    const index: number = selfProductData.findIndex(
      (i: customizeEntity) => i.id === customRowData.id,
    );
    selfProductData[index].productSpecCPQVO = {
      productSpecId: selfProductData[index].productSpecCPQVO.productSpecId || undefined,
      specPrice,
      type: goodsType,
      leaseTerm,
    };
    selfProductData.splice(index, 1, selfProductData[index]);
    setSelfProductData([...selfProductData]);
  };
  const configurePriceHandleCancel = () => {
    setConfigurePriceModalShow(false);
  };
  // 获取等级标签
  const getTagNameList = () => {
    ProduceManageAPI.getCooperationListTag().then(({ result }) => {
      setTagInfoList(result || []);
    });
  };
  // 点击确定,触发表单验证
  const submitSku = () => {
    skuForm
      .validateFields()
      .then(async (values) => {
        if (!isCustomProd) {
          let productObj: productType[0] | undefined = undefined;
          switch (currentDesc) {
            case 2:
              // const schemeObj = schemeList.find((i) => i.id === values.skuId);
              // values.skuName = schemeObj?.solutionName;
              break;
            default:
              productObj = productList.find((i) => i.id === values.skuId);
              values.skuName = productObj?.productName;
          }
          values.specIds = values.specIds.reduce((pre: any, cur: number | string) => {
            const sourceObj = productSpecList.find((i) => i.id === cur);
            const specObj: any =
              curtRowData?.specIds && curtRowData?.specIds.find((i: any) => i.mallSpecId === cur);
            pre.push({
              mallSpecId: cur,
              specName: sourceObj?.specName,
              partNo: sourceObj?.partNo,
              id: specObj ? specObj.id : undefined,
            });
            return pre;
          }, []);
          handleOk({ ...values, id: curtRowData?.id || Math.random() });
        } else {
          const res: any = await Promise.all([validateCustomForm()]);
          handleOk({
            ...values,
            customizeInfo: res[0],
            id: curtRowData?.id || Math.random(),
            skuId: curtRowData?.skuId,
            skuName: values.productName,
            delProductSpecId: selfIds,
          });
        }
        // onCancel();
      })
      .catch(() => {});

    // 验证自定义表单
    const validateCustomForm: any = () => {
      return new Promise((resolve, reject) => {
        selfProduct
          .validateFields()
          .then(async (values) => {
            for (let i = 0; i < selfProductData.length; i++) {
              const v = selfProductData[i];
              if (!v.specImage) {
                return message.warning(`自定义选项第${i + 1}行未上传图片`);
              }
            }
            for (let i = 0; i < selfProductData.length; i++) {
              const v = selfProductData[i];
              if (!(Object.keys(v.productSpecCPQVO).length != 0 && v.productSpecCPQVO.specPrice)) {
                return message.warning(`自定义选项第${i + 1}行未配置价格`);
              }
            }
            const arr: customizeEntity[] = selfProductData.map((i: customizeEntity) => {
              return {
                specName: values[`specName${i.id}`],
                partNo: values[`partNo${i.id}`],
                specImage: i.specImage,
                productSpecCPQVO: i.productSpecCPQVO,
                fileList: i.fileList,
                id: i.productSpec || i.id,
                productSkuId: curtRowData && curtRowData.skuId,
              };
            });
            resolve([...arr]);
          })
          .catch((err) => {
            message.warning(err.errorFields[0].errors[0]).then();
            reject([]);
          });
      });
    };
  };
  useEffect(() => {
    if (Object.keys(curtRowData).length !== 0) {
      setDialogTitle('编辑');
      getProductList(curtRowData.categoryId as number);
      if (!curtRowData.flag) {
        getProductSpecList(curtRowData.skuId as number);
      }
      const specIds: number[] =
        curtRowData.specIds && curtRowData.specIds.map((i: any) => i.mallSpecId);
      skuForm.setFieldsValue({
        goodsSpecName: curtRowData.goodsSpecName,
        chooseType: curtRowData.chooseType,
        skuUnitId: curtRowData.skuUnitId,
        categoryId: curtRowData.categoryId, // 产品类型或所属行业ID
        skuId: curtRowData.skuId, // 产品或方案ID
        must: curtRowData.must,
        specIds, // 选项来源ID数组
        productName: curtRowData.flag === 1 ? curtRowData.skuName : undefined,
        flag: curtRowData.flag,
      });
      setIsCustomProd(curtRowData.flag === 1);
      if (curtRowData.flag === 1) {
        setSelfProductData([...(curtRowData.customizeInfo as customizeEntity[])]);
        const objForm: any = curtRowData.customizeInfo?.reduce((pre: any, cur: customizeEntity) => {
          pre[`partNo${cur.id}`] = cur.partNo;
          pre[`specName${cur.id}`] = cur.specName;
          return pre;
        }, {});
        selfProduct.setFieldsValue(objForm);
      }
    } else {
      setDialogTitle('添加');
    }
  }, [curtRowData]);
  return (
    <div>
      <Modal
        open={open}
        title={`${dialogTitle}规格`}
        onOk={() => submitSku()}
        onCancel={onCancel}
        width={820}
        destroyOnClose
      >
        <Form
          preserve={false}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          form={skuForm}
          initialValues={{ chooseType: 0, skuUnitId: 1, must: 0, flag: 0 }}
        >
          <Form.Item
            label='规格名称'
            name='goodsSpecName'
            rules={[{ required: true, message: '请输入规格名称' }]}
          >
            <Input placeholder='请输入规格名称' maxLength={30} />
          </Form.Item>
          {currentDesc != 2 && (
            <Form.Item label='规格来源' name='flag'>
              <Radio.Group onChange={skuSourceRadioChange}>
                <Radio value={0}>获取</Radio>
                <Radio value={1} disabled={goodsType === 1}>
                  自定义
                </Radio>
              </Radio.Group>
            </Form.Item>
          )}

          {currentDesc != 2 ? (
            <>
              {/*<Form.Item*/}
              {/*  name='categoryId'*/}
              {/*  label='产品类型'*/}
              {/*  rules={[{ required: true, message: '请选择产品类型' }]}*/}
              {/*>*/}
              {/*  <Select*/}
              {/*    placeholder='请选择产品类型'*/}
              {/*    onSelect={handleProdTypeSelect}*/}
              {/*    showSearch*/}
              {/*    filterOption={(input, option: any) =>*/}
              {/*      (option?.label ?? '').toLowerCase().includes(input.toLowerCase())*/}
              {/*    }*/}
              {/*  >*/}
              {/*    {categoryList.map((item) => (*/}
              {/*      <Select.Option value={item.id} key={item.id}>*/}
              {/*        {item.classifyName}*/}
              {/*      </Select.Option>*/}
              {/*    ))}*/}
              {/*  </Select>*/}
              {/*</Form.Item>*/}
              {!isCustomProd ? (
                <Form.Item
                  name='skuId'
                  label='产品'
                  rules={[{ required: true, message: '请选择产品' }]}
                >
                  <Select
                    placeholder='请选择产品'
                    onSelect={handleProdOrInduSelected}
                    filterOption={(input, option) =>
                      (option!.children as unknown as string)
                        .toLowerCase()
                        .includes(input.toLowerCase())
                    }
                    showSearch
                  >
                    {productList.map((item: any) => (
                      <Select.Option value={item.id} key={item.id}>
                        {item.productName}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              ) : (
                <Form.Item
                  name='productName'
                  label='产品'
                  rules={[{ required: true, message: '请选择产品' }]}
                >
                  <Input placeholder='请输入产品名称' maxLength={50} />
                </Form.Item>
              )}
            </>
          ) : (
            <>
              <Form.Item
                label='所属行业'
                name='goodsTypeId'
                rules={[{ required: true, message: '请选择所属行业' }]}
              >
                <Select
                  placeholder='请选择所属行业'
                  // onSelect={handleIndeTypeSelect}
                  filterOption={(input, option) =>
                    (option!.children as unknown as string)
                      .toLowerCase()
                      .includes(input.toLowerCase())
                  }
                  showSearch
                >
                  {/*{categoryList.map((item: categoryEntity) => (*/}
                  {/*  <Select.Option value={item.goodsMasterTypeId} key={item.goodsMasterTypeId}>*/}
                  {/*    {item.goodsMasterType}*/}
                  {/*  </Select.Option>*/}
                  {/*))}*/}
                </Select>
              </Form.Item>
              <Form.Item
                label='方案'
                name='skuId'
                rules={[{ required: true, message: '请选择方案' }]}
              >
                <Select
                  showSearch
                  placeholder='请选择方案'
                  // onSelect={handleProdOrInduSelected}
                  filterOption={(input, option) =>
                    (option!.children as unknown as string)
                      .toLowerCase()
                      .includes(input.toLowerCase())
                  }
                >
                  {/*{schemeList.map((item: any) => (*/}
                  {/*  <Select.Option value={item.id} key={item.id}>*/}
                  {/*    {item.solutionName}*/}
                  {/*  </Select.Option>*/}
                  {/*))}*/}
                </Select>
              </Form.Item>
            </>
          )}
          {isCustomProd ? (
            <Form.Item label='自定义选项'>
              <div style={{ marginBottom: '10px' }}>
                <Button icon={<PlusOutlined />} type='primary' onClick={addSelfSelectItem} />
              </div>
              <Form form={selfProduct} component={false}>
                <Table
                  size='small'
                  rowKey='id'
                  bordered
                  columns={mergedColumns}
                  dataSource={selfProductData}
                  pagination={false}
                  components={{
                    body: {
                      cell: EditableCell,
                    },
                  }}
                />
              </Form>
            </Form.Item>
          ) : (
            <Form.Item
              name='specIds'
              label='选项来源'
              rules={[{ required: true, message: '请选择选项来源' }]}
            >
              <Select
                placeholder='请选择选项来源'
                allowClear
                mode='multiple'
                onSelect={handleSourceSelect}
              >
                {productSpecList.map((item: any) => (
                  <Select.Option value={item.id} key={item.id} disabled={item.disabled}>
                    {item.specName}&nbsp;{item.partNo && `（${item.partNo}）`}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          )}
          <Form.Item label='选择方式' name='chooseType'>
            <Radio.Group>
              <Radio value={0}>单选</Radio>
              <Radio value={1} disabled={goodsType === 1}>
                多选
              </Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label='是否必选' name='must'>
            <Radio.Group>
              <Radio value={0}>非必选</Radio>
              <Radio value={1}>必选</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label='规格单位'
            name='skuUnitId'
            rules={[{ required: true, message: '请选择规格单位' }]}
          >
            <Select placeholder='请选择规格单位'>
              {skuUnitList.map((item: any) => {
                return (
                  <Select.Option value={item.id} key={item.id}>
                    {item.unitName}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
      {/*配置价格*/}
      <ConfigurePriceModal
        open={configurePriceModalShow}
        handleOk={configurePriceHandleOk}
        handleCancel={configurePriceHandleCancel}
        customRowData={customRowData}
        tagInfoList={tagInfoList}
        goodsType={goodsType}
      />
    </div>
  );
};

export default AddOrEditSkuModal;
