import { observable, action, toJS } from 'mobx';
import { WeaTools } from 'ecCom';
import * as API from '../apis/card';
import isEmpty from 'lodash/isEmpty';
import {WeaForm} from 'comsMobx';
import cloneDeep from 'lodash/cloneDeep'
import { message } from 'antd';
import forEach from 'lodash/forEach';
import {i18n} from '../public/i18n';

export class HrmWork {
  loading = false;
  @observable hrmId = ''
  @observable conditions = []
  @observable tableInfo = []
  @observable tabInfo = []
  @observable isEditor = false
  @observable buttons = {}
  @observable loading = false
  @observable tabkey = '0'
  @observable form = new WeaForm();
  @observable date;
  workEditTables;

  @action
  edit = () => {
    this.isEditor = true;
    this.getData();
    this.getTabInfo();
    this.tabkey = '0';
  }

  save = () => {
    if(this.loading)
      return;
    this.loading = true;
    let pDatas = this.form.getFormParams();
    let flag = false;
    this.form.validateForm().then(f => {
      if (f.isValid) {
        if(this.workEditTables){
          const targetDatas = this.tableInfo[this.tabkey].tabinfo.datas,
           isPass = (targetDatas.length > 0) ? this.workEditTables.refs.edit.doRequiredCheck().pass : true

          if(isPass){
            this.tableInfo && this.tableInfo.forEach(t=>{
              t.tabinfo.datas = t.tabinfo.datas || [];
              pDatas[t.tabinfo.rownum] = t.tabinfo.datas.length;
              t.tabinfo && t.tabinfo.datas && t.tabinfo.datas.forEach((item, index) =>{
                  !isEmpty(item) && forEach(item, (value, key)=> {
                      pDatas[`${key}_${index}`] = value;
                  })
              })
            })
            API.editResource({...{operation:'editworkinfo', id: this.hrmId}, ...pDatas}).
            then(data=>{
              if (data.status == '1') {
                  message.success(i18n.message.saveSuccess());
                  this.init();
                  this.getData();
              } else {
                  message.warning(data.message);
              }
              this.loading = false;
            }, error=> {
                message.warning(error.message);
                this.loading = false;
            })
          }else{
            this.loading = false;
          }
        }else{
          API.editResource({...{operation:'editworkinfo', id: this.hrmId}, ...pDatas}).
          then(data=>{
            if (data.status == '1') {
                message.success(i18n.message.saveSuccess());
                this.init();
                this.getData();
            } else {
                message.warning(data.message);
            }
            this.loading = false;
          }, error=> {
              message.warning(error.message);
              this.loading = false;
          })
        }
      } else {
        f.showErrors();
        this.setDate(new Date());
        this.loading = false;
      }
    })
  }

  changeTab = (key) => {
    this.tabkey = key;
  }

  init = () => {
    this.tabkey = '0';
    this.isEditor = false;
    this.form = new WeaForm();
  }

  updateTableInfo = (data) => {
    this.tableInfo = data
  }

  updateTabkey = (key) => {
    this.tabkey = key;
  }

  calYear = (startdate) => {
    let value = 0.00;
    if(startdate){
      const beginTime = new Date(startdate).getTime();
      const endTime = new Date(this.getToday()).getTime();
      if(endTime>beginTime){
        value = ((endTime - beginTime)/(24*3600*1000*365.0)).toFixed(2);
      }
    }
    return value;
  }
  
  getToday = () => {
    let now = new Date(); //当前日期
    let nowYear = now.getFullYear(); //当前年
    let nowMonth = now.getMonth() ; //当前月
    let nowDay = now.getDate(); //当前日
    let today = this.formatDate(new Date(nowYear, nowMonth, nowDay));//今天
    return today;
  }

  formatDate = (date) => {
    var yy = date.getFullYear();
    var mm = date.getMonth()+1;
    var dd = date.getDate();
    return (yy+"-"+this.adjust(mm) + "-" + this.adjust(dd));
  }
  
  adjust = (num) => {
      if(num<10){
        return "0"+num;
      }else{
        return ""+num;
      }
  }

  getTabInfo = () => {
    this.tabInfo = [];
    this.tableInfo && this.tableInfo.forEach((c, idx)=>{
      if(!c.hide){
        this.tabInfo.push({
          key: `${idx}`,
          title: c.tabname,
        })
      }
    })
    if(!isEmpty(this.tabInfo)) this.tabkey = this.tabInfo[0].key;
  }

  getData = (params={}) => {
    this.loading = true;
    params.id=this.hrmId;
    params.viewAttr=this.isEditor?2:1;
    params.is_multilang_set=this.isEditor;
    params.operation = 'getResourceWorkView';
    API.getResourceCard(params).then((data) => {
      this.loading = false;
      this.form.initFormFields(data.result.conditions);
      this.conditions = data.result.conditions;
      this.tableInfo = this.handleTable(data.result.tables) ;
      this.getTabInfo(this.tabInfo);
      this.buttons = data.result.buttons;
      this.hrmId = data.result.id;
    })
  }

  handleTable = (datas) => {
    return datas && datas.map(data => {
      const {tabinfo:{columns}} = data;
      const length = columns.length;
     columns.map(c => {
      c.width = `${95/length}%`
     })
     return data
    })
  }

  setWorkEditTables = (ref) => {
    this.workEditTables = ref;
  }
  
  setDate = (date) => {
    this.date = date;
  } 
}