<template>
  <div class="row" style="padding: 35px; margin-bottom: 80px">
    <div
      class="col-12 row"
      style="
        background: #ffffff;
        border-radius: 3px;
        padding: 17px 20px;
        box-shadow: 0 3px 6px 1px rgba(188, 188, 188, 0.18);
      "
    >
      <div
        class="col-12 row font-18 items-center"
        style="color: #1f2225ff; border-bottom: 1px solid #c1b2e5"
      >
        <div
          v-if="state.pageType === 'create'"
          class="fl-py-sm"
          style="border-bottom: 4px solid #1f2225ff"
        >
          新增
        </div>
        <div
          v-if="state.pageType === 'edit'"
          class="fl-py-sm"
          style="border-bottom: 4px solid #1f2225ff"
        >
          修改
        </div>
        <div
          v-if="state.pageType === 'view'"
          class="fl-py-sm"
          style="border-bottom: 4px solid #1f2225ff"
        >
          查看
        </div>
        <div class="fl-ml-md">
          所属部门：<span v-for="(item, idx) in state.pathName" :key="idx">{{
            item + (idx === state.pathName.length - 1 ? "" : ">")
          }}</span>
        </div>
      </div>

      <div class="col-12 row fl-pt-md">
        <div class="search-item fl-mb-md row items-center col-3">
          <fln-form-item
            type="text"
            :config="{
              placeholder: '请输入岗位名',
              label: '*岗位名：',
              field: 'name',
            }"
            :val="state.formData.name"
            :disable="calcPageDisable()"
            @triggerValChange="handleValChange"
          />
        </div>

        <div class="search-item fl-mb-md row items-center col-3">
          <fln-form-item
            type="text"
            :config="{
              placeholder: '请输入岗位描述',
              label: '岗位描述：',
              field: 'remark',
            }"
            :val="state.formData.remark"
            :disable="calcPageDisable()"
            @triggerValChange="handleValChange"
          />
        </div>

        <div class="search-item fl-mb-md row items-center col-3">
          <fln-form-item
            type="colorpicker"
            :val="state.formData.color"
            :config="{
              label: '标签颜色：',
              field: 'color',
            }"
            :disable="calcPageDisable()"
            @triggerValChange="handleValChange"
          />
        </div>

        <div class="search-item fl-mb-md row items-center col-3">
          <fln-form-item
            type="checkbox"
            :val="state.formData.isOwner"
            :config="{
              field: 'isOwner',
              options: [
                {
                  label: '设为部门负责人',
                  value: 'true',
                },
              ],
            }"
            :disable="calcPageDisable()"
            @triggerValChange="handleValChange"
          />
        </div>
      </div>
    </div>

    <div
      class="col-12 row fl-mt-md"
      style="
        background: #ffffff;
        border-radius: 3px;
        padding: 17px 20px;
        box-shadow: 0 3px 6px 1px rgba(188, 188, 188, 0.18);
      "
    >
      <div class="fl-mb-md row col-12">
        <div class="col-2 font-20">
          *已选页面
          <span style="color: #1f2225ff">{{ state.selectedRows.length }}</span>
          个：
        </div>
        <n-spin
          class="fl-ml-md"
          v-if="state.dataLoading"
          v-show="state.dataLoading"
          description="获取中..."
          style="color: #1f2225ff"
        />
        <div v-else class="col-10 row">
          <div
            v-for="(select, idx) in state.selectedRows"
            :key="idx"
            class="fl-py-xs text-center fl-mr-sm fl-mb-sm row justify-center items-center"
            style="
              border-radius: 3px;
              min-width: 193px;
              background: #f7f7f7ff;
              border: solid 1px #e0e0e5ff;
            "
          >
            {{ select.name
            }}<close-circle-outlined
              v-if="!calcPageDisable()"
              class="fl-ml-md"
              @click="handleClearPage(select)"
            />
          </div>
        </div>
      </div>
      <div class="col-12 row">
        <div class="col-4">
          <div
            class="row overflow-auto"
            style="
              width: calc(100% - 20px);
              background: #f9f9fd;
              border-radius: 3px;
              padding: 16px 38px;
              max-height: 80vh;
            "
          >
            <div
              v-for="(row, rowIdx) in state.leftMenuData"
              :key="rowIdx"
              class="col-12 row fl-my-xs items-center"
            >
              <n-checkbox
                v-model:checked="row.select"
                @update:checked="(e) => handleLeftSelectCheckChange(e, row)"
              />
              <a
                :href="'#' + row.ID + row.name"
                class="fl-anchor fl-ml-sm"
                style="align-content: flex-start"
                @click.prevent="handleSelfHref(row.ID + row.name)"
                >{{ row.name }}</a
              >
              <div v-if="row.children" class="col-12 row justify-end">
                <div
                  v-for="(child, childIdx) in row.children"
                  :key="childIdx"
                  class="col-11 row items-center"
                >
                  <n-checkbox
                    v-model:checked="child.select"
                    @update:checked="
                      (e) => handleLeftSelectCheckChange(e, child)
                    "
                  />
                  <a
                    :href="'#' + child.ID + child.name"
                    @click.prevent="handleSelfHref(child.ID + child.name)"
                    class="fl-anchor fl-ml-sm"
                    style="align-content: flex-start"
                    >{{ child.name }}</a
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="overflow-auto col-8 row" style="max-height: 80vh">
          <div
            v-for="(row, rowIdx) in state.listData"
            :key="rowIdx"
            :id="row.ID + row.name"
            class="col-12 fl-mb-md row items-center fl-pb-xs"
            style="min-height: 40px"
          >
            <div
              class="col-12 row justify-between items-center fl-px-md"
              style="min-height: 40px; background: #46299dff"
              :style="{ borderRadius: row.showChild ? '3px 3px 0 0' : '3px' }"
            >
              <div class="color-white">
                <n-checkbox
                  v-model:checked="row.selected"
                  :disabled="calcPageDisable()"
                  @update:checked="(e) => handlePageSelectChange(e)"
                >
                </n-checkbox>
                {{ row.name }}
              </div>

              <n-button
                tertiary
                v-if="!row.showChild"
                style="background: #ffffffff; color: #46299dff"
                icon-placement="right"
                round
                secondary
                strong
                size="small"
                @click="row.showChild = true"
              >
                <template #icon>
                  <n-icon>
                    <ChevronDownOutline />
                  </n-icon>
                </template>
                展开
              </n-button>
              <n-button
                tertiary
                v-if="row.showChild"
                style="background: #ffffffff; color: #46299dff"
                icon-placement="right"
                round
                secondary
                strong
                size="small"
                @click="row.showChild = false"
              >
                <template #icon>
                  <n-icon>
                    <ChevronUpOutline />
                  </n-icon>
                </template>
                收起
              </n-button>
            </div>
            <div
              v-if="row.showChild"
              style="border: 1px solid #1f2225ff; border-radius: 0 0 3px 3px"
              class="col-12 row"
            >
              <div
                class="col-12 row"
                style="padding: 11px 0; background: #dfd7f2"
              >
                <div class="col-3 text-center">按钮权限</div>
                <div class="col-3 text-center">列表权限</div>
                <div class="col-3 text-center">数据范围权限</div>
                <div class="col-3 text-center">列表字段权限</div>
              </div>
              <div class="col-12 row">
                <div class="col-3 fl-py-md">
                  <div class="" style="margin-left: 30%">
                    <div
                      v-if="
                        Array.isArray(row.buttonList) &&
                        row.buttonList.length > 1
                      "
                      class="row"
                    >
                      <n-checkbox
                        v-model:checked="row.btnSelectedAll"
                        :indeterminate="row.btnIndeterminate"
                        :disabled="calcPageDisable()"
                        @update:checked="
                          (e) => handleBtnSelectAllChange(e, rowIdx)
                        "
                      >
                        全选
                      </n-checkbox>
                    </div>
                    <n-checkbox-group
                      v-model:value="row.btnSelected"
                      @update:value="(e) => handleBtnSelectChange(e, rowIdx)"
                    >
                      <div
                        class="col-12"
                        v-for="(btn, btnIdx) in row.buttonList"
                        :key="btnIdx"
                      >
                        <n-checkbox
                          :value="btn.ID"
                          :disabled="calcPageDisable()"
                        >
                          {{ btn.name }}
                        </n-checkbox>
                      </div>
                    </n-checkbox-group>
                  </div>
                </div>

                <div class="col-9 row">
                  <div
                    v-for="(list, listIdx) in row.interfaceList"
                    :key="listIdx"
                    class="col-12 row"
                    :style="{
                      'border-left':
                        row.interfaceList.length > 1 ? '1px solid #C1B2E5' : '',
                      'border-bottom':
                        listIdx !== row.interfaceList.length - 1
                          ? '1px solid #C1B2E5'
                          : '',
                    }"
                  >
                    <div class="col-4 row fl-pa-md justify-center">
                      <n-checkbox
                        v-model:checked="list.selected"
                        :disabled="calcPageDisable()"
                        @update:checked="
                          (e) => handleListSelectChange(e, rowIdx, listIdx)
                        "
                      >
                        {{ list.name }}
                      </n-checkbox>
                    </div>

                    <div class="col-4 row fl-pa-md justify-center">
                      <n-radio-group v-model:value="list.limitSelected">
                        <n-radio
                          :style="radioStyle"
                          v-for="(limit, limitIdx) in list.limit"
                          :key="limitIdx"
                          :disabled="calcPageDisable()"
                          :value="limit.value"
                        >
                          <div class="relative">
                            {{ limit.label }}
                            <n-button
                              tertiary
                              v-if="
                                list.limitSelected === 5 && limit.value === 5
                              "
                              size="small"
                              style="
                                position: absolute;
                                right: -120px;
                                width: 70px;
                                background: #ffffff;
                                color: #6d5c9c;
                                border: 1px solid #8a67ef;
                              "
                              @click.stop="
                                handleChangeSelfLimitData(rowIdx, listIdx, list)
                              "
                              >设置</n-button
                            >
                          </div>
                        </n-radio>
                      </n-radio-group>
                    </div>

                    <div class="col-4 row fl-pa-md justify-center">
                      <n-checkbox-group
                        v-if="Array.isArray(list.positionRuleFields)"
                        v-model:value="list.fieldsSelected"
                      >
                        <div v-if="!calcPageDisable()" class="col-12">
                          <n-button
                            tertiary
                            class="fl-ml-md"
                            size="small"
                            style="
                              width: 70px;
                              background: #ffffff;
                              color: #6d5c9c;
                              border: 1px solid #8a67ef;
                            "
                            @click="handleEditField(rowIdx, listIdx)"
                            >设置</n-button
                          >
                          <n-button
                            tertiary
                            class="fl-ml-md"
                            size="small"
                            style="
                              width: 70px;
                              background: #ffffff;
                              color: #6d5c9c;
                              border: 1px solid #8a67ef;
                            "
                            @click="handleEditFieldSort(rowIdx, listIdx)"
                            >排序</n-button
                          >
                        </div>
                        <div
                          class="col-12"
                          v-for="(field, fieldIdx) in list.positionRuleFields"
                          :key="fieldIdx"
                        >
                          <n-checkbox
                            :value="field.ID"
                            :disabled="calcPageDisable()"
                          >
                            {{ field.fieldCnName }}
                          </n-checkbox>
                        </div>
                      </n-checkbox-group>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div
    class="width-100 row fl-pt-md fl-pb-lg"
    style="position: fixed; bottom: 0px; background: #f0f0f5"
  >
    <div class="col-10 row justify-center">
      <n-button
        tertiary
        class="fl-mr-md"
        style="width: 161px; background: #c7c7c9ff; color: #ffffffff"
        @click="handleBack"
        >返回</n-button
      >

      <n-button
        tertiary
        v-if="state.pageType === 'edit'"
        style="width: 161px; height: 34px; background: #46299dff; color: #fff"
        :loading="state.btnLoading"
        @click="handleSave"
        >保存</n-button
      >

      <n-button
        tertiary
        v-if="state.pageType === 'create'"
        style="width: 161px; height: 34px; background: #46299dff; color: #fff"
        :loading="state.btnLoading"
        @click="handleCreate"
        >保存</n-button
      >
    </div>
  </div>
  <n-modal
    v-model:show="state.dialogField"
    style="width: 800px"
    :mask-closable="false"
    preset="card"
  >
    <template #header>
      <div
        class="col-12 row justify-center relative"
        style="border-bottom: 1px solid #dfd7f2"
      >
        <div style="font-size: 20px; font-weight: bold; color: #1f2225ff">
          设置字段
        </div>
      </div>
    </template>
    <div class="row justify-center fl-pa-md">
      <div
        class="col-12 row justify-center overflow-auto fl-pa-md"
        style="max-height: 40vh"
      >
        <div
          class="col-11 row font-16"
          style="background: #46299dff; border-radius: 3px 3px 0 0; color: #fff"
        >
          <div class="col-4 fl-pa-md row justify-center items-center">
            字段中文名
          </div>
          <div class="col-4 fl-pa-md row justify-center items-center">
            对应接口中字段名称
          </div>
          <div class="col-4 fl-pa-md row justify-center items-center">操作</div>
        </div>
        <div
          v-if="
            Array.isArray(state.dialogData.fieldList) &&
            state.dialogData.fieldList.length > 0
          "
          class="col-11 row"
          style="border-radius: 0 0 3px 3px"
        >
          <div
            class="col-12 row"
            v-for="(list, idx) in state.dialogData.fieldList"
            :key="idx"
          >
            <div class="col-4 fl-pa-md">
              <n-input v-model:value="list.fieldCnName" />
            </div>
            <div class="col-4 fl-pa-md">
              <n-input v-model:value="list.field" />
            </div>
            <div class="col-4 fl-pa-md row justify-center items-center">
              <div
                class="fl-ma-xs cursor fl-mr-md"
                style="color: #1f2225ff"
                @click="handleDelDialogFieldList(idx)"
              >
                删除
              </div>
            </div>
          </div>
        </div>
        <div
          v-else
          class="col-11 row"
          style="border-radius: 0 0 3px 3px; box-shadow: 0 2px 0 1px #dfd7f2"
        >
          <div class="col-12 row justify-center items-center fl-py-lg">
            暂无数据
          </div>
        </div>
      </div>
      <n-button
        tertiary
        class="fl-my-lg"
        style="
          width: 95px;
          background: #ffffff;
          color: #6d5c9c;
          border: 1px solid #8a67ef;
        "
        @click="handleCreDialogFieldList"
        ><plus-outlined style="color: #000"></plus-outlined>新增</n-button
      >
      <div class="col-12 row justify-center">
        <n-button
          tertiary
          style="width: 161px; background: #c7c7c9ff; color: #ffffffff"
          class="fl-mr-md"
          @click="handleDialogBack"
          >返回</n-button
        >

        <n-button
          tertiary
          style="width: 161px; height: 34px; background: #46299dff; color: #fff"
          :loading="state.btnLoading"
          @click="handleDialogSave"
          >保存</n-button
        >
      </div>
    </div>
  </n-modal>

  <n-modal
    v-model:show="state.dialogFieldSort"
    style="width: 800px"
    :mask-closable="false"
    preset="card"
  >
    <template #header>
      <div
        class="col-12 row justify-center relative"
        style="border-bottom: 1px solid #dfd7f2"
      >
        <div style="font-size: 20px; font-weight: bold; color: #1f2225ff">
          拖拽调整字段顺序
        </div>
      </div>
    </template>
    <div class="row justify-center fl-pa-md">
      <div
        class="col-12 row justify-center overflow-auto fl-pa-md"
        style="max-height: 40vh"
      >
        <draggable
          :list="state.dialogData.fieldList"
          :disabled="!state.enabled"
          item-key="fieldCnName"
          class="list-group col-12"
          ghost-class="ghost"
          :move="checkMove"
          @start="state.dragging = true"
          @end="state.dragging = false"
        >
          <template #item="{ element }">
            <div
              class="list-group-item row"
              :class="{ 'not-draggable': !state.enabled }"
            >
              <div class="col-4 row items-center">
                <drag-outlined class="fl-mr-sm" />{{ element.fieldCnName }}
              </div>
              <div class="col-8">{{ element.field }}</div>
            </div>
          </template>
        </draggable>
      </div>
      <div class="col-12 row justify-center">
        <n-button
          tertiary
          style="width: 161px; background: #c7c7c9ff; color: #ffffffff"
          class="fl-mr-md"
          @click="handleDialogSortBack"
          >返回</n-button
        >
        <n-button
          tertiary
          style="width: 161px; height: 34px; background: #46299dff; color: #fff"
          :loading="state.btnLoading"
          @click="handleDialogSortSave"
          >保存</n-button
        >
      </div>
    </div>
  </n-modal>
  <fl-limit-data
    v-if="state.dialogSelfLimtiData"
    :fatherData="state.dataDepartmentIds"
    @triggerLimitData="handleLimitData"
  />
</template>

<script setup>
// 岗位 直接新建
import {
  UpOutlined,
  DownOutlined,
  CloseCircleOutlined,
  PlusOutlined,
  DragOutlined,
} from "@ant-design/icons-vue";
import flnFormItem from "@/components/flnlayout/form/flnformItem.vue";
import draggable from "vuedraggable";
import {
  ref,
  reactive,
  onBeforeMount,
  onActivated,
  onMounted,
  getCurrentInstance,
  computed,
  nextTick,
} from "vue";
import { processError, processSuccess } from "@/utils/helper/message";
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
const currentInstance = getCurrentInstance();
const { $request } = currentInstance.appContext.config.globalProperties;
import { ChevronDownOutline, ChevronUpOutline } from "@vicons/ionicons5";
import { Local } from "@/utils/storage.js";
import flLimitData from "./limitData.vue";
const radioStyle = reactive({
  display: "flex",
  height: "30px",
  lineHeight: "30px",
});
const state = reactive({
  selectedRows: [],
  dialogField: false,
  dialogData: {
    fieldList: [],
  },
  listData: [],
  formData: {
    name: "",
    remark: "",
    color: "#1F2225",
    isOwner: [],
  },
  btnLoading: false,
  pageType: "create",
  showChildkeys: [],
  enabled: true,
  dragging: false,
  dialogFieldSort: false,
  dataLoading: false,
  pathName: [],
  leftMenuData: [],
  dialogSelfLimtiData: false,
  dialogLimitData: {},
  dataDepartmentIds: [],
});
onBeforeMount(() => {
  getRulesData("getPageData");
  if (route.query.type) {
    state.pageType = route.query.type;
  }
  let treeSelectData = Local.get("posimanage_treeSelectData");
  if (treeSelectData) {
    state.pathName = treeSelectData.pathName;
  }
});
onActivated(() => {
  getRulesData("getPageData");
  if (route.query.type) {
    state.pageType = route.query.type;
  }
  let treeSelectData = Local.get("posimanage_treeSelectData");
  if (treeSelectData) {
    state.pathName = treeSelectData.pathName;
  }
});
onMounted(() => {});
const checkMove = (e) => {
  window.console.log("Future index: " + e.draggedContext.futureIndex);
};
const getRulesData = (type) => {
  let url = "/rule/v2/menu/list";
  $request.HTTP.components.postDataByParams(url, {}).then(
    (res) => {
      if (res.status === 0) {
        let data = res.data.data;
        data.map((item) => {
          item.selected = false;
          item.showChild = false;
          if (state.showChildkeys.includes(item.ID)) {
            item.showChild = true;
          }
          item.btnSelected = [];
          item.btnSelectedAll = false;
          item.btnIndeterminate = false;
          if (Array.isArray(item.interfaceList)) {
            item.interfaceList.map((listItem) => {
              listItem.selected = false;
              listItem.limit = [
                {
                  label: "仅自己",
                  value: 1,
                },
                {
                  label: "自己及下属",
                  value: 2,
                },
                {
                  label: "本部门",
                  value: 3,
                },
                {
                  label: "所有",
                  value: 4,
                },
                {
                  label: "自定义",
                  value: 5,
                },
              ];
              listItem.limitSelected = 4;
              listItem.positionRuleFields = listItem.positionRuleFields || [];
              listItem.fieldsSelected = listItem.positionRuleFields.map(
                (item) => item.ID
              );
            });
          }
        });
        state.listData = data;
        if (route.query.ID && type === "getPageData") {
          getPageData();
        }
        calcleftMenuDefaultData(data);
      } else {
        processError(res.msg || "获取数据失败！");
      }
    },
    () => {
      processError("获取数据失败！");
    },
    () => {
      processError("获取数据失败！");
    }
  );
};
const calcleftMenuDefaultData = (data) => {
  let leftMenuData = [];
  data.map((item) => {
    if (item.pid === 0) {
      let obj = {
        name: item.name,
        ID: item.ID,
        select: item.selected || false,
        weigh: item.weigh,
      };
      leftMenuData.push(obj);
    }
  });
  data.map((item) => {
    leftMenuData.map((menu) => {
      if (item.pid === menu.ID) {
        menu.children = menu.children || [];
        let obj = {
          name: item.name,
          ID: item.ID,
          select: item.selected || false,
          weigh: item.weigh,
        };
        menu.children.push(obj);
      }
    });
  });
  leftMenuData.sort((a, b) => b.weigh - a.weigh);
  leftMenuData.map((item) => {
    if (item.children) {
      item.children.sort((a, b) => b.weigh - a.weigh);
    }
  });
  state.leftMenuData = leftMenuData;
};
const getPageData = () => {
  if (route.query.ID) {
    state.dataLoading = true;
    let url = "/position/v2/detail";
    let params = {
      ID: Number(route.query.ID),
    };
    $request.HTTP.components.postDataByParams(url, params).then(
      (res) => {
        if (res.status === 0) {
          let resData = res.data;
          state.formData.name = res.data.name;
          state.formData.remark = res.data.remark;
          state.formData.color = res.data.color || "";
          state.formData.isOwner = res.data.isLeader ? ["true"] : [];
          resData.positionTreeRule = resData.positionTreeRule || [];
          setRulesDataDefaultVal(resData.positionTreeRule, state.listData);
          state.selectedRows = state.listData.filter((item) => item.selected);
          calcleftMenuSelectData();
        } else {
          processError(res.msg || "获取数据失败！");
        }
        state.btnLoading = false;
        state.dataLoading = false;
      },
      () => {
        processError("获取数据失败！");
        state.btnLoading = false;
        state.dataLoading = false;
      },
      () => {
        processError("获取数据失败！");
        state.btnLoading = false;
        state.dataLoading = false;
      }
    );
  }
};
const handleValChange = ({ val, config }) => {
  console.log(val);
  state.formData[config.field] = val;
};
const handleCreate = () => {
  if (state.formData.name === "") {
    processError("请填写岗位");
    return;
  }
  state.btnLoading = true;
  let url = "/position/v2/create";
  let params = {
    name: state.formData.name,
    remark: state.formData.remark,
    color: state.formData.color,
    positionTreeRule: [],
    departmentID: Number(route.query.departmentID),
    isLeader: state.formData.isOwner.length > 0,
  };
  Object.assign(params, state.formData);
  delete params.isOwner;
  let data = state.listData;
  data
    .filter((item) => item.selected)
    .map((item) => {
      let obj = {
        ID: item.ID,
        buttonList: Array.isArray(item.buttonList)
          ? item.buttonList.filter((btnItem) =>
              item.btnSelected.includes(btnItem.ID)
            )
          : [],
        interfaceList: Array.isArray(item.interfaceList)
          ? item.interfaceList
              .filter((listItem) => listItem.selected)
              .map((listItem) => {
                return {
                  ID: listItem.ID,
                  dataDepartmentIds: listItem.dataDepartmentIds,
                  dataRange: listItem.limitSelected,
                  positionRuleFields: Array.isArray(listItem.positionRuleFields)
                    ? listItem.positionRuleFields.filter((fieldItem) =>
                        listItem.fieldsSelected.includes(fieldItem.ID)
                      )
                    : [],
                };
              })
          : [],
      };
      params.positionTreeRule.push(obj);
    });
  $request.HTTP.components.postDataByParams(url, params).then(
    (res) => {
      state.btnLoading = false;
      if (res.status === 0) {
        processSuccess("操作成功！");
        router.go(-1);
      } else {
        processError(res.msg || "操作失败！");
      }
    },
    () => {
      processError("操作失败！");
      state.btnLoading = false;
    },
    () => {
      processError("操作失败！");
      state.btnLoading = false;
    }
  );
};
const handleSave = () => {
  if (state.formData.name === "") {
    processError("请填写岗位");
    return;
  }
  state.btnLoading = true;
  let url = "/position/v2/update";
  let params = {
    ID: Number(route.query.ID),
    name: state.formData.name,
    remark: state.formData.remark,
    color: state.formData.color,
    positionTreeRule: [],
    departmentID: Number(route.query.departmentID),
    isLeader: state.formData.isOwner.length > 0,
  };
  Object.assign(params, state.formData);
  delete params.isOwner;
  let data = state.listData;
  data
    .filter((item) => item.selected)
    .map((item) => {
      let obj = {
        ID: item.ID,
        buttonList: Array.isArray(item.buttonList)
          ? item.buttonList.filter((btnItem) =>
              item.btnSelected.includes(btnItem.ID)
            )
          : [],
        interfaceList: Array.isArray(item.interfaceList)
          ? item.interfaceList
              .filter((listItem) => listItem.selected)
              .map((listItem) => {
                return {
                  ID: listItem.ID,
                  dataDepartmentIds: listItem.dataDepartmentIds,
                  dataRange: listItem.limitSelected,
                  positionRuleFields: Array.isArray(listItem.positionRuleFields)
                    ? listItem.positionRuleFields.filter((fieldItem) =>
                        listItem.fieldsSelected.includes(fieldItem.ID)
                      )
                    : [],
                };
              })
          : [],
      };
      params.positionTreeRule.push(obj);
    });
  $request.HTTP.components.postDataByParams(url, params).then(
    (res) => {
      if (res.status === 0) {
        processSuccess("操作成功！");
        getRulesData("getPageData");
      } else {
        processError(res.msg || "操作失败！");
      }
    },
    () => {
      processError("操作失败！");
      state.btnLoading = false;
    },
    () => {
      processError("操作失败！");
      state.btnLoading = false;
    }
  );
};
const handleBack = () => {
  router.go(-1);
};
const handleEditField = (rowIdx, listIdx) => {
  state.dialogData.clickData = state.listData[rowIdx];
  state.dialogData.ID = state.listData[rowIdx].interfaceList[listIdx].ID;
  state.dialogData.rowIdx = rowIdx;
  state.dialogData.listIdx = listIdx;
  state.dialogData.fieldList = JSON.parse(
    JSON.stringify(
      state.listData[rowIdx].interfaceList[listIdx].positionRuleFields.map(
        (item) => {
          return {
            ID: item.ID,
            field: item.fieldKey,
            fieldCnName: item.fieldCnName,
          };
        }
      )
    )
  );
  state.dialogField = true;
};
const handleBtnSelectAllChange = (checked, idx) => {
  if (checked) {
    state.listData[idx].btnSelected = state.listData[idx].buttonList.map(
      (item) => item.ID
    );
    state.listData[idx].btnIndeterminate = false;
  } else {
    state.listData[idx].btnSelected = [];
    state.listData[idx].btnIndeterminate = false;
  }
};
const handleBtnSelectChange = (e, idx) => {
  if (e.length === 0) {
    state.listData[idx].btnSelectedAll = false;
    state.listData[idx].btnIndeterminate = false;
  } else if (e.length === state.listData[idx].buttonList.length) {
    state.listData[idx].btnSelectedAll = true;
    state.listData[idx].btnIndeterminate = false;
  } else {
    state.listData[idx].btnSelectedAll = false;
    state.listData[idx].btnIndeterminate = true;
  }
};
const handleListSelectChange = (e, rowIdx, listIdx) => {
  state.listData[rowIdx].listSelected = state.listData[
    rowIdx
  ].interfaceList.filter((item) => item.selected);
};
const handlePageSelectChange = (e) => {
  state.selectedRows = state.listData.filter((item) => item.selected);
  calcleftMenuSelectData();
};
const handleClearPage = (select) => {
  state.listData.forEach((item) => {
    if (item.name === select.name) {
      item.selected = false;
    }
  });
  state.selectedRows = state.listData.filter((item) => item.selected);
  calcleftMenuSelectData();
};
const calcleftMenuSelectData = () => {
  let leftMenuData = JSON.parse(JSON.stringify(state.leftMenuData));
  leftMenuData.map((item) => {
    item.select = false;
    if (
      state.selectedRows.filter((selectRow) => selectRow.ID === item.ID)
        .length > 0
    ) {
      item.select = true;
    }
    if (item.children) {
      item.children.map((child) => {
        child.select = false;
        if (
          state.selectedRows.filter((selectRow) => child.ID === selectRow.ID)
            .length > 0
        ) {
          child.select = true;
        }
      });
    }
  });
  state.leftMenuData = leftMenuData;
};
const handleDelDialogFieldList = (delIdx) => {
  state.dialogData.fieldList.splice(delIdx, 1);
};
const handleCreDialogFieldList = () => {
  state.dialogData.fieldList.push({
    field: "",
    fieldCnName: "",
  });
};
const handleDialogSave = () => {
  state.showChildkeys = [];
  let url = "/rule/v2/update";
  let params = {
    ID: state.dialogData.ID,
    ruleFields: state.dialogData.fieldList
      .filter((item) => item.fieldCnName)
      .map((item) => {
        return {
          ID: item.ID || undefined,
          fieldCnName: item.fieldCnName,
          fieldKey: item.field,
        };
      }),
  };
  $request.HTTP.components.postDataByParams(url, params).then(
    (res) => {
      if (res.status === 0) {
        processSuccess("操作成功！");
        state.dialogField = false;
        state.showChildkeys.push(state.dialogData.clickData.ID);
        getRulesData("getPageData");
      } else {
        processError(res.msg || "操作失败！");
      }
    },
    () => {
      processError("操作失败！");
    },
    () => {
      processError("操作失败！");
    }
  );
};
const handleDialogBack = () => {
  state.dialogField = false;
};
const handleLink = (path) => {
  router.push(path);
};
const calcPageDisable = () => {
  return state.pageType === "view";
};
const setRulesDataDefaultVal = (pageData, listData) => {
  pageData.map((pageDataItem) => {
    listData.map((listItem) => {
      if (pageDataItem.ID === listItem.ID) {
        listItem.selected = true;
        listItem.showChild = false;
        if (state.showChildkeys.includes(listItem.ID)) {
          listItem.showChild = true;
        }
        listItem.btnSelected = Array.isArray(pageDataItem.buttonList)
          ? pageDataItem.buttonList.map((btnItem) => btnItem.ID)
          : [];
        if (
          Array.isArray(listItem.interfaceList) &&
          Array.isArray(pageDataItem.interfaceList)
        ) {
          listItem.interfaceList.map((interfaceItem) => {
            pageDataItem.interfaceList.map((pageDataInterfaceItem) => {
              if (interfaceItem.ID === pageDataInterfaceItem.ID) {
                interfaceItem.dataDepartmentIds =
                  pageDataInterfaceItem.dataDepartmentIds || [];
                interfaceItem.selected = true;
                interfaceItem.limitSelected = pageDataInterfaceItem.dataRange;
                pageDataInterfaceItem.positionRuleFields =
                  pageDataInterfaceItem.positionRuleFields || [];
                interfaceItem.fieldsSelected =
                  pageDataInterfaceItem.positionRuleFields.map(
                    (fieldItem) => fieldItem.ID
                  );
                interfaceItem.positionRuleFields.map((fieldItem) => {
                  pageDataInterfaceItem.positionRuleFields.map(
                    (pageDataFieldItem) => {
                      if (fieldItem.ID === pageDataFieldItem.ID) {
                        fieldItem.index = pageDataFieldItem.index || 0;
                      }
                    }
                  );
                });
              }
            });
          });
        }
      }
    });
  });
};

const handleEditFieldSort = (rowIdx, listIdx) => {
  state.dialogData.clickData = state.listData[rowIdx];
  state.dialogData.ID = state.listData[rowIdx].interfaceList[listIdx].ID;
  state.dialogData.rowIdx = rowIdx;
  state.dialogData.listIdx = listIdx;
  let fieldsSelected =
    state.listData[rowIdx].interfaceList[listIdx].fieldsSelected;
  let fieldList = [];
  state.listData[rowIdx].interfaceList[listIdx].positionRuleFields.map(
    (item) => {
      if (fieldsSelected.includes(item.ID)) {
        fieldList.push({
          ID: item.ID,
          field: item.fieldKey,
          fieldCnName: item.fieldCnName,
          index: item.index || 0,
        });
      }
    }
  );
  fieldList.sort((a, b) => {
    return a.index - b.index;
  });
  state.dialogData.fieldList = fieldList;
  state.dialogFieldSort = true;
};
const handleDialogSortSave = () => {
  let rowIdx = state.dialogData.rowIdx;
  let listIdx = state.dialogData.listIdx;

  state.dialogData.fieldList.forEach((item, idx) => {
    item.index = idx + 1;
  });

  state.listData[rowIdx].interfaceList[listIdx].positionRuleFields.map(
    (item) => {
      state.dialogData.fieldList.map((fieldItem) => {
        if (item.ID === fieldItem.ID) {
          item.index = fieldItem.index;
        }
      });
    }
  );
  state.dialogFieldSort = false;
};
const handleDialogSortBack = () => {
  state.dialogFieldSort = false;
};
const handleLeftSelectCheckChange = (e, row) => {
  row.select = e;
  state.listData.map((item) => {
    if (item.ID === row.ID) {
      item.selected = e;
    }
  });
  state.selectedRows = state.listData.filter((item) => item.selected);
};
const handleChangeSelfLimitData = (rowIdx, listIdx, list) => {
  state.dialogLimitData = {
    rowIdx,
    listIdx,
  };
  state.dataDepartmentIds = list.dataDepartmentIds;
  state.dialogSelfLimtiData = true;
};
const handleLimitData = (data) => {
  let rowIdx = state.dialogLimitData.rowIdx;
  let listIdx = state.dialogLimitData.listIdx;
  state.listData[rowIdx].interfaceList[listIdx].dataDepartmentIds = data;
  state.dialogSelfLimtiData = false;
};
const handleSelfHref = (path) => {
  let anchorElement = document.getElementById(path);
  if (anchorElement) {
    anchorElement.scrollIntoView();
  }
};
</script>

<style lang="scss" scoped>
.search-item {
  :deep(.ant-input-affix-wrapper) {
    background: #fff;
    color: #c3c3c3;
  }
  :deep(.ant-input) {
    color: #000;
    &::placeholder {
      color: #c3c3c3;
    }
  }
  :deep(.ant-picker-input > input) {
    color: #000;
    &::placeholder {
      color: #c3c3c3;
    }
  }
  :deep(.ant-picker) {
    width: 100%;
    border-radius: 20px;
    background: #fff !important;
    color: #c3c3c3;
    border: none;
  }
  :deep(.ant-picker-input > input) {
    color: #000;
    &::placeholder {
      color: #c3c3c3;
    }
  }
}

.fl-anchor {
  cursor: pointer;
  /* 去除下划线 */
  text-decoration: none;

  /* 去除颜色变化 */
  color: #333639;

  /* 去除点击时的焦点轮廓 */
  outline: none;

  /* 其他样式 */
  font-style: normal; /* 去除斜体 */
}

/* 针对悬停状态的样式 */
.fl-anchor:hover {
  text-decoration: none;
}

/* 针对活动状态的样式 */
.fl-anchor:active {
  text-decoration: none;
}
</style>
