import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { difference, uniq } from 'lodash';
import List from '../SimpleList';
import { isEqual } from '@zenview/micro-utils';
import CBox from '../../../themeComponents/CBox';
import TreeTitle from '../../../businessComponents/TreeTitle';
import { RenderItem } from './renderItem';
import CheckAll from './checkAll';
import { Dict } from '@zenview/micro-basic-library';
import { Select } from 'antd';
import { computedCheckStatus, getAllDeviceTypeDict } from './utils';
import './index.less';
const { Option } = Select;
const { deviceStatus } = Dict.device;
function CheckList(props) {
  const { className, style, CustomRender, hasHeader, checkable, itemNameKey, destoryList, activeKey, checkExt, title, onChange, placeholder, list, checkedKeys, itemKey, defaultCheckedIds, titleExt, deviceGroup = [], hasFilter } = props;
  const [state, setState] = useState({ checkedKeys: defaultCheckedIds || checkedKeys || [] });
  const [filterData, setFilterData] = useState({})
  const showList = useMemo(() => {
    const { deviceStatus, deviceType ,lygroupId} = filterData
    let arr = list
    if(deviceStatus && deviceStatus!=='-1'){
      arr = arr.filter(v => String(v.deviceStatus)===deviceStatus)
    }
    if(deviceType){
      arr = arr.filter(v => v.deviceType === deviceType)
    }
    if(lygroupId){
      arr = arr.filter(v => v.lygroupId===lygroupId)
    }
    return arr
  }, [list, filterData])
  const { checkHalfStatus, checkAllStatus, listKey } = useMemo(() => computedCheckStatus(showList, state.checkedKeys, itemKey), [itemKey, showList, state.checkedKeys]);

  const deviceAndMjType = getAllDeviceTypeDict().filter((v) => !(v.value === '-1' || Dict.device.db.value === v.value));
  /**
   * 列表选中处理
  */
  const onChecked = useCallback(
    (e) => {
      let ids = state.checkedKeys || [];
      const id = e.target.value;
      const flag = e.target.checked;
      if (flag) {
        ids.push(id);
      } else {
        ids = ids.filter((v) => v !== id);
      }
      setState((old) => ({ ...old, checkedKeys: [...ids] }));
      props.onChecked && props.onChecked(ids, difference(listKey, ids));
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [listKey, state.checkedKeys]
  );

  /**
   * 列表渲染
   */
  const renderRow = useCallback(
    ({ key, index, style }) => {
      const options = {
        ...state,
        item: showList[index],
        onChecked,
        checkable,
        key,
        index,
        style,
        keywords: props.keywords,
        whatIcon: props.whatIcon,
        renderItemExt: props.renderItemExt,
        onClickItem: props.onClickItem,
        onMouseOutItem: props.onMouseOutItem,
        onMouseOverItem: props.onMouseOverItem,
        itemKey,
        itemNameKey,
        activeKey,
      };
      return CustomRender ? React.cloneElement(CustomRender, options) : <RenderItem {...options} key={key || index} />;
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [showList, state, onChecked, CustomRender, activeKey]
  );

  /**
   * 列表全选处理
   */
  const onChangeCheckAll = useCallback(() => {
    const ids = checkAllStatus ? difference(checkedKeys, listKey) : uniq([].concat(checkedKeys, listKey));
    setState((old) => ({ ...old, checkedKeys: [...ids] }));
    props.onChecked && props.onChecked(ids, difference(listKey, ids));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [checkAllStatus, checkedKeys, listKey]);

  /**
   * 同步选中更新
   */
  useEffect(() => {
    if (props.checkedKeys && !isEqual(props.checkedKeys, state.checkedKeys)) {
      setState((old) => ({ ...old, checkedKeys: props.checkedKeys }));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [props.checkedKeys]);

  const onFilterChange = (option) => {
    setFilterData(old => {
      return { ...old, ...option }
    })
  }


  
  return (
    <CBox className={`lm-c-check-list-wrapper ${className}`} style={style}>
      {hasHeader && <TreeTitle title={title} hasInput={!!onChange} onChange={onChange} titleExt={titleExt} inputPlaceholder={placeholder} />}
      {
        hasFilter && <div className='lm-c-check-list-filter-view'>
          <Select
            allowClear={true}
            placeholder={'设备状态'}
            onChange={(value) => onFilterChange({ deviceStatus: value })}
            value={filterData.deviceStatus}
          >
            {deviceStatus.map((item) => (
              <Option value={item.value} key={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
          <Select
            allowClear={true}
            placeholder={'设备类型'}
            onChange={(value) => onFilterChange({ deviceType: value })}
            value={filterData.deviceType}
          >
            {deviceAndMjType.map((item) => (
              <Option value={item.value} key={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
          {
            !!deviceGroup.length && <Select
              style={{ width: '100%' }}
              filterOption={(input, option) => {
                return (option?.children ?? '').includes(input)
              }} showSearch placeholder="项目分组"
              value={filterData.lygroupId}
              onChange={(value) => onFilterChange({ lygroupId: value })}>

              {deviceGroup.map((item) => (
                <Option key={item.id} value={item.id} title={`${item.name}`}>
                  {item.name}
                </Option>
              ))}
            </Select>
          }
        </div>
      }

      {(checkable || destoryList || checkExt) && <CheckAll onChange={onChangeCheckAll} list={showList} checkable={checkable} destoryList={destoryList} checkExt={checkExt} checkableTitle={props.checkableTitle} checkHalfStatus={checkHalfStatus} checkAllStatus={checkAllStatus} checkedKeys={checkedKeys} />}
      <div className="lm-c-base-list-layout">
        <List className="lm-c-virtual-layout" data={showList} rowHeight={30} rowRenderer={renderRow} />
      </div>
    </CBox>
  );
}

CheckList.defaultProps = {
  className: '',
  title: '摄像机列表',
  checkableTitle: '全选',
  checkNum: false,
  list: [], // 列表数据
  checkable: true, // 是否显示checkbox
  placeholder: '请输入设备名称搜索',
  itemKey: 'id',
  hasHeader: true,
  itemNameKey: 'name',
};

export default CheckList;
