<template>
  <div class="personal">
    <Breadcrumb />
    <div class="personal-head">
      <div class="personal-head-left">
        <el-avatar :size="100" :src="appStore?.userInfo?.userAvatar ? appStore.userInfo.userAvatar : appStore.avatarDefault" />
        <div class="personal-user-info">
          <div class="personal-username">
            <div class="">{{ appStore?.userInfo?.nickName }}</div>
            <template v-if="['0', '1', '2'].includes(appStore?.userInfo?.memberType)"></template>
            <img :src="`/src/assets/imgs/my/vip${appStore?.userInfo?.memberType}@2x.png`" alt="">
            <!-- memberType  会员类型memberType 会员类型分为企业会员（2）和个人会员（1）、免费会员（0） -->
          </div>
          <div class="personal-user-phone mt4">{{ $t('personalCenter.phoneNumber') }}：{{ appStore?.userInfo?.userPhone }}
          </div>
          <div class="">{{ $t('personalCenter.vipEndTime') }}: {{ appStore?.userInfo?.memberExpire }}</div>
          <div class="mt4" v-if="appStore?.userInfo?.skillTags">
            <el-button v-for="(item,index) in appStore.userInfo.skillTags.split(',')" type="primary" plain>{{ item }}</el-button>
          </div>
          <div class="personal-user-list">
            <div class="personal-user-li">
              <span>{{ appStore?.userInfo?.pointsBalance || 0}}</span>
              <span>{{ $t('common.mibi') }}</span>
            </div>
            <div class="personal-user-line"></div>
            <div class="personal-user-li">
              <span>{{ appStore?.userInfo?.baoMiBalance || 0 }}</span>
              <span>{{ $t('common.baomibi') }}</span>
            </div>
            <div class="personal-user-line"></div>
            <div class="personal-user-li">
              <span>{{ collectCount }}</span>
              <span>{{ $t('common.collect') }}</span>
            </div>
          </div>
        </div>

      </div>
      <div class="personal-head-right">
        <div @click="dialogVisible = true" class="personal-head-right-li">
          <img src="/src/assets/imgs/my/bianji@2x.png" alt="">
          <div class="">{{ $t('personalCenter.editProfile') }}</div>
        </div>
        <div @click="router.push({ path: '/member' })" class="personal-head-right-li">
          <img src="/src/assets/imgs/my/huiyuan@2x.png" alt="">
          <div class="">{{ $t('personalCenter.openMembership') }}</div>
        </div>
        <div @click="signIn" class="personal-head-right-li gradient">
          <img src="/src/assets/imgs/my/qiandao@2x.png" alt="">
          <div class="">{{ $t('personalCenter.checkIn') }}</div>
        </div>
      </div>
    </div>
    <div class="personal-main">
      <div class="personal-left">
        <div class="personal-left-list">
          <div @click="toPath(item, index)" :class="{ active: index == navIndex }" class="personal-left-li"
            v-for="(item, index) in navList" :key="index">
            <img v-if="index == navIndex" :src="item.iconActive" alt="">
            <img v-else :src="item.icon" alt="">
            <div class="">{{ $t(item.name) }}</div>
          </div>
        </div>
      </div>
      <div class="personal-right">
        <div class="personal-right-main">
          <router-view />
        </div>

      </div>
    </div>

    <el-dialog v-model="dialogVisible" title="编辑资料" width="784">
      <el-form :model="userInfo" label-width="auto" label-position="top">

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="上传头像">
              <!-- 图片类型 -->
              <FileUploader ref="fileUploader" accept="image/*" :multiple="false" :limit="1" :auto-upload="true"
                list-type="picture-card" :data="{ directory: 'workflow' }" buttonText="" v-model="coverImage" tip="" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="昵称">
              <el-input v-model="userInfo.nickName" :placeholder="$t('common.placeholderInput')" class="inputStyle"
                :input-style="{
                  backgroundColor: 'transparent',
                }" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录手机号">
              <el-input :readonly="userInfo.userPhone ? true : false" v-model="userInfo.userPhone"
                :placeholder="$t('common.placeholderInput')" class="inputStyle" :input-style="{
                  backgroundColor: 'transparent',
                }" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="n8n账号">
              <el-input v-model="userInfo.name" :placeholder="$t('common.placeholderInput')" class="inputStyle"
                :input-style="{
                  backgroundColor: 'transparent',
                }" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Coze账号">
              <el-input v-model="userInfo.name" :placeholder="$t('common.placeholderInput')" class="inputStyle"
                :input-style="{
                  backgroundColor: 'transparent',
                }" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="Dify账号">
              <el-input v-model="userInfo.name" :placeholder="$t('common.placeholderInput')" class="inputStyle"
                :input-style="{
                  backgroundColor: 'transparent',
                }" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="FastGpt账号">
              <el-input v-model="userInfo.name" :placeholder="$t('common.placeholderInput')" class="inputStyle"
                :input-style="{
                  backgroundColor: 'transparent',
                }" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="登录邮箱">
              <el-input v-model="userInfo.name" :placeholder="$t('common.placeholderInput')" class="inputStyle"
                :input-style="{
                  backgroundColor: 'transparent',
                }" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="技能标签">
              <div class="flex tags flex_1">
                <el-tag v-for="tag in dynamicTags" :key="tag" closable @close="handleClose(tag)">
                  {{ tag }}
                </el-tag>
                <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="w-20" size="small"
                  @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" maxlength="5">
                  <template #append>
                    <el-button :icon="Plus" />
                  </template></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput">
                  + {{ $t('common.addTags') }}
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button @click="dialogVisible = false">{{ $t('common.cancel') }}</el-button>
          <el-button class="gradient" type="primary" @click="handleConfirm">
            {{ $t('common.confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script setup lang="ts">

import { Plus } from '@element-plus/icons-vue'

import { useAppStore } from '@/pinia/appStore'

import { ref, onMounted, computed, nextTick } from 'vue';


import type { InputInstance } from 'element-plus'

import { useRoute, useRouter } from 'vue-router'

import { getUserInfo,updateUserInfo } from '@/api/auth.js'

import { checkIn, queryCollectCount } from '@/api/my.js'

import DGTMessage from '@/utils/message'

import { useI18n } from 'vue-i18n'

import FileUploader from '@/components/FileUploader.vue'

const { t } = useI18n()

const appStore = useAppStore();

const route = useRoute()

const router = useRouter()

const navList = ref([
  {
    name: 'personalCenter.myWallet',
    path: '/personal-center/wallet',
    icon: '/src/assets/imgs/my/icon1@2x.png',
    iconActive: '/src/assets/imgs/my/icon1a@2x.png'
  },
  {
    name: 'personalCenter.membershipInfo',
    path: '/personal-center/member-details',
    icon: '/src/assets/imgs/my/icon2@2x.png',
    iconActive: '/src/assets/imgs/my/icon2a@2x.png'
  },
  {
    name: 'personalCenter.myCollection',
    path: '/personal-center/collection',
    icon: '/src/assets/imgs/my/icon3@2x.png',
    iconActive: '/src/assets/imgs/my/icon3a@2x.png'
  },
  {
    name: 'personalCenter.myDemand',
    path: '/personal-center/demand',
    icon: '/src/assets/imgs/my/icon4@2x.png',
    iconActive: '/src/assets/imgs/my/icon4a@2x.png'
  },
  {
    name: 'personalCenter.myOrders',
    path: '/personal-center/orders',
    icon: '/src/assets/imgs/my/icon5@2x.png',
    iconActive: '/src/assets/imgs/my/icon5a@2x.png'
  },
  {
    name: 'personalCenter.myInvoice',
    path: '/personal-center/invoice',
    icon: '/src/assets/imgs/my/icon6@2x.png',
    iconActive: '/src/assets/imgs/my/icon6a@2x.png'
  },
  {
    name: 'personalCenter.myWorkflow',
    path: '/personal-center/workflow',
    icon: '/src/assets/imgs/my/icon7@2x.png',
    iconActive: '/src/assets/imgs/my/icon7a@2x.png'
  },
  {
    name: 'personalCenter.businessManagement',
    path: '/personal-center/business-management',
    icon: '/src/assets/imgs/my/icon8@2x.png',
    iconActive: '/src/assets/imgs/my/icon8a@2x.png',
    show:true,
  },
  // {
  //   name: 'personalCenter.serviceManagement',
  //   path: '/personal-center/business-management',
  //   icon: '/src/assets/imgs/my/icon9@2x.png',
  //   iconActive: '/src/assets/imgs/my/icon9a@2x.png'
  // }
])

const dialogVisible = ref(false)

const navIndex = computed(() => {
  switch (route.name) {
    case 'Wallet':
      return 0
      break;
    case 'MemberDetails':
      return 1
      break;
    case 'Wallet':
      return 0
      break;
    case 'Collection':
      return 2
      break;
    case 'Demand':
      return 3
      break;
    case 'Orders':
      return 4
      break;
    case 'Invoice':
      return 5
      break;
    case 'Workflow':
      return 6
      break;
    case 'BusinessManagement':
      return 7
      break;
    default:
      break;
  }
  return null;
})

const userInfo = ref({})//用户信息

const coverImage = ref([]);

// 更新用户信息
const handleConfirm = async () =>{
  let res = await updateUserInfo({
    nickName: userInfo.value.nickName,
    userAvatar:coverImage.value.map(item => item.url).join(';'),
    skillTags:dynamicTags.value.join(','),
    userPhone:userInfo.value.userPhone,
  })
  if (res.code === 200) {
    appStore.USERINFO();
    DGTMessage.success(`${t('common.modify')}${t('common.success')}`)    
    dialogVisible.value = false;
  }
}

const toPath = (item: any, index: number) => {
  if (item.path) {
    router.push(item.path);
  }
};
// 签到
const signIn = async () => {
  let res = await checkIn({ actionType: 1 });
  if (res.code === 200) {
    appStore.USERINFO();
    DGTMessage.success(`${t('personalCenter.checkIn')}${t('common.success')}`)
  }
}
// 获取用户信息
const getInfo = async () => {
  let res = await getUserInfo();
  if (res?.user?.userAvatar) {
    coverImage.value = [{url:res.user.userAvatar}]
  }
  if (res?.user?.skillTags) {
    dynamicTags.value = res.user.skillTags.split(',')
  }
  userInfo.value = res.user;
}

const collectCount = ref(0)

const inputValue = ref('')

const dynamicTags = ref([])

const inputVisible = ref(false)

const InputRef = ref<InputInstance>()

const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

const getCount = async () => {
  let res = await queryCollectCount();
  collectCount.value = res?.data?.collectCount;
}

onMounted(() => {
  getInfo()
  getCount()
})
</script>
<style lang="scss" scoped>
div {
  -webkit-user-select: none;
  /* Safari, Chrome */
  -moz-user-select: none;
  /* Firefox */
  -ms-user-select: none;
  /* IE 10+ */
  user-select: none;
  /* 标准语法 */
}

.personal-head {
  border-radius: 16px;
  padding: 24px 16px;
  background: #FFFFFF;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .personal-head-left {
    display: flex;

    .personal-user-info {
      margin-left: 16px;

      .personal-username {
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: bold;
        color: #333333;

        img {
          width: 68px;
          height: 21px;
          margin-left: 8px;
        }
      }

      .personal-user-list {
        display: flex;
        margin-top: 16px;
        align-items: center;

        .personal-user-li {
          span {
            color: #333333;
            font-size: 14px;

            &:first-child {
              font-size: 28px;
              font-weight: bold;
              margin-right: 10px;
            }
          }
        }

        .personal-user-line {
          margin: 0 16px;
          height: 20px;
          width: 2px;
          background: #EBEEF5;
        }
      }
    }
  }

  .personal-head-right {
    display: flex;
    align-items: center;

    .personal-head-right-li {
      display: flex;
      padding: 9px 16px;
      align-items: center;
      margin-left: 8px;
      // height: 32px;
      background: #EAF0FF;
      border-radius: 4px;
      cursor: pointer;

      &:first-child {
        margin-left: 0;
      }

      &:last-child {
        background: linear-gradient(270deg, #0055FE 0%, #C832FA 100%);

        div {
          color: #FFFFFF;
        }
      }

      img {
        width: 14px;
        height: 14px;
        margin-right: 4px;
      }

      div {
        color: #2D71FF;
        font-size: 14px;
      }

      &:hover {
        opacity: 0.7;
      }
    }
  }
}

.personal-main {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;

  .personal-left {
    width: 300px;

    .personal-left-list {
      background: #FFFFFF;
      border-radius: 16px;
      padding: 8px;

      .personal-left-li {
        height: 56px;
        display: flex;
        align-items: center;
        padding: 0 8px;
        font-size: 16px;
        color: #333333;
        cursor: pointer;
        border-radius: 8px;

        img {
          width: 20px;
          height: 20px;
          margin-right: 4px;
        }

        &:hover {
          background: #F5F7FF;
        }
      }

      .active {
        position: relative;
        background: #EAF0FF;

        &::after {
          top: 50%;
          transform: translateY(-50%);
          content: '';
          position: absolute;
          right: 8px;
          width: 4px;
          height: 24px;
          background: #2D71FF;
          border-radius: 2px;
        }

        div {
          color: #2D71FF;
        }
      }
    }
  }

  .personal-right {
    flex: 1;

    margin-left: 16px;

    .personal-right-main {
      padding: 0 16px;
      border-radius: 16px;
      background: #FFFFFF;
    }
  }
}

.tags {
  flex-wrap: wrap;
  gap: 16px;
}

.inputStyle {
  width: 368px;
  height: 36px;
  background: #F5F7FA;
  border-radius: 4px;
  border: 1px solid #F2F6FC;
  ::v-deep .el-input__wrapper {
    background-color: transparent;
  }
}
</style>