import {
  observable,
  action,
  computed,
} from 'mobx';
import * as Util from '../util/index';
import {WeaTableNew, WeaForm} from 'comsMobx'
const {TableStore} = WeaTableNew;
import {Modal,message} from 'antd'
const confirm = Modal.confirm;
import cloneDeep from 'lodash/cloneDeep';
import remove from 'lodash/remove';
import isEmpty from 'lodash/isEmpty'
import * as API from '../apis/addressbook';
import datas from './data';
import { toJS } from 'mobx';
import {i18n} from '../public/i18n';
import {
  WeaLocaleProvider,
  WeaTools
} from 'ecCom';
import {Button} from 'antd';
import HrmBaseStore from './baseStore';
import {has} from 'lodash';
const getLabel = WeaLocaleProvider.getLabel;
import HrmAddressBookPlus from './addressBookPlus';

export class HrmAddressBook extends HrmBaseStore{
  @observable hrmAddressBookPlus = new HrmAddressBookPlus(this);

  title = i18n.module.addressBook;
  @observable form = new WeaForm()
  @observable table = new TableStore();
  @observable dataKey = ''
  @observable tabs = []
  @observable tabkey = 'default_3'
  @observable showSearchAd = false
  @observable visible1 = false
  @observable visible2 = false
  @observable templeteValue = ''
  @observable conditioninfo = []
  @observable conditioninfoAll = []
  @observable showAllCondition = false

  @observable transferDatas = []
  @observable transferOptions = []
  @observable transferKeys = []
  @observable transferleftIptVal = ''
  @observable transferRightIptVal = ''
  @observable transferSelectedKey = '0'
  @observable showAllLevel = true;
  @observable rightMenus = []
  @observable defaultShowLeft = false;
  @observable searchFrom = '';
  @observable searchKeyWord = '';
  // @observable subcompanyid1 = '';
  // @observable departmentid = '';
  @observable virtualtype = '';
  @observable companysId = '1';

  searchParams;

  @action
  getRightMenuConfig = () => {
    API.getRightMenuConfig().then(data=>{
      if (data.status == '1') {
        this.rightMenus = data.rightMenus;
        this.defaultShowLeft = data.defaultShowLeft;
      } else {
        message.warning(data.message);
      }
    }, error=> {
        message.warning(error.message);
    })
  }

  changeShowAllLevel = () => {
    this.showAllLevel = !this.showAllLevel;
    if (this.tabkey !== 'default_2') {
      let params;
      if (this.nodeType === '1') {
        params = {
          subcompanyid1: this.subcompanyid1
        }
      }
      if (this.nodeType === '2') {
        params = {
          departmentid: this.departmentid
        }
      }
      this.getData(params);
    } else {
      this.getData();
    }
  }

  updateTransferleftIptVal = (v) => {
    this.transferleftIptVal = v;
  }

  updateTransferRightptVal = (v) => {
    this.transferRightIptVal = v;
  }

  updateTransferSelectedKey = (v) => {
    this.transferSelectedKey = v;
  }

  updateTransferKeys = (v) => {
    this.transferKeys = v;
  }

  updateShowAllCondition = (v) => {
    this.showAllCondition = v;
    this.form = new WeaForm();
    if(this.showAllCondition){
      this.form.initFormFields(this.conditioninfoAll);
    }else{
      this.form.initFormFields(this.conditioninfo);
    }
  }

  updateTempleteValue = (v) => {
    this.templeteValue = v;
  }

  updateVisible1 = (bool) => {
    this.visible1 = bool;
  }

  updateVisible2 = (bool) => {
    this.visible2 = bool;
  }

  updateTabkey = (key) => {
    this.tabkey = key;
    this.showAllLevel = false;
    this.searchFrom = '';
    this.searchKeyWord = '';
    this.getData();
  }

  saveTemplete = () => {
    let __this = this;
    let templeteValue = this.templeteValue ||'';
    if(templeteValue==''){
      message.error(i18n.message.requireFieldNone());
      return;
    }
    let params = this.form.getFormParams();
    params.opera = "insert";
    params.mouldname = templeteValue;
    API.saveHrmSearchCondition(params).then(data=>{
      if (data.status == '1') {
        let tabkey = data.id;
        __this.updateTabkey(tabkey);
        __this.updateVisible2(!this.visible2);
        __this.updateTempleteValue('');
        __this.updateShowSearchAd(false);
        message.success(i18n.message.saveSuccess());
      } else {
        message.error(data.message);
      }
    }, error=> {
        message.error(error.message);
    })
  }
  
  saveHrmSearchUserDefine = () => {
    let __this = this;
    let params = {};
    !isEmpty(toJS(this.transferKeys)) && toJS(this.transferKeys).forEach(c => {
      if(c.endsWith("select"))c=c.replace("select","");
      let paramName = "has"+c;
      params[paramName] = '1';
    });
    API.saveHrmSearchUserDefine(params).then(data=>{
      if (data.status == '1') {
        __this.updateVisible1(!this.visible1);
        __this.updateShowSearchAd(false);
        __this.getConditions();
        message.success(i18n.message.saveSuccess());
      } else {
        message.error(data.message);
      }
    }, error=> {
        message.error(error.message);
    })
  }

  getTabs = () => {
    let params = {};
    params.virtualtype = this.virtualtype;
    API.getHrmSearchMoudleList(params).then(data=>{
      if (data.status == '1') {
         this.tabs=data.tabs;
      } else {
          message.warning(data.message);
      }
    }, error=> {
        message.warning(error.message);
    })
  }

  deleteTabs = (params={}) => {
    let __this = this;
    confirm({
      title: i18n.confirm.systemhints(),
      content: i18n.confirm.remove(),
      onOk(){
        API.saveHrmSearchCondition(params).then(data=>{
          if (data.status == '1') {
            __this.updateTabkey('default_3');
            message.success(i18n.message.deleteSuccess());
          } else {
            message.warning(data.message);
          }
        }, error=> {
            message.warning(error.message);
        })
      },
      onCancel(){},
    });
  }

  formatTransfer= () => {
    const transferDatas = []
    const transferKeys = []
    const transferOptions = [
      {key: "",
      showname: ""}]
    this.transferSelectedKey = '0';
    this.transferleftIptVal = '';
    this.transferRightIptVal = '';
    !isEmpty(toJS(this.conditioninfoAll)) && toJS(this.conditioninfoAll).forEach((c, idx)=> {
      transferOptions.push({
        key: `${idx}`,
        showname: c.title,
      })
      c.items.forEach((i)=> {
        transferDatas.push({
          id: i.domkey[0],
          label: i.label,
          title: c.title,
          idx: `${idx}`
        })
      })
    })
    !isEmpty(toJS(this.conditioninfo)) && toJS(this.conditioninfo).forEach((c, idx)=> {
      c.items.forEach((i)=> {
        transferKeys.push(i.domkey[0]);
      })
    })
    this.transferDatas = transferDatas;
    this.transferKeys = transferKeys;
    this.transferOptions = transferOptions;
  }

  getConditions = (cb) => {
    let params = {};
    params.mouldid = this.tabkey||'default_3';
    this.form = new WeaForm();
    this.showAllCondition=false;
    API.getSearchCondition(params).then((data) => {
      this.conditioninfoAll = data.condition;
      this.conditioninfo = data.defaultcondition||[];
      if(isEmpty(this.conditioninfo)){
        let c = cloneDeep(data.condition)
        c[0].title = i18n.label.commonConditions();
        this.conditioninfo = [c[0]];
      }
      this.form.initFormFields(this.conditioninfo);
      if(this.searchFrom=='quickSearch'){
        this.tabkey = 'default_3';
        this.form.updateFields({
          resourcename:{name:'resourcename',value:this.searchKeyWord},
        });
      }
      this.showAllCondition = false;
      cb && cb();
    });
  }

  @action getSearchList = (params = {}) => {
	  const obj = {};
    let formParams = this.form.getFormParams();
    if(typeof(params) == 'string')
      params = {};
    params.tabkey = this.tabkey || 'default_3';
    params.showAllLevel = this.showAllLevel?'1':'0';
    params.virtualtype = this.virtualtype ? this.virtualtype : params.virtualtype;
    params = {...params,...formParams}
    this.searchParams = params;
    this.table = new TableStore();
  
    API.getSearchList(params).then(action(data => {
      if (!data.sessionkey) return;
      this.table.setSelectedRowKeys([]);
      this.table.getDatas(data.sessionkey,1);
      this.dataKey = data.sessionkey;

      this.hrmAddressBookPlus.setDataKey(data.sessionkey);
    }))
  }

  updateShowSearchAd = (bool) => {
    this.showSearchAd = bool;
  }

  exportExcel = async () => {
    if(window.setShare4ec){
      window.setShare4ec({mouldCode: 'HRM', itemCode: 'ADDRESSBOOK', encrypt: '1'}, this.exportFile);
    }else{
      this.exportFile({status: '1'});
    }
  }

  exportFile = (data = {}) => {
    if(data.status == '1'){
      this.table.exportAll('',i18n.module.addressBook(), {sharepassword: data.sharepassword});
      this.hrmAddressBookPlus.recordExport(this.table.count);
    }
  }

  subcompanyid1;
  departmentid;
  nodeType;
  doSearch = (params = {}) => {
    this.subcompanyid1 = params.subcompanyid1;
    this.departmentid = params.departmentid;
    this.table.tableUpdate({datas:[]});
    this.updateShowSearchAd(false);
    this.getSearchList(params);
  }

  reSearch = (params = {}) => {
    this.form.reset();
    this.updateShowSearchAd(true);
  }

  getData = (params = {}) => {
    this.table.tableUpdate({datas:[]});
    this.getTabs();
    this.getConditions(()=> {
      this.getSearchList(params);
    });
    // if(this.tabkey=='default_1'||this.tabkey=='default_2'||this.tabkey=='default_3'){
    //   this.getConditions();
    //   this.getSearchList();
    // }else{
    //   this.getConditions(()=> {
    //     this.getSearchList();
    //   });
    // }
  }

  //导出excel
  @observable spinning = false;
  @observable templates = [];
  @observable filterLeft = '';//left head searchKey
  @observable filterRight = '';//rightt head searchKey
  @observable _filterLeft = '';//left head searchKey
  @observable _filterRight = '';//rightt head searchKey
  selectedKeys = [];//transfer selectedKeys
  _selectedKeys = [];
  fields = [];//all column fields
  @observable realPath = {
    depRealPath: '0',
    subCompRealPath: '0'
  }
  @observable _realPath = {
    depRealPath: '0',
    subCompRealPath: '0'
  }
  @observable keyfield = '1';
  @observable _keyfield = '1';
  @observable refreshTransfer = new Date().getTime();
  @observable templateStore = new TableStore();
  @observable fieldSettingDialogParams = {
    key: new Date().getTime(),
    visible: false,
    moduleName: 'hrm',
    title: `${getLabel(17416,'导出')}${getLabel(261,'字段')}${getLabel(68,'设置')}`,
    onCancel: () => this.fieldSettingDialogParams.visible = false,
    style: {
        width: 720,
        height: 520
    },
    className: 'exportSetting',
  }
  @observable fieldSettingEditDialogParams = {
    key: new Date().getTime(),
    visible: false,
    moduleName: 'hrm',
    title: getLabel(508026,'导出字段设置'),
    onCancel: () => this.fieldSettingEditDialogParams.visible = false,
    style: {
        width: 720,
        height: 520
    },
    className: 'exportSetting',
  }
  @observable saveFormDialogParams = {
    key: new Date().getTime(),
    visible: false,
    moduleName: 'hrm',
    title: '存为模板',
    onCancel: () => this.saveFormDialogParams.visible = false,
    style: {
        width: 400,
        height: 80
    },
    className: 'formSetting',
  }
  @observable editDialogParams = {
    key: new Date().getTime(),
    visible: false,
    moduleName: 'hrm',
    title: getLabel(508020,'导出模板管理'),
    onCancel: () => {
      this.editDialogParams.visible = false;
      this.initExportSetting();
    },
    style: {
        width: 600,
        height: 520
    },
    className: 'edit',
  }
  @observable selectedTemplate = '0';
  selectedGroup = '0';
  _selectedGroup = '0';
  selectOptions = [{
    key: '0',
    selected: true,
    showname: '全部'
  }];
  getSaveTemplateForm = () => [{
    "title": "基本信息",
    "defaultshow": true,
    "items": [{
        "colSpan": 2,
        "conditionType": "INPUT",
        "detailtype": 1,
        "domkey": ["name"],
        "fieldcol": 12,
        "isQuickSearch": false,
        "label": getLabel('388384',"导出模板名称"),
        rules: "required|string",
        "labelcol": 6,
        "precision": 0,
        "viewAttr": 3,
        otherParams: {
            ...window.inputType
        }
    }]
  }]

  @action getDialogBtn = (type) => {
    let buttons = [], menus = [];
    if(type ==='form'){
      buttons = [
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7o7ph1@1`} type="primary" op="save" onClick={() => this.saveForm()}>{i18n.button.save()}</Button>,
      ]
    }
     if(type==='fieldSettingEdit'){
      buttons = [
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@dqxbp5@2`} type="primary" op="save" onClick={() => this.saveTemplate()}>{i18n.button.save()}</Button>,
      ]
    }
    if(type==='fieldSetting'){
      buttons = [
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pgk3yo@3`} type="primary" op="export" onClick={() => this.doExport()}>{getLabel('17416',"导出")}</Button>,
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@n6suxv@4`} type="primary" op="save" onClick={() => this.showSaveForm()}>{i18n.button.saveAsTemplate()}</Button>,
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@6opopf@5`} type="primary" op="setting" onClick={() => this.templateManager()}>{getLabel('17857',"模板管理")}</Button>
      ]
    }

		buttons.map((btn, index) => {
			const {
				props
			} = btn;
			menus.push({
				key: index.toString(),
				content: props.children,
				icon: <i className={this.menuIconCollection[props.op]}/>,
				onClick: props.onClick
			});
    })
    return {buttons, menus};
  }

  @action setSelectedKeys = (keys) => {
    this.selectedKeys = keys;
    this.refreshTransfer = new Date().getTime();
  }

  @action getDisplayColumns = () => {
    this.timer = setInterval(() => {
      const {columns} = this.toJS(this.table);
      if(columns.length > 0){
        clearInterval(this.timer);
        let keys = [];
        columns.map(c => {
          if(c.dataIndex != 'id' && c.dataIdex != 'randomFieldId' && c.display === 'true')
            keys.push(c.dataIndex);
        });
        this.realPath.depRealPath = '0';
        this.realPath.subCompRealPath = '0';
        this.keyfield = '1';
        this.setSelectedKeys(keys);
      }
    }, 100);
  }

  @action loadTemplateFields = (key) => {
    this.selectedTemplate = key;
    if(key === '-1'){
      this.setSelectedKeys([]);
      this.realPath.depRealPath = '0';
      this.realPath.subCompRealPath = '0';
      this.keyfield = '1';
    }else if(key === '0'){
      this.getDisplayColumns();
    }else if(this.templates && this.templates.length > 0){
      this.realPath.depRealPath = this.templates[this.selectedTemplate].depRealPath.toString();
      this.realPath.subCompRealPath = this.templates[this.selectedTemplate].subCompRealPath.toString();
      this.keyfield = this.templates[this.selectedTemplate].keyfield.toString();
      this.setSelectedKeys(this.templates[this.selectedTemplate].fields.split(','));
    }
  }

  @action onTransChange = (keys, datas) => {
    this.selectedKeys = keys;
  }

   @action _onTransChange = (keys, datas) => {
    this._selectedKeys = keys;
  }

  @action searchField = (t, left = true) => {
    if(left)
      this.filterLeft = t;
    else
      this.filterRight = t;
  }

  @action _searchField = (t, left = true) => {
    if(left)
      this._filterLeft = t;
    else
      this._filterRight = t;
  }


  @action clearState = () => {
    this.saveFormTitle = '';
    this.selectedKeys.length = 0;
    this.fields.length = 0;
    this.selectedGroup = '0';
    this.selectedTemplate = '0';
    this.filterLeft = '';
    this.filterRight = '';
    this.selectOptions.splice(1, this.selectOptions.length);
    this.selectOptions[0].showname = getLabel(82857, '全部');
  }

  @action initExportSetting = () => {
    this.spinning = true;
    this.clearState();
    API.initExportSetting().then(rs => {
			rs.map((data, index) => {
				if (data.status === '1') {
					switch (index) {
            case 0:
              data.conditions.map((group, idx) => {
                this.selectOptions.push({
                  key: (idx + 1).toString(),
                  selected: false,
                  showname: group.title
                });
                group.items.map(f => {
                  this.fields.push({
                    id: f.fieldname,
                    name: f.fieldlabel,
                    gName: group.title
                  })
                })
              })
							break;
            case 1:
              this.templates = data.items;
              this.getDisplayColumns();
							break;
					}
				}
			});
      this.spinning = false;
      this.fieldSettingDialogParams.visible = true;
		}, error => this.spinning = false)
  }

  @action setRealPath = (isDepartment, v) => {
    // if(isDepartment)
      this.realPath.depRealPath = v;
    // else
      this.realPath.subCompRealPath = v;
  }

  @action _setRealPath = (isDepartment, v) => {
    // if(isDepartment)
      this._realPath.depRealPath = v;
    // else
      this._realPath.subCompRealPath = v;
  }

  @action setKeyField = (v) => this.keyfield = v;

  @action _setKeyField = (v) => this._keyfield = v;

  @action setSelectedGroup = (v) => this.selectedGroup = v;

   @action _setSelectedGroup = (v) => this._selectedGroup = v;

  @action getSelectedGroup = (v) => this.selectOptions[this.selectedGroup];

  @action _getSelectedGroup = (v) => this.selectOptions[this._selectedGroup];

  @action getTransferData = () => this.fields;

  @action showSaveForm = (saveAs = false) => {
    if(this.spinning)
      return;
    if(this.selectedKeys.length === 0){
      message.error(getLabel('388383',"请选择导出字段"));
      return;
    }
    this.setFormData('saveForm', this.getSaveTemplateForm());
    if(this.formTarget.saveForm.isFormInit){
      this.saveFormDialogParams.visible = true;
      this.saveFormDialogParams.key = new Date().getTime();
    }
  }

  @action saveForm = () => {
    if(this.spinning)
      return;
    this.formTarget.saveForm.validateForm().then(f => {
			if (f.isValid) {
        this.saveFormDialogParams.visible = false;
        this.spinning = true;
        const formParams = this.formTarget.saveForm.getFormParams();
        const params = {
          ...formParams
        }
        let apiFuc;
        if(this.saveAsId != ''){
          Object.assign(params, {id: this.saveAsId});
          apiFuc = API.saveAs;
        }else{
          if (this.fieldSettingEditDialogParams.visible) {
Object.assign(params, {
            fields: this._selectedKeys.join(","),
            ...this._realPath,
            keyfield: this._keyfield
          });
          }else{

          Object.assign(params, {
            fields: this.selectedKeys.join(","),
            ...this.realPath,
            keyfield: this.keyfield
          });
          }
          apiFuc = API.saveTemplate;
        }

        apiFuc(params).then(data => {
          if(data.status === '1'){
            this.saveAsId = '';
            message.success(i18n.message.saveSuccess());
            if(this.editDialogParams.visible){
              this.loadTemplateTable();
              this.fieldSettingEditDialogParams.visible = false;
            }else{
              API.getTemplate().then(data => {
                if(data.status === '1'){
                  this.templates = data.items;
                  this.selectedTemplate = (this.templates.length - 1).toString();
                  this.realPath.depRealPath = this.templates[this.selectedTemplate].depRealPath.toString();
                  this.realPath.subCompRealPath = this.templates[this.selectedTemplate].subCompRealPath.toString();
                  this.keyfield = this.templates[this.selectedTemplate].keyfield.toString();;
                  this.setSelectedKeys(this.templates[this.selectedTemplate].fields.split(','));
                }
              })
            }
          }else{
            message.error(data.message);
          }
          this.spinning = false;
        }, error => {
          this.spinning = false;
          message.error(i18n.message.actionError())
        });
			} else {
				f.showErrors();
				this.showError = new Date().getTime();
			}
		})
  }

  @action templateManager = () => {
    if(this.spinning)
      return;
    this.loadTemplateTable(() => {
      this.editDialogParams.visible = true;
      // this.fieldSettingDialogParams.visible = false;
    });
  }

  @action loadTemplateTable = (callback, paramas) => {
    API.getTemplateTable(paramas).then(data => {
      if(data.status === "1"){
        this.templateStore = new TableStore();
        this.templateStore.getDatas(data.sessionkey);
        callback && callback();
      }
    })
  }

  @action doExport = () => {
    if(this.spinning)
      return;
      
    this.spinning = true;
    let params = {...this.searchParams};
    let arr = [];
    if(this.realPath.depRealPath === '1')
      arr.push('department');
    if(this.realPath.subCompRealPath === '1')
      arr.push('subcompany');
    params.needRealPath = arr.join(',');
    params.keyfield = this.keyfield;
    API.getSearchList(params).then((data) => {
      if(data.sessionkey != null || data.sessionkey != ''){
        let keys = cloneDeep(this.selectedKeys);
        let arr = [];
        // ['subcompanyid1', 'departmentid'].map(key => {
        //   if(this.selectedKeys.indexOf(key) > -1){
        //     arr.push(key);
        //     remove(keys, k => k === key);
        //   }
        // });
        arr = arr.concat(keys);
        let fields = arr.join(',');

        if(window.setShare4ec){
          window.setShare4ec({mouldCode: 'HRM', itemCode: 'ADDRESSBOOK', encrypt: '1'}, d => {
            if(d.status == '1'){
              this.hrmAddressBookPlus.recordExport(this.table.count);
              this.table.exportAll('',i18n.module.addressBook(), {dataKey: data.sessionkey, fields, sharepassword: d.sharepassword});
            }
          });
        }else{
          this.hrmAddressBookPlus.recordExport(this.table.count);
          this.table.exportAll('',i18n.module.addressBook(), {dataKey: data.sessionkey, fields});
        }
        
        // const downloadUrl='/api/ec/dev/table/export';
        // let formElement = document.createElement('form'); 
        // formElement.style.display = "display:none;"; 
        // formElement.method = 'post'; 
        // formElement.action = downloadUrl; 
        // let inputElement = document.createElement('input'); 
        // inputElement.type = 'hidden'; 
        // inputElement.name = "dataKey" ; 
        // inputElement.value = data.sessionkey; 
        // formElement.appendChild(inputElement);
        // inputElement = document.createElement('input'); 
        // inputElement.type = 'hidden'; 
        // inputElement.name = "fields" ; 
        // inputElement.value = fields; 
        // formElement.appendChild(inputElement); 
        // inputElement = document.createElement('input'); 
        // inputElement.type = 'hidden'; 
        // inputElement.name = "filename" ; 
        // inputElement.value = i18n.module.addressBook(); 
        // formElement.appendChild(inputElement); 
        // document.body.appendChild(formElement); 
        // formElement.submit(); 
        // document.body.removeChild(formElement);

      //   const p = {dataKey: data.sessionkey, fields};
      //   API.exportExcel(p).then(data => {
			// if(data.status && data.url != null && data.url.length > 0){
			// 	const [arrurl, arrdata] = data.url.split('?');
			// 	const [key, val] = arrdata.split('=');

			// 	WeaTools.downloadFile(arrurl, "GET",{[key]:val});
			// 	this.hrmAddressBookPlus.recordExport(this.table.count);
			// }else{

			// }
      //     this.spinning = false;
      //   }, error => {
      //     this.spinning = false;
      //     message.error(i18n.message.actionError())
      //   })
        this.spinning = false;
      }else{
        this.spinning = false;
        message.error(i18n.message.actionError());
      }
    }, error => {
      this.spinning = false;
      message.error(i18n.message.actionError())
    });
  }

  editTarget;
  @action editTemplate = (record) => {
    this.editTarget = record;
    if(record != null){
      this._selectedKeys = record.fields.split(',');
      this._realPath.depRealPath = record.deprealpath.toString();
      this._realPath.subCompRealPath = record.subcomprealpath.toString();
      this._keyfield = record.keyfield.toString();
    }else{
      this._selectedKeys = [];
      this._realPath.depRealPath = '0';
      this._realPath.subCompRealPath = '0';
      this._keyfield = '1';
    }
    this.fieldSettingEditDialogParams.key = new Date().getTime();
    this.fieldSettingEditDialogParams.visible = true;
  }

  @computed get showGroup(){
    return !this.editDialogParams.visible;
  }

  @computed get multiDelete(){
    return this.templateStore.selectedRowKeys.length === 0;
  }

  @action saveTemplate = () => {
    if(this.editTarget != null){
      if(this._selectedKeys.length === 0){
        message.error(getLabel('388383',"请选择导出字段"));
        return;
      }
      const params = {
        fields: this._selectedKeys.join(","),
        ...this._realPath,
        keyfield: this._keyfield,
        id: this.editTarget.id,
        name: this.editTarget.name
      }
      API.saveTemplate(params).then(data => {
        if(data.status === '1'){
          message.success(i18n.message.saveSuccess());
          this.loadTemplateTable();
          this.fieldSettingEditDialogParams.visible = false;
        }else{
          message.error(data.message);
        }
      }, error => message.error(i18n.message.actionError()));
    }else{
      this.showSaveForm();
    }
  }

  saveAsId = '';
  @action saveAs = (id) => {
    this.saveAsId = id;
    this.setFormData('saveForm', this.getSaveTemplateForm());
    if(this.formTarget.saveForm.isFormInit){
      this.saveFormDialogParams.visible = true;
      this.saveFormDialogParams.key = new Date().getTime();
    }
  }

  @action deleteTemplate = (params) => {
    let content;
    if(has(params, 'id')){
      content = i18n.confirm.delete();
    }else{
      content = i18n.confirm.batchDeleteConfirm();
      params = {id: this.templateStore.selectedRowKeys.join(',')}
    }
    this.confirmInfo({
      content,
      onOk: () => {
        API.deleteTemplate(params).then(data => {
          if(data.status === '1'){
            message.success(i18n.message.deleteSuccess());
            this.loadTemplateTable();
          }else{
            message.error(data.message);
          }
        }, error => message.error(i18n.message.actionError()));
      }
    });
  }
  selectVirtual(v) {
    this.virtualtype=v;
    this.companysId = v;
  }

  onTemplateSearchChange=(value)=>{
    this.loadTemplateTable('',{
      name:value
    });
  }
}