import usePagination from '@/hooks/usePagination';
import { getListApi } from '@/pages/capital/StandardMange/api';
import { Button, Input, Modal, Popover, Row, Table, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { debounce } from 'lodash';
import React, { useEffect, useState } from 'react';
import { AssetTypeEnum } from '@/pages/capital/entity';

interface Props {
  visible: boolean;
  onCancel: () => void;
  onChange?: Function;
  value?: any;
  multiple?: boolean;
}

const columns: ColumnsType<StanderList.ListVO> = [
  {
    title: '物品名称',
    dataIndex: 'name',
    render: (text: string, row: StanderList.ListVO) => {
      return (
        <>
          <div>{text}</div>
          <Tag style={{ fontSize: 12 }}>{row.type && AssetTypeEnum[row.type]}</Tag>
        </>
      );
    }
  },
  {
    title: '物品编码',
    dataIndex: 'code',
  },
  {
    title: '规格型号',
    dataIndex: 'specList',
    render: (text, record) => {
      const items = (text || []).map(i => `${i.standardSpecName}：${i.specDetails}`);
      return (
        <Popover
          placement="topLeft"
          content={<div style={{ maxWidth: 260 }}>{items.join('；')}</div>}
        >
          <div>
            {items.slice(0, 3).map((i: string) => {
              return (
                <p key={i} style={{ margin: 0, fontSize: 12 }}>{i}</p>
              );
            })}
            {items.length > 3 ? (<span>...</span>) : null}
          </div>
        </Popover>
      );
    },
  }];

const SelectGoodsTable = (props: Props) => {
  const { visible, onCancel, onChange, multiple = true, value = [] } = props;
  const { list, paginationConfig, loading, setLoading, setParams } = usePagination(getListApi, { status: 1 });
  const [selectedRow, setSelectedRow] = useState<StanderList.ListVO[]>([]);

  useEffect(() => {
    if (value.length > 0) {
      setSelectedRow([...value]);
    }
  }, [value]);
  const start = () => {
    setLoading(true);
    // ajax request after empty completing
    setTimeout(() => {
      setSelectedRow([]);
      setLoading(false);
    }, 1000);
  };

  function saveDate() {
    console.log("🚀 ~ file: SelectGoodsTable.tsx:80 ~ saveDate ~ selectedRow:", selectedRow);

    onChange && onChange(selectedRow);
    onCancel();
  }

  const onFilter = debounce((v: string) => {
    setParams({ keywords: v }, true);
  }, 600);

  const rowSelection = {
    type: multiple ? "checkbox" : "radio",
    selectedRowKeys: selectedRow.map(row => row.code),
    onSelect: (row: any, _selected: boolean) => {
      const index = selectedRow.findIndex((_row) => _row.code == row.code);
      if (!multiple) {
        setSelectedRow([row]);
        return;
      }
      if (_selected) {
       selectedRow.unshift(row);
      } else if (index > -1) {
        selectedRow.splice(index, 1);
      }
      setSelectedRow([...selectedRow]);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      const changedKeys = changeRows.map((row) => row.code);
      let newData = [...selectedRow];
      // 全选
      if (selected) {
        // 过滤掉已选的
        newData = selectedRow.concat(changeRows.filter((row: any) => !selectedRow.some((item) => item.code == row.code)));
      } else {
        // 全不选 - 去掉已选的
        newData = selectedRow.filter((row) => !changedKeys.includes(row.code));
      }
      setSelectedRow(newData);
    },
  };
  const hasSelected = selectedRow.length > 0;

  return (
    <Modal
      visible={visible}
      onCancel={onCancel}
      onOk={saveDate}
      centered
      title="选择规格型号标准"
      width={650}
    >
      <Row style={{ marginBottom: 16, alignItems: "center" }} justify="space-between">
        <Input
          allowClear
          style={{ width: 230 }}
          placeholder="搜索型号名称"
          onChange={(e) => onFilter(e.target.value)}
        />
        {!!multiple && (
          <div>
            <Button type="primary" onClick={start} disabled={!hasSelected} loading={loading}>
              重置
            </Button>
            <span style={{ marginLeft: 8 }}>
              {hasSelected ? `已选择 ${selectedRow.length} 项` : ''}
            </span>
          </div>
        )}
      </Row>
      <Table
        loading={loading}
        rowKey="code"
        pagination={paginationConfig}
        rowSelection={rowSelection}
        columns={columns}
        dataSource={list}
        size="small"
      />
    </Modal>
  );
};

export default SelectGoodsTable;