import { observable, action, computed } from "mobx";
import {WeaLocaleProvider, WeaError} from "ecCom";
import { WeaSwitch } from "comsMobx";
import HrmBaseStore from "../../hrmComsPublic/stores/baseStore";
import { message } from "antd";
import * as api from "../apis/upgrade";
import { i18n } from "../public/i18n";
import has from 'lodash/has';
const getLabel = WeaLocaleProvider.getLabel;


export class HrmUpgrade extends HrmBaseStore {
  /********************* unobservable list *********************/
  tabConfig = {
    tabs: [
      {
        color: "#000000",
        groupId: "g1",
        title: () => getLabel('505755','考勤升级设置'),
        viewCondition: "1"
      }
    ],
    keyParam: "viewCondition",
    activeTabKey: "1"
  };
  
  errRefs = {}

  timer;

  itemRender = {
    startdate: (field, textAreaProps, form, formParams) => {
      const { fieldMap } = form;
      return (
        <div className="itemCondition">
          <div>
            <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@mxluqd`} tipPosition='bottom'
                      ref={d => this.errRefs['startdate'] = d}
                      error={`"${fieldMap["startdate"].label}" ${i18n.message.dataEmpty()}`}>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@y3yr63`}
              fieldConfig={field}
              form={form}
              formParams={formParams}
            />
            </WeaError>
          </div>
          <div>
            <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@anj1mw`} tipPosition='bottom'
                      ref={d => this.errRefs['enddate'] = d}
                      error={`"${fieldMap["enddate"].label}" ${i18n.message.dataEmpty()}`}>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@cv69t7`}
              fieldConfig={fieldMap["enddate"]}
              form={form}
              formParams={formParams}
            />
            </WeaError>
          </div>
        </div>
      );
    },
    enddate: (field, textAreaProps, form, formParams) =>null
  }
  /********************* unobservable list *********************/

  /********************* dialog info setting *********************/

  /********************* dialog info setting *********************/

  /********************* observable list *********************/
  @observable spinning = false;
  @observable timeline = [];
  @observable selectedNode = {};
  @observable upgradeInfo = {};
  @observable upgradeResult = {};
  @observable viewType = 1;
  @observable refreshTime = new Date().getTime();
  @observable progress = 0;
  /********************* observable list *********************/

  /********************* computed list *********************/
  /********************* computed list *********************/

  /********************* action list *********************/
  @action clear = () => {
    this.viewType = 1;
    this.upgradeResult = {};
    this.spinning = false;
  }

  @action init = () => {
    this.containerInitFinished.init = true;
    this.clear();
    api.init().then(
      rs => {
        rs.map((data, index) => {
          if (data.status === "1") {
            switch (index) {
              case 0:
                this.timeline = data.tabs;
                this.selectedNode = data.tabs[0];
                break;
              case 1:
                this.upgradeInfo = data;
                this.initForm(data);
                break;
            }
          }
        });
      }
    ).catch(error => {});
  }

  @action itemClick = node => {
    if(this.spinning)
      return;
    this.selectedNode = node;
    this.goBack();
    api.getUpgradeInfo({type: node.key}).then(data => {
      if(data.status == '1')
        this.upgradeInfo = data;
        this.initForm(data);
    }, error => {});
  }

  @action initForm = data => {
    if(has(data, 'itemList')){
      let conditions = [{
        items: data.itemList
      }]
      this.setFormData("form", conditions);
    }else{
      this.formTarget = {};
    }
    this.refreshTime = new Date().getTime();
  }

  @action checkUpgrade = () => {
    if(this.spinning)
      return;
    this.spinning = true;
    // this.viewType = 2;

    const {form} = this.formTarget;
    if(form != null){
      form.validateForm().then(f => {
        if (f.isValid) {
          let formParams = form.getFormParams();
          let params = { ...formParams, type: this.selectedNode.key};
          this.doUpgrade(params);
        } else {
          f.showErrors();
          const fields = form.fieldMap;
          [...Object.keys(fields)].map(k => {
            const e = form.getError(fields[k]);
            if (e != null && e != "") {
              console && console.debug(e);
              this.errRefs[k] && this.errRefs[k].showError();
            }
          });
          this.showError = new Date().getTime();
          this.spinning = false;
        }
      });
    }else{
      this.doUpgrade({type: this.selectedNode.key});
    }
  }

  @action doUpgrade = async params => {
    this.spinning = false;
    this.showWeaLoadingGlobal(getLabel('505758','正在升级,请稍后...'));
    const data = await api.doUpgrade(params);
    if(data.status == '1'){
      this.viewType = 2;
    }else{
      message.error(data.message);
    }
    this.hideWeaLoadingGlobal();
  }

  // @action doUpgrade = params => {
  //   if(this.timer != null){
  //     clearInterval(this.timer);
  //     this.timer = null;
  //   }
  //   this.spinning = true;
  //   this.upgradeResult = {};
  //   this.progress = 0;
  //   api.doUpgrade(params).then(data => {
  //     if(data.status == '1'){
  //       this.upgradeResult = data;
  //       if(this.selectedNode.key == 'Upgrade12'){
  //         if(data.data > 0){
  //           this.timer = setInterval(() => {
  //             this.getUpgrade12Data();
  //           }, 10000);
  //         }else{
  //           this.spinning = false;
  //         }
  //       }else{
  //         this.spinning = false;
  //       }
  //       // this.upgradeResult.items = [{
  //       //   label: '生成班次',
  //       //   status: '1',
  //       //   results: [
  //       //     '班次09:00~18:00',
  //       //     '班次09:00~18:00',
  //       //     '班次09:00~18:00'
  //       //   ]
  //       // },{
  //       //   label: '生成考勤组',
  //       //   status: '1',
  //       //   results: [
  //       //     '考勤组1：每周一、二、三、四、五 班次: 09:00-18:00',
  //       //     '考勤组2：每周一、二、三、四、五 班次: 09:00-18:00',
  //       //     '考勤组3：每周一、二、三、四、五 班次: 09:00-18:00'
  //       //   ]
  //       // }]
  //     }else{
  //       message.error(data.message); 
  //       this.spinning = false;
  //     }
  //   }, error => {this.spinning = false});
  // }

  @action getUpgrade12Data = () => {
    const {form} = this.formTarget;
    let formParams = form.getFormParams();
    api.getUpgrade12Data(formParams).then(data => {
      if(data.status == '1'){
        if(data.data == 0){
          if(this.timer != null){
            clearInterval(this.timer);
            this.timer = null;
          }
          this.progress = 100;
          this.spinning = false;
        }else{
          this.progress = Math.round((this.upgradeResult.data - data.data) / this.upgradeResult.data * 100);
        }
      }
    }, error => this.spinning = false)
  }

  @action goBack = () => {
    this.viewType = 1;
  }
  /********************* action list *********************/
}

export const hrmUpgrade = new HrmUpgrade();