import React from 'react';
import {connect, routerRedux} from 'dva';
import {Table, Button, Input, Select, Modal, Tooltip, Upload, Icon, Checkbox, Row, Radio, Tag} from "antd";
import styles from './style.less';
import {ConnectState} from "@/models/connect";
// import XLSX from "@/pages/account/xlsx.core.min";
import {router} from "umi";
import CheckGroup from './CheckGroup';
import zhCN from 'ant-design-vue/es/locale-provider/zh_CN';
import moment from 'moment';
import 'moment/locale/zh-cn';


class OrderManagement extends React.Component {

  //构造
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      province: undefined,
      city: undefined,
      district: undefined,
      street: undefined,
      total: 1,
      name: '',
      model: '',
      status: undefined,
      statusList: [{label:"在线",value:"1"}, {label:"故障",value:"3"},{label:"未激活",value:"4"}],
      provinceList: [],
      cityList: [{name: "未选择省"}],
      districtList: [{name: "未选择市"}],
      streetList: [{name: "未选择区"}],
      delData: [],
      visible: false,
      deviceStatus: '',
      selectedRowKeys: [],

      used: null,
      newAdd: null,
      strList: [],
      newList:[],
      authorityList:[
        {
          "children": [
            {
              "children": [],
              "hasChildren": false,
              "is_admin": 1,
              "menuid": 5,
              "name": "组织架构",
              "parentid": 1,
              "sort": 10,
              "state": "",
              "is_checked": true
            },
            {
              "children": [],
              "hasChildren": false,
              "is_admin": 1,
              "menuid": 6,
              "name": "员工管理",
              "parentid": 1,
              "sort": 20,
              "state": "",
              "is_checked": true
            },
            {
              "children": [],
              "hasChildren": false,
              "is_admin": 1,
              "menuid": 11,
              "name": "角色管理",
              "parentid": 1,
              "sort": 30,
              "state": "",
              "is_checked": false
            },
            {
              "children": [],
              "hasChildren": false,
              "is_admin": 1,
              "menuid": 17,
              "name": "企业设置",
              "parentid": 1,
              "sort": 2,
              "state": "",
              "is_checked": true
            },
            {
              "children": [],
              "hasChildren": false,
              "is_admin": 1,
              "menuid": 26,
              "name": "员工管理",
              "parentid": 1,
              "sort": 1,
              "state": "",
              "is_checked": false
            }
          ],
          "hasChildren": true,
          "is_admin": 1,
          "menuid": 1,
          "name": "企业",
          "parentid": 0,
          "sort": 20,
          "state": "closed",
          "is_checked": true
        },
        {
          "children": [
            {
              "children": [],
              "hasChildren": false,
              "is_admin": 1,
              "menuid": 12,
              "name": "供应商订单",
              "parentid": 4,
              "sort": 10,
              "state": "",
              "is_checked": true
            },
            {
              "children": [],
              "hasChildren": false,
              "is_admin": 1,
              "menuid": 15,
              "name": "供应商管理",
              "parentid": 4,
              "sort": 20,
              "state": "",
              "is_checked": false
            },
            {
              "children": [],
              "hasChildren": false,
              "is_admin": 1,
              "menuid": 16,
              "name": "成为供应商",
              "parentid": 4,
              "sort": 30,
              "state": "",
              "is_checked": true
            }
          ],
          "hasChildren": true,
          "is_admin": 1,
          "menuid": 4,
          "name": "供应商",
          "parentid": 0,
          "sort": 11,
          "state": "closed",
          "is_checked": true
        }
      ],
    }
  }

  /*-----------------   方法集  ------------------*/
  //重置
  reset = () => {
    this.setState({
      province: undefined,
      city: undefined,
      district: undefined,
      street: undefined,
      status: undefined,
      name: '',
    },() => {
      this.getDevice();
    });
  };
  //模态框相关
  showModal = () => {
    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]=="4"){
          if(this.state.delData==null||this.state.delData.length<=0){
            alert("未选中删除项！");
            return;
          }
          flag = 1;
          this.setState({
            visible: true,
          });
        }
      }
    }else{
    //alert("找不到用户权限记录！");
      //return;;
    }
    if(flag == 0){
      alert("缺少设备删除权限！");
    }
  };
  handleOk = () => {
    this.del();
    this.setState({
      visible: false,
    });
  };
  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };
  //获取所有设备
  getDevice = () => {
    const params = {
      // address: (this.state.province == undefined ? '' : this.state.province.label) +
      //   (this.state.city == undefined ? '' : '-' + this.state.city.label) +
      //   (this.state.district == undefined ? '' : '-' + this.state.district.label) +
      //   (this.state.street == undefined ? '' : '-' + this.state.street.label),
      name: this.state.name,
      model: this.state.model,
      status: this.state.status,
      id: this.props.currentUser.userid,
      userPhone:"18813787835"
    };
    this.props.dispatch({
      type: 'orderManagementModel/getOrder',
      payload: params,
      callback: (res) => {
        if (res) {

          /*this.setState({
            data: res.rows,
            total: res.total,
          })*/
          if(res.error_code == "0000"){
            this.setState({
              data: res.data.rows,
              total: res.data.total,
            })
          }

          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("Tos查询出错！未知错误！");
          //   }
        }
      }
    });
  };
  //跳转到编辑页面
  edit = (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]=="3"){
            flag = 1;
            this.props.dispatch(routerRedux.push({
              pathname: 'tosUser/create',
              query: params,
            }))
          }
        }
      }else{
        for(let i=0;i<nowUser.permission.length;i++){
          if(nowUser.permission[i]=="2"){
            flag = 1;
            this.props.dispatch(routerRedux.push({
              pathname: '/tosUser/edit',
              query: params,
            }))
          }
        }
      }
    }else{
    //alert("找不到用户权限记录！");
      //return;;
    }
    if(flag == 0){
      if(params==null){
        alert("缺少设备添加权限！");
      }else{
        alert("缺少设备修改权限！");
      }
    }
  };

  //跳转到编辑页面
  edit2 = (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]=="3"){
            flag = 1;
            this.props.dispatch(routerRedux.push({
              pathname: 'tosUser/edit',
              query: params,
            }))
          }
        }
      }else{
        for(let i=0;i<nowUser.permission.length;i++){
          if(nowUser.permission[i]=="2"){
            flag = 1;
            this.props.dispatch(routerRedux.push({
              pathname: '/tosUser/edit',
              query: params,
            }))
          }
        }
      }
    }else{
    //alert("找不到用户权限记录！");
      //return;;
    }
    if(flag == 0){
      if(params==null){
        alert("缺少设备添加权限！");
      }else{
        alert("缺少设备修改权限！");
      }
    }
  };

  //跳转到详情页面
  details = (params) => {
    this.props.dispatch(routerRedux.push({
      pathname: '/orderManagement/Detail',
      query: params,
    }))
  };
  //设备状态变更
  statusChange = (e) => {
    this.setState({status: e == undefined ? undefined : e});
  };
  //设备名称和型号修改
  nameAndModelChange = (e) => {
    this.setState({name: e.target.value});
  };
  //加载省
  provinceload = (code) => {
    this.props.dispatch({
      type: 'deviceModel/getRegion',
      payload: {code: code,},
      callback: (res) => {
        if (res) {
          this.setState({
            provinceList: res.data,
          });
        }
      }
    });
  };
  //省变更
  provinceChange = (e) => {
    if (e == undefined) {
      this.setState({
        cityList: [{name: "未选择省"}],
        districtList: [{name: "未选择市"}],
        streetList: [{name: "未选择区"}],
        province: undefined,
        city: undefined,
        district: undefined,
        street: undefined,
      })
    } else {
      this.setState({province: {label: e.label,}});
      this.props.dispatch({
        type: 'deviceModel/getRegion',
        payload: {code: e.key,},
        callback: (res) => {
          if (res) {
            this.setState({
              cityList: res.data,
              city: undefined,
              district: undefined,
              street: undefined,
            });
          }
        }
      });
    }
  };
  //市变更
  cityChange = (e) => {
    if (e == undefined) {
      this.setState({
        districtList: [{name: "未选择市"}],
        streetList: [{name: "未选择区"}],
        city: undefined,
        district: undefined,
        street: undefined,
      })
    } else {
      this.setState({city: {label: e.label,}});
      this.props.dispatch({
        type: 'deviceModel/getRegion',
        payload: {code: e.key,},
        callback: (res) => {
          if (res) {
            this.setState({
              districtList: res.data,
              district: undefined,
              street: undefined,
            });
          }
        }
      });
    }
  };
  //区变更
  districtChange = (e) => {
    if (e == undefined) {
      this.setState({
        streetList: [{name: "未选择区"}],
        district: undefined,
        street: undefined,
      })
    } else {
      this.setState({district: {label: e.label,}});
      this.props.dispatch({
        type: 'deviceModel/getRegion',
        payload: {code: e.key,},
        callback: (res) => {
          if (res) {
            this.setState({
              streetList: res.data,
              street: undefined,
            });
          }
        }
      });
    }
  };
  //批量删除
  del() {
    this.props.dispatch({
      type: 'deviceModel/delDevice',
      payload: this.state.delData,
      callback: (res) => {
        if (res) {
          if (res.error_code == "0000") {
            alert(res.error_msg);
            this.getDevice();
          } 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("删除失败！未知错误！");
          }
        }
      }
    });
  };
  //显示信息
  info() {
    const { used, newAdd, strList} = this.state;
    const strSelect = strList.map((item) => (
      <p>{item}</p>
    ));
    Modal.info({
      title: '批量导入结果',
      content: (
        <div>
          <p>绑定<span style={{color:"lightgreen",fontSize:24}}>{newAdd}</span>台设备，
            以下<span style={{color:"red",fontSize:24}}>{used}</span>台设备已被占用</p>
          {strSelect}
        </div>
      ),
      onOk() {},
    });
  }
  //初始化
  componentDidMount() {
    // this.provinceload(0);
    this.getDevice();
  }
  /*--------------------------------------*/
  //表格列名
  columns = [
    {
      title: 'Service Community',
      dataIndex: 'communityName',
      key: 'communityName',
    },
    {
      title: 'User Name',
      dataIndex: 'ownerName',
      key: 'ownerName',
    },
    {
      title: 'Service Type',
      dataIndex: 'serviceType',
      key: 'serviceType',
    },
    {
      title: 'Service Content',
      dataIndex: 'serviceContent',
      key: 'serviceContent',
    },
    {
      title: 'Order Time',
      dataIndex: 'orderSendTime',
      key: 'orderSendTime',
    },
    {
      title: 'Appointment',
      dataIndex: 'orderFinishTime',
      key: 'orderFinishTime',
    },
    {
      title: 'Status',
      dataIndex: 'orderStatus',
      key: 'orderStatus',
      render: (text, record) => (
        <span>{record.orderStatus == '0' ? "已发单": "待上门"}</span>
      ),



    },

    /*{
      title: '用户类型',
      dataIndex: 'deviceRegisterTime',
      key: 'deviceRegisterTime',
    },
    {
      title: '状态',
      dataIndex: 'deviceWorking',
      key: 'deviceWorking',
      render: (text, record) => (
        <span>{record.deviceWorking == '1' ? "正常" :
          (record.deviceWorking == '2' ? "离线" :
            (record.deviceWorking == '3' ? "故障" : "未激活"))}</span>
      )
    },*/
    {
      title: 'Actions',
      dataIndex: 'action',
      key: 'action',
      render: (text, record) => (
        <span>
          <Button style={{background: 'transparent', border: 0, color: '#1890FF'}}
                  onClick={() => this.details(record)}>Details</Button>
          {/*<Button style={{background: 'transparent', border: 0, color: '#1890FF'}}*/}
          {/*        onClick={() => this.edit(record)}>Edit</Button>*/}
        </span>
      ),
    },
  ];
  //行选择
  rowSelection = {
    onChange: (selectedRowKeys , selectedRows) => {
      this.setState({
        delData: selectedRows
      });
    },
  };
  //渲染
  render() {
    const {
      data, total, statusList, provinceList, cityList, districtList,
      province, city, district, status, name,newList,authorityList
    } = this.state;
    const uploadprops = {
      // 这里我们只接受excel2007以后版本的文件，accept就是指定文件选择框的文件类型
      accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      name: 'file',
      headers: {
        authorization: 'authorization-text',
      },
      showUploadList: false,
      // 把excel的处理放在beforeUpload事件，否则要把文件上传到通过action指定的地址去后台处理
      // 这里我们没有指定action地址，因为没有传到后台
      beforeUpload: (file, fileList) => {
        const rABS = true;
        const f = fileList[0];
        const reader = new FileReader();
        reader.onload = e => {
          let dataResult = e.target.result;
          if (!rABS) dataResult = new Uint8Array(dataResult);
          const workbook = XLSX.read(dataResult, {
            type: rABS ? 'binary' : 'array',
          });
          // 假设我们的数据在第一个标签
          const firstWorksheet = workbook.Sheets[workbook.SheetNames[0]];
          // XLSX自带了一个工具把导入的数据转成json
          const jsonArr = XLSX.utils.sheet_to_json(firstWorksheet, {header: 1});
          // 通过自定义的方法处理Json,得到Excel原始数据传给后端，后端统一处理
          const oldDeviceList = [];
          for (let i = 0; i < jsonArr.length; i++) {
            //去重
            if (!oldDeviceList.includes(jsonArr[i][0]) && jsonArr[i][0] != '' && jsonArr[i][0] != null && jsonArr[i][0] != undefined) {
              oldDeviceList.push(jsonArr[i][0]);
            }
          }
          this.props.dispatch({
            type: 'deviceModel/importUserDeviceListExcel',
            payload: {
              jsonArr: oldDeviceList,
              userID: this.props.currentUser.userid,
            },
            callback: (res) => {
              if (res) {
                this.setState({
                  used: res.data.used,
                  newAdd: res.data.integer,
                  strList: res.data.strList,
                },() => {
                  this.getDevice();
                  this.info();
                });
              }
            }
          });
        };
        if (rABS) reader.readAsBinaryString(f);
        else reader.readAsArrayBuffer(f);
        return false;
      },
    };
    /*  const statusSelect = statusList.map((item) => (
        <Select.Option value={item.value} label={item.label}>{item.label}</Select.Option>
      ));
      const provinceSelect = provinceList.map((item) => (
        <Select.Option value={item.code} label={item.name}>{item.name}</Select.Option>
      ));
      const citySelect = cityList.map((item) => (
        <Select.Option value={item.code} label={item.name}>{item.name}</Select.Option>
      ));
      const districtSelect = districtList.map((item) => (
        <Select.Option value={item.code} label={item.name}>{item.name}</Select.Option>
      ));*/
    return (
      <div className={styles.body}>
        <div className={styles.inputBox}>
          <Input className={styles.input}
                 placeholder="Community"
                 value={name}
                 onChange={(e) => this.nameAndModelChange(e)}/>
          <Input className={styles.input}
                 placeholder="Service Type"
                 value={name}
                 onChange={(e) => this.nameAndModelChange(e)}/>
          <Input className={styles.input}
                 placeholder="Order State"
                 value={name}
                 onChange={(e) => this.nameAndModelChange(e)}/>
          {/*<Select className={styles.input}*/}
          {/*        placeholder="设备状态"*/}
          {/*        onChange={(e) => this.statusChange(e)}*/}
          {/*        allowClear={true}*/}
          {/*        value={status != undefined ? status: undefined}>{statusSelect}</Select>*/}
          {/*<Select className={styles.downButton}*/}
          {/*        placeholder="省"*/}
          {/*        onChange={(e) => this.provinceChange(e)}*/}
          {/*        allowClear={true}*/}
          {/*        labelInValue={true}*/}
          {/*        value={province}>*/}
          {/*  {provinceSelect}*/}
          {/*</Select>*/}
          {/*<Select className={styles.downButton}*/}
          {/*        placeholder="市"*/}
          {/*        onChange={(e) => this.cityChange(e)}*/}
          {/*        allowClear={true}*/}
          {/*        labelInValue={true}*/}
          {/*        value={city}>*/}
          {/*  {citySelect}*/}
          {/*</Select>*/}
          {/*<Select className={styles.downButton}*/}
          {/*        placeholder="区"*/}
          {/*        onChange={(e) => this.districtChange(e)}*/}
          {/*        allowClear={true}*/}
          {/*        labelInValue={true}*/}
          {/*        value={district}>*/}
          {/*  {districtSelect}*/}
          {/*</Select>*/}

        </div>



        <div>
          <Button className={styles.button1} onClick={() => this.getDevice()}>Search</Button>
          <Button className={styles.button} onClick={() => this.reset()}>重置</Button>
          {/*<Button className={styles.button2} onClick={() => this.edit(null)}>Create New Owner</Button>*/}
          {/*<Upload {...uploadprops}>*/}
          {/*  <Tooltip title="">*/}
          {/*    <Button className={styles.button2}*/}
          {/*            style={{width: 150}}>*/}
          {/*      <Icon type="upload"/>Batch Upload*/}
          {/*    </Button>*/}
          {/*  </Tooltip>*/}
          {/*</Upload>*/}
        </div>
        <div>
          <Table
            rowKey={record => record.deviceID}
            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()}>Delete</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,
}))(OrderManagement);
