<template>
  <WlPopup
    class="choose-group-popup"
    data-weiling-mobile-ui-bc-group-manage-popup
    v-model="popupVisible"
    :overlay="false"
    :round="false"
    duration="0"
    :style="{ height: '100%' }"
    position="bottom"
    @closed="onClose"
  >
    <div class="material-group">
      <WlHeader
        :showBack="showBack"
        :showClose="showClose"
        @onClose="popupVisible = false"
        title="管理分组"
      />
      <div class="material-group-main">
        <div
          class="material-group-main-item-style material-group-main-add-item"
          @click="onAddGroup"
        >
          <WlSvgIcon type="add" width="24" height="24" color="#979797" />
          <p class="add-text">添加分组</p>
        </div>
        <vuedraggable
          v-model="chooseGroupList"
          handle=".sort-icon"
          chosenClass="chosenClass"
          ghostClass="ghostClass"
          item-key="id"
          @update="onGroupSort"
        >
          <template #item="{ element }">
            <div :class="groupItemClass(element)">
              <div>{{ element.group_name }}</div>
              <div class="operation" v-show="!element.is_default">
                <div class="operation-icon sort-icon">
                  <WlSvgIcon
                    type="sort"
                    width="24"
                    height="24"
                    color="#1C9FFF"
                  />
                </div>
                <div
                  class="operation-icon"
                  @click="onActionSheetClick(element)"
                >
                  <WlSvgIcon
                    type="moreHorizontal"
                    width="24"
                    height="24"
                    color="#1C9FFF"
                  />
                </div>
              </div>
            </div>
          </template>
        </vuedraggable>
      </div>
      <ActionSheet
        v-model="actionSheetVisible"
        @onChange="onActionSheetChange"
      />
      <DeleteDialog
        v-model:show="deleteDialogVisible"
        @onConfirm="onDeleteDialogConfirm"
      />
      <OperGroupDialog
        v-model:show="operDialogVisible"
        v-model:groupName="currentGroupName"
        @onConfirm="onAddDialogConfirm"
      />
    </div>
  </WlPopup>
</template>

<script lang="ts">
export default {
  name: "BCGroupManagePopup",
};
</script>

<script setup lang="ts">
import Api from "./http/api";
import WlSvgIcon from "@mobileUI/components/WlSvgIcon/src/index.vue";
import Store from "@mobileUI/store";
import vuedraggable from "vuedraggable";
import { allChooseItem } from "./utils/dict";
import useMessage from "@mobileUI/hooks/useMessage";
import WlHeader from "@mobileUI/components/WlHeader";
import { computed, ref, watchEffect } from "vue";
import ActionSheet from "./components/ActionSheet/index.vue";
import DeleteDialog from "./components/DeleteDialog/index.vue";
import { TActionSheet } from "@mobileUI/typings/WlActionSheet";
import WlPopup from "@mobileUI/components/WlPopup/src/index.vue";
import OperGroupDialog from "./components/OperGroupDialog/index.vue";
import { TChooseGroupList } from "@mobileUI/typings/BCChooseGroupPopup";
import {
  TGroupManageOperParams,
  TOperation,
} from "@mobileUI/typings/BCGroupManagePopup";

type Props = {
  show?: boolean;
  showBack?: boolean;
  showClose?: boolean;
  groupList?: TChooseGroupList;
  group_scope?: number;
  env_data: TEnv.TEnvData;
};

const props = withDefaults(defineProps<Props>(), {
  show: false,
  showBack: false,
  showClose: true,
  groupList: () => {
    return allChooseItem;
  },
  group_scope: 1,
  env_data: () => {
    return {
      sid: "",
      domain: "",
      corp_id: "",
      node_env: "uat",
      app_id: "",
      token: "",
      card_resource: "",
    };
  },
});

Store.corp_id = props.env_data.corp_id;
Store.node_env = props.env_data.node_env;
Store.sid = props.env_data.sid;
Store.token = props.env_data.token;
Store.card_resource = props.env_data.card_resource;

const { onNotify, onWarning } = useMessage();

const chooseGroupList = ref<TChooseGroupList[]>(null);
const chosedItem = ref<TChooseGroupList>(null);
const operStatus = ref<TOperation>("pending");
const hasOperStatus = ref<TOperation>("pending");
const currentGroupName = ref("");
const deleteDialogVisible = ref(false);
const operDialogVisible = ref(false);
const actionSheetVisible = ref(false);
const popupVisible = ref(false);

const groupItemClass = computed(() => {
  return (item) => {
    return {
      "material-group-main-item": true,
      "material-group-main-item-style": true,
      disabled: item.is_default,
    };
  };
});

//上级分组的信息
const upperGroupData = computed(() => {
  return props.groupList[0] ?? allChooseItem;
});

const emit = defineEmits<{
  (e: "update:show", val: boolean);
  (e: "onChange", val: TChooseGroupList);
  (e: "onOperSuccess", val: TGroupManageOperParams);
}>();

const onClose = () => {
  emit("update:show", false);
  popupVisible.value = false;
  if (hasOperStatus.value !== "pending") {
    emit("onOperSuccess", {
      status: hasOperStatus.value,
      data: chosedItem.value,
    });
  }
};

// 获取分组列表
const onGetData = async () => {
  const { parent_id, level } = upperGroupData.value;
  const upperGroupId = level === 1 ? "" : parent_id;
  const res = await Api.getGroupList({
    group_scope: props.group_scope,
    group_id: upperGroupId,
  });
  const { data } = res || {};
  const { data_list = [] } = data;
  //如果没有上级分组，就多一个全部选项
  if (upperGroupId === "") {
    chooseGroupList.value = [allChooseItem, ...data_list];
  } else {
    const { child_group } = data_list[0];
    chooseGroupList.value = child_group;
  }
};

const onJudgeBlank = (group_name: string): boolean => {
  let bool = true;
  if (group_name.length > 30) {
    onWarning("分组名字不能大于30个字");
    bool = false;
  }
  return bool;
};

const onAddGroup = () => {
  currentGroupName.value = "";
  operDialogVisible.value = true;
  operStatus.value = "add";
};

const onActionSheetClick = (item: TChooseGroupList) => {
  chosedItem.value = item;
  actionSheetVisible.value = true;
};

const onActionSheetChange = (item: TActionSheet) => {
  if (item.value === "delete") {
    deleteDialogVisible.value = true;
  } else if (item.value === "edit") {
    operStatus.value = "edit";
    operDialogVisible.value = true;
    currentGroupName.value = chosedItem.value.group_name;
  }
};

const onAddDialogConfirm = (group_name: string) => {
  if (!onJudgeBlank(group_name)) return;
  const interfaceDict = {
    add: "materialGroupAdd",
    edit: "materialGroupEdit",
  };
  const toastDict = {
    add: "新建分组成功",
    edit: "编辑分组成功",
  };
  const { parent_id, level, root_id } = upperGroupData.value;
  //如果是第一级的话level传1
  const levelValue = level === 1 ? "1" : level + 1;
  const params =
    operStatus.value === "add"
      ? {
          parent_id,
          level: levelValue,
          root_id,
          group_name,
          group_scope: props.group_scope,
        }
      : {
          id: chosedItem.value.id,
          group_name,
        };
  Api[interfaceDict[operStatus.value]](params).then(async () => {
    onNotify(toastDict[operStatus.value]);
    hasOperStatus.value = operStatus.value;
    await onGetData();
    if (operStatus.value === "edit") {
      chosedItem.value.group_name = currentGroupName.value;
    }
    operDialogVisible.value = false;
    currentGroupName.value = "";
  });
};

const onDeleteDialogConfirm = (delete_all: boolean) => {
  const { id, group_scope } = chosedItem.value;
  Api.materialGroupDelete({ id, group_scope, delete_all }).then(() => {
    hasOperStatus.value = "delete";
    onNotify("删除成功");
    onGetData();
  });
};

const onGroupSort = (event) => {
  const movedItem = chooseGroupList.value[event.newIndex];
  const targetItem = chooseGroupList.value[event.oldIndex];
  const sortList = chooseGroupList.value
    .map((res) => res.id)
    .filter((res) => res);
  Api.materialGroupSort({
    moved_id: movedItem.id,
    moved_parent_id: movedItem.parent_id,
    target_id: targetItem.parent_id,
    target_parent_id: targetItem.parent_id,
    group_scope: props.group_scope,
    sort_list: sortList,
  }).then(() => {
    hasOperStatus.value = "sort";
    onNotify("移动分组成功");
    onGetData();
  });
};

watchEffect(() => {
  popupVisible.value = props.show;
  if (props.show) {
    onGetData();
  }
});
</script>

<style scoped lang="scss">
.material-group {
  @include container();
  @extend %flex-direction-column;

  &-main {
    flex: 1;
    font-size: j(16);
    @extend %overflow-auto;

    .chosenClass {
      background-color: #fff;
      box-shadow: j(4) j(4) j(10) rgba(0, 0, 0, 0.1);
    }

    .ghostClass {
      background-color: var(--wl-btn-dashed-bg);
      box-shadow: none;
      color: #c1c1c1;
    }

    &-item-style {
      height: j(55);
      padding: 0 0 0 j(15);
      font-weight: 500;
      cursor: pointer;
      @include halfBorder("bottom", #ebebeb);
    }

    &-add-item {
      @extend %flex-middle;
      @include btnClick();

      .add-icon {
        width: j(14);
        height: j(14);
        margin-right: j(5);
      }

      .add-text {
        color: #979797;
        font-size: j(16);
        padding-left: j(5);
      }
    }

    &-item {
      @extend %flex-between;

      &.disabled {
        color: #999;
      }

      .operation {
        @extend %flex-middle;

        &-icon {
          display: flex;
          padding: j(5) j(8);
          cursor: pointer;
        }
      }
    }
  }
}
</style>
