import React, { PureComponent } from 'react';
import { Icon } from 'antd';

import DashboardIndexAdmin from './admin';
import DashboardIndexMember from './member';


class DashboardIndex extends PureComponent { // eslint-disable-line react/prefer-stateless-function
  static defaultProps = {
    namespace: 'dashboard_index',
  };

  // static propTypes = {
  //   dingtalk_config: React.PropTypes.object.isRequired,
  //   upgrade_image: React.PropTypes.string.isRequired,
  //   android_upgrade_image: React.PropTypes.string.isRequired,
  //   org_id: React.PropTypes.number.isRequired,
  // };

  state = {
    dingtalk_config: this.props.dingtalk_config,
    upgrade_image: this.props.upgrade_image,
    android_upgrade_image: this.props.android_upgrade_image,
    org_id: this.props.org_id,
    current_buttons: [], //当前按钮
    actionSheetVisible: true, //ActionSheet 是否可见
    statistic: {},
    documents: [],
    approvingDocuments: [],
    approvedDocuments: [],
    noapprovalDocuments: [],
    titles: [],
    activeTab: 'approving',
    hasPermission: true,
    loading: true,
    logined: true,
    is_admin: false,
    icons:{
      purchase: 'assets/images/symbols.svg#purchase',
      sale: 'assets/images/symbols.svg#sale',
      other: 'assets/images/symbols.svg#other',
      document: 'assets/images/symbols.svg#document',
      inventory: 'assets/images/symbols.svg#inventory',
      customer: 'assets/images/symbols.svg#customer',
      supplier: 'assets/images/symbols.svg#supplier',
      product: 'assets/images/symbols.svg#purchase'
    },
    new_buttons: [],
    purchase_buttons: [],
    sale_buttons: [],
    search_buttons: [],
    other_buttons: [],
  };

  constructor(props, context) {
    super(props, context);
    // const store = IKDataStore.namespace(this.props.namespace);
    // this.setState({
    //   logined: store.get('logined') || this.props.logined,
    //   is_admin: store.get('is_admin') || this.props.is_admin || false,
    //   icons: store.get('icons') || this.props.icons || [],
    //   new_buttons: store.get('new_buttons')||  this.props.new_buttons || [], //新增按钮
    //   purchase_buttons: store.get('purchase_buttons') || this.props.purchase_buttons || [], //采购列表按钮
    //   sale_buttons: store.get('sale_buttons') || this.props.sale_buttons || [], //销售列表按钮
    //   search_buttons: store.get('search_buttons') || this.props.search_buttons || [], //搜索按钮
    //   other_buttons: store.get('other_buttons') ||  this.props.other_buttons || [], //其他列表按钮
    // });
  }

  openActionsheet(type) {
    switch(type) {
      case 'inventory':
        Turbolinks.visit('/mobile/inventories');
        break;
      case 'purchase':
      case 'sale':
      case 'other':
      case 'new':
        this.setState({
          current_buttons: this.state[`${type}_buttons`],
          actionSheetVisible: true
        });
        break;
      default:
        Turbolinks.visit(`/mobile/${type}s`)
        break;
    }
  }

  actionSheetHidden() {
    this.setState({
      actionSheetVisible: false
    });
  }

  toggleTab(type) {
    this.setState({activeTab: type});
  }

  initialData(searched = false, callback) {
    this.setState({loading: true});

    if (getCurrentMember().token) {
      if (this.state.is_admin) {
        $.getJSON('/api/dashboard/statistic', (response) => {
          globalHandleResponse(response, ()=> {
            this.setState({statistic: response.statistic});
          });
        });

        $.getJSON('/api/documents', { approving: true }, (response) => {
          globalHandleResponse(response, () => {
            let title = []
            if (response.has_enabled) {
              title = [{title: '待审批', type: 'approving'}, {title: '已审批', type: 'approved'}]
            }

            if (response.has_disabled) {
              title.push({title: '无需审批', type: 'noapproval'});
            }

            this.setState({
              approvingDocuments: response.approving_documents,
              approvedDocuments: response.approved_documents,
              noapprovalDocuments: response.noapproval_documents,
              titles: title,
              loading: false,
            });

            if (title.length == 1) {
              this.setState({activeTab: 'noapproval'});
            }
          });
        });
      } else {
        $.getJSON('/api/documents', (response) => {
          if (response.status.code == 403 ) {
            this.setState( {
              hasPermission: false,
              loading: false,
            });
            return;
          }

          globalHandleResponse(response, ()=> {
            this.setState({
              documents: response.documents,
              loading: false,
            });
          });
        });
      }
    }

    if (callback) {
      callback.call(null);
    }
  }

  // componentDidMount() {
  //   if (!Cookies.get('checked_latest_notice')) {
  //     $.getJSON('/api/upgrades/get_latest', (response) => {
  //       if (response.status.code == 200) {
  //         Cookies.set('checked_latest_notice', 'checked');

  //         this.upgrade = response.upgrade;
  //         this.upgradeIDKey = 'upgradeID';
  //         this.upgradeID = localStorage.getItem(this.upgradeIDKey);
  //         this.upgradeID = this.upgradeID ? this.upgradeID : 0;

  //         if (this.upgrade.id > this.upgradeID) {
  //           localStorage.setItem(this.upgradeIDKey, `${this.upgrade.id}`);

  //           dd.ready(() => {
  //             let imagePath = this.props.upgrade_image;
  //             if ( Env.isAndroid() ) {
  //               imagePath = this.props.android_upgrade_image;
  //             }
  //             imagePath = `${window.location.protocol}//${window.location.host}${imagePath}`;

  //             dd.device.notification.modal({
  //               image: imagePath,
  //               title: this.upgrade.title,
  //               content: this.upgrade.intro,
  //               buttonLabels: ['查看详情', '知道了'],
  //               onSuccess: (result) => {
  //                 if (result.buttonIndex == 0) {
  //                   Turbolinks.visit(`/mobile/help/upgrades/${upgrade.id}`);
  //                 }
  //               }
  //             });

  //           });
  //         }
  //       }
  //     });
  //   }

  //   if (!getCurrentMember().token && this.state.dingtalk_config) {
  //     let config = this.state.dingtalk_config;
  //     let jsApiList = [
  //       'runtime.info',
  //       'runtime.permission.requestAuthCode',
  //       'device.base.getUUID',
  //       'device.base.getInterface',
  //       'device.launcher.checkInstalledApps',
  //       'device.launcher.launchApp',
  //       'device.connection.getNetworkType',
  //       'device.notification.alert',
  //       'device.notification.confirm',
  //       'device.geolocation.get',
  //       'device.accelerometer.watchShake',
  //       'device.accelerometer.clearShake',
  //       'biz.util.open',
  //       'biz.util.share',
  //       'biz.util.ut',
  //       'biz.util.uploadImage',
  //       'biz.util.uploadImageFromCamera',
  //       'biz.util.previewImage',
  //       'biz.chat.pickConversation',
  //       'biz.ding.post',
  //       'biz.telephone.call',
  //       'biz.util.scan',
  //       'biz.contact.choose',
  //       'biz.contact.complexChoose',
  //       'biz.contact.createGroup',
  //       'biz.navigation.setLeft',
  //       'biz.navigation.setRight',
  //       'biz.navigation.setTitle',
  //       'biz.navigation.close',
  //       'biz.navigation.setIcon',
  //       'biz.util.openLink',
  //     ]
  //     const configParams = {
  //       agentId: config.agent_id,
  //       corpId: config.corp_id,
  //       ticket: config.ticket,
  //       timeStamp: config.timestamp,
  //       nonceStr: config.noncestr,
  //       signature: config.signature,
  //       jsApiList: jsApiList,
  //     };

  //     dd.ready(() => {
  //       dd.config(configParams);
  //       dd.runtime.permission.requestAuthCode({
  //         corpId: config.corp_id,
  //         onSuccess: (requestAuthCodeResult) => {
  //           $.ajax({
  //             type: 'POST',
  //             url: '/api/dingtalk/login',
  //             data: {
  //               suite_id: config.suite_id,
  //               app_id: config.app_id,
  //               corp_id: config.corp_id,
  //               code: requestAuthCodeResult.code,
  //             },
  //             dataType: 'json',
  //           }).done((response) => {
  //             if (response.errcode == 0) {
  //               data = response.data

  //               if (data.member_status) {
  //                 Turbolinks.visit(`/mobile/disabled?authentication_token=${data.token}&uid=${data.uid}`, action: 'replace');
  //                 return
  //               }

  //               setCurrentMember(data.token, data.uid)

  //               if (!isVipNocticeShown(data.org_id)) {
  //                 showVipNotice(data.org_id)
  //               }

  //               const state = {
  //                 logined: true,
  //                 dingtalk_config: null,
  //                 is_admin: data.is_admin,
  //                 icons: data.icons,
  //                 new_buttons: data.new_buttons,
  //                 purchase_buttons: data.purchase_buttons,
  //                 sale_buttons: data.sale_buttons,
  //                 search_buttons: data.search_buttons,
  //                 other_buttons: data.other_buttons,
  //               };

  //               IKDataStore.namespace(this.props.namespace).set(state);
  //               this.setState(state, () => {
  //                 this.initialData();
  //               });
  //             } else {
  //               console.log(JSON.stringify(response));
  //             }
  //           }).fail((xhr, textStatus, errorThrown) => {
  //             console.log(`dingtalk login error: ${textStatus}, ${errorThrown}`);
  //           });
  //         },
  //         onFail: (error) => {}
  //       });
  //     });

  //     dd.error((error) => {
  //       console.log(error);
  //     });
  //   }

  //   this.initialData();
  //   enableRefresh(this.initialData);

  //   dd.ready(() => {
  //     dd.biz.navigation.setRight({
  //       show: true,
  //       control: true,
  //       text: '帮助',
  //       onSuccess: () => {
  //         Turbolinks.visit('/mobile/help/')
  //       },
  //       onFail: () => {
  //         Turbolinks.visit('/mobile')
  //       },
  //     });
  //   });

  //   if (this.state.logined && !isVipNocticeShown(this.state.org_id)) {
  //     showVipNotice(this.state.org_id);
  //   }

  // }

  renderMember() {
    return (<DashboardIndexMember
      current_buttons = {this.state.current_buttons}
      actionSheetVisible = {this.state.actionSheetVisible}
      actionSheetHidden = {this.actionSheetHidden}
      handleSearch = {this.initialData}

      onClick = {this.openActionsheet}
      documents = {this.state.documents}
      hasPermission = {this.state.hasPermission}
      icons = {this.state.icons}
      loading = {this.state.loading}
      logined = {this.state.logined} />);
  }

  renderAdmin() {
    return (<DashboardIndexAdmin
      current_buttons = {this.state.current_buttons}
      actionSheetVisible = {this.state.actionSheetVisible}
      actionSheetHidden= {this.actionSheetHidden}
      openActionsheet = {this.openActionsheet}
      handleSearch = {this.initialData}

      toggleTab = {this.toggleTab}
      activeTab = {this.state.activeTab}
      titles = {this.state.titles}
      approvingDocuments = {this.state.approvingDocuments}
      approvedDocuments = {this.state.approvedDocuments}
      noapprovalDocuments = {this.state.noapprovalDocuments}
      statistic = {this.state.statistic}
      hasPermission = {this.state.hasPermission}
      icons = {this.state.icons}
      loading = {this.state.loading}/>);
  }

  render() {
    if (!this.state.logined && this.state.dingtalk_config) {
      return (<Icon type='loading' />);
    } else {
      if (this.state.is_admin) {
        return this.renderAdmin();
      } else {
        return this.renderMember();
      }
    }
  }
}

export default DashboardIndex;
