import React, { useState, useEffect } from 'react';
import { Form, Button, Select, message, Table, Pagination, Modal, DatePicker } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import AuthButton from '@/components/AuthButton';
import withActions from '@/components/ActionList';
import EditIcon from '@/components/EditIcon';
import Navigate from '@/components/Navigate';
import SelectCity from '../../components/SelectButton/CitySelect'
import BuildSelect from '../../components/SelectButton/BuildSelect'
import apis from '../../services/apis';
import request from '../../utils/request';
import styles from '../style/GoodsList.less';

const { Option } = Select;
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

const ContentTypeDict = {
  'notice': '公告',
  'tpNews': '服务',
  'activity': '活动',
  'news': '资讯',
}

const header = (props) => {
  const [data, setData] = useState({})
  //   const [page, changePage] = useState({})

  useEffect(() => {
    getList({ pageNum: 1, pageSize: 10, showType: 'screen' });
  }, [])

  // 查询列表
  const getList = (params) => {
    request({ ...apis.carsuseFigure.extendContent, params: { ...params }, }).then((data) => {
      console.log(data)
      setData(data)
    })
  }


  // 跳转到编辑商品
  const toEdit = (contentId) => () => {
    router.push({
      pathname: '/carouselFigure/editAdvertising',
      query: {
        contentId
      },
    });
  }

  const columns = [
    {
      title: '主图',
      dataIndex: 'image',
      key: 'image',
      align: 'center',
      render: (image,row) => <Navigate onClick={toEdit(row.contentId)}><img src={image} className={styles.imgSmall} /></Navigate>,
    },
    // {
    //   title: '发布城市',
    //   dataIndex: 'cityName',
    //   key: 'cityName',
    //   align: 'center',
    // },
    // {
    //   title: '关联项目',
    //   dataIndex: 'buildingName',
    //   key: 'buildingName',
    //   align: 'center',
    //   render: (buildingName) => <span>{buildingName === null ? '无' : buildingName}</span>
    // },
    {
      title: '关联内容类型',
      dataIndex: 'contentType',
      key: 'contentType',
      align: 'center',
      render: x => <span>{ContentTypeDict[x] || '无'}</span>
    },
    // {
    //   title: '发布位置',
    //   dataIndex: 'showPosition',
    //   key: 'showPosition',
    //   align: 'center',
    //   render: (showPosition) => <span>{ showPosition === 'index' ? '首页' : showPosition === 'building' ? '项目' : '' }</span>
    // },
    {
      title: '发布时间',
      dataIndex: 'createDate',
      key: 'createDate',
      align: 'center',
      render: (x, row) => <><span>{moment(row.createDate).format('YYYY-MM-DD')}</span></>
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: (status) => <><span>{status == 1 ? '上架' : '下架'}</span></>
    },
    {
      title: '操作',
      dataIndex: 'handle',
      key: 'handle',
      align: 'center',
      render: withActions((x, row) => [
        <AuthButton name="admin.advert.publish" noRight={null}>
          <EditIcon text={row.status === 1 ? '下架' : '上架'} type={row.status === 1 ? 'down' : 'up'}  onClick={changeStatus(row)} />
        </AuthButton>,
        <AuthButton name="admin.advert.put" noRight={null}>
          <EditIcon text="编辑" type="edit" onClick={toEdit(row.contentId)} />
        </AuthButton>,
        <AuthButton name="admin.advert.delete" noRight={null}>
          <EditIcon text="删除" type="delete" onClick={deleteCarouse(row.contentId)}/>
        </AuthButton>,
      ])
    },
  ];

  const finishDynamic = (row) => {
    Modal.confirm({
      title: '结束以后将无法编辑, 是否继续?',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        request({ ...apis.carsuseFigure.finish, data: { dynamicId: row.dynamicId, top: "" }, }).then((data) => {
          console.log(data)
          message.info('操作成功！')
          getList({ pageNum: 1, pageSize: 10, showType: 'screen' })
        }).catch((err) => {
          console.log(err)
          message.info(err.msg || err.message)
        })
      },
    });
  }

  //删除
  const deleteCarouse = (contentId) => () => {
    Modal.confirm({
      title: '确认删除此数据?',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        request({ ...apis.carsuseFigure.deleteExtendContent, urlData: { id: contentId } }).then((data) => {
          message.info('操作成功！')
          getList({ pageNum: 1, pageSize: 10, showType: 'screen' })
        }).catch((err) => {
          console.log(err)
          message.info(err.msg || err.message)
        })
      },
    });
  }

  //   停用启用
  const changeStatus = (row) => () => {
    console.log(row)
    if (row.status === 0) {

      Modal.confirm({
        title: '确认发布此数据?',
        okText: '确定',
        cancelText: '取消',
        onOk() {
          row.status = 1
          request({ ...apis.carsuseFigure.updataExtendContent, urlData: { id: row.contentId }, data: row, }).then((data) => {
            message.info('操作成功！')
            getList({ pageNum: 1, pageSize: 10, showType: 'screen' })
          }).catch((err) => {
            console.log(err)
            message.info(err.msg || err.message)
          })
        },
      });
    } else if (row.status === 1) {

      Modal.confirm({
        title: '停用后不会再显示在小程序端',
        okText: '确定',
        cancelText: '取消',
        onOk() {
          row.status = 0
          request({ ...apis.carsuseFigure.updataExtendContent, urlData: { id: row.contentId }, data: row, }).then((data) => {
            message.info('操作成功！')
            getList({ pageNum: 1, pageSize: 10, showType: 'screen' })
          }).catch((err) => {
            console.log(err)
            message.info(err.msg || err.message)
          })
        },
      });
    }

  }

  const changePageNum = (pageNumber, props) => {
    props.form.validateFields((err, values) => {
      if (!err) {
        getList({ pageNum: pageNumber, pageSize: 10, ...values, showType: 'screen' })
      }
    });
  }

  // 提交事件
  const handleSubmit = (e, props) => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        console.log('提交数据: ', values)
        getList({ pageNum: 1, pageSize: 10, ...values, showType: 'screen' })
      }
    });
  }

  //重置搜索
  function handleReset() {
    props.form.resetFields();
    getList({ pageNum: 1, pageSize: 10, showType: 'screen' });
  }


  const { getFieldDecorator } = props.form
  return (

    <>
      <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>
        {/* <Form.Item>
          {getFieldDecorator('cityId')(
            <SelectCity />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('buildingId')(
            <BuildSelect />,
          )}
        </Form.Item> */}
        <Form.Item>
          {getFieldDecorator('contentType')(
            <Select style={{ width: '180px' }} placeholder="类型">
              <Option value="notice">公告</Option>
              <Option value="tpNews">服务</Option>
              {/* <Option value="project">项目</Option> */}
              <Option value="news">资讯</Option>
              <Option value="activity">活动</Option>
              {/* <Option value="help">助力活动</Option>
              <Option value="group">拼团活动</Option>
              <Option value="h5">H5活动</Option>
              <Option value="live">直播活动</Option>
              <Option value="salesBatch">在线选房</Option> */}
              <Option value="nothing">无</Option>
            </Select>,
          )}
        </Form.Item>
        {/* <Form.Item>
          {getFieldDecorator('showPosition')(
            <Select style={{ width: '180px' }} placeholder="发布位置">
              <Option value="index">首页</Option>
              <Option value="building">项目</Option>
            </Select>,
          )}
        </Form.Item> */}
        <Form.Item>
          {getFieldDecorator('status')(
            <Select style={{ width: '180px' }} placeholder="状态">
              <Option value="1">已上架</Option>
              <Option value="0">已下架</Option>
            </Select>,
          )}
        </Form.Item>
        <Form.Item>
          <AuthButton name="admin.advert.search" noRight={null}>
            <Button type="primary" htmlType="submit" className={styles.searchBtn}>
              搜索
          </Button>
          </AuthButton>
          <Button style={{ marginLeft: 8 }} onClick={handleReset}>
            重置
            </Button>
        </Form.Item>
      </Form>
      <AuthButton name="admin.advert.post" noRight={null}>
        <Button type="danger" className={styles.addBtn} onClick={toEdit()}>新增</Button>
      </AuthButton>
      <Table dataSource={data.records} columns={columns} pagination={false} rowKey="advertisingList" />
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
        <Pagination showQuickJumper defaultCurrent={1} total={data.total} onChange={e => changePageNum(e, props)} current={data.current} />
      </div>
    </>
  )
}
const WrappedHeader = Form.create({ name: 'header' })(header);

export default WrappedHeader
