import React, { useState, useEffect } from 'react';
import { Form, Select, Modal, Button, Table, Divider, Tag, Input } from 'antd';
import { apis, fetch } from '../../utils/request';
import Navigate from '@/components/Navigate';

const getActivities = fetch(apis.integralMall.getTaGoods)
const { Search } = Input;

export default (props) => {
  const {
    value,
    onChange,
    ...rest
  } = props;

  const [list, setList] = useState([]);
  const [visible, setVisible] = useState(false);
  const [activity, setActivity] = useState({ goodsId: undefined, title: '请选择商品' })
  const getActTitle = val => ((list.filter(x => x.goodsId === val)[0]) || {}).goodsName || '请选择商品'
  const setAct = val => setActivity({ goodsId: val, title: getActTitle(val) })

  const buildingId = props.buildingId()

  useEffect(() => {
    getActivities({
      params: {
        buildingId,
        pageNum: 1,
        pageSize: 999,
        activityStatus: 2,
      }
    }).then((data) => {
      setList(data.records || [])

      console.log('----', buildingId, value)

      setAct(buildingId ? undefined : value);
    })
  }, [buildingId]);

  if (value !== activity.goodsId) {
    setAct(value);
  }
  const searchActivity =(e)=>{
    getActivities({
      params: {
        buildingId,
        pageNum: 1,
        pageSize: 999,
        activityStatus: 2,
        name:e
      }
    }).then((data) => {
      setList(data.list || [])

      console.log('----', buildingId, value)

      // setAct(buildingId ? undefined : value);
    })
  }

  let chooseVal = value

  const handleChange = val => chooseVal = val

  const setData = val => {
    setAct(val)
    onChange(val)
    setVisible(false)
  }

  const columns = [
    {
      title: '标题',
      dataIndex: 'goodsName',
      key: 'goodsId',
      align: 'center',
      ellipsis: true,
      render: text => <a>{text}</a>,
    },
    {
      title: '操作',
      dataIndex: 'name',
      align: 'center',
      width: '20%',
      render: (text, record) => (
        <Navigate onClick={() => setData(record.goodsId)}>选择</Navigate>
      ),
    },
  ];

  return (

    <div>
      <div ><Navigate onClick={() => setVisible(true)}>{activity.title}</Navigate></div>
      <Modal
        title="请选择"
        visible={visible}
        onCancel={() => setVisible(false)}
        footer={[]}
      >
        <Search
          placeholder="请输入标题"
          enterButton="搜索"
          size="large"
          onSearch={value => searchActivity(value)}
          style={{ marginBottom: '16px' }}
        />
        <Table rowKey={list => list.goodsId} columns={columns} dataSource={list} />
      </Modal>
    </div>

  );
}
