import {
  observable,
  action
} from 'mobx';
import {
  WeaForm
} from 'comsMobx';
import * as API from '../apis/importresource';
import * as Util from '../util/index';
import {
  validate,
  getFormParamValue
} from '../util'
import {
  message,
  Modal,
  Button
} from 'antd';
import {
  WeaTableNew
} from 'comsMobx'
import * as mobx from 'mobx';
import isEmpty from 'lodash/isEmpty';
import {
  has
} from 'lodash';
const toJS = mobx.toJS;
const {
  TableStore
} = WeaTableNew;
const confirm = Modal.confirm;
import {
  i18n
} from '../public/i18n';


export class HrmImportResource {
  @observable title = "人员导入";
  @observable templetName = "导入模板";
  titleResult = i18n.label.importResult;
  titleHistory = i18n.button.importHistoryQuery;
  titleImportLog = i18n.button.getImportLog;
  importResultColumns = [];
  index = 1;
  @observable scrollTarget;
  @observable visible = false;
  @observable visibleResult = false;
  @observable visibleHistory = false;
  @observable visibleImportLog = false;
  @observable condition = [];
  @observable single = false;
  @observable keyField = 'workcode';
  @observable importType = '';
  @observable operateType = 'add';
  @observable filelist = [];
  @observable excelfile = '';
  @observable searchCondition = [];
  @observable form = new WeaForm();
  @observable showSearchAd = false;
  @observable searchParamsAd = {};
  @observable importResultStore = new TableStore();
  @observable importHistoryStore = new TableStore();
  @observable importLogStore = new TableStore();
  @observable buttons = [];
  @observable importProcessLogDatas = [];
  @observable succnum = 0;
  @observable failnum = 0;
  @observable importResultTip = '';
  @observable importStatus = '';
  @observable pId = '';
  @observable ref;
  @observable errorInfo = '';
  @observable dialogKey = new Date().getTime();
  @observable otherParams;
  @observable showLoadingSpin = false;
  interval;
  importCallback;
  getTemplateUrl;
  @observable importParams = {};

  importResultColumns = [{
    "title": i18n.label.confirmInfo(),
    "width": "100%",
    "dataIndex": "message",
    render: (text, record, index) => {
      return <span style={{ color: '#FF0000' }}>{text}</span>
    }
  }];

  @action
  init() {
    this.condition = [];
    this.keyField = 'workcode';
    this.importType = '';
    this.operateType = 'add';
    this.filelist = [];
    this.excelfile = '';
    this.searchCondition = [];
    this.buttons = [];
    this.importProcessLogDatas = [];
    this.succnum = 0;
    this.failnum = 0;
    this.importResultTip = '';
    this.importStatus = '';
    this.pId = '';
    this.errorInfo = '';
    this.importParams = {};
  }

  @action setParam = (k, v) => {
    const p = toJS(this.importParams);
    Object.assign(p, {
      [k]: v
    });
    this.importParams = p;
  }

  getImportForm(params = {}) {
    this.showLoadingSpin = true;
    params.importType = this.importType;
    this.otherParams != null && Object.assign(params, {
      otherParams: JSON.stringify({ ...this.otherParams,
        type: this.operateType
      })
    })
    API.getImportForm(params).then(data => {
      if (data.status == '1') {
        this.condition = data.condition;
        if (data.condition != null && Array.isArray(data.condition) && data.condition.length > 0) {
          this.condition[0].items.map(item => {
            if (item.conditionType === 'SELECT' && item.domkey[0] === 'importType') {
              item.options.map(op => {
                if (op.selected)
                  this.operateType = op.key;
              })
            }
            item.domkey[0].indexOf('keyField') > -1 && this.setParam(item.domkey[0], item.value);
          })
        }
      } else {
        // message.warning(data.message);
      }

      this.showLoadingSpin = false;
    }, error => {
      message.warning(error.message);
      this.showLoadingSpin = false;
    })
  }

  saveImport = (params = {}) => {
    params.keyField = this.keyField;
    params.importType = this.importType;
    params.operateType = this.operateType;
    params.excelfile = this.excelfile || '';
    if (params.excelfile == '') {
      message.warning(i18n.message.selectImportTemplete());
      return;
    }
    if (this.otherParams != null) {
      Object.assign(params, {
        otherParams: JSON.stringify(this.otherParams)
      })
      has(this.otherParams, 'logSmallType') && Object.assign(params, {
        logSmallType: this.otherParams.logSmallType
      })
    }

    this.importResultColumns = [{
      "title": i18n.label.confirmInfo(),
      "width": "100%",
      "dataIndex": "message",
      render: (text, record, index) => {
        return <span style={{ color: '#FF0000' }}>{text}</span>
      }
    }];
    this.index = 1;
    this.importStatus = '';
    this.importProcessLogDatas = [];
    this.importStatus = 'importing';
    this.getImportProcess();
    this.doImport({...params, ...this.importParams, confirm: 0});
    this.dialogKey = new Date().getTime();
    this.visibleResult = true;
  }

  @action doImport = params => {
    API.saveImport(params).then(data => {
      if (data.status == '1') {
        if(data.message != null && data.message.trim().length > 0 && params.importType == 'matrix'){
          confirm({ 
            title: i18n.confirm.defaultTitle(),
            content: data.message,
            okText: i18n.button.ok(),
            cancelText: i18n.button.cancel(),
            onOk: () => {
              this.doImport({...params, confirm: 1})
            }
          });
        }else if (!isEmpty(data.errorInfo)) {
          this.importStatus = 'error';
          this.importResultTip = i18n.message.selectImportTempleteError();
          this.importResultColumns = [{
            "title": i18n.label.confirmInfo(),
            "width": "100%",
            "dataIndex": "message",
            render: (text, record, index) => {
              return <span style={{ color: '#FF0000' }}>{text}</span>
            }
          }];
          this.importProcessLogDatas = data.errorInfo;
        }else{
          this.importCallback && this.importCallback();
        }
      }else {
        this.importStatus = 'error';
        message.warning(data.message);
      }
    })
  }

  getImportProcess() {
    this.interval = setInterval(() => this.getImportProcessLog(), 2000);
  }

  getImportProcessLog(params = {}) {
    if (this.visibleResult == false || this.importStatus == 'over' || this.importStatus == 'error') {
      clearInterval(this.interval);
      return;
    }
    params.index = this.index;
    params.importType = this.importType;
    let textColor = "";
    this.importResultColumns = [{
      "title": i18n.label.row(),
      "width": "15%",
      "dataIndex": "rownum"
    }, {
      "title": i18n.label.status(),
      "width": "15%",
      "dataIndex": "status",
      render: (text, record, index) => {
        if (text == '1') {
          textColor = "#54D3A2";
        } else {
          textColor = "#FF0000";
        }
        return <span style={{ color: textColor}}>{text=='1'?i18n.label.success():i18n.label.fail()}</span>
      }
    }, {
      "title": i18n.label.confirmInfo(),
      "width": "70%",
      "dataIndex": "message",
      render: (text, record, index) => {
        return <span style={{ color: textColor }}>{text}</span>
      }
    }];
    API.getImportProcessLog(params).then((data) => {
      if (data.status == '1') {
        if (!isEmpty(this.importProcessLogDatas)) {
          this.importProcessLogDatas = [...this.importProcessLogDatas, ...data.datas]
        } else {
          this.importProcessLogDatas = data.datas;
        }
        this.index = data.index;
        if (data.pId) {
          this.pId = data.pId;
        }

        const {importStatus} = data;
        if(['over', 'error'].indexOf(importStatus) > -1)
          this.importStatus = importStatus;
        //this.scrollTarget.scrollToLast();
        if (data.importStatus == 'over') {
          this.getImportResult({
            pId: this.pId
          });
          clearInterval(this.interval);
        }
      } else {
        message.warning(data.message);
      }
    }, error => {
      message.warning(error.message);
    })
  }

  setScrollTarget(scroll) {
    this.scrollTarget = scroll;
  }

  getImportResult(params = {}) {
    this.importStatus = 'over';
    if (params.pId) {
      this.pId = params.pId;
    }
    API.getImportResult(params).then((data) => {
      if (data.status == '1') {
        this.failnum = data.datas.failnum;
        this.succnum = data.datas.succnum;
        if (this.failnum > 0) {
          let info = i18n.label.importResourceResultInfo();
          info = info.replace('{rownum}', this.succnum + this.failnum).replace('{succnum}', this.succnum);
          this.importResultTip = info;
          this.importResultStore.getDatas(data.datas.sessionkey, 1);
        } else {
          let info = i18n.label.importResourceResultInfo1();
          info = info.replace('{rownum}', this.succnum);
          this.importResultTip = info;
        }
      } else {
        message.warning(data.message);
      }
    }, error => {
      message.warning(error.message);
    })
  }

  getImportHistory(params = {}) {
    params.importType = this.importType;
    this.otherParams != null && has(this.otherParams, 'logSmallType') && Object.assign(params, {
      logSmallType: this.otherParams.logSmallType
    })
    API.getImportHistory(params).then((data) => {
      if (data.status == '1') {
        data.sessionkey && this.importHistoryStore.getDatas(data.sessionkey, 1);
      } else {
        message.warning(data.message);
      }
    }, error => {
      message.warning(error.message);
    })
  }

  getImportLogDetail(params = {}) {
    if (this.pId) params.pId = this.pId;
    params.importType = this.importType;
    API.getImportLogDetail(params).then((data) => {
      if (data.status == '1') {
        data.sessionkey && this.importLogStore.getDatas(data.sessionkey, 1);
      } else {
        message.warning(data.message);
      }
    }, error => {
      message.warning(error.message);
    })
  }

  getImportLogSearchCondition(params = {}) {
    if (this.pId) params.pId = this.pId;
    this.form.updateIsFormInit(false);
    this.form = new WeaForm();
    API.getImportLogSearchCondition(params).then((data) => {
      if (data.status == '1') {
        this.searchCondition = data.searchCondition;
        this.form.initFormFields(data.searchCondition);
      } else {
        message.warning(data.message);
      }
    }, error => {
      message.warning(error.message);
    })
  }


  doSearch(params = {}) {
    let formParams = this.form.getFormParams();
    this.getImportLogDetail(formParams);
  }
}