<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      @submit.native.prevent
    >
      <el-form-item label="按钮组名" prop="btnGroupName">
        <el-input
          v-model="queryParams.btnGroupName"
          placeholder="请输入按钮组名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="按钮名称" prop="btnName">
        <el-input
          v-model="queryParams.btnName"
          placeholder="请输入按钮名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:menu:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
          >展开/折叠</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="btnList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        prop="btnGroupName"
        label="按钮组名称"
        :show-overflow-tooltip="true"
        width="160"
        align="center"
      ></el-table-column>
      <el-table-column prop="btnIcon" label="图标" align="center" width="100">
        <template v-if="scope.row.btnIcon" slot-scope="scope">
          <svg-icon :icon-class="scope.row.btnIcon" />
        </template>
      </el-table-column>
      <el-table-column
        prop="btnName"
        label="按钮名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="btnSort"
        label="排序"
        align="center"
        width="60"
      ></el-table-column>
      <el-table-column
        prop="btnHasPermi"
        label="权限标识"
        :show-overflow-tooltip="true"
        align="center"
      ></el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-dropdown>
            <el-button type="warning" plain size="small">
              处理<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                ><el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:menu:edit']"
                  >修改</el-button
                ></el-dropdown-item
              >
              <el-dropdown-item v-if="scope.row.btnType == 'DIRECTORY'"
                ><el-button
                  size="mini"
                  type="text"
                  icon="el-icon-plus"
                  @click="handleAdd(scope.row)"
                  v-hasPermi="['system:menu:add']"
                  >新增</el-button
                ></el-dropdown-item
              >
              <el-dropdown-item
                ><el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:menu:remove']"
                  >删除</el-button
                ></el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>

          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:menu:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:menu:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:menu:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form
        ref="btnGroupFormRef"
        :model="btnGroupFormData"
        :rules="rules"
        label-width="100px"
      >
        <el-row type="flex" style="flex-wrap: wrap">
          <el-col :span="12">
            <el-form-item label="上级按钮" prop="btnParentId">
              <treeselect
                v-model="btnGroupFormData.btnParentId"
                :options="menuOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择上级按钮"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="btnGroupFormData.btnParentId == 0">
            <el-form-item label="按钮组名" prop="btnGroupName">
              <el-input
                v-model="btnGroupFormData.btnGroupName"
                placeholder=""
                size="normal"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="按钮名" prop="btnName">
              <el-input
                v-model="btnGroupFormData.btnName"
                placeholder=""
                size="normal"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="按钮图标" prop="btnIcon">
              <el-popover
                placement="bottom-start"
                width="460"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              >
                <IconSelect
                  ref="iconSelect"
                  @selected="selected"
                  :active-icon="btnGroupFormData.icon"
                />
                <el-input
                  slot="reference"
                  v-model="btnGroupFormData.icon"
                  placeholder="点击选择图标"
                  readonly
                >
                  <svg-icon
                    v-if="btnGroupFormData.btnIcon"
                    slot="prefix"
                    :icon-class="btnGroupFormData.btnIcon"
                    style="width: 25px"
                  />
                  <i
                    v-else
                    slot="prefix"
                    class="el-icon-search el-input__icon"
                  />
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="btnSort">
              <el-input-number
                v-model="btnGroupFormData.btnSort"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识" prop="btnIcon">
              <el-input
                v-model="btnGroupFormData.btnHasPermi"
                placeholder="请输入权限标识"
                maxlength="100"
              />
              <span slot="label">
                <el-tooltip
                  content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"
                  placement="top"
                >
                  <i class="el-icon-question"></i>
                </el-tooltip>
                权限字符
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="按钮类型" prop="btnType">
              <el-select
                v-model="btnGroupFormData.btnType"
                placeholder="请选择按钮类型"
                filterable
              >
                <el-option
                  v-for="item in btnTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 非目录 -->
          <template v-if="btnGroupFormData.btnType != 'DIRECTORY'">
            <el-col
              :span="12"
              v-show="
                btnGroupFormData.btnType != 'DIRECTORY' &&
                btnGroupFormData.btnType != 'OUTLINK' &&
                btnGroupFormData.btnType != 'INNERLINK'
              "
            >
              <el-form-item label="绑定表单" prop="btnFormKey">
                <el-select
                  v-model="btnGroupFormData.btnFormKey"
                  placeholder="请选择表单"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in formOptions"
                    :key="item.fId"
                    :label="item.dfName"
                    :value="item.fId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-show="btnGroupFormData.btnType == 'INITIATED'">
              <el-form-item label="执行流程" prop="btnProcessKey">
                <el-select
                  v-model="btnGroupFormData.btnProcessKey"
                  placeholder="请选择执行流程"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in processOptions"
                    :key="item.processKey"
                    :label="item.processName"
                    :value="item.processKey"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col
              :span="12"
              v-show="
                btnGroupFormData.btnType == 'INSERT' ||
                btnGroupFormData.btnType == 'UPDATE' ||
                btnGroupFormData.btnType == 'DELETE'
              "
            >
              <el-form-item label="绑定表格" prop="btnTableKey">
                <el-select
                  v-model="btnGroupFormData.btnTableKey"
                  placeholder="请选择表格"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in tableOptions"
                    :key="item.tableKey"
                    :label="item.dtName"
                    :value="item.tableKey"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-show="btnGroupFormData.btnType == 'EXECUTE'">
              <el-form-item label="绑定脚本" prop="btnScriptKey">
                <el-select
                  v-model="btnGroupFormData.btnScriptKey"
                  placeholder="请选择绑定节点"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in scriptOptions"
                    :key="item.scriptKey"
                    :label="item.scriptName"
                    :value="item.scriptKey"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col
              :span="24"
              v-show="
                btnGroupFormData.btnType == 3 || btnGroupFormData.btnType == 7
              "
            >
              <el-form-item label="跳转路由" prop="btnParams">
                <el-input
                  v-model="btnGroupFormData.btnParams"
                  placeholder="请输入跳转的路由地址"
                  size="normal"
                ></el-input>
              </el-form-item>
            </el-col>
            <!-- <div class="table-wrap">
              <span class="title mb10">添加query参数</span>
              <el-table
                :data="queryTableData"
                border
                stripe
                style="width: 100%"
              >
                <el-table-column align="center" type="index" width="50" />
                <el-table-column
                  v-for="col in columns"
                  :prop="col.prop"
                  :key="col.prop"
                  :label="col.label"
                  width="150"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row[col.prop]"
                      placeholder=""
                      size="normal"
                      clearable
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteQueryItem(scope.$index)"
                      >删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div> -->
            <el-col :span="24">
              <!-- 
              v-show="
                btnGroupFormData.btnType != 3 && btnGroupFormData.btnType != 7
              " -->
              <!-- <el-form-item label="" prop="btnParams"> -->
              <div class="filter-table-wrap" style="width: 100%">
                <span class="title mb10"
                  >{{
                    btnGroupFormData.btnType != 3 &&
                    btnGroupFormData.btnType != 7
                      ? "公共"
                      : "query"
                  }}参数</span
                >
                <el-table :data="commonFieldData" style="width: 100%">
                  <el-table-column label="序号" type="index" width="50">
                  </el-table-column>
                  <el-table-column
                    prop="fieldName"
                    label="字段名"
                    width="150"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <el-select
                        v-model="scope.row.fieldName"
                        placeholder="请选择"
                      >
                        <el-option
                          v-for="item in rootFieldInfo.fieldList"
                          :key="item.value"
                          :label="item.value"
                          :value="item.key"
                        >
                          <span style="float: left">{{ item.value }}</span>
                          <span
                            style="
                              float: right;
                              color: #8492a6;
                              font-size: 13px;
                            "
                            >{{ item.key }}</span
                          >
                        </el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="flagValue"
                    label="默认值"
                    width="150"
                    align="center"
                  >
                    <template slot="header" slot-scope="">
                      默认值
                      <el-tooltip
                        class="item"
                        effect="dark"
                        content="不设置默认值时,默认为当前行的该字段"
                        placement="top-start"
                      >
                        <i class="el-icon-info"></i>
                      </el-tooltip>
                    </template>
                    <template slot-scope="scope">
                      <!-- <el-button
                          type="info"
                          size="small"
                          icon="el-icon-edit"
                          @click="editFlagHandler(scope.row, scope.$index)"
                        >
                        </el-button> -->
                      <el-input
                        v-model="scope.row.fieldValue"
                        placeholder="请输入默认值"
                        size="normal"
                        clearable
                      >
                      </el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="danger"
                        icon="el-icon-delete"
                        @click="deleteFilterItem(scope.$index)"
                        >删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-button
                  type="primary"
                  class="inline-large-button mb10"
                  icon="el-icon-plus"
                  size="mini"
                  style="width: 100%"
                  @click="addFilterHandler"
                >
                  添加参数
                </el-button>
              </div>
              <!-- </el-form-item> -->
            </el-col>
          </template>
          <!-- 按钮隐藏条件 -->
          <div class="filter-table-wrap" style="width: 100%">
            <span class="title mb10">按钮隐藏条件</span>
            <el-table :data="btnHidenCondtionData" style="width: 100%">
              <el-table-column label="序号" type="index" width="50">
              </el-table-column>
              <el-table-column
                prop="fieldName"
                label="字段名"
                width="150"
                align="center"
              >
                <template slot-scope="scope">
                  <el-select v-model="scope.row.fieldName" placeholder="请选择">
                    <el-option
                      v-for="item in rootFieldInfo.fieldList"
                      :key="item.value"
                      :label="item.value"
                      :value="item.key"
                    >
                      <span style="float: left">{{ item.value }}</span>
                      <span
                        style="float: right; color: #8492a6; font-size: 13px"
                        >{{ item.key }}</span
                      >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                prop="mark"
                label="符号"
                width="150"
                align="center"
              >
                <template slot-scope="scope">
                  <el-select v-model="scope.row.mark" placeholder="请选择">
                    <el-option
                      v-for="item in markList"
                      :key="item"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                prop="refValue"
                label="参考值"
                width="150"
                align="center"
              >
                <template slot-scope="scope">
                  <!-- <el-button
                          type="info"
                          size="small"
                          icon="el-icon-edit"
                          @click="editFlagHandler(scope.row, scope.$index)"
                        >
                        </el-button> -->
                  <el-input
                    v-model="scope.row.refValue"
                    placeholder="请输入默认值"
                    size="normal"
                    clearable
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-delete"
                    @click="deleteBtnHidenCondition(scope.$index)"
                    >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button
              type="primary"
              class="inline-large-button mb10"
              icon="el-icon-plus"
              size="mini"
              style="width: 100%"
              @click="addBtnHidenCondition"
            >
              添加参数
            </el-button>
          </div>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBtn,
  addBtn,
  getBtn,
  updateBtn,
  delBtn,
  checkBtn,
} from "@/api/system/btn";
import { listForm } from "@/api/dragform/form";
import { listProcess } from "@/api/bpmprocess/process";
import { listTable } from "@/api/dragform/tableList";
import { listScript } from "@/api/bpmprocess/process";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";
import { v4 as uuidv4 } from "uuid";
import { dragTableInfo } from "@/api/tablelist/commonTable";
import { camelCase } from "@/utils";
import { mark } from "@/components/updateModule/k-form-design/lib/k-form-design.common";
export default {
  name: "ExcuteBtnMange",
  dicts: ["sys_show_hide", "sys_normal_disable"],
  components: { Treeselect, IconSelect },
  data() {
    return {
      // 记录编辑状态
      editType: true, //true:新增   false:修改
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 菜单表格树数据
      btnList: [],
      // 菜单树选项
      menuOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        btnParentId: 0,
        btnGroupName: "",
        pageNum: 1,
        pageSize: 10,
        btnName: "",
      },
      // btnGroupName: "",
      // 分页数据
      total: 0,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        btnParentId: [
          { required: true, message: "上级按钮不能为空", trigger: "change" },
        ],
        btnGroupName: [
          { required: true, message: "按钮组名不能为空", trigger: "blur" },
        ],
        btnSort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
        btnType: [
          {
            required: true,
            message: "按钮类型不能为空",
            trigger: "change",
          },
        ],
        btnFormKey: [
          {
            validator: this.checkBtnFormKey,
            trigger: "change",
          },
        ],
        btnProcessKey: [
          {
            validator: this.checkBtnProcessKey,
            trigger: "change",
          },
        ],
        btnScriptKey: [
          {
            validator: this.checkBtnScriptKey,
            trigger: "change",
          },
        ],
      },
      // 按钮组表单数据
      btnGroupFormData: {
        btnGroupName: "", //按钮组名
        btnParentId: "", //父节点id
        btnName: "", //按钮显示的文字
        btnIcon: "", //按钮图标
        btnType: "DIRECTORY", //0:操作按钮，1，其他，2表单，3内链，4流程，5脚本, 6,目录, 7:外链
        btnFormKey: null, //表单唯一标识
        btnProcessKey: "", //流程唯一标识
        btnTableKey: "", //表格唯一标识
        btnScriptKey: "", //脚本唯一标识
        btnShowCondition: "", //按钮显示条件
        btnParams: "", //操作参数
        btnHasPermi: "", //权限字符
        btnSort: 0, //按钮顺序
        btnKey: "",
      },
      conditionBtnData: [],
      btnTypeOptions: [
        // {
        //   value: 0,
        //   label: "操作按钮",
        // },
        // {
        //   value: 1,
        //   label: "其它",
        // },
        // {
        //   value: 2,
        //   label: "表单",
        // },
        // {
        //   value: 3,
        //   label: "内链",
        // },
        // {
        //   value: 4,
        //   label: "流程",
        // },
        // {
        //   value: 5,
        //   label: "脚本",
        // },
        {
          // value: "6",
          value: "DIRECTORY",
          label: "目录",
        },
        {
          // value: "7",
          value: "OUTLINK",
          label: "外链",
        },
        {
          // value: "3",
          value: "INNERLINK",
          label: "内链",
        },
        {
          value: "INSERT",
          label: "新增",
        },
        {
          // value: "8",
          value: "UPDATE",
          label: "修改",
        },
        {
          value: "DELETE",
          label: "删除",
        },

        {
          value: "EXECUTE",
          label: "执行脚本",
        },
        {
          value: "INITIATED",
          label: "发起流程",
        },
      ],
      formOptions: [],
      tableOptions: [],
      processOptions: [],
      scriptOptions: [],
      // 普遍字段参数
      commonFieldData: [
        // {
        //   fieldName: "",
        //   fieldValue: "",
        // },
      ],
      // 按钮隐藏条件
      btnHidenCondtionData: [
        // {
        //   fieldName: "", //参考字段
        //   mark: "", //参考符号
        //   refValue: "", //参考值
        // },
      ],
      rootFieldInfo: {
        tableName: "",
        fieldList: [],
      },
      queryTableData: [
        {
          key: "",
          value: "",
        },
      ],
      columns: [
        {
          label: "参数名",
          prop: "key",
        },
        {
          label: "值",
          prop: "value",
        },
      ],
      markList: [">", "<", "=", ">=", "<=", "!="],
    };
  },
  // created() {
  //   this.getList();
  //   this.initFormSubData();
  // },
  mounted() {
    this.getList();
    this.initFormSubData();
  },
  methods: {
    // 自定义字段校验
    checkBtnFormKey(rule, value, callback) {
      let { btnType } = this.btnGroupFormData;
      console.log(btnType);
      if (btnType == "INSERT" || btnType == "UPDATE") {
        if (!value) {
          callback(new Error("请绑定表单"));
        }
      }

      callback();
    },
    checkBtnProcessKey(rule, value, callback) {
      let { btnType } = this.btnGroupFormData;
      console.log(btnType);
      if (btnType == "EXECUTE" || btnType == "INITIATED") {
        if (!value) {
          callback(new Error("请绑定流程"));
        }
      }
      callback();
    },
    checkBtnScriptKey(rule, value, callback) {
      let { btnType } = this.btnGroupFormData;
      console.log(btnType);
      if (btnType == "EXECUTE") {
        if (!value) {
          callback(new Error("请绑定脚本"));
        }
      }
      callback();
    },
    // 删除公共传参
    deleteFilterItem(index) {
      this.commonFieldData.splice(index, 1);
    },
    // 删除query参数
    deleteQueryItem(index) {
      this.queryTableData.splice(index, 1);
    },
    // 添加公共传参
    addFilterHandler() {
      if (this.rootFieldInfo.fieldList.length == 0) {
        this.$message.error("请先将按钮组绑定给表格");
        return;
      }
      this.commonFieldData.push({
        fieldName: "",
        fieldValue: "",
      });
    },
    // 添加按钮隐藏条件
    addBtnHidenCondition() {
      if (this.rootFieldInfo.fieldList.length == 0) {
        this.$message.error("请先将按钮组绑定给表格");
        return;
      }
      this.btnHidenCondtionData.push({
        fieldName: "", //参考字段
        mark: "", //参考符号
        refValue: "", //参考值
      });
    },
    // 删除按钮隐藏条件
    deleteBtnHidenCondition(index) {
      this.btnHidenCondtionData.splice(index, 1);
    },
    // 获取根节点绑定表格的字段数据
    async getRootFieldInfo(btnKey) {
      let res = await checkBtn({ btnKey });
      if (res.code == 200) {
        if (res.rows[0]?.tableKey) {
          let tableInfo = await dragTableInfo({
            queryMap: { tableKey: res.rows[0].tableKey },
          });
          this.rootFieldInfo.fieldList = this.columnsHandler(
            JSON.parse(tableInfo.data.resultMap.template.dtColumnName)
          );
        }
      }
    },
    // 处理列表信息
    columnsHandler(columns) {
      let resArr = [];
      columns.forEach((item) => {
        for (const key in item) {
          let tempObj = {};
          tempObj.key = camelCase(key);
          tempObj.value = item[key];
          resArr.push(tempObj);
        }
      });
      return resArr;
    },
    // 给所有节点设置根节点key
    setRootBtnKey(rows, rootKey = "") {
      if (rows.length == 0) {
        return rows;
      }
      for (let i = 0; i < rows.length; i++) {
        let row = rows[i];
        if (row.btnParentId == 0) {
          row.rootKey = row.btnKey;
        } else {
          row.rootKey = rootKey;
        }
        if (row.children.length != 0) {
          row.children = this.setRootBtnKey(row.children, row.rootKey);
        }
      }
      return rows;
    },
    // 选择图标
    selected(name) {
      this.btnGroupFormData.btnIcon = name;
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      if (this.queryParams.btnGroupName || this.queryParams.btnName) {
        this.queryParams.btnParentId = null;
      } else {
        this.queryParams.btnParentId = 0;
      }
      listBtn(this.queryParams).then((response) => {
        let res = this.setRootBtnKey(response.rows);
        this.btnList = res;
        this.loading = false;
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      // if (node.children && !node.children.length) {
      //   delete node.children;
      // }
      return {
        id: node.id,
        label: node.btnName,
        children: node.children,
      };
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      listBtn({ ...this.queryParams, isEnablePaging: false }).then(
        (response) => {
          this.menuOptions = [];
          const btnTemp = {
            id: 0,
            btnGroupName: "新建按钮组",
            btnName: "新建按钮组",
            children: [],
            btnType: "DIRECTORY",
          };

          let _this = this;
          console.log(response.rows);
          let res = response.rows.filter((node) => _this.getAllMenuList(node));
          btnTemp.children.push(...res);
          this.menuOptions.push(btnTemp);
        }
      );
    },
    // 只保留目录
    getAllMenuList(node) {
      // 如果当前节点的btnType等于6，则保留该节点，否则删除该节点
      if (node.btnType == "DIRECTORY") {
        if (Array.isArray(node.children) && node.children.length != 0) {
          // 递归遍历子节点，并删除所有btnType不等于DIRECTORY的子节点
          let _this = this;
          node.children = node.children.filter((child) =>
            _this.getAllMenuList(child)
          );
        }
        return node;
      } else {
        return false;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.btnGroupFormData = {
        btnGroupName: "", //按钮组名
        btnParentId: "", //父节点id
        btnName: "", //按钮显示的文字
        btnIcon: "", //按钮图标
        btnType: "DIRECTORY", //0:操作按钮，1，其他，2表单，3跳转，4流程，5脚本
        btnFormKey: null, //表单唯一标识
        btnProcessKey: "", //流程唯一标识
        btnTableKey: "", //表格唯一标识
        btnScriptKey: "", //脚本唯一标识
        btnShowCondition: "", //按钮显示条件
        btnParams: "", //操作参数
        btnHasPermi: "", //权限字符
        btnSort: 0, //按钮顺序
        btnKey: "",
      };
      this.commonFieldData = [];
      this.resetForm("btnGroupFormRef");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      console.log(this.queryParams);
      this.handleQuery();
    },
    /** 新增按钮操作 */
    async handleAdd(row) {
      this.reset();
      this.getTreeselect();
      this.editType = row ? true : false;
      if (row != null && row.id) {
        //在已知节点下新增
        await this.getRootFieldInfo(row.rootKey);
        this.btnGroupFormData.btnParentId = row.id;
        this.title = "新增按钮";
      } else {
        this.btnGroupFormData.btnParentId = 0;
        this.title = "添加按钮组";
      }
      this.open = true;
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      this.editType = false;
      //在已知节点下新增
      await this.getRootFieldInfo(row.rootKey);
      getBtn(row.id).then((response) => {
        let { btnType, btnParams, btnShowCondition } = response.data;
        if ((btnType == 3 || btnType == 7) && btnParams) {
          //内链或外链
          let tempObj = JSON.parse(btnParams);
          response.data.btnParams = tempObj.url;
          this.commonFieldData = JSON.parse(tempObj.commonFieldData) || [];
        } else {
          btnParams && (this.commonFieldData = JSON.parse(btnParams) || []);
        }
        this.btnHidenCondtionData = [];
        if (btnShowCondition) {
          this.btnHidenCondtionData = JSON.parse(btnShowCondition);
        }
        this.btnGroupFormData = response.data;
        this.open = true;
        this.title = "修改按钮";
      });
    },
    // 校验复杂逻辑表单数据
    myValidate(formData) {
      // 校验按钮名和按钮必须填一个
      let res = {};
      res.flag = true;
      let nameOrIcon = !!formData.btnName || !!formData.btnIcon;
      if (!nameOrIcon) {
        res.flag = false;
        res.msg = "按钮名称和图标,至少需要有一个!";
        return res;
      }
      return res;
    },
    // 获取公共数据
    // getCommonData(list) {
    //   if (list.length == 0) return '';

    // },
    /** 提交按钮 */
    submitForm() {
      this.$refs["btnGroupFormRef"].validate(async (valid) => {
        console.log(this.btnGroupFormData);
        console.log(valid);
        if (valid) {
          let validateRes = this.myValidate(this.btnGroupFormData);
          if (!validateRes.flag) {
            this.$message.error(validateRes.msg);
            return;
          }
          // 获取公共参数
          // let commonData=this.getCommonData(this.commonFieldData)
          if (
            this.btnGroupFormData.btnType != 3 &&
            this.btnGroupFormData.btnType != 7
          ) {
            this.btnGroupFormData.btnParams = JSON.stringify(
              this.commonFieldData
            );
          } else {
            let tempObj = {};
            tempObj.url = this.btnGroupFormData.btnParams;
            tempObj.commonFieldData = JSON.stringify(this.commonFieldData);
            this.btnGroupFormData.btnParams = JSON.stringify(tempObj);
          }
          this.btnGroupFormData.btnShowCondition = this.getHidenConditions();
          console.log(this.btnGroupFormData.btnShowCondition);
          if (this.editType) {
            // 新增按钮组
            this.btnGroupFormData.btnKey = uuidv4();
            let res = await addBtn(this.btnGroupFormData);
            if (res.code == 200) {
              this.$message.success("添加成功");
            } else {
              this.$message.error("网络异常,请稍后添加");
            }
          } else {
            // 修改按钮组
            let res = await updateBtn(this.btnGroupFormData);
            if (res.code == 200) {
              this.$message.success("修改成功");
            } else {
              this.$message.error("网络异常,请稍后修改");
            }
          }

          this.getList();
          this.open = false;
        }
      });
    },
    // 格式化按钮隐藏条件
    getHidenConditions() {
      console.log(this.btnHidenCondtionData);
      if (this.btnHidenCondtionData.length == 0) return "";
      let temp = this.btnHidenCondtionData.filter((item) => {
        return item.fieldName && item.mark && item.refValue;
      });
      if (temp.length > 0) {
        return JSON.stringify(temp);
      } else {
        return "";
      }
    },
    // 更新路由
    reloadRouter() {
      this.$store.dispatch("GenerateRoutes").then((accessRoutes) => {
        this.$router.addRoutes(accessRoutes); // 动态添加可访问路由表
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除名称为"' + row.btnGroupName + '"的数据项？')
        .then(function () {
          return delBtn(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 初始化表单辅助数据
    async initFormSubData() {
      try {
        //获取表单选项数据
        let formRes = await listForm({ isEnablePaging: false });
        if (formRes.code == 200) {
          formRes.rows.forEach((item) => {
            item.fId = item.fId.toString();
          });
          this.formOptions = formRes.rows;
        } else {
          this.$message.error("网络异常请稍后再试");
        }
        // 获取流程选项数据
        let processRes = await listProcess({ isEnablePaging: false });
        if (processRes.code == 200) {
          this.processOptions = [
            ...processRes.rows,
            {
              processKey: "unknown",
              processName: "未知流程",
            },
          ];
        } else {
          this.$message.error("网络异常请稍后再试");
        }
        // 获取表格选项数据
        let TableRes = await listTable({ isEnablePaging: false });
        if (TableRes.code == 200) {
          this.tableOptions = TableRes.rows;
        } else {
          this.$message.error("网络异常请稍后再试");
        }
        // 获取脚本选项数据
        let scriptRes = await listScript({ isEnablePaging: false });
        if (scriptRes.code == 200) {
          this.scriptOptions = scriptRes.rows;
        } else {
          this.$message.error("网络异常请稍后再试");
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 添加按钮条件
    addConditionHandler() {
      this.conditionBtnData.push({
        tableName: "",
        fieldName: "",
        condition: 1, //1:> 2:< 3:= 4:>= 5:<=
        flagValue: 0,
        fieldList: [],
      });
    },
  },
};
</script>
<style scoped lang="scss" scoped>
/* #app .sidebar-container .submenu-title-noDropdown:hover, #app .sidebar-container .el-submenu__title:hover {
    background-color: rgba(0, 0, 0, 0.06) !important;
}  */
.submenu-title-noDropdown:hover {
  background-color: linear-gradient(to right, blue, rgb(69, 118, 225));
}

.filter-table-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.table-wrap {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.title {
  font-weight: 600;
}
</style>
