import projectTagView from "@base/components/projectTag/view.vue";
import projectTagAddButton from "@base/components/projectTag/addButton.vue";
import projectTagDeleteButton from "@base/components/projectTag/deleteButton.vue";
import tableForm from "@base/components/table/tableForm.vue";
import editView from "@base/views/bd/setting/form_template/edit.vue";
import userDialog from "@base/views/user/user/dialog.vue";
import positionDialog from "@base/views/user/position/dialog.vue";
import scriptDescriptionDialog from "@base/components/scriptDescription/dialog.vue";
import ftHistoryDialog from "@base/views/bd/setting/form_template/ftHistoryDialog.vue";
import itemList from "@base/views/bd/setting/form_template/itemList.vue";
import formTypeEditDialog from "@base/views/user/form/form_type/editDialog.vue";
import projectTagDialog from "@base/views/user/project_tag/dialog.vue";
import {treeScollx} from "@base/utils/global";
import indexUtil from "@base/utils";
import {getBdFlag} from "@base/api/user";
import {
  getJsxBtnList,
  getJsxStatus,
} from "@base/views/bd/setting/utils/index";
import formVersionButton from "@base/views/bd/setting/formVersion/link.vue";

let modules = {};
modules = {
  name: "bd_form_template:list",
  components: {
    projectTagView,
    projectTagAddButton,
    projectTagDeleteButton,
    tableForm,
    editView,
    userDialog,
    positionDialog,
    scriptDescriptionDialog,
    ftHistoryDialog,
    itemList,
    formTypeEditDialog,
    projectTagDialog,
    formDesignerDialog: () => import("@base/views/bd/setting/form_template/formDesignerDialog.vue"),
    formVersionButton,
  },
  data() {
    return {
      isFullscreen: false,
      formDesTabs: "first",
      activeName: "second",
      dataId: 0,
      showEdit: false,
      vxeOption: {},
      formData: {},
      showDesingerDialog: false,
      formCode: null,
      formName: null,
      templateId: null,
      currentFormTemplate: null,

      showItemEdit: false,
      showParamEdit: false,
      vxeOption1: {},
      editId: "",
      itemEditId: "",
      pRow: null,
      currentRow: {},
      serviceId: null,
      itemServiceId: null,

      showWfDialog: false,
      wfUrl: "",
      ph: "",
      dialogActiveName: "first",
      showFunctionScriptList: false,
      showUserDialog: false,
      wfAssignData: [],
      wfAssignCallback: null,
      wfAssignMulti: true,

      showPositionDialog: false,
      wfAssignPositionData: [],
      wfAssignPositionCallback: null,

      showFormTemplateDialog: false,
      wfAssignFormTemplateCallback: null,

      showScriptDescriptionDialog: false,
      showWfDiyAttributeEdit: false,

      showFtHistoryDialog: false,
      operateFtHistory: null,

      defaultProps: {
        label: "name", //这里是树结构中需显示的数据（即接口返回的需展示在页面上的参数）
        children: [],
        isLeaf: "leaf",
      },
      showItemView: false,

      currentFormType: {},
      editFormTypeId: null,
      showFormTypeDialog: false,
      showFormScriptList: false,
      addProjectTagOption: {
        url: USER_PREFIX + `/formTemplate/saveTag`,
        tableDatas: () => {
          return this.$refs["table-m1"].getCheckboxRecords(true);
        },
        reqData: (tagDatas, tableDatas) => {
          let sids = tableDatas.map((item) => item.sid);
          let tagCodes = tagDatas.map((item) => item.tagCode);
          let reqData = {
            tagCodes,
            sids,
          };
          return reqData;
        },
        callback: () => {
          this.searchEvent();
        },
      },
      deleteProjectTagOption: {
        url: USER_PREFIX + `/formTemplate/deleteTag`,
        tableDatas: () => {
          return this.$refs["table-m1"].getCheckboxRecords(true);
        },
        reqData: (tagDatas, tableDatas) => {
          let sids = tableDatas.map((item) => item.sid);
          let tagCodes = tagDatas.map((item) => item.tagCode);
          let reqData = {
            tagCodes,
            sids,
          };
          return reqData;
        },
        callback: () => {
          this.searchEvent();
        },
      },
      showProjectTagDialog3: false,
      checkTags: [],
      isDev: true,
      menuKindAuth: {},
      showTree: false,
      designerReadonly: false,
    };
  },
  computed: {
    currentMenuKindId() {
      return this.currentFormType?.id || null;
    },
    currentMenuKindName() {
      return this.currentFormType?.name || null;
    },
    otherFlag() {
      return this.currentFormType?.menuKindCode === "other"
    }
  },
  watch: {
    formDesTabs(val) {
      if (this.showFormScriptList === false && val === "second") {
        this.showFormScriptList = true;
      }
    },
  },
  mounted() {
    treeScollx({target: this, type: "default"});
    this.getBdEnv();
    this.initTableList();
    this.initWfWinParam();
  },
  methods: {
    searchEvent() {
      this.$refs["table-m1"].commitProxy("reload");
    },
    resetEvent() {
      this.formData = {};
      this.checkTags = [];
      this.$refs["table-m1"].commitProxy("reload");
    },
    openEditDialog(row) {
      let formCode = row?.formCode || null;
      /*this.dataId = !id || typeof id === 'object' ? 0 : id;
      this.activeName = 'first';
      this.showItemEdit = false;
      this.$openEditView('showEdit');*/
      if (!formCode) {
        this.dataId = formCode;
        this.activeName = "first";
        this.$openEditView("showEdit");
      } else {
        this.$refs.xTabs.openEditTab(row);
      }
    },
    openDesingerDialogByAuth(row) {
      if (!this.otherFlag) {
        this.openDesingerDialog(row);
      } else {
        this.getOtherMenuKindAuth(row, (editAuth) => {
          this.openDesingerDialog(row, null, !editAuth);
        })
      }
    },
    getOtherMenuKindAuth(row, callback) {
      if (row.sid) {
        this.$http({
          aes: true,
          url: USER_PREFIX + "/form_template_auth/getAuth",
          method: `post`,
          data: {stringOne: row.sid},
          isLoading: true,
          success: (res) => {
            let menuKindAuth = res.objx || {};
            callback(!!menuKindAuth.editAuth)
          },
        });
      }
    },
    openDesingerDialog(row, callback, readonly = false) {
      this.formCode = row.formCode;
      this.formName = row.formName;
      this.currentFormTemplate = row;
      this.isFullscreen = false;

      this.designerReadonly = readonly
      this.showDesingerDialog = true;
      this.designerSaveCallback = callback ?? null;
    },
    openDesingerDialogByChild({row, readonly, callback}) {
      this.openDesingerDialog(row, callback, readonly);
    },
    reflushTemplateList() {
      this.searchEvent();
      this.designerSaveCallback && this.designerSaveCallback();
    },
    handleFullscreen() {
      let isFullscreen = this.isFullscreen;
      if (!isFullscreen) {
        indexUtil.addClass(document.body, "hideMenu");
      } else {
        indexUtil.removeClass(document.body, "hideMenu");
      }
      this.isFullscreen = !isFullscreen;
    },
    openFtHistoryDialog(row) {
      this.operateFtHistory = row;
      this.showFtHistoryDialog = true;
    },
    confirmFtHistoryDialog(row) {
      this.searchEvent();
    },
    closeFormDesignwinEvent(done) {
      this.$baseConfirm(
        this.$t1('请确认"已保存"报表模板，是否继续关闭？')
      ).then(() => {
        indexUtil.removeClass(document.body, "hideMenu");
        done && done();
      });
    },
    getSearchParam() {
      let tagCodes = null;
      if (this.checkTags.length) {
        tagCodes = this.checkTags.map((item) => item.tagCode);
      }
      let currentFormType = this.currentFormType || {}
      let menuKindCode = currentFormType.menuKindCode && !this.otherFlag ? currentFormType.menuKindCode : null;
      return {
        ...this.formData,
        tagCodes,
        menuKindCode,
        history: false,
      };
    },
    initTableList() {
      let that = this;
      let tableOption = {
        vue: this,
        tableRef: "table-m1",
        tableName: "bd_form_template_list-m1",
        path: () => {
          let url = USER_PREFIX + '/formTemplate/listPage';
          if (this.otherFlag) {
            url = USER_PREFIX + '/formTemplate/listOtherPage';
          }
          return url;
        },
        param: () => {
          return this.getSearchParam();
        },
        columns: [
          {type: "checkbox", width: 48, resizable: false, fixed: "left"},
          {
            title: this.$t1("模板名称"),
            field: "formName",
            width: 150,
            fixed: "left",
          },
          {
            title: this.$t1("项目标签"),
            field: "tag",
            width: 250,
            slots: {default: "tag"},
            params: {
              exportVal: ({row}) => {
                if (row.formTemplateTagDTOs) {
                  return row.formTemplateTagDTOs
                    .map((item) => item.tagName)
                    .join(",");
                }
              },
            },
          },
          {
            title: this.$t1("模板编码"),
            field: "formCode",
            width: 150,
          },
          {
            title: this.$t1("表单分类"),
            field: "menuKindName",
            width: 150,
          },
          {
            title: this.$t1("是否启用"),
            field: "enabled",
            width: 150,
            slots: {
              default: ({row}) => {
                if (row.enabled) {
                  return getJsxStatus(null, this.$t1("启用"));
                } else {
                  return getJsxStatus("s-3", this.$t1("禁用"));
                }
              },
            },
          },
          {
            title: this.$t1("启用流程"),
            field: "hasWf",
            width: 150,
            slots: {
              default: ({row}) => {
                if (row.hasWf) {
                  return getJsxStatus(null, this.$t1("是"));
                } else {
                  return getJsxStatus("s-3", this.$t1("否"));
                }
              },
            },
          },
          {
            title: this.$t1("默认流程单据类型名称"),
            field: "objTypeName",
            width: 200,
          },
          {
            title: this.$t1("引用流程的表单编码"),
            field: "fromWfFormCode",
            width: 200,
          },
          {
            title: this.$t1("备注"),
            field: "remark",
            width: 150,
          },
          {field: "serviceName", title: this.$t1("服务名"), width: 150},
          {
            title: this.$t1("版本号"),
            field: "version",
            width: 150,
          },
          {title: this.$t1("唯一标识"), field: "sid", width: 280},
          {
            field: 'createBy',
            title: this.$t1('创建人'),
            width: 150
          },
          {
            field: 'createDate',
            title: this.$t1('创建时间'),
            width: 150
          },
          {
            field: 'modifyBy',
            title: this.$t1('更新人'),
            width: 150
          },
          {
            field: 'modifyDate',
            title: this.$t1('更新时间'),
            width: 150
          },
          {
            width: 140,
            fixed: "right",
            title: "",
            sortable: false,
            slots: {
              default: "operation",
            },
          },
        ],
        searchColumns: [
          {
            title: this.$t1("表单分类"),
            field: "menuKindName",
            type: "input",
            common: true,
            disabled: true,
            defaultValueEnabled: false,
            slot: "menuKindName",
          },
          {
            title: this.$t1("模板名称"),
            field: "formName",
            type: "input",
            common: true,
          },
          {
            title: this.$t1("模板编码"),
            field: "formCode",
            type: "input",
            common: true,
          },
          {
            title: this.$t1("是否启用"),
            field: "enabled",
            type: "select",
            common: true,
            itemOption: [
              {label: this.$t1("启用"), value: true},
              {label: this.$t1("禁用"), value: false},
            ],
          },
          {
            title: this.$t1("项目标签"),
            field: "tag",
            type: "input",
            common: true,
            slot: "tag",
          },
          {
            title: this.$t1("模板JSON"),
            field: "formViewContent",
            type: "input",
            common: false,
          },
          {title: this.$t1('创建人'), field: "createBy", type: "input", common: false},
          {title: this.$t1('更新人'), field: "modifyBy", type: "input", common: false},
          {title: this.$t1('操作日志'), field: "logContent", type: "input", common: false},
          {
            title: this.$t1('创建时间'),
            field: "startCreateDate",
            field2: "endCreateDate",
            type: "dateRange",
            common: false,
            widgetType: "datetime",
            valueFormat: "yyyy-MM-dd HH:mm:ss"
          },
          {
            title: this.$t1('更新时间'),
            field: "startModifyDate",
            field2: "endModifyDate",
            type: "dateRange",
            common: false,
            widgetType: "datetime",
            valueFormat: "yyyy-MM-dd HH:mm:ss"
          }
        ],
        config: {
          proxyConfig: {
            autoLoad: false,
          },
        },
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then((opts) => {
        this.vxeOption = opts;
        this.showTree = true;
      });
    },
    chooseCellM1(row) {
      this.currentRow = row;
      this.showItemView = true;
    },
    openWfDesignDialog(actModelId) {
      //wfType 0:单据流程，1：场景流程
      let serviceId = this.currentRow.serviceName;
      this.wfUrl =
        WEB_PREFIX +
        "/activiti-explorer/modeler.html?wfType=0&serviceId=" +
        serviceId +
        "&modelId=" +
        actModelId;
      this.dialogActiveName = "first";
      this.showWfDialog = true;
    },
    closeDesignwinEvent(done) {
      this.$baseConfirm(
        this.$t1('请确认"已保存"流程模板，是否继续关闭？')
      ).then(() => {
        this.showWfDialog = false;
        // this.showDesingerDialog = false;
      });
    },
    initWfWinParam() {
      this.initCloseWfDesignWin();
      this.initWinUserDialog();
      this.initWinPositionDialog();
      this.initSysParamForWf();
      this.initWinFormTemplateDialog();
      this.initWinScriptDescriptionDialog();
    },
    initCloseWfDesignWin() {
      window.closeWfDesignWin = () => {
        this.showWfDialog = false;
      };
    },
    initWinUserDialog() {
      window.openAssignUserDialog = (opts) => {
        this.wfAssignMulti = opts.multi;
        this.wfAssignData = opts.data || [];
        this.wfAssignCallback = opts.callback;
        this.showUserDialog = true;
      };
    },
    confirmUser(rows) {
      this.wfAssignCallback(rows);
    },
    initWinPositionDialog() {
      window.openAssignPositionDialog = (opts) => {
        this.wfAssignPositionData = opts.data || [];
        this.wfAssignPositionCallback = opts.callback;
        this.showPositionDialog = true;
      };
    },
    initSysParamForWf() {
      let webPrefix = WEB_PREFIX;
      let baseApi = process.env.VUE_APP_BASE_API;
      window.sysParamForWf = {
        webPrefix,
        baseApi,
      };
    },
    confirmPosition(rows) {
      this.wfAssignPositionCallback(rows);
    },
    initWinFormTemplateDialog() {
      window.openAssignFormTemplateDialog = (opts) => {
        this.wfAssignFormTemplateCallback = opts.callback;
        this.showFormTemplateDialog = true;
      };
    },
    confirmFormTemplate(rows) {
      this.wfAssignFormTemplateCallback(rows);
    },
    initWinScriptDescriptionDialog() {
      window.openScriptDescriptionDialog = (opts) => {
        this.showScriptDescriptionDialog = true;
      };
    },
    handleNodeClick(data, node, v) {
      this.handleNodeData(node);
      this.$forceUpdate();
      this.searchEvent();
    },
    // 异步树叶子节点懒加载逻辑
    loadNode(node, resolve) {
      let id = node && node.data && node.data.id ? node.data.id || "" : 0;
      let param = {enabled: true};
      let url = !id
        ? USER_PREFIX + "/menuKind/getAllList"
        : USER_PREFIX + "/menuKind/getChildren";
      this.$http({
        aes: true,
        url: url,
        method: "post",
        data: {
          parent: id,
          enabled: true,
          dataType: 2
        },
        success: (res) => {
          let rows = res.objx || [];
          rows.forEach((value) => {
            value.leaf = !value.hasChild;
          });
          if (node.level === 0) {
            rows.push({
              id: "other",
              menuKindCode: "other",
              name: "其他分类",
              leaf: true
            })
            if (rows.length > 0) {
              this.$nextTick(() => {
                let firstNode = node.childNodes[0];
                if (rows[0].hasChild) {
                  firstNode.expand();
                }
                this.$refs.tree.setCurrentKey(firstNode.data);
                this.handleNodeClick(firstNode.data, firstNode, this);
              });
            }
          }
          resolve(rows);
        },
      });
    },
    handleNodeData(node) {
      this.currentFormType = node ? node.data : null;
      this.currentNode = node;
    },
    handleFormDesignClose() {
      this.formDesTabs = "first";
      this.showFormScriptList = false;
    },
    openProjectTagDialog3() {
      this.showProjectTagDialog3 = true;
    },
    confirmProjectTagDialog3(rows) {
      this.checkTags = rows;
    },
    getTabNames() {
      return this.checkTags.map((item) => item.tagName).join(",");
    },
    jsonImport() {
      this.$jsonImport({
        saveUrl: USER_PREFIX + "/form_develop/importFormTemplate",
        showResult: true,
        resultColumns: [
          {title: this.$t1("模板名称"), field: "formName", width: 200},
          {title: this.$t1("模板编码"), field: "formCode", width: 200},
          {
            title: this.$t1("结果信息"),
            field: "impReturnMsg",
            width: 300,
            showOverflow: false,
            slots: {
              default: ({row}, h) => {
                let impReturnMsg = row.impReturnMsg;
                let items = impReturnMsg
                  .split(";")
                  .filter((item) => !!item && !!item.trim())
                  .map((item) => {
                    return h("p", {}, `${item.trim()};`);
                  });
                return h("div", {}, items);
              },
            }
          },
        ],
        callback: () => {
          this.searchEvent();
        },
      });
    },
    jsonExport() {
      this.$jsonExport({
        title: "表单模板",
        targetRef: "table-m1",
        url: USER_PREFIX + "/form_develop/exportFormTemplate",
        abcEnabled: true,
        editAuth: this.currentFormType.editAuth,
        selectTypeAuth: this.currentFormType.selectTypeAuth,
      });
    },
    getBdEnv() {
      getBdFlag({
        success: (res) => {
          this.isDev = res.objx === 1;
        },
      });
    },
  },
};
export default modules;
