import React, { FC, useEffect, useState } from 'react';
import { Button, Form, Input, message, Modal, ModalProps, Radio, Select, Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { CategoryManageAPI, ProduceManageAPI } from '~/api';
import { InterDataType, PaginationProps } from '~/api/interface';
import { productListType } from '~/api/interface/produceManageType';
import { categoryListType } from '~/api/interface/categoryManage';

//自定义产品返回类型
type selfProduceItemType = InterDataType<productListType>['list'][0] & {
  radio?: number;
};
//分类通用类型
type categoryResponseType = InterDataType<categoryListType>['list'];

const { Option } = Select;

interface PropsType {
  close: () => void;
  data: selfProduceItemType[]; //已被关联产品
  connectProduceSubmit: (data: selfProduceItemType[]) => void;
  toDesignateSpec: (id: number) => void;
}
// 表单提交
interface FormType {
  keyword?: string;
  userType?: number;
  roleId?: number;
  accountStatus?: number;
}

// 当前选择的参数

const ConnectProduceModal: FC<ModalProps & PropsType> = ({
  open,
  close,
  connectProduceSubmit,
  data,
  toDesignateSpec,
}) => {
  // 表格数据
  const [tableData, setTableData] = useState<selfProduceItemType[]>([]);
  // 所有表格数据
  const [allTableData, setAllTableData] = useState<selfProduceItemType[]>([]);
  // 产品类型列表
  const [productTypeList, setProductTypeList] = useState<categoryResponseType>([]);
  // 表格结构
  const columns: ColumnsType<selfProduceItemType> = [
    { title: '产品名称', dataIndex: 'productName', align: 'center' },
    {
      title: '产品类型',
      dataIndex: 'categoryName',
      align: 'center',
      width: '100px',
    },
    { title: '型号', dataIndex: 'model', align: 'center' },
    { title: '产品品牌', dataIndex: 'productBrand', align: 'center' },
    {
      title: '产品规格',
      align: 'center',
      width: '250px',
      render: (record) => {
        return (
          <div>
            <Radio.Group
              onChange={(e) => {
                const { value } = e.target;
                // 通过index生成新tableData
                const list = tableData.map((i) => {
                  if (i.id === record.id) {
                    return {
                      ...i,
                      radio: value,
                    };
                  }
                  return i;
                });
                setTableData(list);
                const allList = allTableData.map((i) => {
                  if (i.id === record.id) {
                    return {
                      ...i,
                      radio: value,
                    };
                  }
                  return i;
                });
                setAllTableData(allList);
              }}
              value={record.radio}
              disabled={getTableDisable(record.id)}
            >
              <Radio value={0}>不指定</Radio>
              <Radio value={1}>指定</Radio>
            </Radio.Group>
            <Button
              disabled={getTableDisable(record.id) || record.radio === 0}
              onClick={() => toDesignateSpecClick(record.id)}
              type='link'
            >
              去指定
            </Button>
          </div>
        );
      },
    },
  ];
  // 表格分页配置
  const [pagination, setPagination] = useState<
    PaginationProps & { totalCount: number; totalPage: number }
  >({
    totalCount: 0,
    pageSize: 10,
    pageNo: 1,
    totalPage: 0,
  });
  // 表格多选
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  // 表格多选事件
  const onSelectChange = (newSelectedRowKeys: React.Key[], selectedRows: selfProduceItemType[]) => {
    // 新增
    const isAdd: boolean = newSelectedRowKeys.some((v: React.Key) => !selectedRowKeys.includes(v));
    // 删除
    const isDelete: boolean = selectedRowKeys.some(
      (v: React.Key) => !newSelectedRowKeys.includes(v),
    );
    let rowKeys: React.Key[] = [];
    if (isAdd) {
      const filterList: selfProduceItemType[] = selectedRows.filter(
        (v: selfProduceItemType) => !selectedRowKeys.includes(v.id),
      );
      const obj: selfProduceItemType | undefined = filterList.find(
        (v: selfProduceItemType) => !v.productSpecList,
      );
      const currentKeys: React.Key[] = filterList
        .filter((v: selfProduceItemType) => v.productSpecList)
        .map((v: selfProduceItemType) => v.id);
      rowKeys = [...selectedRowKeys, ...currentKeys];
      if (obj) {
        message.warning(`请先为产品${obj?.productName}添加规格`);
      }
    } else if (isDelete) {
      rowKeys = selectedRowKeys.filter((v: React.Key) => {
        const bol: boolean = tableData.every((i: selfProduceItemType) => i.id !== v);
        return bol || newSelectedRowKeys.includes(v);
      });
    }
    setSelectedRowKeys(rowKeys);
  };
  // 根据id判断是否有操作的权限
  const getTableDisable = (id: number) => {
    return !selectedRowKeys.includes(id);
  };
  //获取产品列表
  const getListPageProductSku = (value?: any, tip?: string) => {
    ProduceManageAPI.listPageProductSku({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...value,
    }).then(({ result: { list, totalPage, totalCount } }) => {
      pagination.totalCount = totalCount;
      pagination.totalPage = totalPage;
      setPagination(pagination);
      // 设置产品规格默认项
      if (!list) {
        return setTableData([]);
      }
      const arr = list.map((i) => {
        return {
          ...i,
          radio: 0,
        };
      });
      const brr = arr.map((i) => {
        const item = data.find((j) => j.id === i.id);
        if (item?.id === i.id) {
          return {
            ...i,
            radio: item.radio,
          };
        }
        return i;
      });
      setTableData(brr);
      if (tip === 'all') {
        setAllTableData(brr);
      }
    });
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getListPageProductSku();
  };
  // 表单提交
  const onFinish = (val: FormType) => {
    // 在这里对提交的数据做处理，如range转为开始和结束时间
    const data = Object.fromEntries(
      // 过滤为空项
      Object.entries({
        ...val,
      }).filter((i) => i[1] !== '' && i[1] !== undefined && i[1] !== null),
    );
    getListPageProductSku(data);
  };
  // 获取产品类型
  const getProduceTypeList = () => {
    CategoryManageAPI.getCategoryList({ directoryId: 1, type: 4, pageNo: 1, pageSize: 99999 }).then(
      ({ result }) => {
        setProductTypeList(result.list || []);
      },
    );
  };
  // 关联产品的数据提交
  const handleSubmit = () => {
    if (selectedRowKeys.length === 0) {
      return message.warning('请选择关联产品');
    }
    const connectProduceList = allTableData.filter((i) => selectedRowKeys.includes(i.id));
    connectProduceSubmit(connectProduceList);
  };

  // componentsDidMounted
  useEffect(() => {
    getListPageProductSku();
    getListPageProductSku({ pageNo: 1, pageSize: 99999 }, 'all');
    getProduceTypeList();
    if (data.length !== 0) {
      setSelectedRowKeys(data.map((v) => v.id));
    }
  }, [data]);
  //去指定
  const toDesignateSpecClick = (id: number) => {
    toDesignateSpec(id);
  };

  return (
    <>
      <Modal
        open={open}
        title='关联产品'
        onCancel={() => close()}
        onOk={handleSubmit}
        destroyOnClose
        width={860}
      >
        <Form name='basic' layout='inline' onFinish={onFinish} style={{ marginBottom: '20px' }}>
          <Form.Item name='productName' label='产品名称'>
            <Input placeholder='请输入产品名称' allowClear />
          </Form.Item>
          <Form.Item name='goodsTypeId' label='产品类型'>
            <Select placeholder='请选择产品类型' allowClear>
              {productTypeList.map((i, j) => (
                <Option value={i.id} key={j}>
                  {i.classifyName}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type='primary' htmlType='submit'>
              搜索
            </Button>
          </Form.Item>
        </Form>
        <Table
          size='small'
          dataSource={tableData}
          columns={columns}
          rowKey='id'
          scroll={{ x: '100%' }}
          bordered
          rowSelection={{
            selectedRowKeys,
            onChange: onSelectChange,
          }}
          pagination={{
            total: pagination.totalCount,
            pageSize: pagination.pageSize,
            current: pagination.pageNo,
            showSizeChanger: true,
            showQuickJumper: true,
            onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
            showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
          }}
        />
      </Modal>
    </>
  );
};
export default ConnectProduceModal;
