import React from 'react';
import {connect, routerRedux} from 'dva';
import {Table, Button, DatePicker, Select, Menu, Modal, Input, Icon} from "antd";
import styles from './style.less';
import {ConnectState} from "@/models/connect";
import ExportJsonExcel from 'js-export-excel';
import {router} from "umi";
import { Upload, message} from 'antd';



//npm install js-export-excel



class OrderManagementDetail extends React.Component {

  //构造
  constructor(props) {
    super(props);
    this.state = {
      record: [],
      data: [],
      total: 1,
      type: undefined,
      typeList: ["扫描模块故障", "打印机故障", "触摸屏故障","副屏故障"],
      moment: [],
      current: 'record',
      delData: [],
      visible: false,
      uploadVisible: false,
      fileList: [],
    }
  }

  /*-----------------   方法集  ------------------*/
  //打印excel
  downloadExcel = () => {
    let flag = 0;
    const nowUser = this.props.currentUser;
    if(nowUser.permission!=null){
      for(let i=0;i<nowUser.permission.length;i++){
        if(nowUser.permission[i]=="14"){
          flag = 1;
          const data = this.state.record ? this.state.record : '';//表格数据
          var option={};
          let dataTable = [];
          if (data) {
            for (let i in data) {
              if(data){
                let warnType;
                if(data[i].warn_type == 1) {
                  warnType = '扫描模块故障';
                }else if(data[i].warn_type == 2) {
                  warnType = '打印机故障';
                }else if(data[i].warn_type == 3) {
                  warnType = '触摸屏故障';
                }else if(data[i].warn_type == 4) {
                  warnType = '副屏故障';
                }
                let obj = {
                  '设备名称': data[i].device_name,
                  '设备型号': data[i].device_model,
                  '警报类型': warnType,
                  '报警时间': data[i].warn_time,
                  '地址': data[i].device_address,
                  '联系人': data[i].user_account,
                  '联系方式': data[i].user_phone,
                }
                dataTable.push(obj);
              }
            }
          }
          option.fileName = '警报信息';
          option.datas=[
            {
              sheetData:dataTable,
              sheetName:'sheet',
              sheetFilter:['设备名称','设备型号','警报类型','报警时间','联系人','联系方式','地址'],
              sheetHeader:['设备名称','设备型号','警报类型','报警时间','联系人','联系方式','地址'],
            }
          ];

          var toExcel = new ExportJsonExcel(option);
          toExcel.saveExcel();
        }
      }
    }else{
    //alert("找不到用户权限记录！");
      //return;;
    }
    if(flag == 0){
      alert("缺少批量下载权限！");
      return;
    }
  };
  //模态框相关
  showModal = () => {
    let flag = 0;
    let permissionNum = null;
    const nowUser = this.props.currentUser;
    if(nowUser.permission!=null){
      for(let i=0;i<nowUser.permission.length;i++){
        if(this.state.current == "record"){
          permissionNum = "15";
        }else{
          permissionNum = "12";
        }
        if(nowUser.permission[i]==permissionNum){
          if(this.state.delData==null||this.state.delData.length<=0){
            alert("未选中删除项！");
            return;
          }
          flag = 1;
          this.setState({
            visible: true,
          });
        }
      }
    }else{
    //alert("找不到用户权限记录！");
      //return;;
    }
    if(flag == 0){
      if(this.state.current == "record"){
        alert("缺少警报记录删除权限！");
      }else{
        alert("缺少警报模板删除权限！");
      }
    }
  };
  handleOk = () => {
    this.del();
    this.setState({
      visible: false,
    });
  };
  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };
  //获取警报数据
  getData = () => {
    const nowUser = this.props.currentUser.userid;
    const params = {
      type: this.state.type,
      userID: nowUser,
      userPhone:"18813787835"
    };
    this.props.dispatch({
      type: 'tUModel/getTosUser',
      payload: params,
      callback: (res) => {
        if (res) {
          console.log(res);
          // if(res.error_code == "0000"){
          this.setState({
            data: res.rows,
            total: res.total,
          })
          /*   } 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("获取警报数据失败！未知错误！");
             }*/
        }
      }
    });
  };
  //获取警报记录数据
  getRecord = () => {
    const params = {
      type: this.state.type,
      moment: this.state.moment,
      id: this.props.currentUser.userid,
      userPhone:"18813787835"
    };
    this.props.dispatch({
      type: 'tUModel/getTosUser',
      payload: params,
      callback: (res) => {
        // if (res.error_code == "0000"){
        this.setState({
          record: res.rows,
          total: res.total,
        })
        /*      } 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("获取警报记录失败！未知错误！")
              }*/
      }
    });
  };
  //批量删除
  del(){
    this.props.dispatch({
      type: this.state.current == 'model'?'warnModel/delWarn':'warnModel/delWarnRecord',
      payload: this.state.delData,
      callback: (res) => {
        if (res) {
          console.log(res);
          if(res.error_code == "0000"){
            alert("删除完毕！");
            if(this.state.current == 'model'){
              this.getData();
            }else{
              this.getRecord();
            }
          }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("删除失败！未知错误！");
          }
        }
      }
    });
  };
  //跳转到编辑页面
  edit = (params) => {

    this.props.dispatch(routerRedux.push({
      pathname: '/tosUser/common',
      query: params,
    }))

    let flag = 0;
    const nowUser = this.props.currentUser;
    if(nowUser.permission!=null){
      if(params==null){
        for(let i=0;i<nowUser.permission.length;i++){
          if(nowUser.permission[i]=="11"){
            flag = 1;
            this.props.dispatch(routerRedux.push({
              pathname: '/tosUser/common',
              query: params,
            }))
          }
        }
      }else{
        for(let i=0;i<nowUser.permission.length;i++){
          if(nowUser.permission[i]=="10"){
            flag = 1;
            this.props.dispatch(routerRedux.push({
              pathname: '/warn/edit',
              query: params,
            }))
          }
        }
      }
    }else{
    //alert("找不到用户权限记录！");
      //return;;
    }
    if(flag == 0){
      if(params==null){
        alert("缺少添加警报模板权限！");
      }else{
        alert("缺少修改警报模版权限！");
      }
    }
  };
  //警报启用禁用
  changeStatus = (e) => {
    const params = {
      status: e.warnStatus == '0'? 1:0,
      warnID: e.warnID ? e.warnID : null,
    };
    this.props.dispatch({
      type: 'warnModel/quitAndUserWarn',
      payload: params,
      callback: () => {
        this.getData();
      }
    });
  };
  //状态变更
  typeChange = (e) => {
    this.setState({type: e == undefined?undefined:e+1});
  };
  //日期变更
  dateChange = (e) => {
    this.setState({moment: e});
  };
  //水平导航
  handleClick = (e) => {
    this.setState({
      current: e.key,
    },() => {
      if(this.state.current == "record"){
        this.getRecord();
      }else{
        this.getData(null);
      }
    });
  };
  clickUploadAPP(record) {
    this.setState({
      uploadVisible: true,
      // app_id: record.app_id,
      app_id:'',
      team_head_id:''
    })
  }
  handleSureTableChange = () => {
    this.setState({
      uploadVisible: false
    });
  }

  handleUpload = () => {
    const {fileList} = this.state;
    var fileData;
    fileList.forEach(file => {
      if (file) {
        fileData = file;
      }

    });
    if (fileData) {
      const params = {
        fileBase64Str: fileData.thumbUrl,
        userToken: localStorage.getItem('jwToken'),
        // app_id: this.state.app_id,
        fileName: fileData.name,
        // remark: this.state.remark,
        /**/
        team_head_id: '',
        // fileName: getFileName('uploadFile'),
        // remark: '',
        // fileBase64Str: fileBase64Str

      }
      /* request_post('/teamHead/uploadTeamLogoWeb', params, (json) => {
         if (json.error_code == '0000') {
           Modal.info({
             content: (
               '上传成功'
             ),
             onOk() {
             },
           });
         }else {
           Modal.info({
             content: (
               '上传失败'
             ),
             onOk() {
             },
           });
         }
       })*/
      this.props.dispatch({
        type: '/teamHead/uploadTeamLogoWeb',
        payload: params,
        callback: (res) => {
          if (res) {
            console.log(res);
            // if(res.error_code == "0000"){
            this.setState({
              data: res.rows,
              total: res.total,
            })
            /*   } 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("获取警报数据失败！未知错误！");
               }*/
          }
        }
      });

    }

  }

  handleCancelUserInfo = () => {
    this.currentSelectUserInfo = '';
    this.setState({
      uploadVisible: false
    });
  }


  //跳转到设备页面
  back = () => {
    this.props.dispatch(routerRedux.push({
      pathname: '/orderManagement',
    }))
  };


  handleChange = (info) => {
    const isJpgOrPng = info.file.type === 'image/jpeg' || info.file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('不支持 JPG/PNG 以外的文件!');
      return;
    }
    const isLt2M = info.file.size / 1024 / 1024 < 20;
    if (!isLt2M) {
      message.error('文件大小不能超过 20MB!');
      return;
    }
    let fileList = [...info.fileList];
    fileList = fileList.slice(-6);
    fileList = fileList.map(file => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });
    this.setState({ fileList });
  };

  //提交
  onSubmit = () => {
    // this.phoneBlur();
  };

  //初始化
  componentDidMount() {
    if (this.props.location.query != null) {
      const params = this.props.location.query;
      this.setState({
        current: params.current?params.current:'record',
      },() => {
        if(this.state.current == "record"){
          this.getRecord();
        }else{
          this.getData();
        }
      });
    }
  }

  /*--------------------------------------*/
  //表格列名
  columns = [
    {
      title: 'User Name',
      dataIndex: 'warnType',
      key: 'warnType',
      render: (text, record) => (
        <span>
          {record.warnType == 1?'扫描模块故障':''}
          {record.warnType == 2?'打印机故障':''}
          {record.warnType == 3?'触摸屏故障':''}
          {record.warnType == 4?'副屏故障':''}
        </span>
      ),
    },
    {
      title: 'Contact Details',
      dataIndex: 'warnContactsInformation',
      key: 'warnContactsInformation',
    },
    {
      title: 'E-mail',
      dataIndex: 'warnDetails',
      key: 'warnDetails',
    },
    {
      title: 'Account Type',
      dataIndex: 'enable',
      key: 'warn_time',
    },
    {
      title: 'User Status',
      dataIndex: 'user_account',
      key: 'user_account',

      defaultSortOrder: 'descend',
      sorter: (a, b) => a.user_account - b.user_account,
    },
    /*   {
         title: '状态',
         dataIndex: 'status',
         key: 'status',
         render: (text, record) => (
           <span>
             {record.warnStatus == 1? "启用": "禁用"}
           </span>
         )
       },*/
    {
      title: 'Actions',
      dataIndex: 'action',
      key: 'action',
      render: (text, record) => (
        <span>
          <Button style={{background: 'transparent', border: 0, color: '#1890FF'}}
                  onClick={() => this.edit(record)}>Details</Button>
          {/*   <Button style={{background: 'transparent', border: 0, color: '#1890FF'}}
                  onClick={() => this.changeStatus(record)}>{record.warnStatus == 1? "关闭": "启用"}</Button>*/}
        </span>
      ),
    },
  ];
  columns2 = [
    {
      title: 'User Name',
      dataIndex: 'owerName',
      key: 'device_name',
    },
    {
      title: 'Contact Details',
      dataIndex: 'owerPhone',
      key: 'device_model',
    },
    {
      title: 'E-mail',
      dataIndex: 'buildingNumber',
      key: 'warn_type',
      render: (text, record) => (
        <span>
          {record.warn_type == 1?'扫描模块故障':''}
          {record.warn_type == 2?'打印机故障':''}
          {record.warn_type == 3?'触摸屏故障':''}
          {record.warn_type == 4?'副屏故障':''}
        </span>
      ),
    },
    {
      title: 'Account Type',
      dataIndex: 'enable',
      key: 'warn_time',
    },
    {
      title: 'User Status',
      dataIndex: 'user_account',
      key: 'user_account',

      defaultSortOrder: 'descend',
      sorter: (a, b) => a.user_account - b.user_account,
    },
    {
      title: 'Actions',
      dataIndex: 'action',
      key: 'action',
      render: (text, record) => (
        <span>
          <Button style={{background: 'transparent', border: 0, color: '#1890FF'}}
                  onClick={() => this.edit(record)}>Details</Button>
          {/*   <Button style={{background: 'transparent', border: 0, color: '#1890FF'}}
                  onClick={() => this.edit(record)}>编辑</Button>*/}
        </span>
      ),
    },
    /*    {
          title: '联系方式',
          dataIndex: 'user_phone',
          key: 'user_phone',
        },
        {
          title: '地址',
          dataIndex: 'device_address',
          key: 'device_address',
        },*/
  ];
  //行选择
  rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      this.setState({
        delData: selectedRows
      },() => {
        console.log(this.state.delData);
      });
    }
  };

  //渲染
  render() {

    const props = {
      onRemove: file => {
        const index = fileList.indexOf(file);
        const newFileList = fileList.slice();
        newFileList.splice(index, 1);
        return {
          fileList: newFileList,
        };
      },
      beforeUpload: file => {
        const r = new FileReader();
        r.readAsDataURL(file);
        r.onload = e => {
          file.thumbUrl = e.target.result;
          this.setState(state => ({
            fileList: [...state.fileList, file],
          }));
        };
        return false;
      },
    };

    const {uploadVisible, data, total, typeList, current, record, visible,tosUser } = this.state;

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

    const upload = {
      action: '/api/ad/upload',
      onChange: this.handleChange,
      multiple: true,
    };

    return (
      <div className={styles.body}>

        <div style={{marginTop:48}}>
          <div>
            <span className={styles.detailsTitle}>Reply To Project Maintenance</span>  <Button className={styles.button11} onClick={() => this.back()}>Return</Button>
            <div className={styles.detailsBox}>
              <div>
                <span className={styles.detailsContent}>Status</span>
                {/*<Input className={styles.input} value={""}  placeholder="Name"*/}
                {/*  onChange={(e) => this.snChange(e)}*/}
                {/*/>*/}
                <span className={styles.detailsContent3}>{tosUser}</span>
                <span className={styles.detailsContent}>Pending For Processing</span>
                {/*<span className={styles.detailsContent2}>{tosUser}</span>*/}
                {/*   <span className={styles.detailsContent}>设备ID</span>*/}
                {/*<span className={styles.detailsContent2}>{tosUser}</span>*/}
              </div>
              <div>
                <span className={styles.detailsContent}>Published At</span>
                {/*<Input className={styles.input} value={""} placeholder="Telephone"*/}
                {/*  onChange={(e) => this.snChange(e)}*/}
                {/*/>*/}
                <span className={styles.detailsContent3} style={{width:200}}>{tosUser}</span>
                {/*<span className={styles.detailsContent}>18817589685</span>*/}
                {/*<Input className={styles.input} value={""} placeholder="E-mail"*/}
                {/*  onChange={(e) => this.snChange(e)}*/}
                {/*/>*/}
                {/*<span className={styles.detailsContent2}>{tosUser}</span>*/}
                <span className={styles.detailsContent}>26-03-2020 13：00</span>
                {/*<span className={styles.detailsContent2}>{tosUser}</span>*/}
              </div>
              {/*<div>*/}
              {/*  <span className={styles.detailsContent}>联系地址</span>*/}
              {/*  <span className={styles.detailsContent3}>{total}</span>*/}
              {/*</div>*/}
            </div>
          </div>
        </div>


        <div style={{padding:30}}>
          <Menu
            className={styles.menu}
            onClick={this.handleClick}
            selectedKeys={[current]}
            mode="horizontal">
            <Menu.Item key="record" className={styles.menuItem}>

            </Menu.Item>
            {/*<Menu.Item key="model">*/}
            {/*  Constant company*/}
            {/*</Menu.Item>*/}
          </Menu>
        </div>
        <div className={styles.inputBox}>


          <div>
            <span className={styles.detailsContent1}>Sunshine Stanford</span>
            <span className={styles.detailsContent3}>{tosUser}</span>
            <span className={styles.detailsContent1}>03#06-2050</span>

          </div>
          <div>
            <span className={styles.detailsContent}>Albert Street, 175, Singapore, Albert, Bugis, Victoria Street,</span>
            <span className={styles.detailsContent3}>{tosUser}</span>
            <span className={styles.detailsContent1}>Singapore 189969</span>
            <span className={styles.detailsContent3}>{tosUser}</span>
          </div>

          <div>
            <span className={styles.detailsContent1}>User Name</span>
            <span className={styles.detailsContent3}>{tosUser}</span>
            <span className={styles.detailsContent1}>Josephine</span>
            <span className={styles.detailsContent3}>{tosUser}</span>
            <span className={styles.detailsContent1}>Contact Details</span>
            <span className={styles.detailsContent3}>{tosUser}</span>
            <span className={styles.detailsContent1}>13657724536</span>
            <span className={styles.detailsContent3}>{tosUser}</span>
          </div>

        </div>
        <div>
          <div>
            <span className={styles.detailsContent1}>Complaint Description</span>
            {/*  <span className={styles.detailsContent2}>{tosUser}</span>*/}
            <Input className={styles.input1}   placeholder="The user's notes of property maintenance are written here"
              // onChange={(e) => this.nameChange(e)}
            />
          </div>
          <div>
            <span className={styles.detailsContent1}>Picture</span>
            {/*  <span className={styles.detailsContent2}>{tosUser}</span>*/}
            <img style ={{width:100,height:100,margin:20,}}src= {"https://www.srthinker.com:5305/file/bea3c35262ab4bae8d904701a4e4d1a9.jpg"} />
            <img style ={{width:100,height:100,margin:20,}}src= {"http://120.77.240.215:5205/file/8e23d00533514c3a8506e790498cde5f.jpg"} />
            <img style ={{width:100,height:100,margin:20,}}src= {"https://www.srthinker.com:5305/file/40f3208f17df4a34af65c31f850541a1.jpg"} />

          </div>

          <div style={{padding:30}}>
            <Menu
              className={styles.menu}
              onClick={this.handleClick}
              selectedKeys={[current]}
              mode="horizontal">
              <Menu.Item key="record" className={styles.menuItem}>

              </Menu.Item>

            </Menu>
          </div>
          <div>
            <span className={styles.detailsContent1}>Replied By</span>
            <span className={styles.detailsContent3}>{tosUser}</span>
            <span className={styles.detailsContent1}>Bellamy</span>
            <span className={styles.detailsContent1}>Contact Details</span>
            <span className={styles.detailsContent3}>{tosUser}</span>
            <span className={styles.detailsContent1}>13657724536</span>
            <span className={styles.detailsContent3}>{tosUser}</span>
          </div>
          <div>
            <div>
              <span className={styles.detailsContent1}>Resolved Complaint</span>
              {/*  <span className={styles.detailsContent2}>{tosUser}</span>*/}
              <Input className={styles.input1}   placeholder="Please enter the processing result"
                // onChange={(e) => this.nameChange(e)}
              />
            </div>

            <div>
              <span className={styles.detailsContent1}>Picture</span>
              {/*  <span className={styles.detailsContent2}>{tosUser}</span>*/}
              <img style ={{width:100,height:100,margin:20,}}src= {"http://final.srthinker.com/file/aa68e397ef544ec797ba1897904a5f73.jpg_70x70"} />
              <img style ={{width:100,height:100,margin:20,}}src= {"http://final.srthinker.com/file/b3e6b569a03749328d2408a9be1a00cc.jpg_70x70"} />
              <img style ={{width:100,height:100,margin:20,}}src= {"http://final.srthinker.com/file/fcb12e667b134af5a2799ff900b13912.jpg_70x70"} />

            </div>



            <Button className={styles.button22} onClick={() => this.onSubmit()}>Submit</Button>

          </div>

        </div>

        <div>

        </div>
        <Modal
          title="确认删除？"
          visible={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,
}))(OrderManagementDetail);
