import { observable, action, toJS } from "mobx";
import { WeaTableNew, WeaForm, WeaLogView } from "comsMobx";
import { doFormReset } from "../util/index.js";
import API from "../apis/dataSource.js";
import {
  checkHasOrganization, 
  isCallBackFunction,
  getSearchFormHeight,
  setModal,
} from "../util/IntegrationUtil";
import {
  message,
} from "antd";
import {
  WeaLocaleProvider,
} from "ecCom";

const {getLabel} = WeaLocaleProvider;
const { TableStore } = WeaTableNew;
const {LogStore} = WeaLogView;

export default class DataSource {
  @observable hasRight=false;
  @observable rightLoading= true;
  @observable hasManageDetachableRight = false;
  @observable dropMenuDatas = [];
  @observable ifShowSearchAd = false;
  @observable logStore = new LogStore();
  @observable source = "";
  @observable
  searchAdvance = {
    // 高级搜索的表单
    form: new WeaForm(),
    show: false,
    conditions: [],
    advanceHeight: 72,
  };

  @observable isclusterAttr = 2;
  @observable hasOrganization = false;
  @observable subcompanyid = "";
  @observable
  tab = {
    selectedKey: 0
  };

  @observable
  rightmenus = {
    dataSource: [],
    dataSourceType: []
  }

  @observable dataSourceTable = new TableStore();

  @observable
  dataSourceCreateAndEdit = {
    isEdit: false,
    show: false,
    form: new WeaForm(),
    conditions: [],
    editId: -1,
  };


  @observable
  dataSourceType = {
    table: new TableStore(),
    isEdit: false,
    show: false,
    form: new WeaForm(),
    conditions: [],
    editId: -1,
  };

  @observable loading = false;
  @observable logView = false;
  operateIndex = '';

  setOperateIndex = (val) => {
    this.operateIndex = val;
  }

  init = () => {
    this.rightLoading = true;
    this.hasOrganization = false;
    this.subcompanyid = "";
    this.searchAdvance.form = new WeaForm();
    this.searchAdvance.conditions = [];
    checkHasOrganization((result) => {
      this.hasOrganization = result;
    });
    this.datasourceAPI().getListConditions(() => {
      this.getList();
      this.datasourceAPI().getListRightMenus();
    });
  };

  getList = (isOnChange = false) => {
    let formParams = this.searchAdvance.form && this.searchAdvance.form.getFormParams() || {};
    let typename = this.source ? {typename: this.source} : {};
    let params = Object.assign({}, formParams, typename, {subcompanyid: this.subcompanyid});
    if (this.tab.selectedKey === 0) {
      this.dataSourceTable = new TableStore();
      API.datasource.getList(params).then(res => {
        if(res.ret&&res.ret=="noright"){
          this.hasManageDetachableRight=false;
        }else{
          this.hasManageDetachableRight=true;
        }
        this.rightLoading = false;
        if (res.datas) {
          this.dataSourceTable.getDatas(res.datas, 1);
        }
      });
    } else {
      this.hasManageDetachableRight=true;
      this.getTableList(isOnChange);
    }
  };

  // 联动处理
  @action getIsCluster = (params={}, flag) => {
    this.loading = true;
    API.datasource.getIsCluster(params).then(result => {
      this.isclusterAttr = result.isSelectCluster;
      this.loading = false;
      if(!flag) {
        result.isSelectCluster != '1' && this.dataSourceCreateAndEdit.form.updateFields({iscluster: '0'});
      }
    })
  }

  getTableList = (isOnChange = false) => {
    this.dataSourceType.table = new TableStore();
    API.datasourcetype.getList().then(res => {
      if (res.datas) {
        this.dataSourceType.table.getDatas(res.datas, 1);
      }
    });
  }

  getForm = (params={}, cb=null) => {
    if (params === undefined) {
      // init
      this.getFormDataSource({isEdit: "0"});
      this.getFormDataSourceType({isEdit: "0"});
      this.datasourceAPI().getFormRightMenus({isEdit: "0"});
      this.datasourcetypeAPI().getFormRightMenus({isEdit: "0"});
    } else {
      if (this.tab.selectedKey === 0) {
        this.getFormDataSource(params, cb);
        this.datasourceAPI().getFormRightMenus(params);
      } else {
        this.getFormDataSourceType(params, cb);
        this.datasourcetypeAPI().getFormRightMenus(params);
      }
    }
  };

  getFormDataSource = (params={}, cb=null) => {
    this.hiddenFields = [];
    this.loading = true;
    this.dataSourceCreateAndEdit.form = new WeaForm();

    if(params.isEdit == "0") {
      // 在选择分权的情况下新建
      this.dataSourceCreateAndEdit.editId = '';
      params = {subcompanyid: this.subcompanyid};
    }
    API.datasource.getForm(params).then(res => {
      if (res.condition) {
        // iscluster
        res.condition[0].items[2].value = res.condition[0].items[2].value == "1" ? "0" : "1";
        this.dataSourceCreateAndEdit.form.initFormFields(res.condition);
        this.dataSourceCreateAndEdit.conditions = res.condition;
        this.loading = false;
        if(cb && typeof(cb) === "function") {
          cb();
        }
      }
    });
  }

  getFormDataSourceType = (params={}) => {
    this.loading = true;
    this.dataSourceType.form = new WeaForm();
    if(params.isEdit == "0") {
      this.dataSourceType.editId = '';
      // 在选择分权的情况下新建
      params = {subcompanyid: this.subcompanyid};
    }
    API.datasourcetype.getForm(params).then(res => {
      if (res.condition) {
        this.dataSourceType.form.initFormFields(res.condition);
        this.dataSourceType.conditions = res.condition;
        this.loading = false;
      }
    });
  }

  datasourceAPI = () => {
    return {
      getFormRightMenus: (params={}) => {
        if(params.isEdit == "0") {
          params = {subcompanyid: this.subcompanyid};
        }else {
          params = Object.assign({}, params, {subcompanyid: this.subcompanyid});
        }
        API.datasource.getFormRightMenus(params).then(res => {
          this.rightmenus.dataSource = res.btnMenu;
        })
      },
      insert: (params, func=null, flag=true) => {
        this.loading = true;
        API.datasource.insert(params).then(res => {
          if(flag) {
            this.loading = false;
          }
          if (res.status == "1") {
            if(flag) {
              message.success(getLabel('22619','保存成功'));
              this.dataSourceCreateAndEdit.show = false;
              doFormReset(
                this.dataSourceCreateAndEdit.form,
                toJS(this.dataSourceCreateAndEdit.conditions)
              );
            }
            this.getList();
          }
          if(func) {
            typeof(func) === "function" && func(res);
          }
        });
      },
      update: (params={}, func, flag=true) => {
        this.loading = true;
        API.datasource.update(params).then((res={}) => {
          if(params.operate == "test") {
            this.loading = false;
            if(res.status == "1") {
              setModal(res.datas && typeof(res.datas) === "string" ? res.datas : "");
              typeof(func) === "function" && func(res);
            }
          }else {
            if(flag) {
              this.loading = false;
            }
            if (res.status == "1") {
              if(flag) {
                message.success(getLabel('22619','保存成功'));
                this.dataSourceCreateAndEdit.show = false;
                doFormReset(
                  this.dataSourceCreateAndEdit.form,
                  toJS(this.dataSourceCreateAndEdit.conditions)
                );
              }
              this.getList();
            }
            typeof(func) === "function" && func(res);
          }
        });
      },
      delete: params => {
        API.datasource.delete(params).then(res => {
          this.getList();
        })
      },
      batchDelete: params => {
        API.datasource.batchDelete(params).then(res => {
          this.getList();
        });
      },
      getListConditions: callBack => {
        this.searchAdvance.form = new WeaForm();
        API.datasource.getListConditions({subcompanyid: this.subcompanyid}).then(res => {
          this.searchAdvance.form.initFormFields(res.condition);
          this.searchAdvance.conditions = res.condition;
          this.searchAdvance.advanceHeight = getSearchFormHeight(res.condition);
          if(isCallBackFunction(callBack)) {
            callBack();
          }
        })
      },
      getListRightMenus: params => {
        params = Object.assign({}, params, {subcompanyid: this.subcompanyid});
        API.datasource.getListRightMenus(params).then(res => {
          this.dropMenuDatas = res.btnMenu;
        })
      },
      test: (params, saveCallBack=null) => {
        // this.loading = true;   不需要loading设置为true
        API.datasource.test(params).then(res => {
          this.loading = false;
          if(saveCallBack && typeof(saveCallBack) === "function") {
            saveCallBack();
          }
        })
      },
      listTest: params => {
        this.loading = true;
        API.datasource.listTest(params).then(res => {
          this.loading = false;
        })
      }
    };
  };

  datasourcetypeAPI = () => {
    return {
      getFormRightMenus: (params={}) => {
        this.loading = true;
        if(params.isEdit == "0") {
          params = {subcompanyid: this.subcompanyid};
        }else {
          params = Object.assign({}, params, {subcompanyid: this.subcompanyid});
        }
        API.datasourcetype.getFormRightMenus(params).then(res => {
          this.rightmenus.dataSourceType = res.btnMenu;
        })
      },
      insert: params => {
        this.loading = true;
        API.datasourcetype.insert(params).then(res => {
          this.loading = false;
          if (res.status === "false") {
            return;
          }
          this.dataSourceType.show = false;
          doFormReset(
            this.dataSourceType.form,
            toJS(this.dataSourceType.conditions)
          );
          this.getList();
        });
      },
      update: params => {
        this.loading = true;
        API.datasourcetype.update(params).then(res => {
          this.loading = false;
          if (res.status === "false") {
            return;
          }
          this.dataSourceType.show = false;
          doFormReset(
            this.dataSourceType.form,
            toJS(this.dataSourceType.conditions)
          );
          this.getList();
        });
      },
      delete: params => {
        this.loading = true;
        API.datasourcetype.delete(params).then(res => {
          this.loading = false;
          this.getList();
        })
      },
      batchDelete: params => {
        this.loading = true;
        API.datasourcetype.batchDelete(params).then(res => {
          this.loading = false;
          this.getList();
        });
      }
    };
  };

  toggleView = () => {
    this.logView = !this.logView;
  }
}
