import React, { useState, useEffect } from 'react';
import { Form, Button, Select, message, Menu, Dropdown, 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 apis from '../../services/apis';
import request from '../../utils/request';
import styles from '../style/GoodsList.less';

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

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

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

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

  // 跳转到编辑商品
  const toEditPolicy = (policyId) => () => {
    router.push({
      pathname: '/system/editPolicy',
      query: {
        policyId
      },
    });
  }

  /**
   *
   *
   * @param {*} props
   * @returns
   */
  const columns = [
    {
      title: '购房须知主图',
      dataIndex: 'policyImg',
      key: 'policyImg',
      align: 'center',
      render: (policyImg,row) =><Navigate onClick={toEditPolicy(row.policyId)} ><img src={policyImg} className={styles.touxiang} /></Navigate> ,
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      align: 'center',
      render: (text, record) => <Navigate to={`/system/editPolicy?policyId=${record.policyId}`}>{text}</Navigate>
    },
    {
      title: '城市',
      dataIndex: 'cityName',
      key: 'cityName',
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      key: 'createDate',
      align: 'center',
      render: (createDate) => <><span>{moment(createDate).format('YYYY-MM-DD')}</span></>
    },
    {
      title: '状态',
      dataIndex: 'publishStatus',
      key: 'publishStatus',
      align: 'center',
      render: (publishStatus) => <><span>{publishStatus === 1 ? '已发布' : '未发布'}</span></>
    },
    {
      title: '操作',
      dataIndex: 'handle',
      key: 'handle',
      align: 'center',
      render: withActions((x, row) => [
        <AuthButton name="admin.taPolicy.publish" noRight={null}>
          <EditIcon type={row.publishStatus === 0 ? 'publish' : 'cancel'} text={row.publishStatus === 0 ? '发布' : '取消发布'} onClick={publicOrNoPublic(row)}></EditIcon>
        </AuthButton>,
        
        <AuthButton name="admin.taPolicy.top" noRight={null}>
          <EditIcon type={row.weight === 1 ? 'cancel' : 'top'} text={row.weight === 1 ? '取消置顶' : '置顶'} onClick={topPolicy(row)}></EditIcon>
        </AuthButton>,
        
        <AuthButton name="admin.taPolicy.id.put" noRight={null}>
          <EditIcon type="edit" text="编辑" onClick={toEditPolicy(row.policyId)}></EditIcon>
        </AuthButton>,

        <AuthButton name="admin.taPolicy.id.delete" noRight={null}>
          <EditIcon type="delete" text="删除" onClick={deletePolicy(row.policyId)}></EditIcon>
        </AuthButton>,
      ])
    },
  ];

  // 删除
  const deletePolicy = (policyId) => () => {
    Modal.confirm({
      title: '购房政策会被删除，小程序端和后台都无法再看到',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        request({ ...apis.system.deleteTaPolicy, urlData: { id: policyId }, }).then((data) => {
          message.info('操作成功！')
          getList({ pageNum: 1, pageSize: 10, cityId: '' });
        }).catch((err) => {
          console.log(err)
          message.info(err.msg || err.message)
        })
      },
    });
  }


  //   置顶
  const topPolicy = (row) => () => {
    const weight = Math.abs(row.weight - 1)
    row.weight = weight
    request({ ...apis.system.updateTaPolicy, urlData: { id: row.policyId }, data: row, }).then((data) => {
      console.log(data)
      message.info('操作成功！')
      getList({ pageNum: 1, pageSize: 10, cityId: '' });
    }).catch((err) => {
      console.log(err)
      message.info(err.msg || err.message)
    })
  }

  const publicOrNoPublic = (row) => () => {
    if (row.publishStatus === 1) {
      row.publishStatus = 0
    } else {
      row.publishStatus = 1
    }
    const title = row.publishStatus === 0 ? '购房政策会在小程序端隐藏，后台可继续编辑重新发布' : '确认发布此数据'
    Modal.confirm({
      title: title,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        request({ ...apis.system.updateTaPolicy, urlData: { id: row.policyId }, data: row, }).then((data) => {
          console.log(data)
          message.info('操作成功！')
          getList({ pageNum: 1, pageSize: 10, cityId: '' });
        }).catch((err) => {
          console.log(err)
          message.info(err.msg || err.message)
        })
      },
    });


  }

  const changePageNum = (pageNumber) => {
    getList({ pageNum: pageNumber, pageSize: 10, ...props.form.getFieldsValue() })
  }

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

  const { getFieldDecorator } = props.form
  return (

    <>
      <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>
        <Form.Item>
          {getFieldDecorator('cityId')(
            <SelectCity />,
          )}
        </Form.Item>
        <Form.Item>
          <AuthButton name="admin.taPolicy.search" noRight={null}>
            <Button type="primary" htmlType="submit" className={styles.searchBtn}>
              搜索
          </Button>
          </AuthButton>
        </Form.Item>
      </Form>
      <AuthButton name="admin.taPolicy.post" noRight={null}>
        <Button type="danger" className={styles.addBtn} onClick={toEditPolicy()}>新增</Button>
      </AuthButton>
      <Table rowKey="housingPolicy" dataSource={data.records} columns={columns} pagination={false} />
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
        <Pagination showQuickJumper defaultCurrent={1} total={data.total} onChange={changePageNum} current={data.current} />
      </div>
    </>
  )
}
const WrappedHeader = Form.create({ name: 'header' })(header);

export default WrappedHeader
