import React from 'react';
import {connect, routerRedux} from 'dva';
import {Table, Button, Input, DatePicker, Select, Modal} from "antd";
import styles from './style.less';
import {ConnectState} from "@/models/connect";
import {router} from "umi";

const {RangePicker,} = DatePicker;

class Account extends React.Component {

  //构造
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      total: 0,
      id: '',
      status: undefined,
      statusList: ["正常", "关闭"],
      moment: [],
      delData: [],
      visible: false,
      nowUser: '',
      name: '',
    }
  }

  /*-----------------   方法集  ------------------*/
  //模态框相关
  showModal = () => {
    let flag = 0;
    const { delData } = this.state;
    const nowUser = this.props.currentUser;
    if(nowUser.permission!=null){
      for(let i=0;i<nowUser.permission.length;i++){
        if(nowUser.permission[i]=="19"){
          flag = 1;
        }
      }
    }
    if(flag == 0){
      alert("缺少用户删除权限！");
      return;
    }
    for(let i=0;i<delData.length;i++){
      if(delData[i].userID == 1){
        alert("禁止删除超级管理员！");
        return;
      }
      if(delData[i].userID == this.props.currentUser.userid){
        alert("禁止删除当前用户！");
        return;
      }
    }
    this.setState({
      visible: true,
    });
  };
  handleOk = (e) => {
    this.del();
    this.setState({
      visible: false,
    });
  };
  handleCancel = (e) => {
    this.setState({
      visible: false,
    });
  };
  //批量删除
  del() {
    const { delData } = this.state;
    for(let i=0;i<delData.length;i++){
      if(delData[i].tosUserId == 1){
        alert("禁止删除超级管理员！");
        return;
      }
      if(delData[i].tosUserId == this.props.currentUser.userid){
        alert("禁止删除当前用户！");
        return;
      }
    }
    this.props.dispatch({
      type: 'accountModel/delAdccount',
      payload: this.state.delData,
      callback: (res) => {
        if (res) {
          if (res.error_code == "0000") {
            alert(res.error_msg);
            this.setState({
              delData: '',
            });
            this.getData();
          } else if(res.error_code == "0001"){
            alert(res.error_msg);
          } else if(res.error_code == "0002"){
            alert(res.error_msg);
          } else if(res.error_code == "0008"){
            alert(res.error_msg);
            window.location.href = '/';
            router.replace('/');
          } else {
            alert("删除失败！未知错误！");
          }
        }
      }
    });
  };
  //获取所有用户
  getData = () => {
    const params = {
      id: this.state.id,
      status: this.state.status,
      moment: this.state.moment,
      name: this.state.name,
      // leaderID: this.props.currentUser.userid,
      leaderID:"21232f297a57a5a743894a0e4a801fc3",
      userPhone:"18813787835"
    };
    console.log(params);
    this.props.dispatch({
   type: 'accountModel/getAccount',
      // type: 'tUModel/getTosUser',
      payload: params,
      callback: (res) => {
        if (res) {
          console.log(res);

      /*    for (var i = 0; i < res.rows.length; i++) {
            var model = res.rows[i];
            var updated_date = this.getLocalTime(model.createTime.time);
            model.createTime = updated_date;
          }*/

          this.setState({
            data: res.data.rows,
            total: res.data.total,
           /* data: res.rows,
            total: res.total,*/
          })
        } else if(res.error_code == "0008"){
          alert(res.error_msg);
          window.location.href = '/';
          router.replace('/');
        }
      }
    });
  };

  getLocalTime(nS) {
    return new Date(parseInt(nS)).toLocaleString('chinese', { hour12: false }).replace(/:\d{1,2}$/, ' ');
  }
  //跳转到编辑页面
  edit = (params) => {
    let flag = 0;
    const nowUser = this.props.currentUser;
    let oneself = 0;
    if(params==null&&nowUser.level==1){
      // alert("您当前用户等级不允许创建新用户！");
      // return;
    }
    if(params!=null&&params.userID!=null&&(params.userID == this.props.currentUser.userid)){
      oneself = 1;
    }
    if(nowUser.permission!=null){
      for(let i=0;i<nowUser.permission.length;i++){
        if(params!=null){
          if(oneself == 1){
            flag = 1;
          }
          if(nowUser.permission[i]=="17"){
            flag = 1;
          }
        }else{
          if(nowUser.permission[i]=="16"){
            flag = 1;
          }
        }
      }
    }
    if(flag == 0){
      if(params!=null){
        // alert("缺少用户信息编辑权限！");
        // return;
      }else{
        // alert("缺少创建用户权限！");
        // return;
      }
    }
    this.props.dispatch(routerRedux.push({
      pathname: '/AccountManagement/account/edit',
      query: params,
    }))
  };
  //用户禁用，启用
  changeStatus = (e) => {
    const params = {
      userStatus: e.userStatus == '0' ? 1 : 0,
      userID: e.id,
    };
    this.props.dispatch({
      type: 'accountModel/quitAndUser',
      payload: params,
      callback: (res) => {
        if(res.error_code == "0000"){
          this.getData();
        }else if(res.error_code == "0001"){
          alert(res.error_msg);
        }else if(res.error_code == "0002"){
          alert(res.error_msg);
        }else if(res.error_code == "0008"){
          alert(res.error_msg);
          window.location.href = '/';
          router.replace('/');
        }else{
          alert("修改用户状态失败！未知错误！");
        }
      }
    });
  };
  //搜索状态变更
  statusChange = (e) => {
    this.setState({status: e == undefined ? undefined : (e == 1 ? 0 : 1)});
  };
  //账号名称变更
  nameChange = (e) => {
    this.setState({name: e.target.value});
  };
  //日期变更
  dateChange = (e) => {
    this.setState({moment: e});
  };

  //初始化
  componentDidMount() {
    const nowUser = this.props.currentUser.userid;
    this.setState({
      nowUser: nowUser
    });
    this.getData();
  }

  /*--------------------------------------*/
  //表格列名
  columns = [
    {
      title: 'Account Name',
      dataIndex: 'tosUserName',
      key: 'userAccount',
    },
    {
      title: 'Grade',
      dataIndex: 'tosuserLevel',
      key: 'userLevel',
      render: (text, record) => (
        <span>
          {record.tosuserLevel == 5 ? "超级管理员" : ""}
          {record.tosuserLevel == 4 ? "一级管理员" : ""}
          {record.tosuserLevel == 3 ? "二级管理员" : ""}
          {record.tosuserLevel == 2 ? "三级管理员" : ""}
          {record.tosuserLevel == 1 ? "一级管理员" : ""}
        </span>
      )
    },

    {
      title: 'Status',
      dataIndex: 'userStatus',
      key: 'userStatus',
      render: (text, record) => (
        <span>{record.userStatus == 0 ? "启用" : "禁用"}</span>
      )
    },
    {
      title: 'Created By',
      dataIndex: 'tosUserServiceCell',
      key: 'createAccount',
    },
    {
      title: 'Creation Time',
      dataIndex: 'createTime',
      key: 'createTime',
    },



    {
      title: 'Actions',
      dataIndex: 'action',
      key: 'action',
      render: (text, record) => (
        <span>
          <Button style={{background: 'transparent', border: 0, color: '#1890FF'}}
                  onClick={() => this.edit(record)}>Edit</Button>
           <Button style={{background: 'transparent', border: 0, color: '#1890FF'}}
                   onClick={() => this.changeStatus(record)}> {record.userStatus == 1 ? "lock" : "unlock"}</Button>
          {/*{record.userID == 1||record.userID == this.props.currentUser.userid?'':
          <Button style={{background: 'transparent', border: 0, color: '#1890FF'}}
                  onClick={() => this.changeStatus(record)}>
            {record.userStatus == 1 ? "lock" : "unlock"}</Button>}*/}
        </span>
      ),
    },
  ];
  //行选择
  rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      this.setState({
        delData: selectedRows
      });
    },
  };

  //渲染
  render() {
    const {data, total, statusList} = this.state;

    const statusSelect = statusList.map((item, index) => (
      <Select.Option value={index}>{item}</Select.Option>
    ));

    return (
      <div className={styles.body}>
        <div className={styles.inputBox}>
          <Input id="deviceName" className={styles.input} placeholder="账号名称" onChange={(e) => this.nameChange(e)}/>
          {/*<Input id="Name" className={styles.input} placeholder="发布人姓名" />*/}
          <RangePicker
            style={{marginLeft: 20}}
            renderExtraFooter={() => ''}
            showTime
            onChange={(e) => this.dateChange(e)}
          />
          <Select className={styles.input} placeholder="状态" onChange={(e) => this.statusChange(e)}
                  allowClear={true}>{statusSelect}</Select>
          <Button className={styles.button1} onClick={() => this.getData()}>搜索</Button>
        </div>
        <div style={{marginTop: 10}}>
          <Button className={styles.button2} onClick={() => this.edit(null)}>新建</Button>
        </div>
        <div>
          <Table
            rowKey={record => record.userID}
            className={styles.table}
            rowSelection={this.rowSelection}
            columns={this.columns}
            dataSource={data}
            size="small"
            pagination={{showQuickJumper: true, pageSize: 10, total: total}}
          />
          <Button className={styles.button3} onClick={() => this.showModal()}>删除</Button>
        </div>
        <Modal
          title="确认删除？"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}>
          <div style={{textAlign: "center"}}><p style={{fontSize: 18}}>删除信息将不可恢复</p></div>
        </Modal>
      </div>
    );
  }
}

export default connect(({user}: ConnectState) => ({
  currentUser: user.currentUser,
}))(Account);
