import React, { Component } from "react";
import { connect } from "dva";
import moment from "moment";
import LzEditor from 'react-lz-editor';
import { Input, Button, DatePicker, Table, Modal, message } from "antd";
import MessageDetail from './messageDetail';
import * as ajax from "../../../services/api";
import st from 'styled-components';
import $perModal from '../../../utils/modal/perModal';

const { confirm } = Modal;
const { RangePicker } = DatePicker;
const dateFormat = "YYYY-MM-DD";

@connect(state => ({
  global: state.global,
  currentUser: state.user.currentUser
}))
export default class SendRecord extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      selectedRowIds: [], //需要删除的信息id值集合
      selectedRows:[],//选择要删除的信息的所有行
      listPage: [], //表格数据
      selectedRowKeys: [],
      checkModal: false, //查看消息弹窗
      // uid: this.props.currentUser.perId,
      inputVal: "", //关键字输入框
      startDate: "",
      endDate: "",
      record: {},
      //分页配置
      pageParm: {//数据请求 分页信息
        pageNumber: "1",
        pageSize: '10',
        uid: this.props.currentUser.perId,
        startDate: "",
        endDate: "",
        serachContent: "",
      },
      // dataSource: [], //table 数据源
      pagination: {
        showQuickJumper: true,
        pageSizeOptions: ["5", "10", "15", "25", "50"],
        showSizeChanger: true,
        onChange: this.onPaginationChange,
        onShowSizeChange: this.onPaginationShowSizeChange,
        // showTotal: total => `总共 ${total} 条`,//用于显示数据总量和当前数据顺序
      },
      messageModal: false, //发送消息弹窗
      userIdArrays: [], //表单显示用的人员id集合
      input_wed: '', //发送信息的标题输入框
    };
  }

  componentDidMount() {
    this.search();
  }

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

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

    pageParm.pageNumber = page;
    pagination.current = page;
    pageParm.startDate = startDate;
    pageParm.endDate = endDate;
    pageParm.serachContent = inputVal;

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

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

    pagination.current = 1;

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

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

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

  //点击搜索
  search = (pageParm = this.state.pageParm) => {
    ajax
      .messageRecordList(pageParm)
      // {
      //   pageNumber: 1,
      //   pageSize: 50,
      //   uid: this.state.uid,
      //   startDate: this.state.startDate,
      //   endDate: this.state.endDate,
      //   serachContent: this.state.inputVal
      // }
      .then(
        data => {
          const { pagination } = this.state;
          pagination.total = data.data.total;

          this.setState({
            listPage: data.data.data, pagination,
          });
        },
        err => {
          console.log("err", err);
        }
      );
  };

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

    this.setState(
      {
        startDate: "",
        endDate: "",
        inputVal: "",
        pageParm,
        pagination,
      },
      () => {
        // if(pageParm.endDate || pageParm.startDate || pageParm.serachContent){
        //   return;
        // }
        this.search();
      }
    );
  };

  // 批量删除
  handleDeleteList = () => {
    let _this = this;
    const key_number = this.state.selectedRowIds.length;
    // const key_id = this.state.selectedRowIds;
    const key_id = this.state.selectedRowKeys;
    if (key_number <= 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() {
          _this.orderDelete(IdAndType);
        },
        onCancel() {
          console.log("Cancel");
        }
      });
    }
  };

  // 订单删除
  orderDelete = IdAndType => {
    // ajax.messageDeleteMessageById({ ids: orderID.join(",") }).then(
      ajax.messageDeleteSendMessage({ 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 => {
    let _this = this;
    confirm({
      title: "是否删除所选信息，删除后无法找回。是否确认删除？",
      okText: "确认",
      cancelText: "取消",
      onOk() {
      const arrDelete = [{
        id:record.id,
        messageType:record.messageType,
      }];
        // arrDelete.id = record.id;
        // arrDelete.messageType = record.messageType;
        // _this.orderDeleteXiao(record.id);
        _this.orderDeleteXiao(arrDelete);
      },
      onCancel() {
        console.log("Cancel");
      }
    });
  };

  orderDeleteXiao = orderIdAndType => {
    // ajax.messageDeleteMessageById({ ids: orderID }).then(
      // ajax.messageDeleteMessageById({ messageJson: JSON.stringify(orderIdAndType)}).then(
      ajax.messageDeleteSendMessage({ 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);
      }
    );
  };

  // 表格渲染
  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, changeRows) => {
        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
        });
      }
    };

    /*01开头：系统通知
02开头：任务通知
03开头：企业通知
04开头：考试通知
05开头：公安通知
06开头：平台通知 */
    const noticeAwars = {
      "01": "系统通知",
      "02": "任务通知",
      "03": "企业通知",
      "04": "考试通知",
      "05": "公安通知",
      "06": "平台通知"
    };

    const columns = [
      {
        title: "消息类型",
        dataIndex: "messageType",
        key: "messageType",
        render: text => (
          <span style={{ color: "#666" }}>
            {noticeAwars[text.substr(0, 2)]}
          </span>
        )
      },
      {
        title: "标题",
        dataIndex: "title",
        key: "title",
        render: (text, record) => (
          <span>
            {record.status === "1" ? (
              <span style={{ color: "#999" }}>{record.title}</span>
            ) : (
                <span style={{ color: "#666" }}>{record.title}</span>
              )}
          </span>
        )
      },
      {
        title: "时间",
        dataIndex: "sendTime",
        key: "sendTime"
      }, {
        title: '操作',
        render: (text, record) => (
          <div>
            <span
              style={{
                color: '#108EE9',
                cursor: 'pointer',
                marginRight: '20px'
              }}
              onClick={() => {
                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, i) => {
      val.key = i + 1;
      return val;
    });
    const { pagination } = this.state;

    return (
      <Table
        dataSource={tmp}
        columns={columns}
        rowSelection={rowSelection}
        // pagination={pageInitStudent}
        pagination={pagination}
        rowKey={record=>record.id}
      />
    );
  };
  // 发送消息
  sendMessage = () => {
    this.setState({
      messageModal: true
    });
  };
  // 富文本
  receiveHtml = content => {
    if (this.state.messageModal) {
      this.setState({
        dataSource: {
          briefIntroduce: content //富文本
        }
      });
    }
  };
  //发送消息
  handleMessageOk = () => {
    if (this.state.userIdArrays.length === 0) {
      message.warning('请选择人员');
      return;
    }
    if (this.state.input_wed.trim() === '') {
      //只限制长度
      message.warning('标题不能为空');
      return;
    }
    //修改20个，原来12个就能提交,加正则校验
    let attention = this.state.dataSource.briefIntroduce;
    attention = attention.replace(/&nbsp;|\s/g, '');
    attention = attention.replace(/<br>/g, '');
    attention = attention.replace(/<\/?.+?>/g, '');
    // if (attention.length < 20) {
    //   message.warning('内容不能小于20');
    //   return;
    // }
    if (attention.length === 0) {
      message.warning('内容不能为空');
      return;
    }

    ajax
      .messageSaveMessageCommon({
        title: this.state.input_wed,
        content: this.state.dataSource.briefIntroduce,
        ids: this.state.userIdArrays.map(({perId}) => perId).join(',')
      })
      .then(() => {
        // message.success('发送成功');//全局统一处理，这里不再处理
        this.renderOrderList();
        this.search();
        this.props.dispatch({
          type: 'global/fetchNotices'
        });
      });

    this.setState({
      messageModal: false,
      userIdArrays: [],
      input_wed: '', //发送信息的标题输入框
      dataSource: {
        briefIntroduce: '' //富文本
      }
    });
  };
  //弹窗关闭按钮
  handleMessageCancel = () => {
    this.setState({
      messageModal: false,
      userIdArrays: [],
      input_wed: '', //发送信息的标题输入框
      dataSource: {
        briefIntroduce: '' //富文本
      }
    });
  };
   //树选中事件
   treeSelectOnChangeHandler = value => {
    this.setState({ userIdArrays: value });
  };
  // 发送消息弹窗
  inputMessageName = e => {
    const messageLength = e.target.value.length;
    this.setState({
      titleLength: messageLength,
      input_wed: e.target.value
    });
  };


  render() {
    const { userIdArrays = [] } = this.state;
    const uploadProps = {
      action: ajax.uploadUrl,
      accept: 'image/*',
      onChange: info => {
        let responseList = info.fileList;
        responseList = responseList.slice(-2);

        responseList = responseList.map(file => {
          if (file.response) {
            file.url = `${file.response.data}&t=10`;
          }
          return file;
        });
        responseList = responseList.filter(file => {
          if (file.response) {
            return file.response.retType === '0';
          }
          return true;
        });
        this.setState({ responseList });
      },
      listType: 'picture',
      fileList: this.state.responseList,
      name: 'xfile',
      data: file => {
        console.log(file);
      },
      multiple: true,
      beforeUpload: this.beforeUpload,
      showUploadList: true
    };
    return (
      <div className="message-receive">
        <div className="form">
          <label>
            关键字：
            <Input
              style={{ width: 214, marginBottom: '10px' }}
              placeholder="请输入标题"
              onChange={this.inputTracknameChange}
              value={this.state.inputVal}
              maxLength={20}
            />
          </label>
          <label style={{ marginLeft: 16 }}>
            接收时间：
            <RangePicker
              showTime={{ format: "HH:mm" }}
              format={dateFormat}
              onChange={this.onChangeTime}
              value={[
                this.state.startDate === ""
                  ? null
                  : moment(this.state.startDate, dateFormat),
                this.state.endDate === ""
                  ? null
                  : moment(this.state.endDate, dateFormat)
              ]}
            />
          </label>
          <Button
            style={{ marginLeft: 16 }}
            type="primary"
            onClick={() => {
              const { pageParm, pagination, startDate, endDate, inputVal, } = { ...this.state };
              pageParm.pageSize = 10;
              pageParm.pageNumber = 1;
              pagination.current = 1;
              pageParm.startDate = startDate;
              pageParm.endDate = endDate;
              pageParm.serachContent = inputVal;

              this.setState({
                pageParm,
                pagination,
              },
                () => {
                  this.search();
                }
              );
            }}
          >
            搜索
          </Button>
          <Button style={{ marginLeft: 16 }} onClick={this.resetQueryCond}>
            重置
          </Button>
        </div>
        <div className="receive-list">
          <div className="receive-row">
            <Button type="primary" onClick={this.sendMessage}>
              发送信息
            </Button>
            {/*发送信息弹窗*/}
            <Modal
              width={700}
              title="发送信息"
              maskClosable={false}
              visible={this.state.messageModal}
              onOk={this.handleMessageOk}
              onCancel={this.handleMessageCancel}
              destroyOnClose
            >
              <FlexBox>
                <label
                  style={{
                    display: 'inline-block',
                    width: '80px',
                    textAlign: 'right'
                  }}
                >
                  收件人：
                </label>
                {/* <TreeSelect {...tProps} /> */}
                <InputWrap>
                  <Input 
                      type="text"
                      value={userIdArrays.map(({name}) => name).join(',')}
                      readOnly
                      placeholder="请选择参与人员"
                      onClick={() => {
                        $perModal({
                          title: '选择参与人员',
                          value: userIdArrays,
                          onOk: (values, close) => {
                            this.setState({
                              userIdArrays: values
                            }, () => {
                              close();
                            });
                          }
                        });
                      }}
                    />
                    {
                      !!this.state.userIdArrays.length && 
                      <span className="count_wrap">已选（{this.state.userIdArrays.length}）人</span>
                    }
                </InputWrap>
              </FlexBox>
              <div style={{ position: 'relative' }}>
                <label
                  style={{
                    display: 'inline-block',
                    width: '80px',
                    textAlign: 'right',
                    marginTop: '26px'
                  }}
                >
                  标题：
                </label>
                <Input
                  style={{ width: 560, paddingRight: '60px' }}
                  placeholder="请输入"
                  maxLength={50}
                  onChange={this.inputMessageName}
                  value={this.state.input_wed}
                />
                <span
                  style={{
                    position: 'absolute',
                    top: '28px',
                    right: '20px',
                    color: '#999',
                    fontSize: '12px'
                  }}
                >
                  {this.state.titleLength}
                  /50
                </span>
              </div>
              <div className="clearfix">
                <label
                  style={{
                    display: 'inline-block',
                    width: '80px',
                    textAlign: 'right',
                    marginTop: '26px',
                    float: 'left'
                  }}
                >
                  内容：
                </label>
                <div className="Rich-text">
                  <LzEditor
                    // active={false}
                    uploadProps={uploadProps}
                    autoSave={false}
                    video={false}
                    audio={false}
                    urls={false}
                    cbReceiver={this.receiveHtml}
                    // importContent={stateDataSource.briefIntroduce}  //ie下打开会出错
                    key="LzEditor"
                    image={false}
                    // convertFormat="raw"
                    pasteNoStyle={false}
                  />
                </div>
              </div>
            </Modal>
            <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.dispatch}
        />
      </div>
    );
  }
}
const InputWrap = st.div`
  width: 100%;
  display: flex;
  align-items: center;
  .count_wrap{
    flex-shrink: 0;
    margin-left: 8px;
  }
`;
const FlexBox = st.div`
  width: 100%;
  box-sizing: border-box;
  display: flex;
  aligin-items: center;
  label{
    flex-shrink: 0;
    line-height: 32px;
  }
`;