import React, { useEffect, useState } from 'react';
import SearchBox from '~/components/search-box';
import { Button, message, Modal, Table, Image } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import AddEditModalView from './comp/addEditModal';
import { InterListType, InterReqListType } from '~/api/interface';
import { getMallListType } from '~/api/interface/activityManage';
import { ActivityManageAPI } from '~/api';

// 表格列表
type TableType = InterListType<getMallListType>;
// 搜索表单的类型
type ReqType = InterReqListType<getMallListType>;
// 搜索表单的数据
let query: ReqType = {};

const PointExchangeGoodsPage: React.FC = () => {
  // 新增编辑弹窗是否开启
  const [addEditShow, setAddEditShow] = useState<boolean>(false);
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 需要编辑的数据
  const [recordData, setRecordData] = useState<TableType[0]>();
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // +++++++++++++++++++++++++++++++++++++++++++++++++++ //
  // 新版通用部分(ES6+ for React) ZhangLK 2022/08/30 Start
  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    const res = await ActivityManageAPI.getMallList({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
      ...query,
    });
    if (res && res.code === '200') {
      const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
      setPagination({
        total: totalCount,
        current: pageNo,
        pageSize,
        totalPage,
      });
      setTableData(list || []);
      // console.log('加载列表 --->', list);
    } else {
      message.warning(res.message);
    }
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize }).then();
  };
  // 表单提交
  const onFinish = (data: ReqType) => {
    pagination.current = 1;
    query = data;
    getTableList(data).then();
  };
  // +++++++++++++++++++++++++++++++++++++++++++++++++++ //
  // 删除数据
  const handleDelete = (record: TableType[0]) => {
    Modal.confirm({
      title: '提示',
      content: '删除后将无法恢复，请确认是否删除？',
      onOk: async () => {
        const res = await ActivityManageAPI.deleteMall({ id: record?.id });
        if (res && res.code === '200') {
          paginationChange(
            tableData.length === 1 && pagination.current !== 1
              ? pagination.current - 1
              : pagination.current,
            pagination.pageSize,
          );
          message.success('删除成功');
        }
      },
    });
  };
  // 转换商品图片数据
  const getGoodsUrl = (record: TableType[0]) => {
    try {
      const image = (JSON.parse(record.goodsUrl || `[]`) || [])?.[0];
      return <Image src={image} alt={record.goods} width={35} height={35}></Image>;
    } catch (e) {
      return `无`;
    }
  };
  // 页面挂载
  useEffect(() => {
    query = {};
    (async () => {
      await getTableList();
    })();
  }, []);
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '序号',
      dataIndex: 'accountNo',
      align: 'center',
      width: '50px',
      render: (_text, _record, index) => (pagination.current - 1) * pagination.pageSize + index + 1,
    },
    {
      title: '商品名称',
      dataIndex: 'goods',
      align: 'center',
    },
    {
      title: '商品图片',
      dataIndex: 'goodsUrl',
      align: 'center',
      render: (_text, record) => getGoodsUrl(record),
    },
    {
      title: '消耗积分',
      dataIndex: 'needPoints',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'id',
      align: 'center',
      render: (_text, record) => (
        <>
          <Button
            type={'link'}
            onClick={() => {
              setAddEditShow(true);
              setRecordData(record);
            }}
          >
            编辑
          </Button>
          <Button type={'link'} danger onClick={() => handleDelete(record)}>
            删除
          </Button>
        </>
      ),
    },
  ];
  return (
    <>
      <SearchBox
        child={
          <Button type={'primary'} icon={<PlusOutlined />} onClick={() => setAddEditShow(true)}>
            添加商品
          </Button>
        }
        search={[
          {
            label: '商品名称',
            name: 'name',
            type: 'Input',
            placeholder: '请输入活动名称',
            maxlength: 20,
          },
        ]}
        searchData={onFinish}
      />
      <Table
        size='small'
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        // scroll={{ x: 1000 }}
        bordered
        pagination={{
          total: pagination.total,
          pageSize: pagination.pageSize,
          current: pagination.current,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
          showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
        }}
      />
      <AddEditModalView
        open={addEditShow}
        title={recordData?.id ? '编辑商品' : '添加商品'}
        data={recordData}
        onCancel={() => {
          setAddEditShow(false);
          setRecordData(undefined);
          paginationChange(pagination?.current, pagination?.pageSize);
        }}
      />
    </>
  );
};

export default PointExchangeGoodsPage;
