import {
  observable,
  action,
  computed
} from 'mobx';
import {
  WeaForm
} from 'comsMobx';

import * as API from '../apis/newImport';
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';
import {
  findIndex
} from 'lodash';
import {WeaLocaleProvider } from "ecCom";

const getLabel = WeaLocaleProvider.getLabel;

export class NewImportStore {

  @observable hasRight = '';
  @action getHasRight(){
    API.getHasRight().then(res => {
      if(res.code == 200) {
        this.hasRight = res.data.hasRight;
      }else {
        message.warning(res.msg);
      }
    },error => {
      message.warning(error.msg);
    })
  }
  
  /********************* cardConfig  *********************/


  @observable isMouseOver = false;
  @observable curIndex = '';
  @observable visible = false;

  @action setMouseStatus = (index, bool) => {
    this.curIndex = index;
    this.isMouseOver = bool;
  }



  /********************* stepDialog  *********************/

  steps = [
    { title: '设置导入字段'},
    { title: '获取导入模板' },
    { title: '导入结果' }
  ];
  @observable importType = '';
  @observable current = 0;
  @observable buttonTitle = '';
  @observable pvisable = false;


  /********************* stepContent  *********************/
  @observable data = [];
  @observable selectedKeys = [];
  selectData = [];

  @observable condition = [];
  @observable importParams = {}; //重复验证字段
  @observable operateType = 'add'; //导入类型
  @observable filelist = []; //文件信息
  @observable excelfile = ''; //文件id
  @observable templetName = "导入模板";
  @observable percent = 0;
  @observable failnum = 0; //失败数量
  @observable succnum = 0; //成功数量
  @observable importResultTip = ''; //导入结果提示
  @observable importResultStore = new TableStore();
  @observable importStatus = 'importing'; //导入状态
  @observable loading = true;
  @observable date = '';
  @observable keyField = 'workcode';
  @observable otherParams; //表单其它参数
  @observable pId = '';//导入记录

  interval

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

  @action("获取导入字段") getImportField() {
    this.loading = true;
    const params = {
      importType:this.importType
    }
    API.getImportFields(params).then(res => {
      if(res.code == 200) {
        this.data = res.data.data;
        this.selectedKeys = res.data.selectedKeys;
        res.data.data && this.selectedKeys.forEach(id => {
          const index = findIndex(res.data.data, { id });
          this.selectData.push(res.data.data[index])
        })
        this.loading = false;
      }else {
        message.warning(res.msg);
      }
    },error => {
      message.warning(error.msg);
    })
  }

  
  @action("获取导入表单")  getImportForm() {
    let columns = [];
    this.selectData.forEach(item => {
        columns.push(item.name)
    })
    
    
    const params = {
      importType: this.importType,
      columns:columns
    }
    API.getImportForm(params).then(res => {
      if (res.code == 200) {
        this.condition = res.data.condition;
        if (res.data.condition != null && Array.isArray(res.data.condition) && res.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(res.msg);
      }
    }, error => {
      message.warning(error.msg);
    })
  }

  @action("开始导入") startImport() {
    if(this.filelist.length == 0) {
      message.error(`${i18n.message.checkFile()}`)
      this.current = this.current - 1;
      return;
    }
    this.pvisable = true;
    //导入文件提交
    let params = {
      //keyField:this.keyField,
      importType:this.importType,
      operateType:this.operateType,
      excelfile:this.excelfile,
      ...this.importParams,
    }
    if (this.otherParams != null) {
      Object.assign(params, {
        otherParams: JSON.stringify(this.otherParams)
      })
    }
    this.doImport(params)
    this.interval = setInterval(() => this.getImportProcess(), 200);

  }

  @action("文件提交") doImport(params) {
    API.saveImport(params).then(res => {
      if(res.code == 200) {
        this.pId = res.data.pId;
      }else {
        clearInterval(this.interval);
        this.pvisable = false;
        message.error(`${i18n.message.checkFileContent()}`)
      }
    })
  }

  // @computed get pId() {
  //   return this.percent = 100;
  // }

  @action("获取导入进度") getImportProcess() {
    if(this.pId != '') {
      clearInterval(this.interval);
      this.percent = 100;
      const _this = this;
      setTimeout(function(){
        _this.pvisable = false;
        _this.getImportResult();
      },1000)
    }else {
      //调用导入进度api
      let max = 95;
      let min = this.percent;
      if(this.percent < max) {
        this.percent = Math.floor(Math.random() * (max - min)) + min;
      }
     
    }
  }

  @action("获取导入结果") getImportResult() {
    let params = {
      pId:this.pId
    }
    API.getImportResult(params).then((res) => {
      if (res.code == 200) {
        this.failnum = res.data.failnum;
        this.succnum = res.data.succnum;
        this.importStatus = res.data.importStatus;
        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(res.data.datas, 1);
        } else {
          let info = i18n.label.importResourceResultInfo1();
          info = info.replace('{rownum}', this.succnum);
          this.importResultTip = info;
        }
      } else {
        message.warning(res.msg);
      }
    }, error => {
      message.warning(error.msg);
    })
  }

  setSelectedKeys(keys) {
    this.selectedKeys = keys;
    this.date = new Date();
  }

  setSelectData(value){
    this.selectData = value;
  }

  @action("初始化弹框内容") init() {
    this.filelist = [];
    this.excelfile = '';
    this.visible = false;
    this.percent = 0;
    this.failnum = 0;
    this.succnum = 0;
    this.importResultTip = '';
    this.importResultStore = new TableStore();
    this.importStatus = 'importing';
    this.data = [];
    this.selectData = [];
    this.selectedKeys = [];
    this.condition = [];
    this.keyField = 'workcode';
    this.pId = '';
  }


}