<template>
  <div class="personal">
    <Breadcrumb />
    <div class="personal-head">
      <el-avatar :size="100"
        :src="appStore?.userInfo?.userAvatar ? appStore.userInfo.userAvatar : appStore.avatarDefault" />
      <div class="personal-head-box">
        <div class="personal-head-top">
          <div class="personal-head-left">

            <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="`${ getImgUrl(`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="" v-if="['1', '2'].includes(appStore?.userInfo?.memberType)">{{
                $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>

          </div>
          <div class="personal-head-right">
            <div @click="changeSHow" 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-head-bot">
          <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="btn">
              <el-button type="primary" class="gradient" @click="router.push({
                path: `/order-confirm`,
              })">{{ $t('route.recharge') }}</el-button>
            </div>


            <!-- <div class="personal-user-line"></div> -->

          </div>
          <div class="personal-user-list">
            <div class="personal-user-li">
              <span>{{ collectCount }}</span>
              <span>{{ $t('common.collect') }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="personal-main">
      <div class="personal-left">
        <div class="personal-left-list">
          <template v-for="(item, index) in navList" :key="index">
            <div v-if="item.show" @click="toPath(item, index)" :class="{ active: index == navIndex }"
              class="personal-left-li">
              <img v-if="index == navIndex" :src="item.iconActive" alt="">
              <img v-else :src="item.icon" alt="">
              <div class="">{{ $t(item.name) }}</div>
            </div>
          </template>

        </div>
      </div>
      <div class="personal-right">
        <div class="personal-right-main">
          <router-view />
        </div>

      </div>
    </div>

    <!-- 工单 -->

    <div class="workOrder-dot" @click="show = true">
      <img src="/src/assets/imgs/my/icon9a@2x.png" alt="">
      <div class="">{{ $t('personalCenter.gongdan') }}</div>
    </div>

    <el-dialog v-model="show" :title="`${$t('personalCenter.gongdan')}`" width="784">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane v-for="tab in tabs" :key="tab.name" :label="`${$t(tab.label)}`" :name="tab.name">
          <template v-if="activeName == 0">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
              <el-form-item :label="`${$t('personalCenter.gongdanleixing')}`" prop="issueCategory">
                <el-select v-model="ruleForm.issueCategory"
                  :placeholder="`${$t('personalCenter.gongdanleixing_placeholder')}`" style="width: 100%">
                  <el-option v-for="item in workTypeList" :key="item.value" :label="`${$t(item.label)}`"
                    :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item :label="`${$t('personalCenter.gongdanbiaoti')}`" prop="issueTitle">
                <el-input v-model="ruleForm.issueTitle"
                  :placeholder="`${$t('personalCenter.gongdanbiaoti_placeholder')}`" />
              </el-form-item>
              <el-form-item :label="`${$t('personalCenter.gongdanneirong')}`" prop="issueContent">
                <el-input v-model="ruleForm.issueContent"
                  :placeholder="`${$t('personalCenter.gongdanneirong_placeholder')}`" :rows="10" type="textarea" />
              </el-form-item>
            </el-form>
          </template>
          <template v-else>
            <el-collapse v-model="workName" accordion>
              <el-collapse-item :title="item.issueTitle || `${index + 1}、${item.question}`" :name="item.id"
                v-for="(item, index) in workList" :key="index">
                <template #title>
                  <div class="work-head">
                    <div class="work-head-left">
                      <img v-if="activeName == 2" src="/src/assets/imgs/my/Q@2x.png" alt="">
                      <div class="">{{ `${activeName == 2 ? (index + 1) + '、' : ''}` }}{{ item.issueTitle ||
                        item.question }}</div>
                    </div>
                    <el-tag v-if="activeName == 1" :type="item.issueStatus == 2 ? 'success' : 'primary'">{{ item.issueStatus == 0 ?
                        $t('personalCenter.daijiejue') : item.issueStatus == 2 ? $t('personalCenter.yijiejue') : ''
                        }}</el-tag>
                  </div>
                </template>
                <div class="work-content">
                  <template v-if="activeName == 2">
                    <img src="/src/assets/imgs/my/A@2x.png" alt="">
                    <div class="">{{ item.issueContent || item.answer }}</div>
                  </template>
                  <el-descriptions style="width: 100%;" class="margin-top" :column="2" border v-else :label-width="langStore.currentLang == 'en' ? 180 : 80">
                    <el-descriptions-item>
                      <template #label>
                        <div class="cell-item">{{ $t('personalCenter.gongdanbianhao') }}</div>
                      </template>
                      {{ item.issueNo }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template #label>
                        <div class="cell-item">{{ $t('personalCenter.gongdanzhuangtai') }}</div>
                      </template>

                      <el-tag :type="item.issueStatus == 2 ? 'success' : 'primary'">{{ item.issueStatus == 0 ?
                        $t('personalCenter.daijiejue') : item.issueStatus == 2 ? $t('personalCenter.yijiejue') : ''
                        }}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template #label>
                        <div class="cell-item">{{ $t('personalCenter.gongdanleixing') }}</div>
                      </template>
                      {{ $t(getName(item.issueCategory)) }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template #label>
                        <div class="cell-item">{{ $t('personalCenter.gongdanbiaoti') }}</div>
                      </template>
                      {{ item.issueTitle }}

                    </el-descriptions-item>
                    <el-descriptions-item :span="2">
                      <template #label>
                        <div class="cell-item">{{ $t('personalCenter.gongdanneirong') }}</div>
                      </template>
                      {{ item.issueContent }}
                    </el-descriptions-item>
                    <el-descriptions-item :span="2" v-if="item.issueStatus == 2">
                      <template #label>
                        <div class="cell-item">{{ $t('personalCenter.gongdanhuifu') }}</div>
                      </template>
                      {{ item.remark }}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </el-collapse-item>
            </el-collapse>
            <template v-if="workList && workList.length">
              <Pagination :total="workForm.total" :page-size="workForm.pageSize" :current-page="workForm.pageNum"
                @page-change="handlePageChange" />
            </template>
            <el-empty v-else :description="$t('common.empty')" />
          </template>

        </el-tab-pane>
      </el-tabs>
      <template #footer v-if="activeName == 0">
        <div class="dialog-footer flex-center">
          <el-button @click="resetForm">{{ $t('common.cancel') }}</el-button>
          <el-button class="gradient" type="primary" @click="submitForm(ruleFormRef)">{{ $t('common.confirm')
          }}</el-button>
        </div>
      </template>
    </el-dialog>



    <el-dialog v-model="dialogVisible" :title="$t('personalCenter.editProfile')" width="784" :destroy-on-close="true">
      <el-form ref="userFormRef" :model="userInfo" label-width="auto" label-position="top" :rules="rules">
        <el-row :gutter="16">
          <el-col :span="24">
            <div class="flex-center">

              <el-form-item label="">
                <!-- $t('personalCenter.uploadAvatar') -->
                <!-- 图片类型 -->
                <FileUploader ref="fileUploader" accept="image/*" :multiple="false" :limit="1" :auto-upload="true"
                  :isUploadAvatar="true"
                  list-type="picture-card" :data="{ directory: 'workflow' }" buttonText="" v-model="coverImage" tip="" />
              </el-form-item>
            </div>
          </el-col>
          
           <el-col :span="12">
            <el-form-item :label="$t('personalCenter.nickName')" prop="nickName">
              <el-input v-model="userInfo.nickName" :placeholder="$t('personalCenter.pinickName')" class="inputStyle"
                :input-style="{
                  backgroundColor: 'transparent',
                }" maxlength="15" />
            </el-form-item>
          </el-col>
         
          <el-col :span="12">
            <el-form-item :label="$t('personalCenter.loginPhone')">
              <el-input :disabled="appStore?.userInfo?.userPhone ? true : false" v-model="userInfo.userPhone"
                :placeholder="$t('workflowTradeAdd.placeholderPhoneNumber')" class="inputStyle" :input-style="{
                  backgroundColor: 'transparent',
                }" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!appStore?.userInfo?.userPhone">
            <el-form-item :label="$t('personalCenter.phoneCode')" prop="verifyCode">
              <el-input v-model="userInfo.verifyCode" maxlength="6" :placeholder="$t('login.placeholderCaptcha')"
                class="inputStyle" :input-style="{
                  backgroundColor: 'transparent',
                }">
                <template #append>
                  <el-button :disabled="smsCountdown > 0" @click="sendSmsCode" style="width:120px"
                    :class="{ 'countdown-btn': smsCountdown > 0 }" size="small">
                    {{ smsCountdown > 0 ? `${smsCountdown}s` : $t('login.sendCaptcha') }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('personalCenter.loginEmail')">
              <el-input v-model="userInfo.email" :placeholder="$t('workflowTradeAdd.placeholderEmail')"
                class="inputStyle" :input-style="{
                  backgroundColor: 'transparent',
                }" :disabled="appStore?.userInfo?.email ? true : false" />
            </el-form-item>

          </el-col>
          <el-col :span="12" v-if="!appStore?.userInfo?.email">
            <el-form-item :label="$t('personalCenter.emailCode')" prop="verifyCode">
              <el-input v-model="userInfo.verifyCode" maxlength="6" :placeholder="$t('login.placeholderCaptcha')"
                class="inputStyle" :input-style="{
                  backgroundColor: 'transparent',
                }">
                <template #append>
                  <el-button :disabled="smsCountdown > 0" @click="sendSmsCode" style="width:120px"
                    :class="{ 'countdown-btn': smsCountdown > 0 }" size="small">
                    {{ smsCountdown > 0 ? `${smsCountdown}s` : $t('login.sendCaptcha') }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('personalCenter.n8nAccout')">
              <el-input disabled v-model="userInfo.n8nAccount" :placeholder="$t(!appStore?.userInfo?.email ? 'personalCenter.bdyxjcjzh' : 'personalCenter.createN8n')"
                class="inputStyle" :input-style="{
                  backgroundColor: 'transparent',
                }">
                <template #append v-if="appStore?.userInfo?.email && !appStore?.userInfo?.n8nAccount">
                  <el-tooltip class="box-item" effect="dark" :content="$t('personalCenter.ceraten8n')" placement="top">
                    <el-button @click="createAi('0')" :icon="Refresh" />
                  </el-tooltip>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('personalCenter.n8nPassword')">
              <el-input v-model="userInfo.n8nPassword" :placeholder="$t('personalCenter.createN8n')" class="inputStyle"
                :input-style="{
                  backgroundColor: 'transparent',
                }" readonly type="password" show-password />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('personalCenter.cozeAccout')">
              <el-input disabled v-model="userInfo.cozeAccount" :placeholder="$t(!appStore?.userInfo?.email ? 'personalCenter.bdyxjcjzh' :'personalCenter.createCoze')"
                class="inputStyle" :input-style="{
                  backgroundColor: 'transparent',
                }">
                <template #append v-if="appStore?.userInfo?.email && !appStore?.userInfo?.cozeAccount">
                  <el-tooltip class="box-item" effect="dark" :content="$t('personalCenter.ceratenCoze')"
                    placement="top">
                    <el-button @click="createAi('1')" :icon="Refresh" />
                  </el-tooltip>
                </template>
              </el-input>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('personalCenter.cozePassword')">
              <el-input v-model="userInfo.cozePassword" :placeholder="$t('personalCenter.createCoze')"
                class="inputStyle" :input-style="{
                  backgroundColor: 'transparent',
                }" readonly type="password" show-password />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('personalCenter.difyAccout')">
              <el-input disabled v-model="userInfo.difyAccount" :placeholder="$t(!appStore?.userInfo?.email ? 'personalCenter.bdyxjcjzh' :'personalCenter.createDify')"
                class="inputStyle" :input-style="{
                  backgroundColor: 'transparent',
                }">
                <template #append v-if="appStore?.userInfo?.email && !appStore?.userInfo?.difyAccount">
                  <el-tooltip class="box-item" effect="dark" :content="$t('personalCenter.ceratenDify')"
                    placement="top">
                    <el-button @click="createAi('2')" :icon="Refresh" />
                  </el-tooltip>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('personalCenter.difyPassword')">
              <el-input v-model="userInfo.difyPassword" :placeholder="$t('personalCenter.createDify')"
                class="inputStyle" :input-style="{
                  backgroundColor: 'transparent',
                }" readonly type="password" show-password />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('personalCenter.fastGptAccout')">
              <el-input disabled v-model="userInfo.fastGptAccount" :placeholder="$t(!appStore?.userInfo?.email ? 'personalCenter.bdyxjcjzh' :'personalCenter.createFastGpt')"
                class="inputStyle" :input-style="{
                  backgroundColor: 'transparent',
                }">
                <template #append v-if="appStore?.userInfo?.email && !appStore?.userInfo?.fastGptAccount">
                  <el-tooltip class="box-item" effect="dark" :content="$t('personalCenter.ceratenFastGpt')"
                    placement="top">
                    <el-button @click="createAi('3')" :icon="Refresh" />
                  </el-tooltip>

                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('personalCenter.fastGptPassword')">
              <el-input v-model="userInfo.fastGptPassword" :placeholder="$t('personalCenter.createFastGpt')"
                class="inputStyle" :input-style="{
                  backgroundColor: 'transparent',
                }" readonly type="password" show-password />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item :label="`${$t('personalCenter.skillTag')}(${ $t('personalCenter.zdtjwg') })`">
              <div class="flex tags flex_1">
                <el-tag v-for="tag in dynamicTags" :key="tag" closable @close="handleClose(tag)">
                  {{ tag }}
                </el-tag>
                <template v-if="dynamicTags.length < 5">
                  <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="w-20" size="small"
                  @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" maxlength="5" show-word-limit :placeholder="
                    $t('personalCenter.psrjnbq')
                  ">
                  <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>
                </template>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button @click="userInfo = {}, dialogVisible = false">{{ $t('common.cancel') }}</el-button>
          <el-button class="gradient" type="primary" @click="handleConfirm(userFormRef)">
            {{ $t('common.confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>

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

import { Plus, Refresh } 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, getSmsCode, getEmailCode,sendBindCode } from '@/api/auth.js'

import { checkIn, queryCollectCount, issue, issueList, faqList, getfaq, createAiAccount } from '@/api/my.js'

import DGTMessage from '@/utils/message'

import { useI18n } from 'vue-i18n'

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

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


import type { FormInstance, FormRules } from 'element-plus'
import { useLangStore } from '@/pinia/langStore'
const langStore = useLangStore();
interface RuleForm {
  issueCategory: string
  issueTitle: string
  issueContent: string
}

const ruleFormRef = ref(null);

const userFormRef = ref();

const { t } = useI18n()

const appStore = useAppStore();

const route = useRoute()

const router = useRouter()

const getImgUrl = (path) => {
  return new URL(`/src/assets/imgs/my/${path}`, import.meta.url).href
}

const navList = ref([
  {
    name: 'personalCenter.myWallet',
    path: '/personal-center/wallet',
    icon: getImgUrl('icon1@2x.png'),
    iconActive: getImgUrl('icon1a@2x.png'),
    show: true
  },
  {
    name: 'personalCenter.membershipInfo',
    path: '/personal-center/member-details',
    icon: getImgUrl('icon2@2x.png'),
    iconActive: getImgUrl('icon2a@2x.png'),
    show: true
  },
  {
    name: 'personalCenter.myCollection',
    path: '/personal-center/collection',
    icon: getImgUrl('icon3@2x.png'),
    iconActive: getImgUrl('icon3a@2x.png'),
    show: true
  },
  {
    name: 'personalCenter.myDemand',
    path: '/personal-center/demand',
    icon: getImgUrl('icon4@2x.png'),
    iconActive: getImgUrl('icon4a@2x.png'),
    show: true
  },
  {
    name: 'personalCenter.myOrders',
    path: '/personal-center/orders',
    icon: getImgUrl('icon5@2x.png'),
    iconActive: getImgUrl('icon5a@2x.png'),
    show: true
  },
  {
    name: 'personalCenter.myInvoice',
    path: '/personal-center/invoice',
    icon: getImgUrl('icon6@2x.png'),
    iconActive: getImgUrl('icon6a@2x.png'),
    show: true
  },
  {
    name: 'personalCenter.myWorkflow',
    path: '/personal-center/workflow',
    icon: getImgUrl('icon7@2x.png'),
    iconActive: getImgUrl('icon7a@2x.png'),
    show: true
  },
  {
    name: 'personalCenter.businessManagement',
    path: '/personal-center/business-management',
    icon: getImgUrl('icon8@2x.png'),
    iconActive: getImgUrl('icon8a@2x.png'),
    show: false
  },
  // {
  //   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 show = ref(false)

const tabs = ref([
  { label: 'personalCenter.tijiaogongdan', name: 0 },
  { label: 'personalCenter.lishigongdan', name: 1 },
  { label: 'personalCenter.changjianwenti', name: 2 }
])

const workList = ref([])

const workForm = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
})

const activeName = ref(0)

const workName = ref(null)

const workTypeList = ref([
  {
    value: 'account',
    label: 'personalCenter.zhanghaowenti'
  },
  {
    value: 'payment',
    label: 'personalCenter.zhifuwenti'
  },
  {
    value: 'course',
    label: 'personalCenter.kechengwenti'
  },
  {
    value: 'workflow',
    label: 'personalCenter.gongzuoliuwenti'
  },
  {
    value: 'other',
    label: 'personalCenter.qitawenti'
  }
])
// 获取工单分类
const getName = (value) => {
  let txt = ''
  workTypeList.value.forEach(item => {
    if (item.value == value) {
      txt = item.label
    }
  })
  return txt
}

const ruleForm = ref<RuleForm>({
  issueCategory: '',
  issueTitle: '',
  issueContent: ''
})

const rules = ref<FormRules<RuleForm>>({
  issueCategory: [
    {
      required: true,
      message: t('personalCenter.gongdanleixing_placeholder'),
      trigger: 'change',
    },
  ],
  issueTitle: [
    { required: true, message: t('personalCenter.gongdanbiaoti_placeholder'), trigger: 'blur' },
  ],
  issueContent: [
    { required: true, message: t('personalCenter.gongdanneirong_placeholder'), trigger: 'blur' },
  ],
  nickName: [
    {
      required: true, message: t('personalCenter.pinickName'), trigger: 'blur'
    }
  ]
})

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 smsCountdown = ref(0)
const passwordresetCountdown = ref(0)
const emailCountdown = ref(0)

// 正则表达式
const PHONE_REGEX = /^1[3-9]\d{9}$/;
// 优化后的邮箱正则（兼顾准确性和实用性）
const EMAIL_REGEX = /^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/;
const isPasswordPhone = computed(() => {
  return PHONE_REGEX.test(passwordForm.account);
});

const isPasswordEmail = computed(() => {
  return EMAIL_REGEX.test(passwordForm.account);
});

// 创建ai相关账号
const createAi = async (creatFlag) => {
  let res = await createAiAccount({ creatFlag });
  if (res.code === 200) {
    if (creatFlag == '0') {
      userInfo.value.n8nAccount = res.data.n8nAccount;
      userInfo.value.n8nPassword = res.data.n8nPassword;
    } else if (creatFlag == '1') {
      userInfo.value.cozeAccount = res.data.cozeAccount;
      userInfo.value.cozePassword = res.data.cozePassword;
    } else if (creatFlag == '2') {
      userInfo.value.difyAccount = res.data.difyAccount;
      userInfo.value.difyPassword = res.data.difyPassword;
    } else if (creatFlag == '3') {
      userInfo.value.fastGptAccount = res.data.fastGptAccount;
      userInfo.value.fastGptPassword = res.data.fastGptPassword;
    }
    appStore.USERINFO();
    DGTMessage.success(`${t('common.success')}`)
  }
}

// 发送短信验证码
const sendSmsCode = async () => {
  let account = appStore?.userInfo?.userPhone ? userInfo.value.email : userInfo.value.userPhone
  if (!account) {
    DGTMessage.warning(appStore?.userInfo?.userPhone ? t('workflowTradeAdd.placeholderEmail') : t('workflowTradeAdd.placeholderPhoneNumber'))
    return
  }

  // 验证手机号格式 
  if ((!PHONE_REGEX.test(account) && appStore?.userInfo?.email) || (!EMAIL_REGEX.test(account) && appStore?.userInfo?.userPhone)) {
    DGTMessage.warning(appStore?.userInfo?.userPhone ? t('common.pleaseInputRightEmail') : t('common.pleaseInputRightPhoneNumber'))
    return
  }

  let res = await sendBindCode({
    account: account,
    type: appStore?.userInfo?.userPhone ? 'email' : 'phone'
  });

  if (res.code !== 200) {
    return
  }

  // 模拟发送验证码
  DGTMessage.success(t('login.captchaSendSuccess'))

  // 开始倒计时
  smsCountdown.value = 60
  const timer = setInterval(() => {
    smsCountdown.value--
    if (smsCountdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}


const handlePageChange = (page, pageSize) => {
  workForm.value.pageNum = page;
  if(pageSize)workForm.value.pageSize = pageSize;
  getList()
}

const handleClick = async (tab) => {
  activeName.value = tab.props.name
  workForm.value.pageNum = 1;
  getList()
}

const getList = async () => {
  if (activeName.value == 0) return;
  let api = activeName.value == 1 ? issueList(workForm.value) : faqList(workForm.value);
  let res = await api;
  workList.value = res.rows;
  workForm.value.total = res.total;
}


const resetForm = () => {
  show.value = false;
  for (const key in ruleForm.value) {
    ruleForm.value[key] = ''
  }
}

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl[0].validate(async (valid, fields) => {
    if (valid) {
      let res = await issue(ruleForm.value);
      if (res.code === 200) {
        resetForm();
        DGTMessage.success(`${t('common.submitSuccess')}`)
      }
    }
  })
}

// 更新用户信息
const handleConfirm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (!appStore.userInfo.userPhone || !appStore.userInfo.email) {
        userInfo.value.bindType = appStore.userInfo.userPhone ? 'email' : 'phone'
      }
      let obj = !appStore.userInfo.userPhone && userInfo.value.userPhone || !appStore.userInfo.email && userInfo.value.email ? { email: userInfo.value.email, bindType: userInfo.value.bindType, userPhone: userInfo.value.userPhone, verifyCode: userInfo.value.verifyCode } : {}
      let res = await updateUserInfo({
        nickName: userInfo.value.nickName,
        userAvatar: coverImage.value.map(item => item.url).join(';'),
        skillTags: dynamicTags.value.join(','),
        ...obj
      })
      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(',')
  } else {
    dynamicTags.value = []
  }
  userInfo.value = res.user;
  navList.value.forEach(item => {
    if (item.name === 'personalCenter.businessManagement' && res?.user?.isCompanyAuth == 1) {
      item.show = true;
    }
  })
}

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;
}


const changeSHow = async () => {
  await getInfo()
  dialogVisible.value = true;
}
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;

  .personal-head-box {
    flex: 1;
    margin-left: 16px;
  }

  .personal-head-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .personal-head-bot {
    margin-top: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .personal-user-list {
      display: flex;

      align-items: center;

      .btn {
        margin-left: 16px;
      }

      .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-left {
    display: flex;

    .personal-user-info {


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

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


    }
  }

  .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;
      min-height: calc(100vh - 350px);
    }
  }
}

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

.inputStyle {
  width: 368px;
  height: 36px;
  background: #F5F7FA;
  border-radius: 4px;
  border: 1px solid #F2F6FC;
}

.workOrder-dot {
  display: flex;
  cursor: pointer;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  right: 80px;
  bottom: 70px;
  width: 84px;
  height: 84px;
  position: fixed;
  color: #2D71FF;
  font-size: 14px;
  background: #FFFFFF;
  box-shadow: 2px 2px 10px 0px rgba(45, 113, 255, 0.15);
  border-radius: 50px;

  img {
    width: 24px;
    height: 24px;
  }
}

.work-head {
  display: flex;
  color: #333333;
  font-size: 18px;
  font-weight: bold;
  align-items: center;
  justify-content: space-between;

  .work-head-left {
    display: flex;
    align-items: center;
  }

  img {
    width: 24px;
    height: 24px;
    margin-right: 8px;
  }
}

.work-content {
  padding: 16px;
  background: #F5F7FA;
  border-radius: 16px;
  color: #333333;
  line-height: 24px;
  font-size: 16px;
  display: flex;

  img {
    width: 24px;
    height: 24px;
    margin-right: 16px;
  }
}

:deep(.el-collapse-item__header) {
  padding: 0 8px;
  background-color: transparent;
}

:deep(.el-collapse-item__content) {
  padding: 0 16px 16px;
}

.w-20 {
  width: 200px;
}
</style>