import React from 'react';
// import { Link } from 'react-router-dom';
// import { Button } from 'antd';
import './index.less';
import Page from '@src/containers/Page';
import Block from '@src/components/Block';
// import FilterLayout from '@src/layouts/FilterLayout';
import ActionLayout from '@src/layouts/ActionLayout';
import TableLayout from '@src/layouts/TableLayout';
import { asyncSMessage, asyncForm, asyncDelConfirm } from '@src/services/AsyncTools';
import { formatDate, getMap, formatTreeData, flattenTree } from '@src/services/Tools';
import { AdChannel, AdPlace } from '../../../../Constant';
import { System } from '../../../stores/system';


const AdChannelTree = formatTreeData(AdChannel, 'value', 'label', 'parent');
const AdChannelFlatten = flattenTree(AdChannelTree, (row, item) => {
  row = Object.assign({}, row);
  row.value = `${item.value}-${row.value}`;
  row.label = `${item.label}-${row.label}`;
  return row;
}, 'children');
const AdChannelMap = getMap(AdChannelFlatten, 'value', 'label');

const AdPlaceTree = formatTreeData([].concat(AdChannelFlatten.map(row => Object.assign({}, row)), AdPlace), 'value', 'label', 'parent');
const AdPlaceChannelMap = getMap(AdPlaceTree, 'value', 'children');
const AdPlaceMap = getMap(AdPlaceTree, 'value', 'label', 'children');

export default class extends Page {
  init() {
    this.formF = null;
    this.itemList = [{
      key: 'id',
      type: 'hidden',
    }, {
      key: 'channel',
      type: 'cascader',
      allowClear: true,
      name: '频道',
      select: AdChannelTree,
      placeholder: '请选择',
      onChange: (value) => {
        this.changeSearch(this.itemList, this.formF, value.join('-'), null, 2);
      },
    }, {
      key: 'place',
      type: 'select',
      allowClear: true,
      name: '位置',
      select: [],
      placeholder: '请选择',
    }, {
      key: 'title',
      type: 'input',
      name: '广告名称',
    }, {
      key: 'time',
      type: 'daterange',
      name: '广告时间',
    }, {
      key: 'image',
      type: 'image',
      name: '广告图片',
      onUpload: ({ file }) => {
        return System.uploadImage(file).then(result => { return result; });
      },
    }, {
      key: 'link',
      type: 'input',
      name: '链接地址',
    }];
    this.filterForm = [{
      key: 'channel',
      type: 'cascader',
      allowClear: true,
      name: '频道',
      select: AdChannelTree,
      placeholder: '请选择',
    }];
    this.actionList = [{
      key: 'add',
      type: 'primary',
      name: '创建',
    }];
    this.columns = [{
      title: '频道',
      dataIndex: 'channel',
      render: (text) => {
        return AdChannelMap[text] || '';
      },
    }, {
      title: '位置',
      dataIndex: 'place',
      render: (text, record) => {
        return (AdPlaceMap[record.channel] || {})[text];
      },
    }, {
      title: '广告名称',
      dataIndex: 'title',
    }, {
      title: '展示时间',
      dataIndex: 'time',
      render: (text, record) => {
        return record.startTime && record.endTime ? `${formatDate(record.startTime, 'YYYY-MM-DD')}-${formatDate(record.endTime, 'YYYY-MM-DD')}` : '长期';
      },
    }, {
      title: '操作',
      dataIndex: 'handler',
      render: (text, record) => {
        return <div className="table-button">
          {(
            <a onClick={() => {
              this.editAction(record);
            }}>编辑</a>
          )}
          {(
            <a onClick={() => {
              this.deleteAction(record);
            }}>删除</a>
          )}
        </div>;
      },
    }];
  }

  changeSearch(list, component, key, value, index = 1) {
    if (key) {
      list[index].select = AdPlaceChannelMap[key];
      list[index].disabled = false;
    } else {
      list[index].disabled = true;
    }
    component.setFieldsValue({ [list[index].key]: value });
    component.setState({ load: false });
  }

  initData() {
    System.listAd(Object.assign({}, this.state.search)).then(result => {
      this.setTableData(result.list, result.total);
    });
  }

  addAction() {
    asyncForm('创建广告', this.itemList, {}, data => {
      if (data.time && data.time.length > 0) {
        data.startTime = data.time[0].format('YYYY-MM-DD');
        data.endTime = data.time[1].format('YYYY-MM-DD');
      }
      data.channel = data.channel.join('-');
      return System.addAd(data).then(() => {
        asyncSMessage('添加成功!');
        this.refresh();
      });
    }).then(component => {
      this.formF = component;
      this.changeSearch(this.itemList, this.formF, null, null, 2);
    });
  }

  editAction(row) {
    const info = Object.assign({}, row);
    info.channel = info.channel.split('-');
    asyncForm('编辑广告', this.itemList, info, data => {
      if (data.time && data.time.length > 0) {
        data.startTime = data.time[0].format('YYYY-MM-DD');
        data.endTime = data.time[1].format('YYYY-MM-DD');
      }
      data.channel = data.channel.join('-');
      return System.editAd(data).then(() => {
        asyncSMessage('编辑成功!');
        this.refresh();
      });
    }).then(component => {
      this.formF = component;
      this.changeSearch(this.itemList, this.formF, row.channel, row.place, 2);
    });
  }

  deleteAction(row) {
    asyncDelConfirm('删除确认', '是否删除选中?', () => {
      const handler = System.delAd({ id: row.id });
      return handler.then(() => {
        asyncSMessage('删除成功!');
        this.refresh();
      });
    });
  }

  renderView() {
    return <Block flex>
      {/* <FilterLayout
        show
        itemList={this.filterForm}
        data={this.state.search}
        onChange={data => {
          data.page = 1;
          this.search(data);
        }} /> */}
      <ActionLayout
        itemList={this.actionList}
        selectedKeys={this.state.selectedKeys}
        onAction={key => this.onAction(key)}
      />
      <TableLayout
        columns={this.tableSort(this.columns)}
        list={this.state.list}
        pagination={this.state.page}
        loading={this.props.core.loading}
        onChange={(pagination, filters, sorter) => this.tableChange(pagination, filters, sorter)}
        onSelect={(keys, rows) => this.tableSelect(keys, rows)}
        selectedKeys={this.state.selectedKeys}
      />
    </Block>;
  }
}