<template>
  <div
    class="user-page flex-column card h-100 overflow-hidden"
    style="position: relative"
  >
    <div class="card-header">
      <span>系统配置</span>
    </div>
    <div class="cardBox">
      <div v-for="(item, index) in formList" style="width: 600px" :key="index">
        <el-form
          v-if="item.type === 'RIIN'"
          class="form"
          ref="formRef"
          label-width="120"
          :model="item"
        >
          <div class="formBox">
            <el-form-item label="转至RIIN生产">
              <el-switch
                v-model="item.enable"
                class="ml-2"
                style="--el-switch-on-color: #42b983"
              />
            </el-form-item>
            <div class="formContent" v-if="item.enable">
              <el-form-item
                label="账号"
                prop="appKey"
                :rules="[{ required: true, message: '请输入RIIN账号' }]"
              >
                <ElInput
                  ref="productionOrderRef"
                  v-model="item.appKey"
                  placeholder="请输入RIIN账号"
                  clearable
                  style="width: 100%"
              /></el-form-item>
              <el-form-item
                label="App Secret"
                prop="appSecret"
                :rules="[{ required: true, message: '请输入App Secret' }]"
              >
                <ElInput
                  ref="productionOrderRef"
                  v-model="item.appSecret"
                  placeholder="请输入App Secret"
                  clearable
                  style="width: 100%"
              /></el-form-item>
            </div>
          </div>

          <ElButton
            class="btn"
            color="#42b983"
            @click="saveConfiguration(item, index)"
            >保存配置</ElButton
          >
        </el-form>
        <el-form
          v-if="item.type === 'TRACK'"
          class="form"
          ref="formRef"
          label-width="120"
          :model="item"
        >
          <div class="formBox">
            <el-form-item label="物流轨迹跟踪">
              <el-switch
                v-model="item.enable"
                class="ml-2"
                style="--el-switch-on-color: #42b983"
              />
            </el-form-item>
            <div class="formContent" v-if="item.enable">
              <el-form-item
                label="17Track账号"
                prop="appKey"
                :rules="[{ required: true, message: '请输入17Track账号' }]"
              >
                <ElInput
                  ref="productionOrderRef"
                  v-model="item.appKey"
                  placeholder="请输入17Track账号"
                  clearable
                  style="width: 100%"
              /></el-form-item>
              <el-form-item
                label="账号Token"
                prop="token"
                :rules="[{ required: true, message: '请输入账号Token' }]"
              >
                <ElInput
                  ref="productionOrderRef"
                  v-model="item.token"
                  placeholder="请输入账号Token"
                  clearable
                  style="width: 100%"
              /></el-form-item>
            </div>
          </div>

          <ElButton
            class="btn"
            color="#42b983"
            @click="saveConfiguration(item, index)"
            >保存配置</ElButton
          >
        </el-form>
      </div>
    </div>
    <div class="logBox">
      <div>操作日志</div>
      <LogList :log-list="logList" style="font-size: 14px; height: 90%" />
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  addExternalAuthorisationApi,
  getExternalAuthorisationListApi,
  baseExternalAccountLogsApi,
} from '@/api/externalAuth'
import { ExternalAuthListData } from '@/types/api/externalAuth'

interface formType {
  id?: number
  enable?: boolean
  appKey?: string
  appSecret?: string
  type?: string
}

const formRef = ref()

const logList = ref([])
async function saveConfiguration(item: formType, index: number) {
  let loading
  try {
    await formRef.value[index]?.validate()
    const params = { ...item }

    const url = !params.id
      ? 'factory/baseExternalAccount/add'
      : 'factory/baseExternalAccount/update'
    loading = ElLoading.service({
      fullscreen: true,
      text: '操作中...',
      background: 'rgba(0, 0, 0, 0.3)',
    })
    const res = await addExternalAuthorisationApi(url, params)
    console.log(res)
    // ElMessage.success('保存配置成功')
    await ElMessageBox.confirm('保存配置成功！！需重新登录才能生效', '提示', {
      confirmButtonText: '确定',
      showCancelButton: false,
      type: 'success',
    })
    await getDetail()
    handleClick()
  } catch (error) {
    console.log(error)
  } finally {
    loading?.close()
  }
}

const formList = ref<ExternalAuthListData[]>([])
async function getDetail() {
  let loading

  try {
    loading = ElLoading.service({
      fullscreen: true,
      text: '操作中...',
      background: 'rgba(0, 0, 0, 0.3)',
    })
    const res = await getExternalAuthorisationListApi({}, 1, 100)
    const records = res.data.records || []

    const newArr = records.filter((el) => el.type)
    const typeSet = new Set(newArr.map((el) => el.type))
    const hasRIIN = typeSet.has('RIIN')
    const hasTRACK = typeSet.has('TRACK')
    if (newArr.length === 0) {
      formList.value = [{ type: 'RIIN' }, { type: 'TRACK' }]
    } else {
      const result = [...newArr]
      if (!hasRIIN) result.push({ type: 'RIIN' })
      if (!hasTRACK) result.push({ type: 'TRACK' })

      formList.value = result
    }

    console.log('Form list:', formList.value)
  } catch (error) {
    console.error('Failed to get external authorizations:', error)
  } finally {
    loading?.close()
  }
}

async function handleClick() {
  try {
    let ids = ''
    const idList = formList.value.map((el) => el.id).filter((el) => el)
    console.log(222, idList)

    if (idList.length) {
      ids = idList.join(',')
    }
    console.log(205, ids)

    const res = await baseExternalAccountLogsApi({
      ids,
    })
    logList.value = res.data
    console.log(res)
  } catch (error) {
    console.log(error)
  }
}

onMounted(async () => {
  await getDetail()
  handleClick()
})
</script>

<style lang="scss" scoped>
.card-header {
  margin-left: 200px;
  font-size: 30px;
  margin-bottom: 20px;
}
:deep() {
  .demo-tabs {
    height: calc(100% - 60px);
  }
  .cardBox {
    flex: 3;
    overflow-y: scroll;
    height: 100%;
    .el-card__footer {
      border: none !important;
    }

    .formBox {
      width: 100%;
      margin-bottom: 15px;
      padding: 20px;
      border: 1px solid #ebebeb;
      border-radius: 8px;
      &:last-child {
        margin-bottom: 0;
      }
      .formContent {
        padding: 20px;
        background-color: #f9f9f9;
        border-radius: 5px;
        .el-form-item:last-child {
          margin-bottom: 0 !important;
        }
      }
    }
    .btn {
      color: #fff;
    }
  }
  .logBox {
    border-top: 1px solid #ebebeb;
    padding-top: 10px;
    height: 200px;
  }
  .form {
    margin-bottom: 15px;
  }
}
</style>
