<template>
  <div class="container">
    <div class="head-title">
      <span> {{ route.meta.title }} </span>
      <a-button type="primary" @click="evAddMenu">{{ $t('global.newMenu') }}</a-button>
    </div>

     <a-space direction="vertical" :style="{ width: '100%' }">
      <a-upload  :show-file-list="false"  :custom-request="customRequest" />
 
    </a-space>
    <!-- default-expand-all-rows -->
    <a-table
      class="table"
      :columns="columns"
      :data="refData.dataSource"
      :pagination="false"
      row-key="id"
      :scroll="{ x: '120%' }"
    >
        <template #name="{ record }">
          <span> {{ getParseLang(record.name, lang.getLang) }} </span>
          <template v-if="record.permsArr && record.permsArr.length > 0">
            <a-tag v-for="item in record.permsArr" :key="item.id" class="tag-name">{{ item.name }}</a-tag>
          </template>
        </template>
        <template #refresh="{ record }">
          <span v-if="['1', '2'].includes(record.type)">{{
            record.refresh ? "是" : "否"
          }}</span>
        </template>
        <template #icon="{ record }">
          <!-- <a>123456789</a> -->
          <span v-if="!record.icon"></span>
          <svg-icon v-else class="icon" :icon="record.icon" />
        </template>

        <template #id="{ record }">
          <a
            href="javascript:;"
            class="a-link"
            style="margin-right: 1rem"
            @click="evEdit(record)"
            >编辑</a
          >
          <a-popconfirm
            content="确认删除该信息?"
            ok-text="确定"
            cancel-text="取消"
            @ok="evDelete(record.id)"
          >
            <a href="javascript:;" class="a-link">删除</a>
        </a-popconfirm>
        </template>
    </a-table>

    <a-modal
      v-model:visible="refData.visible"
      title="菜单信息"
      :centered="true"
      :width="700"
      :footer="false"
      simple
    >
      <div class="form-box">
        <a-form
          :model="refData.fromData"
        
          @submit-success="evHandleSubmit"
        >
          <a-form-item
            field="name"
            label="路由名称"
            :rules="[{ required: true, message: '请输入路由名称' }]"
            :validate-trigger="['change', 'input', 'blur']"
          >
            <!-- <a-input
              v-model="refData.fromData.name"
              placeholder="请输入路由名称"
            /> -->

            <MonacoEditor  v-model="refData.fromData.name"  />
          </a-form-item>

          <a-form-item
            field="menu_id"
            label="上级路由"
            :validate-trigger="['change', 'input', 'blur']"
          >
            <a-tree-select
              v-model="refData.fromData.menu_id"
              placeholder="一级菜单"
              :data="refData.menuTree"
              :allow-clear="true"
              :field-names="{
                children: 'children',
                title: 'name',
                key: 'id',
              }"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            />
          </a-form-item>

          <a-form-item
            field="path"
            label="路由标识"
            :rules="[{ required: true, message: '请输入路由标识' }]"
            :validate-trigger="['change', 'input', 'blur']"
          >
            <a-input
              v-model="refData.fromData.path"
              placeholder="请输入路由标识"
            />
          </a-form-item>

          <a-form-item
            v-if="!refData.fromData.menu_id"
            field="icon"
            label="路由图标"
            :rules="[{ required: true, message: '请选择路由图标' }]"
            :validate-trigger="['change', 'input', 'blur']"
          >
            <a-input
              v-model="refData.fromData.icon"
              placeholder="请设置菜单图标"
            >
              <template
                v-if="refData.fromData.icon"
                #suffix
              >
                <svg-icon class="input-icon" :icon="refData.fromData.icon" />
              </template>
              <template #append>
                <icon-settings class="icon-append" @click="evIconModal" />
                <!-- <setting-outlined class="icon-append" @click="evIconModal" /> -->
              </template>
            </a-input>
          </a-form-item>

          <a-form-item v-if="isUrlView" field="url" label="路由地址">
            <!-- :rules="[{ required: true, message: '请输入路由名称' }]"
            :validate-trigger="['change', 'input', 'blur']" -->
<!--      
            <a-select v-model:value="refData.fromData.url" placeholder="请选择路由地址">
              <a-select-option v-for="item in refData.menuList" :key="item" :value="item"> {{  item  }}</a-select-option>
            </a-select> -->

            <a-select v-model="refData.fromData.url"  :options="refData.menuList" :field-names="{ value: 'item', label: 'item' }"  placeholder="请选择路由地址" />
           
          </a-form-item>


          <a-form-item v-if="isUrlView" label="权限标识">
            <div class="flex-col-body">
              <a-form-item
                v-for="(item, index) in refData.fromData.permsArr"
                :key="index"
              >
                <a-input v-model="item.name" placeholder="名称" />
                <a-input
                  v-model="item.perms"
                  style="margin-left: 1rem"
                  placeholder="请输入权限标识"
                />
                <div class="flex-row-icon">
                  <icon-close-circle-fill
                    v-if="refData.fromData.permsArr.length > 1"
                    @click="refData.fromData.permsArr.splice(index, 1)"
                  />
                  <icon-plus-circle-fill
                    v-if="refData.fromData.permsArr.length - 1 === index"
                    class="icon-plus-circle-fill"
                    @click="
                      refData.fromData.permsArr.push({
                        menuName: '',
                        perms: '',
                      })
                    "
                  />
                </div>
              </a-form-item>
            </div>
          </a-form-item>


          <a-form-item v-if="isUrlView" name="refresh" label="缓存">
            <a-switch
              v-model:checked="refData.fromData.refresh"
              checked-value="1"
              unchecked-value="0"
            >
              <template #checked> ON </template>
              <template #unchecked> OFF </template>
            </a-switch>
          </a-form-item>

          <a-form-item
            name="sortNumber"
            label="序号"
            :rules="[{ required: true, message: '请输入序号' }]"
            :validate-trigger="['change', 'input', 'blur']"
          >
            <a-input-number v-model="refData.fromData.sortNumber" :min="0" />
          </a-form-item>

          <a-form-item>
            <div class="modal-footer">
              <a-button type="primary" size="large" html-type="submit"
                >确定</a-button
              >
              <a-button size="large" @click="evCancel"> 取消</a-button>
            </div>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>

    <a-modal v-model:visible="refData.visibleIcon" simple :footer="false">
      <div class="font-view">
        <div
          v-for="(item, index) in refData.iconfontArr"
          :key="index"
          class="icon-box"
        >
          <svg-icon
            :icon="item.font_class"
            :class="{
              icon: true,
              'icon-active': item.font_class === refData.fromData.icon,
            }"
            @click="evOnIconName(item.font_class)"
          />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { onMounted, reactive, computed, ref, watch} from "vue";

import { useRoute } from "vue-router";
import { Message, Notification } from '@arco-design/web-vue'
import MonacoEditor from "@/components/MonacoEditor/index.vue"
import iconsvgJson from "@/assets/iconsvg/iconfont.json";
import { useLangStore } from '@/store/modules/langStore'
import {  getParseLang } from '@/utils'
import _ from "lodash";
import { columns } from './config'
import { systemSetMenu, systemFinMenuAll, systemDeleteMenu, systemUpdateMenu } from "@/api/path/system.api"
import { useSystemStore } from '@/store/modules/systemStore'

const route = useRoute();
const lang = useLangStore()
const systemStore = useSystemStore()

 
const refData = reactive({
  visible: false,
  visibleIcon: false,
  dataSource: [],
  fromData: {
    name: "",
    parentId: undefined,
    menu_id: undefined,
    type: "0",
    url: "",
    sortNumber: 99,
    refresh: 0,
    permsArr: [{ name: "", perms: "" }],
  },
  menuTree: [],
  menuList: [],
  iconfontArr: []
});
const menuTreeList = ref([])

const isUrlView = computed(() => {
  // if (refData.fromData.menu_id) {
  //   const obj =  menuTreeList.value.find(item => item.id == refData.fromData.menu_id)
  //   return refData.fromData.menu_id && ["1", "2"].includes(obj.type);
  // }
  // return false;
  return true;
});

const fnTreeData = (data) => {
  return data.map((item) => {
    if (item.children && item.children.length > 0 && item.type !== "3") {
      item.children = item.children.sort((a, b) => {
        if (a.sortNumber === b.sortNumber) {
          return a.id - b.id;
        }
        return a.sortNumber - b.sortNumber;
      });
      item.children = fnTreeData(item.children);
    }
    if (item.type === '2') {
      item.permsArr = item.children;
      Reflect.deleteProperty(item, "children");
    }
    return item;
  });
};

const fnDeleteTreeSon = (data) => {
  return data.filter((item) => {
    item.name = getParseLang(item.name, lang.getLang)
    Reflect.deleteProperty(item, 'icon')
    if (item.children && item.children.length > 0) {
      item.children = fnDeleteTreeSon(item.children);
    }
    return ["1"].includes(item.type);
  });
};

const fnGetFormData = async () => {
  const arr = [];
  const comp = import.meta.glob("../../../views/**/index.vue");
  if (comp) {
    Object.keys(comp).forEach((key) => {
      arr.push(`${comp[key]}`. replace(/^.*import\("\/src\/([^?"]+).*$/, '$1'));
    });
    arr.push("views/system/menu/index.vue")
    refData.menuList = arr
  }
};

const evCancel = () => {
  refData.visibleIcon = false;
  refData.visible = false;
};

const evInitData = async () => {
  evCancel();
  const { data } = await systemFinMenuAll();
  const arr = fnTreeData(_.cloneDeep(data));
  refData.dataSource = arr
  refData.menuTree = fnDeleteTreeSon(_.cloneDeep(data));
  menuTreeList.value = fnGetTreeList(_.cloneDeep(data))
};


const fnGetTreeList = (data) => {
  return data.reduce((iter, val) => {
    if (["1"].includes(val.type)) {
      iter.push(val);
    }
    return val.children ? [...iter, ...fnGetTreeList(val.children)] : iter;
  }, []);
};

const evEdit = async (data) => {
  refData.fromData = data;
  if(!data.permsArr || data.permsArr.length == 0){
    refData.fromData.permsArr = [{ name: "", perms: "" }]
  }
  refData.visible = true;
};

const evHandleSubmit = async (values) => {
  const data = JSON.parse(JSON.stringify(values));
  data.type = "1"
  if (data.url)  data.type = "2";
  if(data.id){
    await systemUpdateMenu(data)
  }else{
    await systemSetMenu(data);
  }
  evInitData();
};

const evDelete = async (id) => {
  await systemDeleteMenu({ id });
  evInitData();
};

const evAddMenu = async () => {
  refData.fromData = {
    name: `{
  "zh-CN": "",
  "en-US": "",
  "th-TH": ""
}`,
    permsArr: [{ name: "", perms: "" }]
  };
  try {
    await fnGetFormData();
  } catch (e) {
    //
  }
  refData.visible = true;
};

const evIconModal = async () => {
  refData.iconfontArr = iconsvgJson.glyphs.filter((item) => {
    return ["menu", "Dh"].includes(item.font_class.split("-")[0]);
  });
  refData.visibleIcon = true;
};

const evOnIconName = (item) => {
  refData.fromData.icon = item;
  refData.fromData = { ...refData.fromData };
  refData.visibleIcon = false;
  Message.success({
    content: `选中  ${item}`,
    duration: 2000,
  });
};

// 上传
const customRequest = async (option) => { 
   const { file } = option.fileItem;
  // 上传
  const fileName = `thumbnail_${file.name}`
  const key = `test/${fileName}`

  const client = await systemStore.getSTSClient()
  const resClient = await client.putObject({
    key: key,
    body: file
  })
  
  if (resClient.statusCode === 200) {
    console.log('上传成功')
    console.log("resClient=",resClient)
  }

};
 
onMounted(() => {
  evInitData()
 
});
</script>

<style scoped lang="less">
.head-title {
  display: flex;
  justify-content: space-between;
  .fn-headTitleDiv();
  padding: 0.5rem 0;
}

.table {
  margin-top: 1.5rem;
  .tag-name {
    margin: 0.2rem;
  }
  .icon {
    font-size: 20px;
  }
}

.icon-append {
  &:hover {
    cursor: pointer;
  }
}

:deep(.arco-col-19) {
  flex: none !important;
  width: 340px !important;
}

.form-box {
  padding-left: 4rem;
  .flex-col-body {
    display: flex;
    flex-direction: column;
    .flex-row-icon {
      min-width: 35px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-left: 10px;
      .icon-plus-circle-fill {
        font-size: 16px;
        margin-left: 0.5rem;
        // color: @orange_1;
        &:hover {
          cursor: pointer;
          transform: scale(1.4);
          // color: @blue_0;
        }
      }
      svg:hover {
        cursor: pointer;
        transform: scale(1.4);
        // color: @red_0;
      }
    }
  }
}
.modal-footer {
  width: 150px;
  margin: 0 auto 16px auto;
  display: flex;
  justify-content: space-between;
}

.font-view {
  display: flex;
  flex-wrap: wrap;
  .icon-box {
    width: 30px;
    height: 30px;
    margin: 10px;
    .icon {
      width: 100%;
      height: 100%;
      font-size: 100px;
      transform: scale(1, 1);
      animation: mymove 1s;
      animation-fill-mode: forwards;
      color: #9696a0;
      cursor: pointer;

      &:hover,
      &.icon-active {
        background: #dbdbf3;
        transform: scale(1, 1);
        animation: mymove2 1s;
        animation-fill-mode: forwards;
      }
    }
  }
}
@keyframes mymove {
  0% {
    transform: scale(1, 1);
  }
  50% {
    transform: scale(1.2, 1.2);
  }
  100% {
    transform: scale(1.1, 1.1);
  }
}
@keyframes mymove2 {
  0% {
    transform: scale(1, 1);
  }
  50% {
    transform: scale(1.3, 1.3);
  }
  100% {
    transform: scale(1.1, 1.1);
  }
}
</style>
