import React, { useEffect, useState } from 'react'
import { List, Input, Button, notification } from 'antd'
import { fetch, apis, fetchList } from '@/utils/request'
import TemplateItem from './TemplateItem'

const getTemplateList = fetchList(apis.mp.template.list)
const saveTemplate = fetch(apis.mp.template.save)
const updateTemplate = fetch(apis.mp.template.update)
const deleteTemplate = fetch(apis.mp.template.delete)

export default props => {
  const [loading, setLoading] = useState(false)
  const [listData, setListData] = useState([])
  const [query, setQuery] = useState({pageSize: 999})

  const isTemp = x => !x.serialNo || `${x.serialNo}`.indexOf('tmp') > -1

  const handleAdd = () => {
    const template = {
      orgId: props.value.orgI,
      appid: props.value.appid,
      typeCode: undefined,
      typeName: undefined,
      templateCode: undefined,
      serialNo: `tmp-${Math.random().toString(36).substring(2)}`
    }

    setListData([template].concat(listData))
  }

  const handleRowChange = row => {
    if (isTemp(row)) {
      saveTemplate({data: {
        ...row,
        serialNo: undefined,
      }}).then(res => {
        notification.success({message: '保存信息成功'})
        setQuery({...query})
      })
    } else {
      updateTemplate({data: row, urlData: {id: row.serialNo}}).then(res => {
        notification.success({message: '更新信息成功'})
        setQuery({...query})
      })
    }
  }

  const handleRowDelete = row => {
    if (isTemp(row)) {
      setListData(listData.filter(x => x.serialNo !== row.serialNo))
    } else {
      deleteTemplate({urlData: {id: row.serialNo}}).then(res => {
        notification.success({message: '删除信息成功'})
        setQuery({...query})
      })
    }
  }

  useEffect(() => {
    setLoading(true)
    getTemplateList(query).then(res => {
      const [list] = res
      setListData(list || [])
      setLoading(false)
    }).catch(() => setLoading(false))
  }, [query])


  return (
    <div>
      {/* <Button onClick={handleAdd}>新增</Button> */}
      <div style={{maxWidth: '800px', marginTop: '24px'}}>
        <List
          loading={loading}
          dataSource={listData}
          size="large"
          bordered={false}
          itemLayout="horizontal"
          renderItem={item => {
            return (
              <List.Item>
                  <TemplateItem value={item} onChange={handleRowChange} onDelete={handleRowDelete} />
              </List.Item>
            )
          }}
        />
      </div>
    </div>
  )
}
