import React from 'react';
import './index.less';
import { Switch } from 'antd';
import Page from '@src/containers/Page';
import { getMap, formatDate } from '@src/services/Tools';
import UserAction from '../../../components/UserAction';
import Tabs from '../../../components/Tabs';
import Filter from '../../../components/Filter';
import Icon from '../../../components/Icon';
import { DataItem } from '../../../components/Item';
import UserTable from '../../../components/UserTable';
import UserPagination from '../../../components/UserPagination';
import { FeedbackErrorDataModal } from '../../../components/OtherModal';
import { DataType } from '../../../../Constant';
import { Main } from '../../../stores/main';
import { Course } from '../../../stores/course';
import { My } from '../../../stores/my';
import { User } from '../../../stores/user';


const dataHistoryColumns = [
  { title: '更新时间', key: 'time', width: 120 },
  { title: '位置', key: 'position', width: 120 },
  { title: '原内容', key: 'originContent', width: 120 },
  { title: '更改为', key: 'content', width: 120 },
  { title: '更新至', key: 'version', width: 90 },
];

export default class extends Page {
  initState() {
    const dataTypeSelect = DataType.map((row) => {
      return {
        title: row.label,
        key: row.value,
      };
    });
    dataTypeSelect.unshift({
      title: '全部',
      key: '',
    });
    return {
      tab: '',
      filterMap: {},
      sortMap: {},
      list: [],
      dataStructSelect: [],
      dataTypeSelect,
      // type: [
      //   { title: '长难句', key: '1', open: true, children: [{ key: '1', title: 'OG19 语法千行' }] },
      //   { title: '语文 Verbal', key: '2', open: true, children: [{ key: '1', title: 'OG19 语法千行' }] },
      //   { title: '数学 Quant', key: '3', open: true, children: [{ key: '1', title: 'OG19 语法千行' }] },
      // ],
    };
  }

  init() {
    Main.dataStruct().then(result => {
      const dataStructSelect = result.filter(row => row.level === 1).map(row => {
        return {
          title: `${row.titleZh}${row.titleEn}`,
          key: `${row.id}`,
        };
      });
      dataStructSelect.unshift({
        title: '全部',
        key: '',
      });
      const dataStructMap = getMap(dataStructSelect, 'key');
      this.setState({ dataStructSelect, dataStructMap });
    });
  }

  initData() {
    const data = Object.assign(this.state, this.state.search);
    if (data.order) {
      data.sortMap = { [data.order]: data.direction };
    }
    data.filterMap = this.state.search;
    this.setState(data);
    switch (data.tab) {
      case 'history':
        this.refreshHistory();
        break;
      default:
        this.refreshData();
    }
  }

  refreshData() {
    Course.listData(Object.assign({}, this.state.search))
      .then(result => {
        this.setState({ list: result.list, total: result.total });
      });
  }

  refreshHistory() {
    let { all, dataId } = this.state;
    dataId = Number(dataId);
    if (!all) {
      Course.listData({ page: 1, size: 1000 })
        .then(result => {
          this.dataMap = getMap(result.list, 'id');
          const allIds = [];
          result.list.forEach(row => {
            if (allIds.indexOf(row.structId) >= 0) return;
            allIds.push(row.structId);
          });
          all = allIds.map(row => {
            return { id: row, children: [] };
          });
          result.list.forEach(row => {
            const index = allIds.indexOf(row.structId);
            all[index].children.push(row);
            if (row.id === dataId) all[index].open = true;
          });
          if (!dataId) {
            dataId = result.list[0].id;
            all[0].open = true;
          }

          this.refreshHistoryList(dataId);
          this.setState({ all });
        });
    } else if (dataId) {
      this.refreshHistoryList(dataId);
    }
  }

  refreshHistoryList(dataId) {
    Course.historyData({ dataId, page: 1, size: 1000 })
      .then(result => {
        result.list = result.list.map(row => {
          row.time = formatDate(row.time, 'YYYY-MM-DD\nHH:mm:ss');
          return row;
        });
        this.setState({ item: this.dataMap[dataId], list: result.list, dataId });
      });
  }

  onTabChange(tab) {
    const data = { tab };
    this.refreshQuery(data);
  }

  onFilter(key, value) {
    const { filterMap } = this.state;
    filterMap[key] = value;
    this.search(filterMap, false);
    this.initData();
  }

  onChangePage(page) {
    this.search({ page }, false);
    this.initData();
  }

  onSort(value) {
    const keys = Object.keys(value);
    // this.search({ order: keys.length ? keys.join('|') : null, direction: keys.length ? Object.values(value).join('|') : null });
    const { sortMap } = this.state;
    const index = keys.length > 1 && sortMap[keys[0]] ? 1 : 0;
    this.search({ order: keys.length ? keys[index] : null, direction: keys.length ? value[keys[index]] : null });
  }

  onOpen(index) {
    const { all } = this.state;
    all[index].open = !all[index].open;
    this.setState({ all });
  }

  onSelect(dataId) {
    this.search({ dataId }, false);
    this.initData();
  }

  subscribe(dataId, subscribe) {
    User.needLogin()
      .then(() => {
        My.subscribeData(dataId, subscribe)
          .then(() => {
            this.refresh();
          });
      });
  }

  renderView() {
    const { tab } = this.state;
    return (
      <div>
        <div className="top content t-8">
          千行课堂 > <span className="t-1">资料列表</span>
          <div className="f-r"><a href="/my/tools?tab=data">我的资料</a></div>
        </div>
        <div className="center content">
          <Tabs
            type="division"
            theme="theme"
            size="small"
            space={2.5}
            width={100}
            border
            active={tab}
            tabs={[{ title: '全部资料', key: '' }, { title: '更新日志', key: 'history' }]}
            onChange={key => this.onTabChange(key)}
          />
          {this[`renderTab${tab}`]()}
        </div>
      </div>
    );
  }

  renderTab() {
    const { list = [], total, page, sortMap, filterMap, dataStructSelect, dataTypeSelect } = this.state;
    return [
      <Filter
        filter={filterMap}
        list={[
          {
            key: 'structId',
            placeholder: '学科',
            children: dataStructSelect,
          },
          {
            placeholder: '形式',
            key: 'dataType',
            children: dataTypeSelect,
          },
        ]}
        onFilter={(key, value) => this.onFilter(key, value)}
      />,
      <UserAction
        // search
        defaultSearch={filterMap.keyword}
        sortList={[
          { label: '更新时间', key: 'updateTime', fixed: true },
          { label: '销量', key: 'saleNumber', fixed: true },
        ]}
        sortMap={sortMap}
        onSort={value => this.onSort(value)}
      />,
      <div className="data-list">
        {list.map(item => {
          return <DataItem data={item} />;
        })}
      </div>,
      total > 0 && list.length > 0 && (
        <UserPagination total={total} current={page} pageSize={this.state.search.size} onChange={p => this.onChangePage(p)} />
      ),
    ];
  }

  renderTabhistory() {
    const { all = [], dataId, item = {}, list = [], dataStructMap = {}, showFeedbackError, feedbackError } = this.state;
    return [
      <div className="update-search">
        {/* <UserAction search defaultSearch={filterMap.keyword} /> */}
      </div>,
      <div className="update-log">
        <div className="left">
          {all.map((node, index) => {
            const struct = dataStructMap[node.id] || {};
            return (
              <div className="block">
                <div className="title" onClick={() => this.onOpen(index)}>
                  {struct.title}
                  <div className="f-r">
                    {node.open ? <Icon name="arrow-up" noHover /> : <Icon name="arrow-down" noHover />}
                  </div>
                </div>
                <div className={`list ${node.open ? 'open' : ''}`}>
                  {node.children.map(child => {
                    return <div className={`item ${child.id === dataId ? 't-4' : ''}`} onClick={() => this.onSelect(child.id)}>{child.title}</div>;
                  })}
                </div>
              </div>
            );
          })}
        </div>
        <div className="right">
          <div className="item">
            <div className="m-b-5">
              <span className="t-1 t-s-18 f-w-b">{item.title}</span>
              <div className="f-r">
                <span className="m-r-5">订阅</span>
                <Switch checked={item.subscribe} onChange={() => {
                  this.subscribe(item.id, !item.subscribe);
                }} />
                <a className="m-l-5 t-4" onClick={() => this.setState({ showFeedbackError: true, feedbackError: { dataId: item.id, title: item.title, position: ['', '', ''] } })}>纠错</a>
              </div>
            </div>
            <UserTable size="small" columns={dataHistoryColumns} data={list} />
          </div>
        </div>
      </div>,
      <FeedbackErrorDataModal
        show={showFeedbackError}
        defaultData={feedbackError}
        onConfirm={() => this.setState({ showFeedbackError: false })}
        onCancel={() => this.setState({ showFeedbackError: false })}
      />,
    ];
  }
}