import React, { useEffect, useState } from 'react'
import { PageHeader, Form, Input, Button, Icon, Table, Rate, Tag, Spin, notification, Tooltip, Divider, Popconfirm } from 'antd'
import router from 'umi/router'
import { fetchList, fetch, apis } from '@/utils/request'

const getData = fetchList(apis.shop.type.list)
const deleteData = fetch(apis.shop.type.delete)

const FilterForm = Form.create({})((props) => {
  const handleSubmit = (e) => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        props.onSearch(values)
      }
    });
  }

  const handleReset = () => {
    props.form.resetFields();
    props.onSearch(undefined)
  }

  const { getFieldDecorator } = props.form

  return (
    <Form layout="inline" onSubmit={e => handleSubmit(e)}>
      <Form.Item>
        {getFieldDecorator('name')(
            <Input
            prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
            placeholder="分类名称"
          />,
        )}
      </Form.Item>
      <Form.Item>
        <Button type="primary" htmlType="submit">
          搜索
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={handleReset}>
          重置
          </Button>
      </Form.Item>
    </Form>
  )
})

const DataTable = (props) => {
  const handleDetail = (row) => () => {
    props.onDetail(row)
  }

  const columns = [
    {
      title: '图标',
      dataIndex: 'thumb',
      key: 'thumb',
      render: imgURL => (
        <span>
          {imgURL && <img src={imgURL} width={64} height={64} />}
        </span>
      )
    },
    {
      title: '名称',
      dataIndex: 'typeName',
      key: 'typeName',
    },
    {
      title: '排序',
      dataIndex: 'sortNo',
      key: 'sortNo'
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      key: 'createDate',
      render: dt => (
        <span>
          {dt.substring(0,10)}
        </span>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <span>
          <Button type="link" onClick={handleDetail(record)}><Icon type="edit" />详情</Button>
          <Divider type="vertical" />
          <Popconfirm
            title="确认删除?"
            icon={<Icon type="question-circle-o" style={{ color: 'red' }} />}
            onConfirm={() => props.onDelete(record)}
          >
            <Button type="link" style={{ color: 'red' }}><Icon type="delete" />删除</Button>
          </Popconfirm>
        </span>
      ),
    },
  ];

  const pagination = {
    ...props.pagination,
    onChange: (page, pageSize) => {
      props.onPageChange(page, pageSize)
    }
  }

  return <Table rowKey="typeId" columns={columns} dataSource={props.dataSource} pagination={pagination} />
}

export default (props) => {
  const defaultPageInfo = { pageNum: 1, pageSize: 10 }
  const [loading, updateLoading] = useState(false)
  const [filterParams, updateFilterParams] = useState({})
  const [pageData, updatePageData] = useState({})

  const getList = (params) => {
    updateLoading(true)
    getData(params).then(res => {
      updateLoading(false)
      updatePageData({
        list: res[0],
        pagination: res[1]
      })

      if (!res[1].total) {
        notification.info({ message: '没有查询到数据' })
      }
    }).catch(err => {
      updateLoading(false)
      // do nothing
    })
  }

  const handleAdd = () => {
    router.push('/shop/type/detail')
  }

  const toDetailPage = (shopType) => {
    router.push(`/shop/type/detail?id=${shopType.typeId}`)
  }

  const handleSearch = (params) => {
    updateFilterParams(params || {})
    
    getList({
      ...defaultPageInfo,
      ...(params || {})
    })
  }

  const handleDelete = (record) => {
    deleteData({ urlData: { id: record.typeId } }).then(() => {
      const newList = pageData.list.filter(x => x.typeId !== record.typeId)
      updatePageData({
        ...pageData,
        list: newList
      })
    })
  }

  const handlePageChange = (pageNum, pageSize) => {
    getList({
      pageNum,
      pageSize,
      ...filterParams
    })
  }

  useEffect(() => {
    getList(defaultPageInfo)
  }, [])

  return (
    <div>
      <PageHeader
        ghost={false}
        backIcon={false}
        title="分类列表"
        extra={[<Button key={1} type="primary" onClick={handleAdd}>新增</Button>]}
      ></PageHeader>
      <FilterForm onSearch={handleSearch} />
      <div style={{marginTop: '16px'}}>
        <Spin spinning={loading} delay={300} tip="请稍候...">
          <DataTable
            dataSource={pageData.list}
            pagination={pageData.pagination}
            onDetail={toDetailPage}
            onDelete={handleDelete}
            onPageChange={handlePageChange}
          />
        </Spin>
      </div>
    </div>
  )
}
