import React, { useState, useRef, useEffect } from 'react';
import { Upload, Modal, Transfer, Input, Search, Tag, List, Button, message } from 'antd';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import { SendCouponByUser, GetCustomerInfo } from '../service';
import { UploadOutlined } from '@ant-design/icons';

const sendCoupon = (props) => {
  const actionRef = useRef();
  const key = 'sendCoupon';
  const { Search } = Input;
  const [mockDataAll, setMockDataAll] = useState([]);
  const [mockData, setMockData] = useState([]);
  const [oneWay, setOneWay] = useState(true);
  // 右侧的集合
  const [targetKeys, setTargetKeys] = useState();
  //已选中
  const [selectedKeys, setSelectedKeys] = useState([]);

  const [filteredItems, setfilteredItems] = useState([]);

  const [notAvailable, notAvailableState] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);

  //初始化数据
  useEffect(() => {
    const initCustomerInfo = async (value) => {
      await GetCustomerInfo({
        CurrentPage: 1,
        PageSize: 7,
      }).then((r) => {
        var list = [];
        r.data.forEach((item) => {
          list.push({
            key: item.memberId,
            title: item.phone,
            description: value,
            disabled: false,
            tag: item.memberId,
          });
        });
        setMockData(list);
        setMockDataAll(list);
      });
    };
    initCustomerInfo();
  }, []);

  const columns = [
    {
      title: '主键',
      dataIndex: 'phone',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      search: false,
      valueType: 'textarea',
      width: 110,
    },
    {
      title: '客户ID',
      dataIndex: 'memberId',
      search: false,
      valueType: 'textarea',
      width: 250,
    },
    {
      title: '原因',
      dataIndex: 'msg',
      search: false,
      valueType: 'textarea',
      width: 250,
    },
  ];

  const uploadProps = {
    beforeUpload: (file) => {
      if (
        file.type !== 'application/vnd.ms-excel' &&
        file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      ) {
        message.error(`${file.name} 不是 exelce 文件`);
      }
      return file.type == 'application/vnd.ms-excel' ||
        file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ? true
        : Upload.LIST_IGNORE;
    },
    name: 'file',
    maxCount: 1,
    multiple: false,
    action: `/kitchen/api/member/uploadcustomer/${props.values?.couponId}`,
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info) {
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
        info.file.response.available;
        notAvailableState(info.file.response.notAvailable);
        var list = mockData
          .filter((item) => {
            var data = info.file.response.available.filter((item2) => {
              if (item2.memberId == item.key) {
                return item2;
              }
            });
            if (data.length > 0) {
              return item;
            }
          })
          .map((item) => item.key);
        setTargetKeys(list);
        setIsModalVisible(true);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败.`);
      }
    },
  };

  const uploadHandleChange = (info) => {

    let fileList = [...info.fileList];

    fileList = fileList.slice(-2);
    fileList = fileList.map((file) => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });

    fileListDataState({ fileList });
  };

  //选项在两栏之间转移时的回调函数
  const onChange = (nextTargetKeys, direction, moveKeys) => {
    setTargetKeys(nextTargetKeys);
  };

  //选中项发生改变时的回调函数
  const onSelectChange = (sourceSelectedKeys, targetSelectedKeys) => {
    setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  };

  //选择列表滚动滚动
  const onScroll = (direction, e) => {};
  const onSearch = async (direction, value) => {
    if (direction == 'right') {
      return;
    }

    await GetCustomerInfo({
      CurrentPage: 1,
      PageSize: 7,
      phone: value,
    }).then((r) => {
      var list = [];
      r.data.forEach((item) => {
        list.push({
          key: item.memberId,
          title: item.phone,
          description: value,
          disabled: false,
          tag: item.memberId,
        });
      });
      setMockData(list);
    });

    // var list = mockData;
    // if (list.find(function (x) { return x.key == value; }) == undefined) {
    //     list.push({
    //         key: value,
    //         title: value,
    //         description: value,
    //         disabled: false,
    //         tag: value,
    //     });
    // }
    // if (list.find(x => x.key != value)) {
    //     setMockData(list);
    // }

    // if (oneWay) {
    //     setOneWay(false);
    // } else {
    //     setOneWay(true);
    // }
  };

  //正定会员发卷
  const sendCoupon = async (props) => {
    if (targetKeys == undefined || targetKeys.length <= 0) {
      //正定会员发卷
      message.error('请选择会员');
      return;
    }
    if(targetKeys.length>props.lastNum){
      message.error('优惠券数量不够');
      return;
    }
    message.loading('正在发送...', key);
    try {
      await SendCouponByUser({
        memberId: targetKeys,
        couponId: props.couponId,
        couponRangeId: props.couponRangeId,
      }).then((r) => {
        message.destroy(key);
        if (r.data) {
          message.success('发送成功');
          setTargetKeys([]);
          setSelectedKeys([]);
        } else {
          message.error('发送失败');
        }
      });
      return true;
    } catch (error) {
      message.destroy(key);
      message.error('发送请重试！');
      return false;
    }
  };
  return (
    <Modal
      destroyOnClose
      visible={props.shows}
      width={700}
      onCancel={() => {
        setMockData(mockDataAll);
        props.onCancel();
      }}
      onOk={() => {
        sendCoupon(props.values);
        props.actionRef.current.reload();
      }}
    >
      <PageContainer
        header={{
          title: '指定发放',
          breadcrumb: {},
        }}
      >
        {/* <Search
                    placeholder="请输入会员"
                    allowClear
                    enterButton="添加"
                    size="large"
                    onSearch={onSearch}
                /> */}
        {/* <br /> <br /> */}
        <div
          style={{
            height: '68px',
          }}
        >
          <span>
            {/* <div >
                            <a href='/file/会员发券导入模板.xls'> 导入模板</a>
                        </div> */}
            <Upload {...uploadProps} nostyle>
              <Button icon={<UploadOutlined />}>上传文件</Button>
            </Upload>
          </span>
        </div>
        <Transfer
          oneWay={oneWay}
          showSearch
          showSelectAll
          onSearch={onSearch}
          dataSource={mockData}
          titles={['未选择', '已选中']}
          targetKeys={targetKeys}
          selectedKeys={selectedKeys}
          onChange={onChange}
          onSelectChange={onSelectChange}
          onScroll={onScroll}
          render={(item) => item.title}
          pagination={{ pageSize: 8 }}
          listStyle={{
            width: 500,
            height: 400,
          }}
        />
      </PageContainer>

      {/* 无效会员弹窗 */}
      <Modal
        footer={null}
        title="无效会员"
        visible={isModalVisible}
        width={600}
        onCancel={() => {
          setIsModalVisible(false);
        }}
      >
        <ProTable
          headerTitle="无效会员"
          actionRef={actionRef}
          rowKey="phone"
          columns={columns}
          toolBarRender={false}
          search={false}
          scroll={{ y: 450 }}
          pagination={false}
          request={async (params) => {
            return {
              data: notAvailable,
              success: true,
              total: notAvailable.length,
            };
          }}
        ></ProTable>
      </Modal>
    </Modal>
  );
};
export default sendCoupon;
