import { 
  observable, 
  action, 
  toJS, 
} from "mobx";
import { 
  Modal, 
  message, 
  Button, 
} from "antd";
import { 
  isEmpty, 
  remove, 
} from 'lodash';
import { 
  WeaLocaleProvider, 
  WeaCheckbox, 
  WeaSelect, 
} from "ecCom";
import { 
  WeaTableNew, 
  WeaForm, 
} from "comsMobx";
import {
  getSearchFormHeight,
  checkNonstandard,
  checkHasOrganization,
  isCallBackFunction,
} from '../util/IntegrationUtil';
import * as API from "../apis/Webservice";

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

export default class Webservice {
  @observable hasRight = false;
  @observable rightLoading = true;
  @observable status = {};
  @observable tableStore = new TableStore(); //流程接口注册
  @observable form = new WeaForm(); //高级查询的表单
  @observable formCreate = new WeaForm(); //新建的表单
  editRecordId = '';

  @action("清空store")
  cleanStore = () => {
    this.setState({
      subcompanyid: "",
      condition: [],
      conditionCreate: [],
      columns: [],
      rightMenu: [],
      rightMenuForm: [],
      visible: false,
      showRegister: true,
      analysisWSDL: true,
      wsdlParamData: [],
      wsdlinfo: [],
      selectedRowKeys: [],
      loading: false,
      loadingCreate: false,
      webserviceid: '0',
      type: 'create',
      wsdlParamPass: false,//解析WSDL通过
      advanceHeight: 0,
      collectParams: {
        favname: getLabel(33717, "WebService注册"),
        favouritetype: 2,
        objid: 0,
        importantlevel: 1,
        link: 'wui/engine.html#/main/integration/webservice',
      },
    })
    this.form = new WeaForm(); //高级查询的表单
    this.formCreate = new WeaForm(); //新建的表单
  }

  @action
  doInit = () => {
    this.setState({
      nonStandLoading: true,
    });
    checkNonstandard({num: "057"}, (result) => {
      this.setState({
        hasNonStandard: result.isOpen,
        nonStandLoading: false,
      })
      if(result.isOpen) {
        this.cleanStore();
        checkHasOrganization((hasOrg) => {
          this.setState({
            hasOrganization: hasOrg,
          })
        });
        this.getConditions(this.getTableInfo);
      }
    })
  };

  doInitCreate = () => {
    this.setState({ visible: false, loadingCreate: false, analysisWSDL: true
      , wsdlParamData: [], lastDataLen: 0, selectedRowKeys: [], type:'create', wsdlParamPass: false });
    this.formCreate.reset();
    window.e9ChangedFormFieldKey = 'clearFormInfo';
  }

  setState = (params = {}) => {
    let status = { ...this.status };
    Object.keys(params).forEach(v => {
      status[v] = params[v];
    });
    this.status = status;
  }

  doOperation = (type) => {
    if (type === 'BTN_Insert') {
      this.getForm({ webserviceid: '0', type: 'create' });
      this.getFormRightMenus({ webserviceid: '0' });
      this.setState({ visible: true, webserviceid: '0', type: 'create' });
    } else {
      const selectedRowKeys = toJS(this.tableStore.selectedRowKeys);
      const params = { pointid: selectedRowKeys.join(',') };
      this.delList(params);
    }
  }

  getTopButton = () => {
    const rightMenu = this.status.rightMenu, selectedRowKeys = toJS(this.tableStore.selectedRowKeys);
    let arr = [];
    rightMenu && rightMenu.forEach(v => {
      arr.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@d52lid@integrationWebserviceCreateButtonBatchDelete`} type='primary' disabled={v.type == 'BTN_BatchDelete' && isEmpty(selectedRowKeys)} onClick={() => this.doOperation(v.type)}>{v.menuName}</Button>)
    })
    return arr;
  }

  getRightMenuData = () => {
    const rightMenu = this.status.rightMenu, selectedRowKeys = toJS(this.tableStore.selectedRowKeys);
    let arr = [];
    rightMenu && rightMenu.forEach(v => {
      arr.push({
        key: v.type,
        content: v.menuName,
        disabled: v.type == 'BTN_BatchDelete' && isEmpty(selectedRowKeys),
        icon: <span className={v.menuIcon} />,
        onClick: () => this.doOperation(v.type),
      })
    })
    return arr;
  }

  getConditions = (callBack=null) => {
    this.form = new WeaForm();
    API.getConditions({subcompanyid: this.status.subcompanyid}).then(result => {
      if(result.status == 1) {
        this.form.initFormFields(result.condition || []);
        this.setState({
          advanceHeight: getSearchFormHeight(result.condition),
          condition: result.condition || [],
        });
      }
      if(isCallBackFunction(callBack)) {
        callBack();
      }
    })
  }

  getTableInfo = (params={}) => {
    this.setState({loading: true});
    this.tableStore = new TableStore();
    params = Object.assign({}, params, this.form.getFormParams(), {subcompanyid: this.status.subcompanyid});
    Promise.all([
      API.getRightMenu(params),
      API.getList(params),
    ]).then(([result1, result2]) => {
      if(result2.ret && result2.ret == "false"){
        this.setState({loading: false});
        this.hasRight = false;
        this.rightLoading = false;
      } else {
        this.tableStore.getDatas(result2.datas, 1);
        this.setState({
          loading: false,
          rightMenu: result1.btnMenu || [],
        });
        this.hasRight = true;
        this.rightLoading = false;
      }
    })
  }

  getList = (params = {}) => {
    this.setState({loading: true});
    this.tableStore = new TableStore();
    params = Object.assign({}, params, this.form.getFormParams(), {subcompanyid: this.status.subcompanyid});
    API.getList(params).then(result => {
      if(result.ret && result.ret == "false"){
        this.setState({loading: false});
        this.hasRight = false;
        this.rightLoading = false;
      }else {
        this.tableStore.getDatas(result.datas, 1);
        this.setState({ loading: false });
        this.hasRight = true;
        this.rightLoading = false;
      }
    })
  }

  getRightMenu = (params = {}) => {
    params = Object.assign({}, params, {subcompanyid: this.status.subcompanyid});
    API.getRightMenu(params).then(result => {
      if(result.status == 1) {
        this.setState({rightMenu: result.btnMenu || []});
      }
    })
  }

  delList = (params = {}, bool = true) => {
    Modal.confirm({
      title: bool ? getLabel(385625,'确定要删除选择的记录吗？'): getLabel(15097,'确定要删除吗？'),
      onOk: () => {
        API.delList(params).then(result => {
          this.doInit();
          this.doInitCreate();
          this.form.reset();
        })
      }
    })
  }

  edit = (record) => {
    this.setEditRecordId(record.id);
    this.getFormRightMenus({ webserviceid: record.id });
    this.getForm({ webserviceid: record.id, type: "edit" }).then(() => {
      this.formCreate.updateFields({
        customname: { value: record.customname },
        webserviceurl: { value: record.webserviceurl },
      });
      this.parseWSDL({ webserviceurl: record.webserviceurl, type: '1' }, 'wsdl');
      this.setState({ visible: true, webserviceid: record.id, type: 'edit' });
    });
  }

  doTest = (params = {}) => {
    API.doTest(params).then(result => {
      Modal.info({
        content: result.errmsgTip,
      })
    })
  }

  setEditRecordId = (val) => {
    this.editRecordId = val;
  }

  onOperatesClick = (record, index, operate, flag) => {
    const funName = operate.href.replace(/(javascript\:)|(\(\))/g, () => '');
    this.setEditRecordId(record.id);
    switch (funName) {
      case 'doEditById': this.edit(record); break;
      case 'doTest': this.doTest({ id: record.id }); break;
      case 'doDelete': this.delList({ pointid: record.id }, false); break;
    }
  }

  //Dialog操作
  getFormRightMenus = (params = {}) => {
    API.getFormRightMenus(params).then(result => {
      this.setState({ rightMenuForm: result.btnMenu });
    })
  }

  getComType = (com, dataIndex, options) => {
    if (dataIndex === 'methodreturntype') {
      com = {
        ...com,
        type: 'CUSTOM',
        render: (text, record, index) => {
          return <span>{record.outparamtype || record.methodreturntype || ''}</span>;
        }
      }
    } else if (dataIndex === 'paramname') {
      com = {
        ...com,
        type: 'CUSTOM',
        render: (text, record, index) => {
          const arr = record.paraminfo || record.inparams || [], res = [];
          arr.forEach(v => {
            res.push(<div key={v.id}>
              {v.paramname || v.name}
            </div>)
          })
          return res;
        }
      }
    } else if (dataIndex === 'paramtype') {
      com = {
        ...com,
        type: 'CUSTOM',
        render: (text, record, index) => {
          const arr = record.paraminfo || record.inparams || [], res = [];
          arr.forEach(v => {
            res.push(<div>
              {v.paramtype || v.kind}
            </div>)
          })
          return res;
        }
      }
    } else if (dataIndex === 'isarray') {
      com = {
        ...com,
        type: 'CUSTOM',
        render: (text, record, index) => {
          const arr = record.paraminfo || record.inparams || [], res = [];
          arr.forEach((v, index) => {
            res.push(<div>
              <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@h25a36@integrationWebserviceCreateColumns${dataIndex}`}
                value={v.isarray && v.isarray == '1'}
                onChange={(value) => {
                  let _wsdlParamData = toJS(this.status.wsdlParamData);
                  _wsdlParamData.forEach((v, l) => {
                    if (v.methodid === record.methodid) {
                      _wsdlParamData[l].paraminfo[index]['isarray'] = value;
                    }
                  })
                  this.setState({ wsdlParamData: _wsdlParamData })
                }} />
            </div>)
          })
          return res;
        }
      }
    } else if (dataIndex === 'methodname') {
      com = {
        ...com,
        type: 'CUSTOM',
        render: (text, record, index) => {
          return <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@xz1bdt`}
            options={options}
            viewAttr={record.methodid.indexOf('$') > -1 ? 3 : 1}
            value={record.methodname}
            onChange={(value) => {
              let _wsdlParamData = toJS(this.status.wsdlParamData);
              _wsdlParamData.forEach((v, l) => {
                if (v.methodid === record.methodid) {
                  _wsdlParamData[l].methodname = value;
                }
              })
              this.onTableChange(_wsdlParamData, index);
            }} />
        }
      }
    }
    return com;
  }

  getColumns = (wsdlinfo, type) => {
    let {columns, wsdlParamData} = toJS(this.status), options = [];
    wsdlinfo.forEach((v, key) => {
      options.push({
        key: v.name,
        showname: v.name,
        selected: false,
      })
    });
    if(type == '2') {
      // 检测更新
      wsdlParamData && wsdlParamData.forEach((data, index) => {
        let temp = wsdlinfo.find(option => option.name === data.methodname);
        if(temp) {
          let paraminfo = [], flag = false;
          temp.inparams && temp.inparams.forEach(o => {
            paraminfo.push({
              paramname: o.name,
              paramtype: o.kind,
              isarray: "0"
            })
          })
          // paraminfo有没有变化的判断
          if(paraminfo.length != wsdlParamData[index].paraminfo.length) {
            flag = true;
          }else {
            wsdlParamData[index].paraminfo && wsdlParamData[index].paraminfo.forEach(v => {
              let index = paraminfo.find(param => param.paramname === v.paramname && param.paramtype === v.paramtype);
              if(index == -1) {
                flag = true;
              }
            })
          }
          if(temp.outparamtype != wsdlParamData[index].methodreturntype || flag) {
            wsdlParamData[index] = {
              ...wsdlParamData[index],
              methodreturntype: temp.outparamtype || '',
              paraminfo
            }
          }
        }
      })
      this.setState({wsdlParamData});
    }
    columns.forEach(v => {
      if (v.dataIndex !== 'methoddesc') v.com[0] = this.getComType(v.com[0], v.dataIndex, options);
    })
    return columns;
  }

  getForm = (params = {}) => {
    if(params && params.type === "create") {
      params = Object.assign({}, params, {subcompanyid: this.status.subcompanyid});
    }
    delete params.type;
    return API.getForm(params).then(result => {
      result.condition[0].items[1]['showOtherCom'] = true;
      this.setState({
        conditionCreate: [result.condition[0]],
        columns: result.condition[1].WeaTableEdit,
        wsdlParamData: result.wsdlParamData,
      });
      this.formCreate.initFormFields([result.condition[0]]);
    })
  }

  parseWSDL = (params = {}, type = 'wsdl') => {
    if (!params.webserviceurl || params.webserviceurl == '') message.warning(getLabel(386096,"请输入WEBSERVICE地址！"));
    else {
      this.setState({ loadingCreate: true });
      API.parseWSDL(params).then(result => {
        if (Array.isArray(result.wsdlinfo)) {
          this.setState({ analysisWSDL: false, wsdlinfo: result.wsdlinfo, columns: this.getColumns(result.wsdlinfo, params.type), wsdlParamPass: true });
          message.success(result.resulttip);
        } else {
          message.error(result.resulttip);
        }
        this.setState({ loadingCreate: false });
      })
    }
  }


  addRegister = () => {
    const len = this.status.wsdlParamData.length;
    const wsdlParamData = [
      ...this.status.wsdlParamData,
      {
        methodid: '$' + len,//标记新加的数据
        methoddesc: '',
        methodname: '',
        methodreturntype: '',
        paraminfo: [],
      }
    ];
    this.setState({ wsdlParamData });
  }

  delRegister = () => {
    Modal.confirm({
      title: getLabel(385625,'确定要删除选择的记录吗？'),
      onOk:() => {
        const selectedRowKeys = toJS(this.status.selectedRowKeys), wsdlParamData = toJS(this.status.wsdlParamData);
        selectedRowKeys.forEach(v =>
          remove(wsdlParamData, n => v === n.methodid)
        );
        this.setState({ wsdlParamData,selectedRowKeys: [] });
      }
    })
  }

  onTableChange = (wsdlParamData, index = 0) => {
    const wsdlinfo = toJS(this.status.wsdlinfo);
    const temp = wsdlinfo.find(o => o.name == wsdlParamData[index].methodname);
    if (temp) {
      wsdlParamData[index].methodreturntype = temp.outparamtype || '';
      wsdlParamData[index].paraminfo = [];
      temp.inparams.forEach(o => {
        wsdlParamData[index].paraminfo.push({
          paramname: o.name,
          paramtype: o.kind,
          isarray: '0',
        })
      })
    }
    this.setState({ wsdlParamData });
  }

  doSave = (param = {}) => {
    const params = {
      webserviceid: this.status.webserviceid,
      ...this.formCreate.getFormParams(),
      wsdlParamData: JSON.stringify(param),
    };
    this.setState({ loadingCreate: true });
    API.doSave(params).then(result => {
      this.setState({ loadingCreate: false });
      if (result.errmsg == '0') {
        message.success(getLabel(22619,'保存成功'));
        this.doInitCreate();
        this.doInit();
      } else {
        message.error(result.errmsgtip || getLabel(22620,'保存失败'));
      }
    })
  }
}