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 projectTagDialog from "@base/views/user/project_tag/dialog.vue";
import MenuKindDialog from "@base/views/bd/setting/menu_kind/dialog.vue";
import editView from "@base/views/bd/setting/form_script/edit1.vue";
import { treeScollx } from "@base/utils/global";
import { getBdFlag } from "@base/api/user";
import { getJsxBtn, getJsxStatus } from "@base/views/bd/setting/utils/index";
import formVersionButton from "@base/views/bd/setting/formVersion/link.vue";

let modules = {};
modules = {
  name: "form_script:list1",
  components: {
    projectTagView,
    projectTagAddButton,
    projectTagDeleteButton,
    tableForm,
    projectTagDialog,
    MenuKindDialog,
    editView,
    formVersionButton,
  },
  data() {
    return {
      activeName: "second",
      dataId: 0,
      showEdit: false,
      vxeOption: {},
      formData: {},
      defaultProps: {
        label: "name", //这里是树结构中需显示的数据（即接口返回的需展示在页面上的参数）
        children: [],
        isLeaf: "leaf",
      },
      currentFormType: {},
      addProjectTagOption: {
        url: USER_PREFIX + `/formScript/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 + `/formScript/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,
    };
  },
  computed: {
    currentMenuKindId() {
      return this.currentFormType?.id || null;
    },
    currentMenuKindName() {
      return this.currentFormType?.name || null;
    },
    otherFlag() {
      return this.currentFormType?.menuKindCode === "other";
    },
  },
  mounted() {
    treeScollx({ target: this, type: "default" });
    this.getBdEnv();
    this.initTableList();
  },
  methods: {
    searchEvent() {
      this.$refs["table-m1"].commitProxy("reload");
    },
    resetEvent() {
      this.formData = {};
      this.checkTags = [];
      this.$refs["table-m1"].commitProxy("reload");
    },
    openEditDialog(row) {
      /*this.dataId = !id || typeof id === 'object' ? 0 : id;
      this.activeName = 'first';
      this.$openEditView('showEdit');*/

      let dataId = row?.id || 0;
      if (!dataId) {
        this.dataId = dataId;
        this.activeName = "first";
        this.$openEditView("showEdit");
      } else {
        this.$refs.xTabs.openEditTab(row);
      }
    },
    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,
        scriptType: 1,
      };
    },
    initTableList() {
      let that = this;
      let tableOption = {
        vue: this,
        tableRef: "table-m1",
        tableName: "bd_form_script_list1-m1",
        path: () => {
          let url = USER_PREFIX + "/formScript/listPage";
          if (this.otherFlag) {
            url = USER_PREFIX + "/formScript/listOtherPage";
          }
          return url;
        },
        param: () => {
          return this.getSearchParam();
        },
        columns: [
          { type: "checkbox", width: 48, resizable: false, fixed: "left" },
          {
            title: this.$t1("脚本名称"),
            field: "scriptName",
            width: 180,
            fixed: "left",
          },
          {
            title: this.$t1("项目标签"),
            field: "tag",
            width: 250,
            slots: { default: "tag" },
            params: {
              exportVal: ({ row }) => {
                if (row.formScriptTagDTOs) {
                  return row.formScriptTagDTOs
                    .map((item) => item.tagName)
                    .join(",");
                }
              },
            },
          },
          {
            title: this.$t1("脚本编码"),
            field: "scriptCode",
            width: 180,
          },
          { title: this.$t1("表单分类"), field: "menuKindName", width: 150 },
          {
            title: this.$t1("表单模板编码"),
            field: "formCode",
            width: 150,
          },
          {
            title: this.$t1("Url路径"),
            field: "url",
            width: 200,
            slots: {
              default: ({ row }) => {
                return `/${row.formCode}/${row.scriptCode}`;
              },
            },
          },
          {
            title: this.$t1("脚本说明"),
            field: "scriptRemark",
            width: 250,
          },
          {
            title: this.$t1("自定义URL"),
            field: "uri",
            width: 250,
          },
          {
            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("禁用"));
                }
              },
            },
          },
          {
            field: "transactions",
            title: this.$t1("开启事务"),
            width: 150,
            slots: {
              default: ({ row }) => {
                if (row.transactions === 1) {
                  return getJsxStatus(null, this.$t1("是"));
                } else {
                  return getJsxStatus("s-3", this.$t1("否"));
                }
              },
            },
          },
          { field: "serviceName", title: this.$t1("服务名"), width: 150 },
          { field: "version", title: this.$t1("版本号"), width: 150 },
          {
            field: "sid",
            title: this.$t1("唯一标识"),
            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: 100,
            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: "scriptName",
            type: "input",
            common: true,
          },
          {
            title: this.$t1("脚本编码"),
            field: "scriptCode",
            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: "scriptRemark",
            type: "input",
            common: true,
          },
          {
            title: this.$t1("脚本"),
            field: "script",
            type: "input",
            common: true,
          },
          {
            title: this.$t1("表单模板编码"),
            field: "formCode",
            type: "input",
            common: true,
          },
          {
            title: this.$t1("项目标签"),
            field: "tag",
            type: "input",
            common: true,
            slot: "tag",
          },
          {
            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;
      });
    },
    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: 3,
        },
        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;
    },
    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/importFormScript",
        showResult: true,
        resultColumns: [
          {
            title: this.$t1("脚本名称"),
            field: "scriptName",
            width: 180,
            fixed: "left",
          },
          {
            title: this.$t1("脚本编码"),
            field: "scriptCode",
            width: 180,
          },
        ],
        callback: () => {
          this.searchEvent();
        },
      });
    },
    jsonExport() {
      this.$jsonExport({
        title: "逻辑脚本",
        targetRef: "table-m1",
        url: USER_PREFIX + "/form_develop/exportFormScript",
        abcEnabled: true,
        editAuth: this.currentFormType.editAuth,
        selectTypeAuth: this.currentFormType.selectTypeAuth,
      });
    },
    getBdEnv() {
      getBdFlag({
        success: (res) => {
          this.isDev = res.objx === 1;
        },
      });
    },
  },
};
export default modules;
