<template>
  <cwg-page-wrapper class="create-page" :isHeaderFixed="true">
    <cwg-header :title="t('Ib.PammManager.title')">
      <template #right>
        <view class="header-btn" @click="backIndex">
          <cwg-icon name="icon_back" :size="18" />
          <text>{{ t('Ib.Settings.Title') }}</text>
        </view>
      </template>
    </cwg-header>

    <view class="main-content account-content">
      <view class="box">
        <view class="tit"></view>
        <view class="des">{{ t('Ib.PammManager.tips4') }}</view>

        <view class="b-card">
          <uni-forms ref="formRef" label-width="120" :model="params" :rules="rules" label-position="top">
            <uni-row :gutter="20">
              <uni-col :xs="24" :sm="12">
                <uni-forms-item :label="t('Ib.PammManager.accountId')" name="accountId" required>
                  <cwg-combox v-model:value="params.accountId" :options="accountIdOptions"
                    :placeholder="t('placeholder.choose')" />
                </uni-forms-item>
              </uni-col>
              <uni-col :xs="24" :sm="12">
                <uni-forms-item :label="t('Ib.PammManager.ownerId')" name="ownerId" required>
                  <cwg-combox v-model:value="params.ownerId" :options="ownerIdOptions"
                    :placeholder="t('placeholder.choose')" />
                </uni-forms-item>
              </uni-col>
              <uni-col :xs="24" :sm="12">
                <uni-forms-item :label="t('Ib.PammManager.percent')" name="percent" required>
                  <uni-easyinput v-model.trim="params.percent" :placeholder="t('placeholder.input')" />
                </uni-forms-item>
              </uni-col>
              <uni-col :span="24">
                <button class="s-btn" type="primary" @click="newAccount">{{ t('Ib.PammManager.btn') }}</button>
              </uni-col>
            </uni-row>
          </uni-forms>
        </view>
      </view>

      <view class="box">
        <view style="margin: 20px 0; font-size: 14px; line-height: 1.7;">
          <view style="font-weight: bold; margin-bottom: 5px;">{{ t('Ib.PammManager.tips2') }}</view>
        </view>
      </view>
    </view>

    <!-- 提交结果弹窗 -->
    <cwg-popup :visible="dialogCheck" :showClose="false" :showFooters="true" :confirmText="t('Btn.Confirm')"
      :cancelText="t('Btn.Cancel')" @confirm="handleDialogAction" @close="handleDialogAction">
      <view class="result-dialog">
        <view v-if="dialogVisible" class="icon-wrap">
          <cwg-icon name="icon_success" :size="50" color="#67C23A" />
          <view class="result-text">{{ t('ApplicationDialog.Des1') }}</view>
          <view class="result-sub-text">{{ t('ApplicationDialog.Des12') }}</view>
        </view>
        <view v-else class="icon-wrap">
          <cwg-icon name="icon_warning" :size="50" color="#E6A23C" />
          <view class="result-text">{{ t('ApplicationDialog.Des43') }}</view>
          <view class="result-text" style="color: #e6a23c; margin: 10px 0;">{{ RES }}</view>
          <view class="result-sub-text">{{ t('ApplicationDialog.Des45') }}</view>
        </view>
      </view>
    </cwg-popup>

  </cwg-page-wrapper>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import { ibApi } from '@/service/ib'
import Config from '@/config/index'

const { t } = useI18n()
const { Code } = Config

const pictLoading = ref(false)
const showData = ref<any[]>([])

const flag = ref(false)
const RES = ref('')
const dialogCheck = ref(false)
const dialogVisible = ref(false)

const formRef = ref()

const params = reactive({
  type: null as number | null,
  ownerId: null as string | null,
  accountId: null as string | null,
  percent: '',
})

// 验证规则
const rules = {
  ownerId: { rules: [{ required: true, errorMessage: t('vaildate.select.empty') }] },
  accountId: { rules: [{ required: true, errorMessage: t('vaildate.select.empty') }] },
  percent: {
    rules: [
      { required: true, errorMessage: t('vaildate.input.empty') },
      {
        validateFunction: (rule: any, value: any, data: any, callback: any) => {
          if (!value && value !== 0) {
            callback(t('vaildate.input.empty'))
          } else if (!/^[0-9]+([.]{1}[0-9]{1,2})?$/.test(String(value))) {
            callback('0.00-100.00')
          } else {
            return true
          }
        }
      }
    ]
  },
}

// 动态计算下拉选项 (处理 disabled 逻辑)
const accountIdOptions = computed(() => {
  return showData.value.map(item => {
    // disabled="(item.login == params.ownerId) || item.equity!=0"
    const isDisabled = (item.login === params.ownerId) || (Number(item.equity) !== 0)
    return {
      text: item.login,
      value: item.login,
      disable: isDisabled
    }
  })
})

const ownerIdOptions = computed(() => {
  return showData.value.map(item => {
    // disabled="item.login == params.accountId"
    const isDisabled = item.login === params.accountId
    return {
      text: item.login,
      value: item.login,
      disable: isDisabled
    }
  })
})

// 获取账号集合
const getMustData = async () => {
  pictLoading.value = true
  try {
    const res = await ibApi.mamApplyPammManagerLogins({})
    if (res.code === Code.StatusOK) {
      showData.value = res.data || []
    } else {
      uni.showToast({ title: res.msg, icon: 'none' })
    }
  } finally {
    pictLoading.value = false
  }
}

// 提交申请
const newAccount = async () => {
  try {
    await formRef.value?.validate()
  } catch (error) {
    return
  }

  if (flag.value) return
  flag.value = true

  try {
    const res = await ibApi.mamApplyPammManagerAdd({ ...params })
    if (res.code === Code.StatusOK) {
      dialogCheck.value = true
      dialogVisible.value = true
    } else {
      RES.value = res.msg
      dialogCheck.value = true
      dialogVisible.value = false
    }
  } catch (err) {
    RES.value = t('Msg.Fail')
    dialogCheck.value = true
    dialogVisible.value = false
  } finally {
    flag.value = false
  }
}

// 关闭弹窗
const closeDia = () => {
  formRef.value?.clearValidate()
  dialogCheck.value = false
  dialogVisible.value = false
}

// 成功后返回
const backIndex = () => {
  formRef.value?.clearValidate()
  dialogCheck.value = false
  dialogVisible.value = false
  uni.navigateBack({ delta: 1 })
}

// 统一处理弹窗操作
const handleDialogAction = () => {
  if (dialogVisible.value) {
    backIndex()
  } else {
    closeDia()
  }
}

onLoad((options: any) => {
  if (options && options.type) {
    params.type = Number(options.type)
  } else {
    params.type = 1
  }
  getMustData()
})
</script>

<style lang="scss" scoped>
@import "@/uni.scss";

.header-btn {
  display: flex;
  align-items: center;
  font-size: px2rpx(14);
  color: var(--bs-heading-color);
  cursor: pointer;

  text {
    margin-left: px2rpx(5);
  }
}

.main-content {
  padding: px2rpx(10);
  min-height: calc(100vh - 100px);
}

.box {
  padding: px2rpx(15) px2rpx(20);
  background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;
  border-radius: px2rpx(4);
  margin-bottom: px2rpx(20);

  .tit {
    display: flex;
    align-items: center;
    font-size: px2rpx(16);
    font-weight: bold;
    margin-bottom: px2rpx(10);

    text {
      margin-left: px2rpx(5);
    }
  }

  .des {
    font-size: px2rpx(14);
    font-weight: bold;
    line-height: 1.5;
    margin-bottom: px2rpx(20);
    color: var(--bs-heading-color);
  }
}

.b-card {
  margin-top: px2rpx(15);
}

.s-btn {
  margin-top: px2rpx(10);
  min-width: px2rpx(120);
}

.result-dialog {
  text-align: center;
  padding: px2rpx(20);

  .icon-wrap {
    margin-bottom: px2rpx(20);
  }

  .result-text {
    font-size: px2rpx(16);
    font-weight: bold;
    margin-top: px2rpx(20);
    margin-bottom: px2rpx(10);
  }

  .result-sub-text {
    font-size: px2rpx(12);
    color: var(--bs-heading-color);
    margin-bottom: px2rpx(20);
  }

  .dialog-footer {
    display: flex;
    justify-content: center;
    gap: px2rpx(15);
    margin-top: px2rpx(30);

    button {
      min-width: px2rpx(100);
      margin: 0;
    }
  }
}
</style>