import React, { useState, useEffect, useRef } from 'react';
import {
  Form,
  Input,
  Button,
  Icon,
  Typography,
  message,
  Table,
  Pagination,
  Modal,
  DatePicker,
  Card,
} 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 QueryTable from '@/components/QueryTable';

const type = 'dymic';

const SignupActivity = props => {
  const ref = useRef();

  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: 'time',
      label: '时间',
      placeholder: '请选择时间',
      type: 'datepicker',
    },
  ];

  const toSignupActivityDetail = dynamicId => () => {
    router.push({
      pathname: '/activity/SignupActivity/detail',
      query: {
        dynamicId,
      },
    });
  };

  // 跳转到编辑
  const toSignupActivityEdit = dynamicId => {
    router.push({
      pathname: '/activity/SignupActivity/edit',
      query: {
        dynamicId,
      },
    });
  };

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

  //   推首页
  const homeDynamic = row => () => {
    const home = Math.abs(row.home - 1);
    request({ ...apis.activity.home, params: { dynamicId: row.dynamicId, home } })
      .then(data => {
        message.info('操作成功！');
        ref.current.reload();
      })
      .catch(err => {
        console.log(err);
        message.info(err.msg || err.message);
      });
  };

  //结束活动
  const finishDynamic = row => {
    Modal.confirm({
      title:
        '活动会被强制结束，小程序端无法再发起或参与此活动，如果不想让客户看到活动，请再点击取消发布按钮',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        request({ ...apis.activity.finish, data: { dynamicId: row.dynamicId, top: '' } })
          .then(data => {
            message.info('操作成功！');
            ref.current.reload();
          })
          .catch(err => {
            console.log(err);
            message.info(err.msg || err.message);
          });
      },
    });
  };

  // 发布活动
  const sendDynamic = row => {
    Modal.confirm({
      title: '确定发布吗？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        request({ ...apis.activity.send, urlData: { id: row.dynamicId } })
          .then(data => {
            message.info('操作成功！');
            ref.current.reload();
          })
          .catch(err => {
            console.log(err);
            message.info(err.msg || err.message);
          });
      },
    });
  };

  // 取消活动
  const cancelDynamic = row => {
    Modal.confirm({
      title: '活动会在小程序端隐藏，后台可以继续编辑重新发布',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        request({ ...apis.activity.cancel, urlData: { id: row.dynamicId } })
          .then(data => {
            message.info('操作成功！');
            ref.current.reload();
          })
          .catch(err => {
            console.log(err);
            message.info(err.msg || err.message);
          });
      },
    });
  };

  //   发布or取消发布
  const sendOrPublicDynamic = row => {
    if (row.status === 1) {
      cancelDynamic(row);
    } else {
      sendDynamic(row);
    }
  };

  const getJoinPeople = dynamicId => () => {
    router.push({
      pathname: '/activity/SignupActivity/registrationRecord',
      query: {
        dynamicId,
      },
    });
  };

  const columns = [
    {
      title: '活动标题',
      dataIndex: 'title',
      key: 'title',
      align: 'center',
      width: '20%',
      render: (x, row) => (
        <AuthButton name="activity.enroll.detail" noRight={null}>
          <Navigate onClick={toSignupActivityDetail(row.dynamicId)}>
            <Typography.Text ellipsis>{row.title}</Typography.Text>
          </Navigate>
        </AuthButton>
      ),
    },
    {
      title: '活动时间',
      dataIndex: 'startDate',
      key: 'startDate',
      align: 'center',
      width: '15%',
      // width: '20%',
      render: (x, row) => (
        <>
          <span>{`${moment(row.startDate).format('YYYY-MM-DD')} —— ${moment(row.endDate).format(
            'YYYY-MM-DD',
          )}`}</span>
        </>
      ),
    },
    {
      title: '已参与人数',
      dataIndex: 'count',
      key: 'count',
      align: 'center',
      render: (x, row) => <Navigate onClick={getJoinPeople(row.dynamicId)}>{row.count}</Navigate>,
    },
    // {
    //   title: '阅读量',
    //   dataIndex: 'pvNum',
    //   key: 'pvNum',
    //   align: 'center',
    //   // width: '10%',
    // },
    // {
    //   title: '转发量',
    //   dataIndex: 'shareNum',
    //   key: 'shareNum',
    //   align: 'center',
    //   // width: '10%',
    // },
    // {
    //   title: '收藏数',
    //   dataIndex: 'saveNum',
    //   key: 'saveNum',
    //   align: 'center',
    //   // width: '10%',
    // },
    {
      title: '报名状态',
      dataIndex: 'activityStatus',
      key: 'activityStatus',
      align: 'center',
      render: activityStatus =>
        activityStatus == 0 ? '进行中' : activityStatus == 1 ? '未开始' : '已结束',
    },
    {
      title: '权重',
      dataIndex: 'heavy',
      key: 'heavy',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'handle',
      key: 'handle',
      align: 'center',
      render: withActions((x, row) => [
        <AuthButton name="activity.enroll.publish" noRight={null}>
          <EditIcon
            type={row.status === 1 ? 'cancel' : 'publish'}
            text={row.status === 1 ? '取消发布' : '发布'}
            onClick={() => sendOrPublicDynamic(row)}
          />
        </AuthButton>,

        // //   <EditIcon type="look" text="查看详情" onClick={toSignupActivityDetail(row.dynamicId)} />,

        row.activityStatus === 0 ? (
          <AuthButton name="activity.enroll.finish" noRight={null}>
            <EditIcon type="end" text="结束活动" onClick={finishDynamic.bind(this, row)} />
          </AuthButton>
        ) : null,

        <AuthButton name="activity.enroll.index" noRight={null}>
          <EditIcon
            type={row.home === 1 ? 'cancel' : 'top'}
            text={row.home === 1 ? '取消推首页' : '推荐首页'}
            onClick={homeDynamic(row)}
          />
        </AuthButton>,

        row.activityStatus === 0 || row.activityStatus === 1 ? (
          <AuthButton name="activity.enroll.edit" noRight={null}>
            <EditIcon
              type="edit"
              text="编辑"
              onClick={() => toSignupActivityEdit(row.dynamicId, row.count)}
            />
          </AuthButton>
        ) : null,
      ]),
    },
  ];

  const actionRender = () => {
    return (
      <AuthButton name="activity.enroll.add" noRight={null}>
        <Button type="primary" icon="plus" onClick={() => toSignupActivityEdit()}>
          新增
        </Button>
      </AuthButton>
    );
  };

  return (
    <QueryTable
      ref={ref}
      rowKey="dynamicId"
      api={apis.activity.list}
      searchFields={searchFields}
      columns={columns}
      postData={data => {
        data.time && (data.time = `${moment(data.time).format('YYYY-MM-DDT00:00:00.000')}Z`);
        data.type = type;
        return data;
      }}
      actionRender={actionRender}
      // onPageChange={(pg) => setPage(pg)}
    />
  );
};

export default SignupActivity;
