import React, { useMemo, useRef, useCallback, useState } from 'react';
// import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { Button, notification, Spin, Modal, message } from 'antd';
import { router } from 'umi';
import QueryTable from '@/components/QueryTable';
import request from '@/utils/request';
import apis from '@/services/apis';
import SelectCity from '@/components/SelectButton/CitySelect';
import NewsTypeSelect from '../../../components/SelectButton/NewTypeSelect';
import BuildSelect from '@/components/SelectButton/BuildSelect';
import moment from 'moment';
import OperButton from '@/components/OperButton';
import AuthButton from '@/components/AuthButton';
import withActions from '@/components/ActionList';

export default props => {
  const ref = useRef();
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState({ current: 1, pageSize: 10 });
  const onPublish = useCallback(row => {
    const newsStatus = row.newsStatus === 1 ? 0 : 1;
    request({ ...apis.news.put, urlData: { id: row.newsId }, data: { ...row, newsStatus } })
      .then(() => {
        notification.success({ message: '操作成功' });
        setLoading(false);
        ref.current.reload();
      })
      .catch(err => {
        console.error(err);
        setLoading(false);
      });
  }, []);

  // 跳转到编辑资讯列表
  const toEditList = newsId => {
    router.push({
      pathname: '/news/list/Edit',
      query: {
        newsId,
      },
    });
  };

  const onDelete = useCallback(row => {
    setLoading(true);
    request({ ...apis.news.delete, urlData: { id: row.newsId } })
      .then(() => {
        notification.success({ message: '操作成功' });
        setLoading(false);
        ref.current.reload();
      })
      .catch(err => {
        console.error(err);
        setLoading(false);
      });
  }, []);

  //   置顶
  const topNews = (weightParam, newsId) => {
    const weight = Math.abs(weightParam - 1);
    request({ ...apis.news.weight, params: { newsId: newsId, weight } })
      .then(data => {
        console.log(data);
        message.info('操作成功！');
        ref.current.reload();
      })
      .catch(err => {
        console.log(err);
        message.info(err.msg || err.message);
      });
  };

  //发布
  function cancelRelease(newsId, newsStatus, buildingId, newsTypeId) {
    console.log('newsId' + newsId + 'status' + newsStatus);
    if (newsStatus === 1) {
      Modal.confirm({
        title: '资讯会在小程序端隐藏，后台可继续编辑重新发布',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          request({
            ...apis.news.cancel,
            data: { newsStatus: newsStatus, buildingId: buildingId, newsTypeId: newsTypeId },
            urlData: { id: newsId },
          })
            .then(data => {
              message.info('操作成功！');
              ref.current.reload();
            })
            .catch(err => {
              console.log(err);
              message.info(err.msg || err.message);
            });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    } else if (newsStatus === 0) {
      Modal.confirm({
        title: '确认发布该资讯？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          request({
            ...apis.news.cancel,
            data: { newsStatus: newsStatus, buildingId: buildingId, newsTypeId: newsTypeId },
            urlData: { id: newsId },
          })
            .then(data => {
              message.info('操作成功！');
              ref.current.reload();
            })
            .catch(err => {
              console.log(err);
              message.info(err.msg || err.message);
            });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    }
  }

  const searchFields = [
    {
      name: 'cityId',
      label: '城市',
      placeholder: '请选择城市',
      render: () => <SelectCity style={{ width: 160 }} />,
    },
    {
      name: 'buildingId',
      label: '项目',
      placeholder: '请选择项目',
      render: () => <BuildSelect style={{ width: 160 }} />,
    },
    {
      name: 'title',
      label: '标题',
      placeholder: '请输入标题',
    },
    // {
    //   name: 'newsTypeId',
    //   label: '资讯类型',
    //   placeholder: '请选择资讯类型',
    //   render: () => <NewsTypeSelect style={{ width: 160 }} />,
    // },

    {
      name: 'newsStatus',
      label: '状态',
      placeholder: '楼盘状态',
      type: 'select',
      options: [
        { label: '已发布', value: 0 },
        { label: '未发布', value: 1 },
      ],
    },
  ];

  const tableColumns = [
    {
      title: '资讯主图',
      key: 'newsImg',
      dataIndex: 'newsImg',
      align: 'center',
      render: t => <img src={t} width={128} height={72} style={{ borderRadius: '4px' }} alt="" />,
    },
    {
      title: '标题',
      key: 'newsName',
      dataIndex: 'newsName',
      align: 'center',
      with: 300,
      ellipsis: true,
    },
    {
      title: '发布时间',
      dataIndex: 'createDate',
      key: 'createDate',
      align: 'center',
      render: t => moment(t).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '阅读量',
      key: 'pvNum',
      dataIndex: 'pvNum',
      align: 'center',
      render: t => t || 0,
    },
    // {
    //   title: '转发数',
    //   key: 'shareNum',
    //   dataIndex: 'shareNum',
    //   align: 'center',
    //   render: t => t || 0,
    // },
    {
      title: '收藏数',
      key: 'saveNum',
      dataIndex: 'saveNum',
      align: 'center',
      render: t => t || 0,
    },
    {
      title: '状态',
      dataIndex: 'newsStatus',
      key: 'newsStatus',
      align: 'center',
      render: t => (t == 0 ? '已发布' : '未发布'),
    },

    {
      title: '操作',
      key: 'options',
      align: 'center',
      render: withActions(
        (_, row) => [
          <AuthButton name="news.publish" noRight={null}>
            <OperButton
              onClick={() =>
                cancelRelease(
                  row.newsId,
                  row.newsStatus === 0 ? 1 : 0,
                  row.buildingId,
                  // row.newsType.newsTypeId,
                )
              }
            >
              {row.newsStatus === 0 ? '取消发布' : '发布'}
            </OperButton>
          </AuthButton>,
          //   <AuthButton name="admin.taNews.top" noRight={null}>
          //   <span style={{ position: 'absolute', right: '83px', top: '16px', fontSize: ' 0.106rem', zIndex: 1, color: '#FF7E48', cursor: 'pointer' }} onClick={topNews(data.weight, data.newsId)}>{data.weight === 1 ? '取消置顶' : '置顶'}</span>
          // </AuthButton>
          row.newsStatus === 0 && (
            <AuthButton name="news.add" noRight={null}>
              <OperButton onClick={() => topNews(row.weight, row.newsId)}>
                {row.weight === 1 ? '取消置顶' : '置顶'}
              </OperButton>
            </AuthButton>
          ),

          <AuthButton name="news.edit" noRight={null}>
            <OperButton onClick={() => toEditList(row.newsId)}>编辑</OperButton>
          </AuthButton>,

          <AuthButton name="news.delete" noRight={null}>
            <OperButton.Confirm
              title="确认删除?"
              content="删除之后不可恢复"
              onClick={() => onDelete(row)}
            >
              删除
            </OperButton.Confirm>
          </AuthButton>,
        ],
        { noMargin: true },
      ),
    },
  ];
  const actionRender = () => {
    return (
      <AuthButton name="news.add" noRight={null}>
        <Button type="primary" icon="plus" onClick={() => toEditList()}>
          新增
        </Button>
      </AuthButton>
    );
  };

  return (
    <QueryTable
      ref={ref}
      rowKey="newsId"
      api={apis.news.getList}
      searchFields={searchFields}
      columns={tableColumns}
      actionRender={actionRender}
    />
  );
};
