import React, { FC, useEffect, useState } from 'react';
import { Form, Input, Modal, message, Table, Button, ModalProps } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { InterDataType, PaginationProps } from '~/api/interface';
import { Uploader } from '~/components/uploader';
import { UploadOutlined } from '@ant-design/icons';
import { productListType } from '~/api/interface/produceManageType';
import { IndustryManageAPI } from '~/api';
import { filterObjAttr } from '~/utils';
import { industrySpecDetailType } from '~/api/interface/industryManageType';

//自定义产品返回类型
type selfProduceItemType = InterDataType<productListType>['list'][0] & {
  radio?: number;
};
//方案规格详情返回类型
type specDetailType = InterDataType<industrySpecDetailType>;

interface PropsType {
  produceSpecList: selfProduceItemType[];
  close: () => void;
  connectSpecModalShow: () => void;
  industrySkuId: number;
  handleSuccess: () => void;
  specDetail: specDetailType;
}

const AddOrEditSpecModal: FC<ModalProps & PropsType> = ({
  open,
  produceSpecList,
  close,
  connectSpecModalShow,
  industrySkuId,
  specDetail,
  handleSuccess,
}) => {
  // 表格事件
  const [form] = Form.useForm<{ specName: string; specImage: string; list: any }>();
  //图片
  const [fileList, setFileList] = useState<
    {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[]
  >([]);
  // 表格结构
  const columns: ColumnsType<selfProduceItemType> = [
    {
      title: '序号',
      align: 'center',
      render: (text: string, record: selfProduceItemType, index: number) => {
        return (pagination.pageNo - 1) * pagination.pageSize + index + 1;
      },
    },
    { title: '产品名称', dataIndex: 'productName', align: 'center' },
    { title: '产品类型', dataIndex: 'categoryName', align: 'center' },
    { title: '型号', dataIndex: 'model', align: 'center' },
    { title: '产品品牌', dataIndex: 'productBrand', align: 'center' },
    {
      title: '产品规格',
      // align: "left",
      width: 300,
      ellipsis: true,
      render: (record: selfProduceItemType) => {
        if (record.radio === 0) {
          return '不指定';
        }
        return record.productSpecList.map((i: any, index: number) => (
          <div key={index}>
            {i.specName}({i.partNo})
          </div>
        ));
      },
      onHeaderCell: () => {
        return {
          style: {
            textAlign: 'center',
          },
        };
      },
    },
  ];
  // 分页
  const [pagination, setPagination] = useState<PaginationProps>({
    pageNo: 1,
    pageSize: 10,
  });

  // 关闭弹窗
  const handleClosed = async () => {
    setFileList([]);
    form.resetFields();
    close();
  };
  // 打开关联产品弹窗
  const handleConnectSpecModalShow = () => {
    connectSpecModalShow();
  };
  //图片上传成功
  const uploadFileSuccess = (
    fileList: {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[],
  ) => {
    form.setFieldsValue({
      specImage: fileList[0].url,
    });
  };
  // 触发表单验证
  const handleSubmit = () => {
    form
      .validateFields()
      .then((values) => {
        const productInventoryList: any = produceSpecList.map((v) => ({
          productSku: {
            id: v.id,
            directoryId: v.directoryId,
            goodsTypeId: v.categoriesId,
            model: v.model,
            productBrand: v.productBrand,
            productBrandId: v.productBrandId,
            productName: v.productName,
          },
          select: v.radio,
          productSpecList: v.productSpecList,
        }));
        IndustryManageAPI[specDetail.id ? 'editIndustrySpec' : 'addIndustrySpec']({
          ...filterObjAttr(values, ['list']),
          productInventoryList,
          industrySkuId,
          id: specDetail.id ? specDetail.id : undefined,
        }).then(({ code }) => {
          if (code === '200') {
            message.success(specDetail.id ? '编辑成功' : '新增成功');
            form.resetFields();
            handleSuccess();
          }
        });
      })
      .catch((err) => {
        message.warning(err.errorFields[0].errors[0]).then();
      });
  };

  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    setPagination({ ...pagination });
  };
  // componentsDidMounted
  useEffect(() => {
    form.setFieldsValue({
      list: produceSpecList.length !== 0 ? produceSpecList : undefined,
    });
  }, [produceSpecList]);
  useEffect(() => {
    form.setFieldsValue({
      specName: specDetail.specName || undefined,
      specImage: specDetail.specImage || undefined,
    });
    if (specDetail.specImage) {
      setFileList([
        {
          id: Math.random(),
          name: 'img',
          uid: Math.random(),
          url: specDetail.specImage,
        },
      ]);
    } else {
      setFileList([]);
    }
  }, [specDetail]);

  return (
    <>
      <Modal
        open={open}
        title='新增'
        onCancel={handleClosed}
        onOk={handleSubmit}
        destroyOnClose
        width={800}
      >
        <Form name='form' form={form} layout='horizontal'>
          <Form.Item
            name='specName'
            label='规格名称'
            rules={[{ required: true, message: '请输入方案产品名称' }]}
          >
            <Input
              placeholder='请输入规格名称'
              allowClear
              style={{ width: '400px' }}
              maxLength={30}
            />
          </Form.Item>
          <Form.Item
            name='specImage'
            label='规格图片'
            rules={[{ required: true, message: '请上传规格图片' }]}
          >
            <Uploader
              listType='picture-card'
              fileUpload
              onChange={uploadFileSuccess}
              defaultFileList={fileList}
            >
              <UploadOutlined />
            </Uploader>
          </Form.Item>
          <Form.Item
            label='产品清单'
            name='list'
            rules={[{ required: true, message: '请选择产品清单' }]}
          >
            <Button type='primary' onClick={handleConnectSpecModalShow}>
              添加关联
            </Button>
          </Form.Item>
          <Form.Item>
            <Table
              size='small'
              dataSource={produceSpecList}
              columns={columns}
              rowKey='id'
              style={{ width: '100%' }}
              pagination={{
                pageSize: pagination.pageSize,
                current: pagination.pageNo,
                onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
              }}
              bordered
            />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};
export default AddOrEditSpecModal;
