/*
 * @Author: wfl
 * @LastEditors: wfl
 * @description:
 * @updateInfo:
 * @Date: 2022-08-03 17:15:24
 * @LastEditTime: 2022-10-24 14:49:43
 */
import { deleteMenu, getAllMenu, toSortMenu, updateMenu } from '@/mainApp/api/sys-default/menu';
import GlContentHeader from '@/global/components/GlContentHeader';
import { MenuBtnEnum } from '@/global/enums/menuEnum';
import { useMessage } from '@/global/hooks/web/useMessage';
import { getAppEnvConfig } from '@/mainApp/utils/env';
import { PlusOutlined, UnorderedListOutlined } from '@ant-design/icons-vue';
import { Button, Image, Skeleton, Switch, Table } from 'ant-design-vue';
import { ikTree } from 'iking-utils';
import * as _ from 'lodash-es';
import Sortable from 'sortablejs';
import { computed, defineComponent, Ref, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import MenuModal from './menuModal.vue';
import { tableKeys } from './tableKeys';
import TranslateModal from './translateModal.vue';
const menuManage = defineComponent({
  setup() {
    const { t } = useI18n();
    const { createMessage, createConfirm } = useMessage();
    const menuTree: Ref<null | Array<any>> = ref(null);
    const loading = ref(false);
    const defaultExpand: Ref<string[]> = ref([]);
    const isChild = ref(false);
    const moving = ref(false);
    const dragTable: Ref<null | { $el: HTMLElement }> = ref(null);
    // const { menuTypes } = useMenuDiction();
    const getAccept = getAppEnvConfig();
    const downLoadUrl = computed(() => getAccept.VITE_GLOB_DOWNLOAD_URL);
    // const searchForm = ref({
    //   name: '',
    //   remark: '',
    //   menuType: '',
    // });

    const getMenuTreeData = (statu = false) => {
      // 排序时DOM结构被更改，此操作用于正确显示排序后的结果
      if (statu) {
        menuTree.value = [];
      }
      loading.value = true;
      getAllMenu()
        .then(({ success, data, msg }) => {
          if (success) {
            menuTree.value = ikTree.listToTree(
              data.map((item, index) => {
                item.key = '' + index;
                return item;
              }),
            );
            defaultExpand.value = menuTree.value?.map((item: { key: string }) => item.key) || [];
          } else {
            createMessage.warning(msg);
          }
          loading.value = false;
        })
        .catch(() => {
          loading.value = false;
          menuTree.value = [];
        });
    };
    getMenuTreeData();

    const visible = ref(false);
    const editData = ref(null);
    const handNewMenu = () => {
      editData.value = null;
      visible.value = true;
    };
    const handleShow = (visib: boolean) => {
      visible.value = visib;
      if (!visib) {
        editData.value = null;
        isChild.value = false;
      }
    };

    const sortMenu = async (move, newdata, position: string) => {
      loading.value = true;
      const params = {
        currentOrder: move.sortOrder,
        parentId: move.parentId,
        position: position,
        targetOrder: newdata.sortOrder,
        targetParentId: newdata.parentId,
      };
      const { success, msg } = await toSortMenu(params);
      if (success) {
      } else {
        createMessage.warning(msg);
      }
      loading.value = false;
      getMenuTreeData(true);
    };

    let sortVal: Sortable | null = null;
    const handSortMenu = () => {
      moving.value = !moving.value;

      if (!moving.value && sortVal) {
        sortVal.destroy();
        sortVal = null;
        return;
      }
      const el = dragTable.value!.$el.querySelectorAll(
        '.ant-table-body > table > tbody',
      )[0] as HTMLElement;

      sortVal = Sortable.create(el, {
        ghostClass: 'sortable-ghost',
        dataIdAttr: '__nodekey',
        setData: function (dataTransfer) {
          dataTransfer.setData('Text', '');
        },
        onEnd: (evt) => {
          const { newIndex } = evt;
          const nodes = evt.target.querySelectorAll('.ant-table-row');
          const len = nodes.length;
          if (newIndex) {
            const move = JSON.parse(nodes[newIndex - 1].getAttribute('__attrs') || '');
            const newdata = JSON.parse(
              nodes[newIndex === len ? newIndex - 2 : newIndex].getAttribute('__attrs') || '',
            );
            // const pos = newIndex === len ? 'DOWN' : 'UP'
            sortMenu(move, newdata, newIndex === len ? 'DOWN' : 'UP');
          }
        },
      });
    };

    const handChangeVisible = (val: boolean, record: any) => {
      loading.value = true;
      updateMenu(record)
        .then(({ success, msg }) => {
          if (success) {
            // getMenuTreeData();
          } else {
            createMessage.warning(msg);
            record.visible = !val;
          }
          loading.value = false;
        })
        .catch(() => {
          loading.value = false;
        });
    };

    const handEditMenu = (record: any) => {
      visible.value = true;
      editData.value = record;
    };

    const handAddChild = (record: any) => {
      isChild.value = true;
      editData.value = record;
      visible.value = true;
    };

    const handDeleteMenu = (record: any) => {
      createConfirm({
        title: '提示',
        content: '确定删除该菜单吗？',
        iconType: 'warning',
        onOk: () => {
          loading.value = true;
          deleteMenu(record.id)
            .then(({ success, msg }) => {
              if (success) {
                getMenuTreeData();
              } else {
                createMessage.warning(msg);
              }
              loading.value = false;
            })
            .catch(() => {
              loading.value = false;
            });
        },
      });
    };

    const transVisible = ref(false);
    const transData = ref(null);
    const handTranslate = (record: any) => {
      transData.value = record;
      transVisible.value = true;
    };

    const i18nToText = (text: string) => {
      return t(text);
    };

    const btnPagging = '!px-5px';
    return () => (
      <>
        <MenuModal
          title={isChild.value ? '新增子菜单' : editData.value ? '修改菜单' : '新增菜单'}
          visible={visible.value}
          isChild={isChild.value}
          editData={editData.value}
          onVisibleChange={(val) => handleShow(val)}
          onDataChange={() => getMenuTreeData()}
        />
        <TranslateModal
          visible={transVisible.value}
          onVisibleChange={(val) => (transVisible.value = val)}
          editData={transData.value}
        />
        <GlContentHeader
          onSearch={() => getMenuTreeData()}
          onRefresh={() => getMenuTreeData()}
          title={t('routes.basic.menuManager')}
          btnList={[]}
        >
          {{
            btnList: () => {
              return (
                <>
                  <Button type="primary" onClick={() => handNewMenu()}>
                    {{
                      icon: () => <PlusOutlined />,
                      default: t('btn.addMenu'),
                    }}
                  </Button>
                  <Button onClick={() => handSortMenu()}>
                    {{
                      icon: () => <UnorderedListOutlined />,
                      default: !moving.value ? t('btn.sortMenu') : t('btn.cancelSort'),
                    }}
                  </Button>
                </>
              );
            },
            default: ({ height, size }) => {
              return menuTree.value ? (
                <Table
                  size={size}
                  ref={dragTable}
                  loading={loading.value}
                  bordered
                  defaultExpandedRowKeys={defaultExpand.value}
                  pagination={false}
                  columns={tableKeys}
                  customRow={(record) => {
                    const attrs = _.cloneDeep(record);
                    attrs?.children && delete attrs.children;
                    return {
                      __attrs: JSON.stringify(attrs),
                    };
                  }}
                  dataSource={menuTree.value || []}
                  scroll={{
                    scrollToFirstRowOnChange: true,
                    y: height,
                  }}
                >
                  {{
                    bodyCell: ({ column, record }) => {
                      return column.dataIndex === '_0' ? (
                        <Switch
                          v-model:checked={record.visible}
                          checkedValue={true}
                          unCheckedValue={false}
                          checked-children="显示"
                          un-checked-children="隐藏"
                          onChange={(val: boolean) => handChangeVisible(val, record)}
                        />
                      ) : column.dataIndex === '_1' ? (
                        record.menuType ? (
                          <>
                            {record.menuType === MenuBtnEnum.MENU ? (
                              <Button
                                type="link"
                                onClick={() => handAddChild(record)}
                                class={btnPagging}
                              >
                                {i18nToText('btn.addChildMenu')}
                              </Button>
                            ) : null}
                            <Button
                              type="link"
                              onClick={() => handEditMenu(record)}
                              class={btnPagging}
                            >
                              {i18nToText('btn.edit')}
                            </Button>
                            {record.menuType === MenuBtnEnum.MENU ? (
                              <Button
                                type="link"
                                onClick={() => handTranslate(record)}
                                class={btnPagging}
                              >
                                {i18nToText('btn.international')}
                              </Button>
                            ) : null}

                            <Button
                              type="text"
                              onClick={() => handDeleteMenu(record)}
                              danger
                              class={btnPagging}
                            >
                              {i18nToText('btn.delete')}
                            </Button>
                          </>
                        ) : null
                      ) : column.dataIndex === '应用图标' ? (
                        <div>
                          {record.logo ? (
                            <Image src={`${downLoadUrl.value}${record.logo}`} width={40} />
                          ) : (
                            '--'
                          )}
                        </div>
                      ) : (
                        <div>
                          {column.dataIndex === 'icon' ? (
                            <i className={`ik ${record[column.dataIndex]} mr-5px`}></i>
                          ) : moving.value && column.dataIndex === 'name' ? (
                            <i className="ik ik-tuodong mr-8px cursor-move"></i>
                          ) : null}
                          {record[column.dataIndex]}
                        </div>
                      );
                    },
                  }}
                </Table>
              ) : (
                <>
                  <Skeleton active />
                  <Skeleton active />
                </>
              );
            },
          }}
        </GlContentHeader>
      </>
    );
  },
});

export default menuManage;
