import React, { useCallback, useEffect, useState, useMemo } from 'react';
import classNames from 'classnames';
import { Input, Select, Button, Form, DatePicker, Table, Pagination, Modal } from 'antd';
import { Link } from "react-router-dom";

import { paperCheckStatusArr, publishModeArr, taskStatusAllArr, showUserModeArr, main_web_site_url } from '../static';
import { getTaskAdminList, changeShowUserMode, deleteTask, recommendTask } from '../api';
import '../index.scss';
import './index.scss';
const format = "YYYY-MM-DD HH:mm:ss";
const Option = Select.Option;

const statusArr = [];
for (const item of taskStatusAllArr) {
  statusArr[item.dicItemCode] = item.dicItemName;
}
const checkStatusArr = [];
for (const item of paperCheckStatusArr) {
  checkStatusArr[item.dicItemCode] = item.dicItemName;
}


export default Form.create()(({ form, showNotification, match, history }) => {
  const { getFieldDecorator, setFieldsValue, getFieldsValue } = form;

  const [reload, setReload] = useState();
  const [loading, setLoading] = useState(false);
  const [statusString, setStatusString] = useState('');
  const [publishMode, setPublishMode] = useState('');
  const [showUserMode, setShowUserMode] = useState('');
  const [isDelete, setIsDelete] = useState('0');
  const [recommend, setRecommend] = useState('');

  const [sort, setSort] = useState('Desc');
  const [order, setOrder] = useState('createdAt');
  const [searchObj, setSearchObj] = useState({});
  const [curPage, setCurPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [taskList, setTaskList] = useState([]);


  useEffect(() => {
    const params = {
      ...searchObj,
      statusString,
      publishMode: publishMode.length > 1 ? '' : publishMode,
      showUserMode: showUserMode.length > 1 ? '' : showUserMode,
      curPage,
      pageSize: 10,
      orderBy: order + sort,
      isDelete,
      recommend,
    };
    setLoading(true);
    getTaskAdminList(params).then(data => {
      if (data) {
        setTaskList(data.rows);
        setTotal(data.total);
      }
      setLoading(false);
    })
  }, [statusString, order, sort, publishMode, showUserMode, curPage, searchObj, isDelete, reload, recommend]);


  const helper = useCallback(
    (label, name, rules, widget, initialValue) => (
      <Form.Item label={label}>
        {getFieldDecorator(name, { rules, initialValue, validateFirst: true, })(widget)}
      </Form.Item>
    ), []);


  function onSearch() {
    let values = getFieldsValue(['nameInput', 'endTime', 'startTime', 'enterpriseNameInput']);
    if (values.startTime) values.startTime = values.startTime.format(format);
    if (values.endTime) values.endTime = values.endTime.format(format);
    if (values.checkStatus === '0,1,2') values.checkStatus = '';
    setSearchObj(values);
  }

  function clearSearch() {
    setFieldsValue({
      startTime: '',
      endTime: '',
      nameInput: '',
      enterpriseNameInput: ''
    });
    setSearchObj({});
  }

  const columns = useMemo(() => {
    return [
      {
        title: '序号',
        dataIndex: 'index',
        render: (text, record, index) => {
          return <div style={{ textAlign: 'center' }}>{index + 1}</div>
        }
      },
      {
        title: '任务编号',
        dataIndex: 'number',
      },
      {
        title: '任务名称',
        dataIndex: 'name',
        width: "15%",
        render: (text, record) => (
          <Link className="line_1 primary-link" target="_blank" to={`/task/taskDetail/${record.id}`} >{text}</Link>
        ),
      },
      {
        title: <Select
          className="column-select"
          showArrow
          defaultValue={'0,1'}
          onChange={setPublishMode}
        >
          <Option key={'0,1'} >发布方式</Option>
          <Option key={'0'} >自主提交</Option>
          <Option key={'1'} >统筹任务</Option>
        </Select>,
        dataIndex: 'publishMode',
        render: (text, record) => {
          return publishModeArr[text]
        }
      },
      {
        title: <Select
          className="column-select"
          showArrow
          defaultValue={'0,1,2,3,4,5,6,7,8,9'}
          onChange={setStatusString}
        >
          <Option key={'0,1,2,3,4,5,6,7,8,9'} >任务状态</Option>
          {
            taskStatusAllArr.map(item => {
              return <Option key={item.dicItemCode} >{item.dicItemName}</Option>
            })
          }
        </Select>,
        width: '10%',
        dataIndex: 'status',
        render: (text, record) => {
          return record.exceptClosedBoolean ? '已关闭' : statusArr[text]
        }
      },
      {
        title: '稿件数',
        dataIndex: 'papersCount',
      },
      {
        title: '发布主体',
        dataIndex: 'enterpriseName',
      },
      {
        title: '发布时间',
        dataIndex: 'publishedAt',
        render: (text, record) => {
          return text || '--'
        }
      },
      {
        title: '截稿时间',
        dataIndex: 'collectingEndTime',
        render: (text, record) => {
          return text || '--'
        }
      },
      {
        // title: '应征者名单公示',
        title: <Select
          className="column-select"
          showArrow
          placeholder="请选择审核状态"
          defaultValue={'0,1,2'}
          onChange={setShowUserMode}
        >
          <Option key={'0,1,2'}>应征者名单公示</Option>
          {
            showUserModeArr.map(item => {
              return <Option key={item.dicItemCode}>{item.dicItemName}</Option>
            })
          }
        </Select>,
        dataIndex: 'showUserMode',
        render: (text, record) => {
          return <Select
            className="column-select"
            showArrow
            placeholder="请选择审核状态"
            defaultValue={text}
            onChange={(key) => { changeStatus(key, record.id) }}
          >
            {
              showUserModeArr.map(item => {
                return <Option key={item.dicItemCode} value={item.dicItemCode}>{item.dicItemName}</Option>
              })
            }
          </Select>
        }
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <React.Fragment>

            {
              isDelete == '0' ? <Button className="mr5 font-12" type="danger" size="small" onClick={() => { deleteItem(record.id, '1') }}>隐藏</Button>
                : <Button className="mr5 font-12" type="primary" size="small" onClick={() => { deleteItem(record.id, '0') }}>恢复</Button>
            }

            {
              !record.recommend && [3, 4, 5, 6, 7, 8].includes(record.status) && <Button className="mr5 font-12" type="primary" size="small" onClick={() => { recommendItem(record.id, '1') }}>首页推荐</Button>
            }

            {
              record.recommend && <Button className="mr5 font-12" type="danger" size="small" onClick={() => { recommendItem(record.id, '0') }}>撤销推荐</Button>
            }

            {/* <Link className="line_1 color-grey3" to={`/task/taskDetail/${record.taskId}`}>查看</Link> */}
          </React.Fragment>
        ),
      },
    ]
  }, [isDelete]);

  function recommendItem(id, recommend) {
    Modal.confirm({
      title: "警告",
      content: recommend == '0' ? "确认撤销该推荐吗 ？撤销后首页中将不再展示该任务" : "确认推荐吗？推荐后，用户可以在首页看到推荐任务中点击量前三的任务！",
      okText: '确定',
      cancelText: '取消',
      onOk() {
        recommendTask(id, recommend).then(res => {
          if (res.message === 'success') {
            showNotification('操作成功!');
            setReload(Math.random());
          }
        });
      },
    });
  }

  function deleteItem(id, isDelete) {
    Modal.confirm({
      title: "警告",
      content: isDelete == '0' ? "确认恢复该任务吗？恢复后用户可以重新看到该任务！" : "确认隐藏？隐藏后用户无法看到该任务！",
      okText: '确定',
      cancelText: '取消',
      onOk() {
        deleteTask(id, isDelete).then(res => {
          if (res.message === 'success') {
            showNotification('操作成功!');
            setReload(Math.random());
          }
        });
      },
    });
  }

  function changeStatus(showUserMode, taskId) {
    changeShowUserMode({
      taskId,
      showUserMode
    }).then(res => {
      if (res && res.message === 'success') {
        showNotification('修改成功!');
      }
    })
  }


  // 改变排序字段
  const changeSortName = useCallback((sortType) => {
    setOrder(sortType);
    setCurPage(1);
  }, []);

  // 改变排序
  const changeSort = useCallback((sort) => {
    setSort(sort);
    setCurPage(1);
  }, []);

  const changeShow = useCallback((isDelete) => {
    setIsDelete(isDelete);
    setCurPage(1);
  });

  const changeRecommend = useCallback((recommend) => {
    if (recommend === 'all') {
      setRecommend('');
    } else {
      setRecommend(recommend);
    }
    setCurPage(1);
  });

  function downloadFile() {
    window.open(main_web_site_url + '/admin/tasks.xlsx');
  }

  return (
    <div className="centerbox task-manage-all ">

      <div className="search-screen" >
        {helper(
          "任务名称",
          "nameInput",
          [{ max: 20, message: '长度不能超过20个字符' }],
          <Input
            placeholder="输入任务名称进行检索"
          />
        )}

        {helper(
          "发布主体名称",
          "enterpriseNameInput",
          [{ max: 20, message: '长度不能超过20个字符' }],
          <Input
            placeholder="输入发布主体名称进行检索"
          />
        )}

        <div className="center-right-but">

          {helper(
            "发布时间:",
            "startTime",
            [],
            <DatePicker
              showTime
              format={format}
              placeholder="请选择开始时间"
            />
          )}

          {helper(
            "",
            "endTime",
            [],
            <DatePicker
              showTime
              format={format}
              placeholder="请选择结束时间"
            />
          )}
        </div>
        <div className="button-div">
          {/* <a href="/admin/tasks.xlsx" class="fr edu-default-btn edu-blueback-btn plr30">导出</a> */}
          <Button className="mr10" type="primary" onClick={onSearch}>搜索</Button>
          <Button className="mr10" onClick={clearSearch}>清除</Button>
          <Button className="mr10" type="primary" onClick={downloadFile}>导出</Button>
        </div>
      </div>

      <div className="select-box">
        <Form.Item className="inline-form" label="显示状态">
          <Select
            style={{ width: '200px' }}
            showArrow
            onChange={changeShow}
            defaultValue='0'
          >
            <Option key={'0'} >正常显示（默认）</Option>
            <Option key={'1'} >已隐藏</Option>
          </Select>
        </Form.Item>

        <Form.Item className="inline-form" label="是否推荐">
          <Select
            style={{ width: '200px' }}
            showArrow
            onChange={changeRecommend}
            defaultValue='all'
          >
            <Option key={'all'} >全部</Option>
            <Option key={'0'} >未推荐</Option>
            <Option key={'1'} >已推荐</Option>
          </Select>
        </Form.Item>

        <Form.Item className="inline-form" label="排序">
          <Select
            style={{ width: '200px' }}
            showArrow
            onChange={changeSortName}
            defaultValue='createdAt'
          >
            <Option key={'createdAt'} >创建时间</Option>
            <Option key={'publishedAt'} >发布时间</Option>
          </Select>

          <span className={classNames({ "sort-active": sort === 'Desc', 'sort-icon': true, 'ml10': true })} onClick={() => { changeSort('Desc') }}>
            <i className="fa fa-long-arrow-down font-16  "></i>
          </span>
          <span className={classNames({ "sort-active": sort === 'Asc', 'sort-icon': true })} onClick={() => { changeSort('Asc') }}>
            <i className="fa fa-long-arrow-up font-16 "></i>
          </span>

        </Form.Item>
      </div>





      <div className="center-content">

        <Table
          loading={loading}
          rowKey={(row) => row.id}
          dataSource={taskList}
          columns={columns}
          pagination={false}
          className="mt10"
        />
        {total > 10 &&
          <Pagination
            onChange={(page) => { setCurPage(page) }}
            current={curPage}
            total={total}
          />}

      </div>


    </div>
  )
}
)