/**
 * 我的消息
 */
import React, { Component } from 'react';
// import { connect } from 'dva';
import LzEditor from 'react-lz-editor';
import {
  Input,
  Button,
  DatePicker,
  TreeSelect,
  Table,
  Select,
  Modal,
  message,
  LocaleProvider
} from 'antd';
import moment from 'moment';
import zh_CN from 'antd/lib/locale-provider/zh_CN';
moment.locale('zh-cn');
import $perModal from '../../../utils/modal/perModal';
import { gup } from '../../../utils/utils';
import * as ajax from '../../../services/api';
import MessageDetail from './messageDetail';
import st from 'styled-components';
const { confirm } = Modal;
const { Option } = Select;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';

// @connect(state => ({
//   global: state.global,
//   currentUser: state.user.currentUser,
//   fetchingNotices: state.global.fetchingNotices
// }))
export default class ReceiveList extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      treeData: [],
      // visibleuser:false,
      selectedRowIds: [], //需要删除的信息id值集合1
      listPage: [], //表格数据
      selectedRowKeys: [],
      // selectUserIdArrays:[], //选中的id集合，保存用的
      responseList: [],
      dataSource: {
        briefIntroduce: '' //富文本
      },
      checkModal: false, //查看消息弹窗
      titleLength: '0', //发送消息弹窗  标题的长度
      record: {},
      inputVal: '', //关键字输入框
      startDate: '',
      endDate: '',
      isRead: '', //已读未读
      //分页配置
      pageParm: {
        //数据请求 分页信息
        pageNumber: '1',
        pageSize: '10',
        startDate: '',
        endDate: '',
        key: '',
        isRead: ''
      },
      // dataSource: [], //table 数据源
      pagination: {
        showQuickJumper: true,
        pageSizeOptions: ['5', '10', '15', '25', '50'],
        showSizeChanger: true,
        onChange: this.onPaginationChange,
        onShowSizeChange: this.onPaginationShowSizeChange
        // showTotal: total => `总共 ${total} 条`,//用于显示数据总量和当前数据顺序
      }
    };

  }

  componentWillReceiveProps(nextProps) {
    // if (this.props.global.notices !== nextProps.global.notices) {
    //   this.search();
    // }
  }

  componentDidMount() {
    this.search();

    //获取部门树数据
    ajax.getTreeperBydepart({}).then(data => {
      data.data = this.checkMember(data.data);
      this.setState({ treeData: data.data });
    });
  }

  handleTreeSelect(value, node, extra) {
    console.log(value, node, extra);
  }

  // 遍历部门人员数据
  checkMember(data) {
    data = data.map(item => {
      if (item.children && item.children.length) {
        let needDisable = true;
        const temp = subItem => {
          subItem.filter(tempItem => {
            if (tempItem.children && tempItem.children.length) {
              temp(tempItem.children);
              return tempItem;
            } else {
              if (tempItem.treeType === '2') {
                needDisable = false;
              }
              return tempItem;
            }
          });
        };
        temp(item.children);
        needDisable ? (item.disableCheckbox = true) : null;
        this.checkMember(item.children);
        return item;
      } else {
        if (item.treeType !== '2') {
          item.disableCheckbox = true;
          item.disabled = true;
          item.isLeaf = true;
        }
        return item;
      }
    });

    return data;
  }

  //页码改变
  onPaginationChange = (page, pageSize) => {
    const { pageParm, pagination, startDate, endDate, inputVal, isRead } = {
      ...this.state
    };

    pageParm.pageNumber = page;
    pagination.current = page;
    pageParm.startDate = startDate;
    pageParm.endDate = endDate;
    pageParm.key = inputVal;
    pageParm.isRead = isRead;

    this.setState({ pageParm, pagination });
    this.search();
  };

  //pageSize 变化的回调
  onPaginationShowSizeChange = (current, size) => {
    const { pageParm, pagination, startDate, endDate, inputVal, isRead } = {
      ...this.state
    };
    //切换每页显示多少条记录的时候，重置为第一页。重新排版 table
    pageParm.pageSize = size;
    pageParm.pageNumber = 1;
    pageParm.startDate = startDate;
    pageParm.endDate = endDate;
    pageParm.key = inputVal;
    pageParm.isRead = isRead;

    pagination.current = 1;

    this.setState({ pageParm, pagination });
    this.search();
  };

  //时间选择
  onChangeTime = (date, dateString) => {
    this.setState({
      startDate: dateString[0],
      endDate: dateString[1]
    });
  };

  //已读，未读
  handleChangeIsRead = value => {
    this.setState({ isRead: value });
  };

  //输入框的书写
  inputTracknameChange = e => {
    // let tmp = Object.assign({}, this.state.ajaxPagePara);
    // tmp.data.Trackname = e.target.value.trim();
    this.setState({
      inputVal: e.target.value.trim()
    });
  };

  //分页消息列表（收件人方）
  search = (pageParm = this.state.pageParm) => {
    ajax.messageReceiveList(pageParm).then(
      data => {
        // const { pagination } = this.state;
        // pagination.total = data.data.total;

        this.setState({
          listPage: data.data.data,
          pagination: {
            ...this.state.pagination,
            total: data.data.total,
            current: data.data.pageNumber,
            pageSize: data.data.pageSize
          },
        });
      },
      err => {
        console.log('err', err);
      }
    );
  };

  //重置
  resetQueryCond = () => {
    const { pageParm, pagination } = { ...this.state };
    pageParm.pageSize = 10;
    pageParm.pageNumber = 1;
    pagination.current = 1;
    pageParm.startDate = '';
    pageParm.endDate = '';
    pageParm.key = '';
    pageParm.isRead = '';

    this.setState(
      {
        startDate: '',
        endDate: '',
        inputVal: '',
        isRead: '',
        pageParm,
        pagination
      },
      () => {
        this.search();
      }
    );
  };

  // 订单删除
  orderDelete = IdAndType => {
    ajax
      .messageDeleteMessageById({ messageJson: JSON.stringify(IdAndType) })
      .then(
        data => {
          this.setState({
            selectedRowIds: [],
            selectedRowKeys: [],
            selectedRows: []
          });

          const { pageParm, pagination } = { ...this.state };
          pageParm.pageSize = 10;
          pageParm.pageNumber = 1;
          pagination.current = 1;

          this.setState(
            {
              pageParm,
              pagination
            },
            () => {
              this.search();
            }
          );
        },
        err => {
          message.warning('消息删除失败！' + err);
        }
      );
  };

  showDeleteConfirm = record => {
    confirm({
      title: '是否删除所选信息，删除后无法找回。是否确认删除？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        const arrDelete = [
          {
            id: record.id,
            messageType: record.messageType
          }
        ];
        this.orderDeleteXiao(arrDelete);
      },
      onCancel() {
        console.log('Cancel');
      }
    });
  };

  orderDeleteXiao = orderIdAndType => {
    ajax
      .messageDeleteMessageById({ messageJson: JSON.stringify(orderIdAndType) })
      .then(
        data => {
          const { pageParm, pagination } = { ...this.state };
          pageParm.pageSize = 10;
          pageParm.pageNumber = 1;
          pagination.current = 1;

          this.setState(
            {
              pageParm,
              pagination
            },
            () => {
              this.search();
            }
          );
        },
        err => {
          message.warning('消息删除失败！' + err);
        }
      );
  };

  // 批量删除
  handleDeleteList = () => {
    const that = this;
    const keyNumber = this.state.selectedRowIds.length;
    const keyId = this.state.selectedRowKeys;
    if (keyNumber <= 0) {
      message.warning('请选择需要删除的信息！');
    } else {
      const IdAndType = this.state.selectedRows.filter(val => {
        delete val.key;
        delete val.sendTime;
        delete val.title;
        return val;
      });
      confirm({
        title: '是否删除所选方案，删除后方案不可找回。是否确认删除？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          that.orderDelete(IdAndType);
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    }
  };

  // 批量设置已读
  handleRead = () => {
    const keyNumber = this.state.selectedRowIds.length;
    // const keyId = this.state.selectedRowKeys;
    if (keyNumber <= 0) {
      message.warning('请选择需要设为已读的信息！');
    } else {
      const IdAndType = this.state.selectedRows.filter(val => {
        delete val.addresser;
        delete val.key;
        delete val.isRead;
        delete val.sendTime;
        delete val.title;
        return val;
      });
      ajax
        .updateSelectMessageRead({
          messageJson: JSON.stringify(IdAndType)
        })
        .then(
          () => {
            this.setState({
              selectedRowIds: [],
              selectedRowKeys: []
            });

            const { pageParm, pagination } = { ...this.state };
            pageParm.pageSize = 10;
            pageParm.pageNumber = 1;
            pagination.current = 1;

            this.setState(
              {
                pageParm,
                pagination
              },
              () => {
                this.search();
              }
            );
          },
          err => {
            message.warning('设置为已读失败！' + err);
          }
        );
    }
  };

  // 表格渲染
  renderOrderList = () => {
    // const pageInitStudent = {
    //   defaultPageSize: 10,
    //   showQuickJumper: true,
    //   pageSizeOptions: ['5', '10', '15', '20', '25'],
    //   showSizeChanger: true
    // };

    const selectedRowKey = this.state.selectedRowKeys;
    const rowSelection = {
      selectedRowKeys: selectedRowKey,

      onChange: selectedRowKeys => {
        this.setState({
          selectedRowKeys
        });
      },
      onSelect: (record, selected, selectedRows) => {
        const selectId = this.state.selectedRowIds;
        if (selected === true) {
          selectId.push(record.perNewsRelaId);
        } else {
          for (let i = 0; i < selectId.length; i++) {
            if (selectId[i] === record.perNewsRelaId) {
              selectId.splice(i, 1);
              break;
            }
          }
        }
        this.setState({
          selectedRowIds: selectId,
          selectedRows
        });
      },
      onSelectAll: (selected, selectedRows) => {
        let selectId = [];
        if (selected === true) {
          for (let i = 0; i < selectedRows.length; i++) {
            selectId.push(selectedRows[i].perNewsRelaId);
          }
        } else {
          selectId = [];
          // selectedRowKeys:selectedRowKey
        }
        this.setState({
          selectedRowIds: selectId,
          selectedRows
        });
      }
    };

    const columns = [
      {
        title: '发件人',
        dataIndex: 'addresser',
        key: 'addresser',
        width:300,
        render: (text, record) => (
          <span>
            {record.isRead === '1' ? (
              // <span style={{ color: '#27121254' }}>{record.addresser}</span>
              <span style={{ color: 'rgba(39, 18, 18, 0.33)' }}>
                {record.addresser}
              </span>
            ) : (
              <span style={{ color: '#666' }}>{record.addresser}</span>
            )}
          </span>
        )
      },
      {
        title: '标题',
        dataIndex: 'title',
        key: 'title',
        // width: 300,
        render: (text, record) => (
          <span>
            {record.isRead === '1' ? (
              <span
                style={{
                  // color: '#27121254',
                  color: 'rgba(39, 18, 18, 0.33)',
                  display: 'inline-block',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis'
                }}
              >
                {record.title}
              </span>
            ) : (
              <span
                style={{
                  color: '#666',
                  display: 'inline-block',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis'
                }}
              >
                {record.title}
              </span>
            )}
          </span>
        ),
      },
      {
        title: '时间',
        dataIndex: 'sendTime',
        key: 'sendTime',
        width:160,
      },
      {
        title: '状态',
        dataIndex: 'isRead',
        key: 'isRead',
        width:60,
        render: (text, record) => (
          <span>
            {record.isRead === '1' ? (
              <span
                style={{
                  // color: '#27121254',
                  color: 'rgba(39, 18, 18, 0.33)',
                  display: 'inline-block',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis'
                }}
              >
                已读
              </span>
            ) : (
              <span
                style={{
                  color: '#666',
                  display: 'inline-block',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis'
                }}
              >
                未读
              </span>
            )}
          </span>
        )
      },
      {
        title: '操作',
        fixed: 'right',
        width: 100,
        render: (text, record) => (
          <div>
            <span
              style={{
                color: '#108EE9',
                cursor: 'pointer',
                marginRight: '10px'
              }}
              onClick={() => {
                const { messageType } = record;
                // 公安通知公告
                if((messageType + '').indexOf('050301') != -1) {
                  this.props.history.push('/PoliceDeclare/police-notice');
                }else {
                  this.setState({ record, checkModal: true });
                }
              }}
            >
              查看
            </span>
            <span
              style={{ color: '#108EE9', cursor: 'pointer' }}
              onClick={this.showDeleteConfirm.bind(this, record)}
            >
              删除
            </span>
          </div>
        )
      }
    ];

    const tmp = this.state.listPage.map(val => {
      const param = val;
      param.key = val.id;
      return param;
    });
    const { pagination } = this.state;

    return (
      <LocaleProvider locale={zh_CN}>
        <Table
          dataSource={tmp}
          columns={columns}
          rowSelection={rowSelection}
          // pagination={pageInitStudent}
          pagination={pagination}
          scroll={{ x: '1100px' }}
        />
      </LocaleProvider>
    );
  };

  render() {
    return (
      <div className="message-receive">
        <div className="form">
          <label style={{ marginRight: 16 }}>
            关键字：
            <Input
              style={{ width: '214px', marginBottom: '10px' }}
              placeholder="请输入发件人/标题"
              onChange={this.inputTracknameChange}
              value={this.state.inputVal}
              maxLength={20}
            />
          </label>
          <label style={{ marginRight: 16 }}>
            接收时间：
            <LocaleProvider locale={zh_CN}>
              <RangePicker
                showTime={{ format: 'HH:mm' }}
                format={dateFormat}
                onChange={this.onChangeTime}
                style={{ marginBottom: '10px' }}
                value={[
                  this.state.startDate === ''
                    ? null
                    : moment(this.state.startDate, dateFormat),
                  this.state.endDate === ''
                    ? null
                    : moment(this.state.endDate, dateFormat)
                ]}
              />
            </LocaleProvider>
          </label>
          <br/>
          <label style={{ marginRight: 16 }}>
            是否已读：
            <Select
              style={{ width: 120 }}
              value={this.state.isRead}
              onChange={this.handleChangeIsRead}
              placeholder="请选择"
            >
              <Option value="">全部</Option>
              <Option value="1">已读</Option>
              <Option value="0">未读</Option>
            </Select>
          </label>
          <Button
            style={{
              marginRight: '16px',
              marginBottom: '16px',
              padding: window && window.innerWidth <= 1366 ? '0 10px' : '0 15px'
            }}
            type="primary"
            onClick={() => {
              const {
                pageParm,
                pagination,
                startDate,
                endDate,
                inputVal,
                isRead
              } = { ...this.state };
              // pageParm.pageSize = 10;
              pageParm.pageNumber = 1;
              pagination.current = 1;
              pageParm.startDate = startDate;
              pageParm.endDate = endDate;
              pageParm.key = inputVal;
              pageParm.isRead = isRead;

              console.log(pageParm)
              this.setState(
                {
                  pageParm,
                  pagination
                },
                () => {
                  this.search();
                }
              );
            }}
          >
            搜索
          </Button>
          <Button
            onClick={this.resetQueryCond}
            style={{
              padding: window && window.innerWidth <= 1366 ? '0 10px' : '0 15px',
              marginRight:'16px'
            }}
          >
            重置
          </Button>
          <Button onClick={this.handleRead} style={{marginRight:'16px'}}>批量设置为已读</Button>
            <Button type="danger" ghost onClick={this.handleDeleteList}>
              批量删除
            </Button>
        </div>
        {/* <div className="receive-list">
          <div className="receive-row">
            <Button onClick={this.handleRead} style={{marginRight:'5px'}}>批量设置为已读</Button>
            <Button type="danger" ghost onClick={this.handleDeleteList}>
              批量删除
            </Button>
          </div>
        </div> */}
        {this.renderOrderList()}
        {/*查看信息弹窗1*/}
        <MessageDetail
          record={this.state.record}
          visible={this.state.checkModal}
          closeModal={() => {
            this.setState({ checkModal: false });
            this.search();
          }}
          dispatch={this.props.basicLayoutDispatch}
        />
      </div>
    );
  }
}
