import React, {useEffect, useMemo, useState} from 'react';
import {Modal, Table, Input, message, Button, Select, Switch} from 'antd';
import Column from 'antd/lib/table/Column';
import { debounce } from 'lodash';
import {getPartTypeApi} from '@/pages/pms/part/Repertory/api';
import useInitail from '@/hooks/useInitail';
import {planPoolTypeData} from '@/pages/pms/entity';

const Search = Input.Search;
interface Props {
  onCancel: () => any,
  visible: boolean,
  parts: any[]
  onOk: (parts: any[]) => any
  setParams: Function
  _supplierId: number | undefined
}
const {Option} = Select;
export default function Index({ onCancel, visible, parts = [], onOk, setParams, _supplierId }: Props) {
  const [selectedParts, setSelectedParts] = useState<any[]>([]);
  const [dfParam, setDfParam] = useState<any>({keywords: ''});
  const [partList, setPartList] = useState(parts);
  const [info, setInfo] = useState<{open: boolean, partName: string, poolId?: number}>({open: false, partName: '', poolId: undefined});
  const [partArr, setPartArr] = useState<any[]>([]);

  const shopNames = useMemo(() => {
    return Array.from(new Set(parts.map(it => it.shopName || '').filter(it => !!it)));
  }, [parts]);
  
  const storageNames = useMemo(() => {
    return Array.from(new Set(parts.map(it => it.storageName || '').filter(it => !!it)));
  }, [parts]);

  const supplierNames = useMemo(() => {
    return Array.from(new Set(parts.map(it => it.supplierName || '').filter(it => !!it)));
  }, [parts]);

  const { data: partTypeData } = useInitail(getPartTypeApi, [], {});
  
  useEffect(() => {
    if (!visible) {
      setSelectedParts([]);
      setPartArr([]);
      setPartList(parts);
    }
  }, [visible, parts]);

  function handSave() {
    if (selectedParts.length == 0) {
      message.error("请选择配件");
      return;
    }
    if (partArr.some(it => !!it.supplierId)) {
      for (const item of partArr) {
        if (!!item.supplierId && item.supplierId != _supplierId) {
          setInfo({ open: true, partName: item.partName, poolId: item.poolId });
          return;
        }
      }
    }
    onOk && onOk(selectedParts);
    onCancel && onCancel();
  }

  const handleChange = debounce((value) => {
    setDfParam({...dfParam, keywords: value || ''});
  }, 500);

  useEffect(() => {
    setPartList(parts.filter(it => {
      return (it.partCode || '').includes(dfParam.keywords)
        || (it.partName || '').includes(dfParam.keywords)
        || (it.supplierName || '').includes(dfParam.keywords);
    })
    .filter(it => {
      return (dfParam.partTypeName && it.partTypeName.includes(dfParam.partTypeName)) || !dfParam.partTypeName;
    })
    .filter(it => {
      return (dfParam.storageName && it.storageName == dfParam.storageName) || !dfParam.storageName;
    })
    .filter(it => {
      return (dfParam.shopName && it.shopName == dfParam.shopName) || !dfParam.shopName;
    })
    .filter(it => {
      return (dfParam.supplierName && it.supplierName == dfParam.supplierName) || !dfParam.supplierName;
    })
    .filter(i => (dfParam.typeName && i.typeName == planPoolTypeData.find(item => item.value == dfParam.typeName)?.label) || !dfParam.typeName));
  }, [dfParam]);
  
  return (
    <Modal
      width={1300}
      visible={visible}
      title="配件采购明细"
      onCancel={onCancel}
      maskClosable={false}
      footer={[
        <Button key="cancel" onClick={onCancel}>取消</Button>,
        <Button
          key="submit"
          disabled={selectedParts.length == 0}
          onClick={handSave}
          type="primary"
          htmlType="submit"
        >
          确认
        </Button>
      ]}
    >
      <div style={{display: 'flex', flexWrap: 'wrap', justifyContent: 'flex-start', alignItems: 'center', marginBottom: 10}}>
        <Search
          allowClear
          enterButton
          placeholder="请输入配件名称/编码"
          onSearch={handleChange}
          style={{ maxWidth: 200, marginRight: 10 }}
        />
        <Select
          allowClear
          style={{ width: 150, marginRight: 10}}
          onChange={(v) => {
            setDfParam({...dfParam, partTypeName: partTypeData.find(i => i.value == v)?.label});
          }}
          placeholder="请选择配件类型"
          showSearch
          optionFilterProp="children"
        >
          {partTypeData.map((item: any) => (
            <Option value={item.value} key={item.value}>{item.label}</Option>
          ))}
        </Select>
        <Select
          allowClear
          style={{ width: 150, marginRight: 10}}
          onChange={(storageName) => {
            setDfParam({...dfParam, storageName});
          }}
          placeholder="请选择库房"
          showSearch
          optionFilterProp="children"
        >
          {storageNames.map((item: any) => (
            <Option value={item} key={item}>{item}</Option>
          ))}
        </Select>
        <Select
          allowClear
          style={{ width: 150, marginRight: 10}}
          onChange={(shopName) => {
            setDfParam({...dfParam, shopName});
          }}
          placeholder="请选择门店"
          showSearch
          optionFilterProp="children"
        >
          {shopNames.map((item: any) => (
            <Option value={item} key={item}>{item}</Option>
          ))}
        </Select>
        <Select
          allowClear
          style={{ width: 150}}
          onChange={(typeName) => {
            setDfParam({...dfParam, typeName});
          }}
          placeholder="配件来源类型"
          showSearch
          optionFilterProp="children"
        >
          {planPoolTypeData.map((item: any) => (
            <Option value={item.value} key={item.value}>{item.label}</Option>
          ))}
        </Select>
        <Select
          allowClear
          style={{ width: 150, marginLeft: 10}}
          onChange={(supplierName) => {
            setDfParam({...dfParam, supplierName});
          }}
          placeholder="上次采购供应商"
          showSearch
          optionFilterProp="children"
        >
          {supplierNames.map((item: any) => (
            <Option value={item} key={item}>{item}</Option>
          ))}
        </Select>
        <Switch
          checkedChildren="油料" 
          unCheckedChildren="非油料" 
          onChange={checked => setParams({isOil: checked}, true)} 
          style={{marginLeft: 10}}
        />
      </div>
      <Table
        dataSource={partList}
        scroll={{y: 400}}
        style={{width: '100%'}}
        pagination={false}
        rowSelection={{
          type: "checkbox",
          selectedRowKeys: selectedParts.map(part => `${part.poolId}`),
          onSelect: (row: any, _selected: boolean) => {
            const index = selectedParts.findIndex(_row => _row.poolId == row.poolId);
            let newData = [...selectedParts];
            if (_selected) {
              newData.unshift(row);
            } else if (index > -1) {
              newData.splice(index, 1);
            }
            setPartArr(newData);
            setSelectedParts([...newData]);
          },
          onSelectAll: (selected, selectedRows, changeRows) => {
            const changedKeys = changeRows.map(row => `${row.poolId}`);
            let newData = [...selectedParts];
            // 全选
            if (selected) {
              newData = selectedParts.concat(changeRows.filter(row => !selectedParts.some(item => item.poolId == row.poolId)),);
            } else {
              newData = selectedParts.filter(row => !changedKeys.includes(`${row.poolId}`));
            }
            setPartArr(newData);
            setSelectedParts(newData);
          },
        }}
        rowKey={(record) => `${record.poolId}`}
      >
        <Column title="配件编码" dataIndex="partCode" />
        <Column title="配件名称" dataIndex="partName" />
        <Column title="库房名称" dataIndex="storageName" />
        <Column title="门店名称" dataIndex="shopName" />
        <Column title="配件数量" dataIndex="count" />
        <Column title="配件类型" dataIndex="partTypeName" />
        <Column title="配件来源类型" dataIndex="typeName" />
        <Column title="上次采购供应商" dataIndex="supplierName" />
      </Table>
      <Modal
        title="提示"
        open={info.open}
        maskClosable={false}
        closable={false}
        cancelText="重新选择"
        okText="继续"
        onCancel={() => {
          setPartArr(partArr.filter((i => i.poolId != info.poolId)));
          setSelectedParts(selectedParts.filter((i => i.poolId != info.poolId)));
          setInfo({open: false, partName: '', poolId: undefined});
        }}
        onOk={() => {
          setPartArr(partArr.filter((i => i.poolId != info.poolId)));
          setInfo({ open: false, partName: '', poolId: undefined });
        }}
      >
        <p style={{ color: 'red' }}><span style={{ color: '#333333', fontWeight: '500', marginRight: 3}}>【{info.partName}】</span>本次采购供应商和上次采购供应商不一致，是否继续？</p>
      </Modal>
    </Modal>
  );
}
