import Vue from 'vue';
import settingConfig from '@/settings.js'

let f;
let configUtil = {
  getWfObj(path) {
    return require(`../../components/wf${path}`).default;
  },
  Vue,
  settingConfig
};

f = async function (option) {
  let serviceId = getServiceId(option.serviceId);
  if (!serviceId) return;
  let that = this;
  if (option.objId && option.wfCode) {
    /*
    if (option.wfViewRegion === false || !wfViewRegion) {
      return;
    }*/

    let hasWf = false;
    let wfInfo, currentTask, taskParam;
    await initWfInfo(that, option).then(res => {
      if (res && res.type == 'success') {
        if (res.objx && res.objx.procInstId) {
          hasWf = true;
          wfInfo = res.objx;
        }
      }
    });

    if (hasWf) {
      if (wfInfo.taskId) {
        await getTaskParams(that, option, wfInfo.taskId).then(res2 => {
          if (res2.type == 'success') {
            taskParam = res2.objx;
            taskParam.objId = option.objId;
          }
        });
      }
    }

    let done = () => {
      let $wfBtnRegion = that.$refs[option.wfBtnRegion || "wfBtnRegion"];
      let $wfViewRegion = that.$refs[(option.wfViewRegion || "wfViewRegion")];

      let wfBtnRegion = $wfBtnRegion ? $wfBtnRegion.$el : that.$el.querySelector(
        ".el-form .d-header >.fr");
      let wfViewRegion = $wfViewRegion ? $wfViewRegion.$el : that.$el.querySelector(
        ".el-form .d-cont");

      let slideWrap = $wfViewRegion ? $wfViewRegion.$el : that.$el.querySelector(
        ".el-form .slide-wrap");

      let showStartBtn = option.showStartBtn != null ? option.showStartBtn : true;
      let showModifyBtn = option.showModifyBtn != null ? option.showModifyBtn : true;

      if (wfInfo) {
        let wfModel = configUtil.settingConfig.wfModel || 1;
        let url = wfModel == 2 ? '/content2.vue' : '/content.vue';
        let a = configUtil.Vue.extend(configUtil.getWfObj(url));
        let defaultShowWfContent = that.$attrs.defaultShowWfContent;
        let instance = new a({
          i18n: that._i18n,
          propsData: {
            objId: option.objId,
            wfCode: option.wfCode,
            serviceId: serviceId,
            _wfInfo: wfInfo,
            _taskParam: taskParam,
            parentVue: that,
            defaultShowWfContent: defaultShowWfContent,
            wfConfig: option
          }
        });
        let _hideWf = that._hideWf || that.$attrs._hideWf;
        let isHideWf = _hideWf === true || _hideWf === 'true';
        if (!_hideWf && slideWrap) {
          let navDom = new configUtil.Vue({
            render: function (h) {
              let node = h("div", {}, [
                h("a", {
                  staticClass: "slide-nav",
                  attrs: {
                    id: "wfNavBtn"
                  },
                  on: {
                    click: (event) => {
                      instance.$children[0].handleFold(true);
                      that.$nextTick(() => {
                        instance.$el.scrollIntoView();
                      })
                    }
                  }
                }, [h('i', {
                  staticClass: "ico"
                }), h("p", that.$t2('流程信息', 'components.wf.wfInfo'))])
              ]);
              return node;
            }
          }).$mount().$el;
          if (settingConfig.version == 'oa') {
            slideWrap = slideWrap.children[0];
          }
          setTimeout(() => {
            slideWrap.append(navDom);
            if (that.$attrs.toWfArea) {
              //待办进来，直接跳到流程模块
              this.$nextTick(() => {
                navDom.querySelector('a').click();
              });
              that.$emit("update:toWfArea", false);
            }
          }, 500);
        }
        wfViewRegion && wfViewRegion.append(instance.$mount().$el);
      }

      if (wfBtnRegion && showModifyBtn && hasWf && taskParam && taskParam.url && wfInfo.toSubmit && !option.hiddenAllButton) {
        let buttonName = getModifyButtonName(that, taskParam);
        let dom = new configUtil.Vue({
          render: function (h) {
            let modifyNode = h("el-button", {
              attrs: {
                type: "primary",
                plain: "",
                icon: "el-icon-edit"
              },
              staticClass: "button-sty",
              on: {
                click: () => {
                  openWfModifyDialog(that, taskParam, buttonName, wfInfo);
                }
              }
            }, buttonName);
            return modifyNode;
          }
        }).$mount().$el;
        appendPrevChildDom(wfBtnRegion, dom);
      }

      if (wfBtnRegion && showStartBtn && !hasWf && !option.hiddenAllButton) {
        let wfStartButtonName = configUtil.settingConfig.wfStartButtonName || this.$t2('流程启动', 'components.wf.wfStart');
        let dom = new configUtil.Vue({
          render: function (h) {
            let startNode = h("el-button", {
              attrs: {
                type: "success",
                icon: "el-icon-video-play"
              },
              staticClass: "button-sty",
              on: {
                click: () => {
                  openStartWfDialog(that, option);
                }
              }
            }, wfStartButtonName);
            return startNode;
          }
        }).$mount().$el;
        appendPrevChildDom(wfBtnRegion, dom)
      }
    }

    if (true || wfInfo) {
      if (option.callback) {
        option.callback({
          wfInfo,
          currentTask,
          taskParam,
          hasWf,
          done
        });
      }
    }
    if (option.auto !== false) {
      done();
    }
  }
}

function getModifyButtonName(that, taskParam) {
  let buttonName = null;
  if (!taskParam.buttonName || taskParam.buttonName == "修改单据") {
    buttonName = that.$t2("修改单据", 'components.wf.modifyBill');
  } else {
    buttonName = taskParam.buttonName;
  }
  return buttonName;
}

function getServiceId(str) {
  let serviceId;
  if (str) {
    let strArr = str.split('/');
    serviceId = strArr[0] == '/' ? strArr[1] : str;
  } else {
    serviceId = '';
  }
  return serviceId;
}

function getCurrentPrefix(serviceId) {
  let currentPrefix;
  if (serviceId) {
    currentPrefix = serviceId.split('/')[0] == '/' ? serviceId : ('/' + serviceId);
  } else {
    currentPrefix = '';
  }
  return currentPrefix;
}

async function initWfInfo(that, option) {
  let id = option.objId;
  let code = option.wfCode;
  return that.$http({
    url: getCurrentPrefix(option.serviceId) + '/wf/getWfInfo',
    method: `post`,
    data: {
      objTypeCode: code,
      objId: id
    },
    isLoading: true,
    modalStrictly: true
  });
}

async function getTaskParams(that, option, taskId) {
  return that.$http({
    url: getCurrentPrefix(option.serviceId) + '/wf/getTaskVariables',
    method: `post`,
    data: {
      stringOne: taskId
    },
    isLoading: true,
    modalStrictly: true
  });
}

function openStartWfDialog(that, option) {
  let done = () => {
    let a = configUtil.Vue.extend(configUtil.getWfObj('/wfStartDialog.vue'));
    let instance = new a({
      i18n: that._i18n,
      propsData: {
        code: option.wfCode,
        dataId: option.objId,
        serviceId: getServiceId(option.serviceId),
        startParam: option.startParam,
        parentVue: that,
        visible: true,
        formCode:(option.formCode || null),
        option
      }
    });
    document.body.append(instance.$mount().$el)
  }
  if (option.onStart) {
    option.onStart(done)
  } else {
    done();
  }
}

function openWfModifyDialog(that, paramData, title, wfInfo) {
  let a = configUtil.Vue.extend(configUtil.getWfObj('/wfModifyDialog.vue'));
  let instance = new a({
    i18n: that._i18n,
    propsData: {
      paramData: paramData,
      parentVue: that,
      visible: true,
      wfInfo: wfInfo,
      title: title
    }
  });
  document.body.append(instance.$mount().$el)
}

function appendPrevChildDom(parentDom, newDom) {
  if (parentDom.hasChildNodes()) {
    let currentDom = parentDom.children[0];
    parentDom.insertBefore(newDom, currentDom);
  } else {
    parentDom.append(newDom);
  }
}

export const initWf = f;
