<template>
  <div id="containt">
    <el-tabs v-model="activeName" class="tab-box">
      <el-tab-pane :label="$t1('常规2')" name="first">
        <component
          v-if="showWfContent && wfContent"
          :is="wfContent"
          visible-key="showWfContent"
          v-bind="param"
          :parent-target="_self"
          :defaultShowWfContent="true"
          :_viewType="1"
          @reload="$reloadHandle"
        ></component>
      </el-tab-pane>
      <el-tab-pane :label="$t1('我的流程2')" name="second">
        <div class="tree-box fl">
          <div class="tit">
            <b>{{ $t1("待办类型") }}</b>
          </div>
          <el-tree
            :props="defaultProps"
            :load="loadNode"
            node-key="uuid"
            ref="tree"
            highlight-current
            lazy
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            class="tree-list"
            icon-class="el-icon-arrow-down"
          ></el-tree>
        </div>
        <label id="labBtn">
          <div class="icon">
            <i class="el-icon-more"></i>
            <i class="el-icon-more"></i>
          </div>
        </label>
        <div class="main-right fr" style="padding-left: 6px">
          <div class="grid-height">
            <vxe-grid
              ref="table-m1"
              v-bind="vxeOption"
              @resizable-change="$vxeTableUtil.onColumnWitchChange"
              @custom="$vxeTableUtil.customHandle"
            >
              <template #form>
                <div class="clearfix screen-btns">
                  <div class="fl">
                    <base-table-export
                      :option="{
                        title: $t1('流程待办导出'),
                        targetRef: 'table-m1',
                      }"
                      :parent-target="_self"
                    />
                  </div>
                  <div class="fr">
                    <vxe-button
                      icon="el-icon-brush"
                      class="button-sty"
                      @click="resetEvent"
                      type="text"
                      status="primary"
                      plain
                      >{{ $t1("重置") }}
                    </vxe-button>
                    <vxe-button
                      status="warning"
                      icon="el-icon-search"
                      class="button-sty"
                      @click="searchEvent"
                    >
                      {{ $t1("搜索") }}
                    </vxe-button>
                  </div>
                </div>
                <vxe-form
                  ref="form"
                  class="screen-box"
                  title-width="92px"
                  title-align="right"
                  :data="formData"
                  @submit="searchEvent"
                  @reset="searchEvent"
                >
                  <vxe-form-item :title="$t1('待办类型') + ':'">
                    <template v-slot>
                      <el-input
                        v-model="checkNodeData.label"
                        size="small"
                        disabled
                      />
                    </template>
                  </vxe-form-item>
                  <vxe-form-item :title="$t1('流程主题') + ':'" field="name">
                    <template v-slot>
                      <el-input
                        v-model="formData.name"
                        size="small"
                        clearable
                      />
                    </template>
                  </vxe-form-item>
                  <vxe-form-item
                    :title="$t1('单据类型') + ':'"
                    field="objTypeName"
                  >
                    <template v-slot>
                      <el-input
                        class="search-input"
                        max="200"
                        v-model="formData.objTypeName"
                        @clear="
                          formData.objTypeCode = null;
                          $forceUpdate();
                        "
                        v-el-readonly
                        clearable
                      >
                        <i
                          slot="suffix"
                          class="el-input__icon el-icon-search"
                          @click="showWfObjConfigDialog = true"
                        ></i>
                      </el-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item :title="$t1('流程状态') + ':'" field="stat">
                    <template v-slot>
                      <el-select v-model="formData.stat" clearable>
                        <el-option
                          :value="1"
                          :label="$t1('审核中')"
                        ></el-option>
                        <el-option
                          :value="2"
                          :label="$t1('已完成')"
                        ></el-option>
                        <el-option
                          :value="3"
                          :label="$t1('已驳回')"
                        ></el-option>
                      </el-select>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item
                    :title="$t1('启动人') + ':'"
                    field="starterName"
                  >
                    <template v-slot>
                      <el-input
                        v-model="formData.starterName"
                        size="small"
                        clearable
                      />
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="启动时间:">
                    <template v-slot>
                      <el-date-picker
                        v-model="formData.startTime"
                        type="datetime"
                        placeholder=""
                        size="small"
                        clearable
                        value-format="yyyy-MM-dd HH:mm:ss"
                        :picker-options="
                          $baseStartPickerOptions(formData.endTime)
                        "
                      ></el-date-picker>
                      <span>-</span>
                      <el-date-picker
                        v-model="formData.endTime"
                        type="datetime"
                        placeholder=""
                        size="small"
                        clearable
                        value-format="yyyy-MM-dd HH:mm:ss"
                        default-time="23:59:59"
                        :picker-options="
                          $baseEndPickerOptions(formData.startTime)
                        "
                      ></el-date-picker>
                    </template>
                  </vxe-form-item>
                </vxe-form>
              </template>
            </vxe-grid>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t1('全部流程2')" name="third" v-if="flag == 1">
        <div class="grid-height">
          <vxe-grid
            ref="table-m2"
            v-bind="vxeOption2"
            @resizable-change="$vxeTableUtil.onColumnWitchChange"
            @custom="$vxeTableUtil.customHandle"
          >
            <template #form>
              <div class="clearfix screen-btns">
                <div class="fl">
                  <base-table-export
                    :option="{
                      title: $t1('流程待办导出'),
                      targetRef: 'table-m2',
                    }"
                    :parent-target="_self"
                  />
                </div>
                <div class="fr">
                  <vxe-button
                    icon="el-icon-brush"
                    class="button-sty"
                    @click="resetEvent2"
                    type="text"
                    status="primary"
                    plain
                    >{{ $t1("重置") }}
                  </vxe-button>
                  <vxe-button
                    status="warning"
                    icon="el-icon-search"
                    class="button-sty"
                    @click="searchEvent2"
                  >
                    {{ $t1("搜索") }}
                  </vxe-button>
                </div>
              </div>
              <vxe-form
                ref="form"
                class="screen-box"
                title-width="92px"
                title-align="right"
                :data="formData2"
                @submit="searchEvent2"
                @reset="searchEvent2"
              >
                <vxe-form-item :title="$t1('流程主题') + ':'" field="name">
                  <template v-slot>
                    <el-input v-model="formData2.name" size="small" clearable />
                  </template>
                </vxe-form-item>
                <vxe-form-item
                  :title="$t1('单据类型') + ':'"
                  field="objTypeName"
                >
                  <template v-slot>
                    <el-input
                      class="search-input"
                      max="200"
                      v-model="formData2.objTypeName"
                      @clear="
                        formData2.objTypeCode = null;
                        $forceUpdate();
                      "
                      v-el-readonly
                      clearable
                    >
                      <i
                        slot="suffix"
                        class="el-input__icon el-icon-search"
                        @click="showWfObjConfigDialog2 = true"
                      ></i>
                    </el-input>
                  </template>
                </vxe-form-item>
                <vxe-form-item :title="$t1('流程状态') + ':'" field="stat">
                  <template v-slot>
                    <el-select v-model="formData2.stat" clearable>
                      <el-option :value="1" :label="$t1('审核中')"></el-option>
                      <el-option :value="2" :label="$t1('已完成')"></el-option>
                      <el-option :value="3" :label="$t1('已驳回')"></el-option>
                    </el-select>
                  </template>
                </vxe-form-item>
                <vxe-form-item
                  :title="$t1('当前任务用户') + ':'"
                  field="candidateNames"
                >
                  <template v-slot>
                    <el-input
                      v-model="formData2.candidateNames"
                      size="small"
                      clearable
                    />
                  </template>
                </vxe-form-item>
              </vxe-form>
            </template>
          </vxe-grid>
        </div>
      </el-tab-pane>
    </el-tabs>
    <wfObjConfigDialog
      v-if="showWfObjConfigDialog"
      :visiable.sync="showWfObjConfigDialog"
      :type.sync="type"
      @confirm="confirmInsertWfObjConfig"
      :multi="false"
    ></wfObjConfigDialog>
    <wfObjConfigDialog
      v-if="showWfObjConfigDialog2"
      :visiable.sync="showWfObjConfigDialog2"
      :type="99"
      @confirm="confirmInsertWfObjConfig2"
      :multi="false"
    ></wfObjConfigDialog>
  </div>
</template>
<script>
import { treeScollx } from "@base/utils/global.js";
import wfObjConfigDialog from "../wf_obj_config/dialog.vue";

export default {
  name: "wf_manage:list2",
  components: { wfObjConfigDialog },
  created() {},
  async mounted() {
    treeScollx({ target: this, type: "default" });
    await this.initWfParam();
    this.initTableList();
    this.initRole();
  },
  data() {
    return {
      activeName: "second",
      // dataId: 0,
      // showEdit: false,
      vxeOption: {},
      formData: {},
      checkNode: {},
      defaultProps: {
        label: "label", //这里是树结构中需显示的数据（即接口返回的需展示在页面上的参数）
        children: [],
        isLeaf: "leaf",
      },
      wfObjTypes: [],
      showWfObjConfigDialog: false,
      showWfObjConfigDialog2: false,
      flag: 0,
      vxeOption2: {},
      formData2: {},

      param: {},
      wfContent: null,
      showWfContent: false,
    };
  },
  computed: {
    type() {
      return this.checkNode && this.checkNode.data
        ? this.checkNode.data.type
        : "";
    },
    checkNodeData() {
      return this.checkNode && this.checkNode.data ? this.checkNode.data : {};
    },
  },
  methods: {
    searchEvent() {
      this.$refs["table-m1"].commitProxy("reload");
    },
    resetEvent() {
      this.formData = {};
      this.$refs["table-m1"].commitProxy("reload");
    },

    initTableList() {
      let that = this;
      let paramColumns = this.wfParamDTOs.map((item) => {
        let flag = item.paramName == "单号";
        return {
          title: this.$t1(item.paramName),
          field: item.paramKey,
          width: 150,
          fixed: flag ? "left" : "",
          slots: flag
            ? {
                default: ({ row }) => {
                  return [
                    <div>
                      <a
                        href="javascript:void(0);"
                        class="a-link"
                        onclick={() => {
                          this.openEditDialog(row);
                        }}
                        style="font-weight:bold; text-decoration: underline"
                      >
                        <el-tooltip
                          class="item"
                          effect="dark"
                          content={this.$t1("查看")}
                          placement="top-start"
                        >
                          <span>{row.param1}</span>
                        </el-tooltip>
                      </a>
                    </div>,
                  ];
                },
              }
            : "",
        };
      });

      // let statuses = {0: '未启动', 1: '审核中', 2: '已完成', 3: '已驳回', 4: '中断'};
      var statuses = {
        0: [<el-tag type="warning">{this.$t1("未启动")}</el-tag>],
        1: [<el-tag>{this.$t1("审核中")}</el-tag>],
        2: [<el-tag type="success">{this.$t1("已完成")}</el-tag>],
        3: [<el-tag type="danger">{this.$t1("已驳回")}</el-tag>],
        4: [<el-tag type="danger">{this.$t1("中断")}</el-tag>],
      };
      let tableOption = {
        vue: this,
        tableRef: "table-m1",
        tableName: "user-wf-wf_manage-list-m2",
        path: USER_PREFIX + "/wf_info/listPage",
        param: () => {
          return {
            type: this.type,
            ...this.formData,
          };
        },
        /*config: {
          proxyConfig: {
            autoLoad: false
          }
        },*/
        columns: [
          { type: "checkbox", width: 48, resizable: false, fixed: "left" },
          {
            title: this.$t1("流程主题"),
            field: "name",
            width: 150,
            fixed: "left",
          },
          {
            title: this.$t1("单据类型"),
            field: "objTypeName",
            width: 150,
          },
          {
            title: this.$t1("启动人"),
            field: "starterName",
            width: 150,
          },
          {
            title: this.$t1("当前任务"),
            field: "taskName",
            width: 150,
          },
          {
            title: this.$t1("当前任务用户"),
            field: "candidateNames",
            width: 150,
          },
          {
            title: this.$t1("流程状态"),
            field: "stat",
            width: 150,
            slots: {
              default: ({ row }) => {
                let html = statuses[row.stat] || "";
                return html;
              },
            },
          },
          {
            title: this.$t1("启动时间"),
            field: "createDate",
            width: 150,
          },
          ...paramColumns,
          {
            width: 47,
            fixed: "right",
            title: "",
            sortable: false,
            slots: {
              default: ({ row }) => {
                return [
                  <a
                    href="javascript:void(0);"
                    class="a-link"
                    onclick={() => {
                      // this.$refs["wfIframeDialog"].wfEdit(row);
                      this.openEditDialog(row);
                    }}
                  >
                    <el-tooltip
                      enterable={false}
                      effect="dark"
                      content={this.$t1("查看")}
                      placement="top"
                      popper-class="tooltip-skin"
                    >
                      <i class="el-icon-edit" />
                    </el-tooltip>
                  </a>,
                ];
              },
            },
          },
        ],
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then((opts) => {
        this.vxeOption = opts;
      });
    },
    openEditDialog(row) {
      /*let a = 1;
      let url = row.url + '.vue';
      let id = row.objId;
      this.dataId = !id || typeof id == 'object' ? 0 : id;
      this.content = require('@/views' + url).default;*/
      // this.activeName = 'first';
      // this.$openEditView('showEdit');

      let id = row.objId;
      let wfDataId = !id || typeof id == "object" ? 0 : Number(id);

      if (row.url == "form") {
        let formCode = null;
        if (row.formCode) {
          formCode = row.formCode;
        } else {
          formCode = row.objTypeCode.substr(9);
        }
        this.param = {
          formCode: formCode,
          dataId: wfDataId,
        };
        let url = "/user/form/vform/render.vue";
        this.wfContent = require("@base/views" + url).default;
      } else {
        this.param = {
          _dataId: wfDataId,
        };
        let url = row.url + ".vue";
        this.wfContent = require("@/views" + url).default;
      }
      this.activeName = "first";
      this.$openEditView("showWfContent");
    },
    guid() {
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
        /[xy]/g,
        function (c) {
          var r = (Math.random() * 16) | 0,
            v = c == "x" ? r : (r & 0x3) | 0x8;
          return v.toString(16);
        }
      );
    },
    clearNodeClick() {
      /* this.formData.saleOrgId = '';
      this.formData.saleOrgName = '';
      this.$refs.tree.setCurrentKey();
      this.searchEvent(); */
    },
    handleNodeClick(data, node, v) {
      this.checkNode = node;
      this.formData.objTypeName = null;
      this.formData.objTypeCode = null;
      this.$forceUpdate();
      this.searchEvent();
    },
    // 异步树叶子节点懒加载逻辑
    loadNode(node, resolve) {
      if (!node || !node.data || node.data.type === undefined) {
        this.initNodeData(node, resolve);
        return;
      }
      this.$http({
        url: USER_PREFIX + "/wf_obj_config/getWfGroups",
        method: "post",
        data: {
          type: node.data.type,
        },
        success: (res) => {
          let rows = res.objx || [];
          rows.forEach((item) => {
            item.leaf = true;
            item.label = item.objTypeName + "(" + item.num + ")";
            item.type = node.data.type;
            item.uuid = this.guid();
          });
          resolve(rows);
        },
      });
    },
    initNodeData(node, resolve) {
      let data = [
        {
          uuid: -1,
          label: this.$t1("待审批的"),
          type: 0,
          leaf: true,
        },
        {
          uuid: -2,
          label: this.$t1("我发起的"),
          type: 1,
          leaf: true,
        },
        {
          uuid: -3,
          label: this.$t1("已审批的"),
          type: 2,
          leaf: true,
        },
        {
          uuid: -4,
          label: this.$t1("已完成的"),
          type: "3",
          leaf: true,
        },
        {
          uuid: -5,
          label: this.$t1("我转办的"),
          type: "4",
          leaf: true,
        },
      ];
      resolve(data);
      this.$nextTick(() => {
        if (node.childNodes.length) {
          let firstNode = node.childNodes[0];
          this.$refs.tree.setCurrentKey(firstNode.data.uuid);
          this.checkNode = firstNode;
          this.$forceUpdate();
          // this.handleNodeClick(firstNode.data, firstNode);
        }
      });
      /*this.$nextTick(() => {
        if (node.childNodes.length) {
          let nodedata = node.childNodes[0];
          nodedata.expanded = true;
          nodedata.loadData(arr => {
            if (arr.length) {
              setTimeout(() => {
                this.$refs.tree.setCurrentKey(arr[0].uuid);
                let node = this.$refs.tree.getNode(arr[0]);
                this.handleNodeClick(arr[0], node);
              }, 50);
            }
          });
        }
      });*/
    },
    confirmInsertWfObjConfig(rows) {
      if (rows.length) {
        let row = rows[0];
        this.$set(this.formData, "objTypeName", row.objTypeName);
        this.$set(this.formData, "objTypeCode", row.objTypeCode);
      }
    },
    async initWfParam() {
      return this.$http({
        url: USER_PREFIX + "/wf_param/list",
        method: `post`,
        data: {},
        success: (res) => {
          this.wfParamDTOs = res.objx || [];
        },
      });
    },
    //m2
    initRole() {
      this.$http({
        url: USER_PREFIX + "/user/currentUser",
        method: "post",
        success: (res) => {
          let userInfo = res.objx;
          this.getIsAdmin(userInfo);
        },
      });
    },
    getIsAdmin(userInfo) {
      this.$http({
        url: USER_PREFIX + "/userb/getUserRole",
        method: `post`,
        data: { id: userInfo.id },
        success: (res2) => {
          let rows = res2.objx || [];
          let codes = rows.map((row) => row.roleCode);
          if (codes.includes("superadmin") || codes.includes("wfadmin")) {
            this.flag = 1;
            setTimeout(() => {
              this.initTableList2();
            }, 200);
          }
        },
      });
    },
    searchEvent2() {
      this.$refs["table-m2"].commitProxy("reload");
    },
    resetEvent2() {
      this.formData2 = {};
      this.$refs["table-m2"].commitProxy("reload");
    },
    initTableList2() {
      let that = this;
      let paramColumns = this.wfParamDTOs.map((item) => {
        let flag = item.paramName == "单号";
        return {
          title: this.$t1(item.paramName),
          field: item.paramKey,
          width: 150,
          fixed: flag ? "left" : "",
          slots: flag
            ? {
                default: ({ row }) => {
                  return [
                    <div>
                      <a
                        href="javascript:void(0);"
                        class="a-link"
                        onclick={() => {
                          this.openEditDialog(row);
                        }}
                        style="font-weight:bold; text-decoration: underline"
                      >
                        <el-tooltip
                          class="item"
                          effect="dark"
                          content={this.$t1("查看")}
                          placement="top-start"
                        >
                          <span>{row.param1}</span>
                        </el-tooltip>
                      </a>
                    </div>,
                  ];
                },
              }
            : "",
        };
      });

      var statuses = {
        0: [<el-tag type="warning">{this.$t1("未启动")}</el-tag>],
        1: [<el-tag>{this.$t1("审核中")}</el-tag>],
        2: [<el-tag type="success">{this.$t1("已完成")}</el-tag>],
        3: [<el-tag type="danger">{this.$t1("已驳回")}</el-tag>],
        4: [<el-tag type="danger">{this.$t1("中断")}</el-tag>],
      };
      let tableOption = {
        vue: this,
        tableRef: "table-m2",
        tableName: "user-wf-wf_manage-list-m3",
        path: USER_PREFIX + "/wf_info/listPageAll",
        param: () => {
          return {
            ...this.formData2,
          };
        },
        columns: [
          { type: "checkbox", width: 48, resizable: false, fixed: "left" },
          {
            title: this.$t1("流程主题"),
            field: "name",
            width: 150,
            fixed: "left",
          },
          {
            title: this.$t1("单据类型"),
            field: "objTypeName",
            width: 150,
          },
          {
            title: this.$t1("启动人"),
            field: "starterName",
            width: 150,
          },
          {
            title: this.$t1("当前任务"),
            field: "taskName",
            width: 150,
          },
          {
            title: this.$t1("当前任务用户"),
            field: "candidateNames",
            width: 150,
          },
          {
            title: this.$t1("流程状态"),
            field: "stat",
            width: 150,
            slots: {
              default: ({ row }) => {
                let html = statuses[row.stat] || "";
                return html;
              },
            },
          },
          {
            title: this.$t1("启动时间"),
            field: "createDate",
            width: 150,
          },
          ...paramColumns,
          {
            width: 47,
            fixed: "right",
            title: "",
            sortable: false,
            slots: {
              default: ({ row }) => {
                return [
                  <a
                    href="javascript:void(0);"
                    class="a-link"
                    onclick={() => {
                      this.openEditDialog(row);
                    }}
                  >
                    <el-tooltip
                      enterable={false}
                      effect="dark"
                      content={this.$t1("查看")}
                      placement="top"
                      popper-class="tooltip-skin"
                    >
                      <i class="el-icon-edit" />
                    </el-tooltip>
                  </a>,
                ];
              },
            },
          },
        ],
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then((opts) => {
        this.vxeOption2 = opts;
      });
    },
    confirmInsertWfObjConfig2(rows) {
      if (rows.length) {
        let row = rows[0];
        this.$set(this.formData2, "objTypeName", row.objTypeName);
        this.$set(this.formData2, "objTypeCode", row.objTypeCode);
      }
    },
  },
};
</script>
