import React, { useEffect, useState } from 'react'
import { PageHeader, Form, Input, Select, 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.list)
const deleteData = fetch(apis.shop.delete)
const getTypeData = fetchList(apis.shop.type.list)
const getBadgeData = fetchList(apis.shop.badge.list)

const FilterForm = Form.create({})((props) => {
  const [typeList, updateTypeList] = useState([])

  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


  useEffect(() => {
    getTypeData({ pageNum: 1, pageSize: 999 }).then(res => {
      updateTypeList(res[0])
    })
  }, [])

  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>
        {getFieldDecorator('typeId')(
          <Select placeholder="选择分类" style={{ minWidth: 260 }}>
            <Select.Option value="">全部</Select.Option>
            {
              (typeList || []).map(tp => <Select.Option value={tp.typeId} key={tp.typeId}>{tp.typeName}</Select.Option>)
            }
          </Select>
        )}
      </Form.Item>
      <Form.Item>
        {getFieldDecorator('isIndex')(
          <Select placeholder="首页推荐" style={{ minWidth: 260 }}>
            <Select.Option value={undefined}>全部</Select.Option>
            <Select.Option value={true}>是</Select.Option>
            <Select.Option value={false}>否</Select.Option>
          </Select>
        )}
      </Form.Item>
      <Form.Item>
        <Button type="primary" htmlType="submit">
          搜索
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={handleReset}>
          重置
          </Button>
      </Form.Item>
    </Form>
  )
})

const DataTable = (props) => {
  const [badgeList, setBadgeList] = useState([])

  useEffect(() => {
    getBadgeData({ pageNum: 1, pageSize: 999 }).then(res => setBadgeList(res[0]))
  }, [])

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

  const columns = [
    {
      title: '图片',
      dataIndex: 'shopLogo',
      key: 'shopLogo',
      render: imgURL => (
        <span>
          {imgURL && <img src={imgURL} width={64} height={64} />}
        </span>
      )
    },
    {
      title: '名称',
      dataIndex: 'shopName',
      key: 'shopName',
    },
    {
      title: '分类',
      dataIndex: 'typeName',
      key: 'typeName',
    },
    // {
    //   title: '商户标签',
    //   dataIndex: 'tags',
    //   key: 'tags',
    //   render: tags => (
    //     <span>
    //       <Tooltip title={tags}>
    //         {
    //           (tags || '').split(',').slice(0,3).filter(Boolean).map(tag => (<Tag key={tag}>{tag}</Tag>))
    //         }
    //       </Tooltip>
    //     </span>
    //   )
    // },
    {
      title: '外卖标签',
      dataIndex: 'badges',
      key: 'badges',
      render: badges => (
        <span>
          {
            (badges || '').split(',').filter(Boolean).map(b => {
              const item = badgeList.filter(x => x.shopBadgeCode === b)[0]
              if (!item) return <></>
              return (<Tag key={item.shopBadgeCode} color={item.color}>{item.shopBadgeCode}</Tag>)
            })
          }
        </span>
      )
    },
    {
      title: '得分',
      dataIndex: 'score',
      key: 'score',
      render: score => (
        <Rate disabled value={score} />
      )
    },
    // {
    //   title: '消费',
    //   dataIndex: 'costAvg',
    //   key: 'costAvg',
    //   render: costAvg => (
    //     <span>{`￥ ${costAvg} /人`}</span>
    //   )
    // },
    {
      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="shopId" 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 handleAddShop = () => {
    router.push('/shop/detail')
  }

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

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

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

  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={handleAddShop}>新增</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>
  )
}
