<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 class="card-box-item-container">
        <template v-for="(item, index) in formList" :key="index">
          <div v-if="item.type === 'RIIN'" class="card-box-item">
            <div class="formBox">
              <div class="form-item">
                <span>转至RIIN生产</span>
                <el-switch
                  v-model="item.enable"
                  class="ml-2"
                  style="--el-switch-on-color: #42b983"
                />
              </div>
              <div v-if="item.enable" class="formContent">
                <el-form
                  v-if="item.type === 'RIIN'"
                  ref="formRef"
                  class="form"
                  label-width="120"
                  :model="item"
                >
                  <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>
                </el-form>
              </div>
            </div>

            <ElButton
              class="btn"
              color="#42b983"
              @click="saveConfiguration(item, index)"
              >保存配置</ElButton
            >
          </div>
          <div v-if="item.type === 'TRACK'" class="card-box-item">
            <div class="formBox">
              <div class="form-item">
                <span>物流轨迹跟踪</span>
                <el-switch
                  v-model="item.enable"
                  class="ml-2"
                  style="--el-switch-on-color: #42b983"
                />
              </div>
              <div v-if="item.enable" class="formContent">
                <el-form
                  v-if="item.type === 'TRACK'"
                  class="form"
                  ref="formRef"
                  label-width="120"
                  :model="item"
                >
                  <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>
                </el-form>
              </div>
            </div>

            <ElButton
              class="btn"
              color="#42b983"
              @click="saveConfiguration(item, index)"
              >保存配置</ElButton
            >
          </div>
        </template>
        <div class="card-box-item">
          <div class="formBox">
            <div class="form-item">
              <span>库存预警下限:</span>
            </div>
            <div class="formContent">
              <ElInput
                v-model="inventoryLowerLimit"
                clearable
                placeholder="请输入库存预警下限"
              />
            </div>
          </div>
          <ElButton class="btn" color="#42b983" @click="saveInventoryLowerLimit"
            >保存配置</ElButton
          >
        </div>
      </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,
  saveInventoryLowerLimitApi,
  getInventoryLowerLimitApi,
} 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 inventoryLowerLimit = ref<number | null>(100)
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)
  }
}
const saveInventoryLowerLimit = async () => {
  if (!inventoryLowerLimit.value) {
    ElMessage.error('请输入库存预警下限')
    return
  }
  try {
    const res = await saveInventoryLowerLimitApi(inventoryLowerLimit.value)
    if (res.code !== 200) {
      return
    }
    await ElMessageBox.confirm('保存配置成功！！需重新登录才能生效', '提示', {
      confirmButtonText: '确定',
      showCancelButton: false,
      type: 'success',
    })
    getInventoryLowerLimit()
    handleClick()
  } catch (error) {
    console.log(error)
  }
}
const getInventoryLowerLimit = async () => {
  try {
    const res = await getInventoryLowerLimitApi()
    if (res.code !== 200) {
      return
    }
    inventoryLowerLimit.value = res.data
  } catch (error) {
    console.log(error)
  }
}

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

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

    .formBox {
      width: 100%;
      margin-bottom: 15px;
      padding: 20px;
      border: 1px solid #ebebeb;
      border-radius: 8px;
      height: 220px;
      display: flex;
      flex-direction: column;
      &:last-child {
        margin-bottom: 0;
      }
      .formContent {
        padding: 20px;
        background-color: #f9f9f9;
        border-radius: 5px;
        overflow: auto;
        flex: 1;
        .el-form-item:last-child {
          margin-bottom: 0 !important;
        }
      }
    }
    .btn {
      color: #fff;
    }
  }
  .logBox {
    border-top: 1px solid #ebebeb;
    padding-top: 10px;
    height: 200px;
  }
}
.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 10px;
  span {
    color: #606266;
    font-size: 14px;
  }
}
.card-box-item-container {
  display: grid;
  grid-template-columns: repeat(3, minmax(100px, 1fr));
  gap: 10px;
}
</style>
