<template>
  <cwg-popup :title="t('Documentary.TundManagement.item41')" :visible="visible" @close="closeDia" @confirm="confirmDia" width="700px">
    <uni-forms ref="formRef" :model="formData" :rules="rules" labelWidth="200" label-position="top" class="crm-form">
      <view class="dia-content">
        <!-- 名片信息 -->
        <view class="fllow-title">
          <text class="title">{{ t('Documentary.tradingCenter.item126') }}</text>
        </view>
        <view class="form-item">
          <uni-forms-item :label="t('Documentary.console.item20')" name="nickname">
            <uni-easyinput v-model="formData.nickname" :placeholder="t('placeholder.input')" />
          </uni-forms-item>
        </view>

        <view class="form-row">
          <view class="form-col">
            <view class="form-item">
              <uni-forms-item :label="t('Documentary.console.item21')" name="personalSignature">
                <uni-easyinput type="textarea" v-model="formData.personalSignature" :maxlength="100"
                  @input="val => filterChineseEnglishOnly('personalSignature', val)"
                  :placeholder="t('placeholder.input')" maxlength="24" minlength="6" />
              </uni-forms-item>
            </view>
          </view>
          <view class="form-col">
            <view class="form-item">
              <uni-forms-item :label="t('Documentary.console.item22')" name="traderStrategy">
                <uni-easyinput type="textarea" v-model="formData.traderStrategy" :maxlength="150"
                  @input="val => filterChineseEnglishOnly('traderStrategy', val)"
                  :placeholder="t('placeholder.input')" />
              </uni-forms-item>
            </view>
          </view>
        </view>

        <view class="tip-red">
          <text>{{ t('Documentary.console.item37') }}</text>
        </view>

        <!-- 账户信息 -->
        <view class="fllow-title">
          <text class="title">{{ t('Documentary.TundManagement.item29') }}<text
              style="color: #eb3f57; font-weight: 500">{{ t('Documentary.item3') }}</text></text>
        </view>

        <view class="form-row">
          <view class="form-col">
            <view class="form-item">
              <uni-forms-item :label="t('Label.TradingAccount')" name="dealLogin">
                <cwg-combox v-model:value="formData.dealLogin" :options="loginOptionsData"
                  :placeholder="t('placeholder.choose')" @change="selectLogin" />
              </uni-forms-item>
            </view>
          </view>
          <view class="form-col">
            <view class="form-item">
              <uni-forms-item :label="t('Label.PlatformType')" name="platform">
                <cwg-combox v-model:value="formData.platform"
                  :options="[{ text: 'MT4', value: 'MT4' }, { text: 'MT5', value: 'MT5' }]"
                  :placeholder="t('placeholder.choose')" />
              </uni-forms-item>
            </view>
          </view>
        </view>
        <view class="form-row">
          <view class="form-col">
            <view class="form-item">
              <uni-forms-item :label="t('Label.AccountType')" name="loginType">
                <cwg-combox disabled v-model:value="formData.loginType" :options="accountTypeOptions"
                  :placeholder="t('placeholder.choose')" />
              </uni-forms-item>
            </view>
          </view>
          <view class="form-col">
            <view class="form-item">
              <uni-forms-item :label="t('Label.Leverage')" name="leverage">
                <uni-easyinput disabled v-model="formData.leverage" :placeholder="t('placeholder.input')" />
              </uni-forms-item>
            </view>
          </view>
        </view>

        <!-- 展示设置 -->
        <view class="fllow-title">
          <text class="title">{{ t('Documentary.TundManagement.item32') }}</text>
        </view>
        <view class="form-row">
          <view class="form-col">
            <view class="form-item">
              <uni-forms-item :label="t('Documentary.TundManagement.item34')" name="historyShow">
                <cwg-combox v-model:value="formData.historyShow"
                  :options="[{ text: t('Btn.item6'), value: 1 }, { text: t('Btn.item7'), value: 0 }]"
                  :placeholder="t('placeholder.choose')" />
              </uni-forms-item>
            </view>
          </view>
          <view class="form-col">
            <view class="form-item">
              <uni-forms-item :label="t('Documentary.TundManagement.item35')" name="historyTime">
                <uni-datetime-picker type="date" v-model="formData.historyTime"
                  :placeholder="t('Documentary.TundManagement.item37')" />
              </uni-forms-item>
            </view>
          </view>
        </view>
        <view class="form-item">
          <uni-forms-item :label="t('Documentary.TundManagement.item36')" name="introduceShow">
            <cwg-combox v-model:value="formData.introduceShow"
              :options="[{ text: t('Btn.item6'), value: 1 }, { text: t('Btn.item7'), value: 0 }]"
              :placeholder="t('placeholder.choose')" />
          </uni-forms-item>
        </view>

        <!-- 分润设置 -->
        <view class="fllow-title">
          <text class="title">{{ t('Documentary.TundManagement.item33') }}</text>
        </view>
        <view class="form-row">
          <view class="form-col">
            <view class="form-item">
              <uni-forms-item :label="t('Documentary.TundManagement.item38')" name="distributionType">
                <cwg-combox v-model:value="formData.distributionType"
                  :options="[{ text: t('Documentary.TundManagement.item59'), value: 1 }]"
                  :placeholder="t('placeholder.choose')" />
              </uni-forms-item>
            </view>
          </view>
          <view class="form-col">
            <view class="form-item">
              <uni-forms-item :label="t('Documentary.TundManagement.item39')" name="distributionRatio">
                <view style="display: flex; align-items: center;">
                  <uni-easyinput v-model="formData.distributionRatio" :placeholder="t('placeholder.input')"
                    style="flex: 1;" />
                  <text style="margin-left: 5px;">(%)</text>
                </view>
              </uni-forms-item>
            </view>
          </view>
          <view class="form-col">
            <view class="form-item">
              <uni-forms-item :label="t('Documentary.tradingCenter.item32')" name="settlementCycle">
                <cwg-combox v-model:value="formData.settlementCycle"
                  :options="optList1"
                  :placeholder="t('placeholder.choose')" />
              </uni-forms-item>
            </view>
          </view>
        </view>

        <!-- 协议 -->
        <uni-forms-item class="form-item agree">
          <uni-forms-item name="agree">
            <checkbox-group @change="onAgreeChange">
              <label class="checkbox-agree">
                <checkbox value="1" :checked="!!formData.agree" />
                <text class="agree-text">
                  {{ t('Documentary.TundManagement.item42') }}
                  <cwg-link type="pdf" class="a" v-if="['cn', 'zhHant'].indexOf(locale) != -1"
                    url="pdf/CopyTradeUserAgreementcn.pdf" target="_blank" title="Documentary.TundManagement.item43" />
                  <cwg-link type="pdf" class="a" v-else url="pdf/CopyTradeUserAgreement.pdf"
                    target="_blank" title="Documentary.TundManagement.item43" />
                  {{ t('Documentary.TundManagement.item42_2') }}
                </text>
              </label>
            </checkbox-group>
          </uni-forms-item>
        </uni-forms-item>
      </view>
    </uni-forms>

    <template #footer>
      <button @click="closeDia">{{ t('Btn.Cancel') }}</button>
      <button type="primary" @click="confirmDia">{{ t('Btn.Confirm') }}</button>
    </template>
  </cwg-popup>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import Config from '@/config/index'
import { documentaryApi } from '@/service/documentary'
import {useFollowEnum} from '@/pages/follow/const/enum'

const props = defineProps({
  visible: { type: Boolean, default: false },
  loginOptions: { type: Array, default: () => [] }
})

const emit = defineEmits(['close', 'confirm'])
const { t, locale } = useI18n()
const { Code } = Config
const {optList1} = useFollowEnum()

const formRef = ref(null)
const formData = ref({
  nickname: '',
  personalSignature: '',
  traderStrategy: '',
  dealLogin: '',
  platform: '',
  loginType: '',
  leverage: '',
  historyShow: '',
  historyTime: '',
  introduceShow: '',
  distributionType: '',
  distributionRatio: '',
  settlementCycle: '',
  agree: false
})
const isSubmitting = ref(false)

const accountTypeOptions = [
  { text: t('AccountType.ClassicAccount'), value: 1 },
  { text: t('AccountType.SeniorAccount'), value: 2 },
  { text: t('AccountType.SpeedAccount'), value: 5 },
  { text: t('AccountType.SpeedAccount'), value: 6 },
  { text: t('AccountType.StandardAccount'), value: 7 },
  { text: t('AccountType.CentAccount'), value: 8 }
]

const loginOptionsData = computed(() => {
  return props.loginOptions.map(item => ({
    text: `${item.login} - ${groupTypeName(item.type)} - ${t('Custom.Deposit.AvailableBalance')}${groupCurrency(item.currency)}${item.balance}`,
    value: item.login,
    disabled: item.balance < 200
  }))
})

const groupTypeName = (type) => {
  const option = accountTypeOptions.find(opt => opt.value == type)
  return option ? option.text : type
}

const groupCurrency = (type) => {
  if (type == "GBP") {
    return ": £";
  } else if (type == "USD") {
    return ": $";
  } else if (type == "EUR") {
    return ": €";
  } else if (type == "USC") {
    return ": ￠";
  } else {
    return ": $";
  }
}

const rules = {
  password: {
    rules: [
      {
        required: true,
        validateFunction: (rule, value, data, callback) => {
          if (Config.Pattern.Password.test(value)) {
            callback()
          } else {
            callback(t('vaildate.password.format'))
          }
          return true
        }
      }
    ]
  },
  agree: {
    rules: [
      {
        validateFunction: (rule, value, data, callback) => {
          if (value) {
            callback()
          } else {
            callback(t('vaildate.agree.empty'))
          }
          return true
        }
      }
    ]
  },
  platform: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.select.empty')
      }
    ]
  },
  currency: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.select.empty')
      }
    ]
  },
  leverage: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.select.empty')
      }
    ]
  },
  loginType: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.select.empty'),
      }
    ]
  },
  dealLogin: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.select.empty')
      }
    ]
  },
  distributionType: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.select.empty')
      }
    ]
  },
  distributionRatio: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.input.empty')
      },
      {
        validateFunction: (rule, value, data, callback) => {
          if (value >= 0 && value <= 50) {
            callback()
          } else {
            callback('0-50')
          }
          return true
        }
      }
    ]
  },
  settlementCycle: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.input.empty')
      }
    ]
  },
  historyShow: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.select.empty')
      }
    ]
  },
  historyTime: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.select.empty')
      }
    ]
  },
  introduceShow: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.select.empty')
      }
    ]
  },
  protectAmount: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.input.empty')
      }
    ]
  },
  protectRatio: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.input.empty')
      }
    ]
  },
  nickname: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.input.empty')
      },
      {
        validateFunction: (rule, value, data, callback) => {
          if (value && /^[0-9a-zA-Z]{6,24}$/.test(value)) {
            callback()
          } else {
            callback(t('Msg.nickname'))
          }
          return true
        }
      }
    ]
  },
  personalSignature: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.input.empty')
      },
      {
        validateFunction: (rule, value, data, callback) => {
          if (!value || /^[\u4e00-\u9fa5a-zA-Z\s]*$/.test(value)) {
            callback()
          } else {
            callback(t('Documentary.console.item38'))
          }
          return true
        }
      }
    ]
  },
  traderStrategy: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.input.empty')
      },
      {
        validateFunction: (rule, value, data, callback) => {
          if (!value || /^[\u4e00-\u9fa5a-zA-Z\s]*$/.test(value)) {
            callback()
          } else {
            callback(t('Documentary.console.item38'))
          }
          return true
        }
      }
    ]
  },
  followType: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.select.empty')
      }
    ]
  },
  volume: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.input.empty')
      }
    ]
  },
  ratio: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.input.empty')
      }
    ]
  }
}

const filterChineseEnglishOnly = (field, value) => {
  if (!value) return
  const filtered = value.replace(/[^\u4e00-\u9fa5a-zA-Z\s]/g, '')
  formData.value[field] = filtered
}

const selectLogin = (val) => {
  const selected = props.loginOptions.find(item => item.login === val)
  if (selected) {
    formData.value.leverage = `1:${selected.leverage}`
    formData.value.loginType = selected.type
    formData.value.platform = selected.platform
  }
}

const onAgreeChange = (e) => {
  formData.value.agree = e.detail.value?.includes('1')
}

const closeDia = () => {
  emit('close')
  resetForm()
}

const confirmDia = async () => {
  try {
    await formRef.value.validate()
  } catch (err) {
    return
  }

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

  try {
    const res = await documentaryApi.followDealApply({
      ...formData.value
    })
    if (res.code === Code.StatusOK) {
      uni.showToast({ title: t('Msg.Success'), icon: 'none' })
      emit('confirm')
      closeDia()
    } else {
      uni.showToast({ title: res.msg, icon: 'none' })
    }
  } catch (e) {
    uni.showToast({ title: t('Msg.Fail'), icon: 'none' })
  } finally {
    isSubmitting.value = false
  }
}

const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = {
    nickname: '',
    personalSignature: '',
    traderStrategy: '',
    dealLogin: '',
    platform: '',
    loginType: '',
    leverage: '',
    historyShow: '',
    historyTime: '',
    introduceShow: '',
    distributionType: '',
    distributionRatio: '',
    settlementCycle: '',
    agree: false
  }
}

watch(() => props.visible, (val) => {
  if (val && props.loginOptions?.length) {
    // 自动填充默认值，与原版保持一致
    const defaultOption = props.loginOptions.find(item => item.balance >= 200)
    if (defaultOption) {
      formData.value.dealLogin = defaultOption.login
      selectLogin(defaultOption.login)
    }
  }
})
</script>

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

.dia-content {
  padding: px2rpx(20);

  .uni-forms-item {
    width: 100%;
  }

  .grid-layout {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: px2rpx(20);
    margin: px2rpx(24) 0;
    padding: px2rpx(20);
    background-color: transparent;
    border-radius: px2rpx(8);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  }



  .fllow-title {
    margin: px2rpx(10) 0 px2rpx(16);
    padding-left: px2rpx(8);
    border-left: 4px solid #dc3545;
    border-bottom: none;

    .title {
      font-size: px2rpx(16);
      font-weight: 600;
      color: var(--bs-emphasis-color);
    }
  }

  .delete-grid {
    margin: px2rpx(16) 0;
  }

  .delete-row {
    display: flex;
    gap: px2rpx(12);
  }

  .delete-item {
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: px2rpx(12) 0;
    border-bottom: 1px dashed #e9ecef;

    &:first-child {
      padding-right: px2rpx(16);
    }

    &:last-child {
      padding-left: px2rpx(16);
    }
  }

  .delete-label {
    font-size: px2rpx(14);
    color: var(--bs-body-color);
  }

  .delete-value {
    font-size: px2rpx(14);
    color: var(--bs-emphasis-color);
    font-weight: 400;
  }

  .delete-tip {
    margin-top: px2rpx(16);
    font-size: px2rpx(14);
    color: var(--bs-emphasis-color);
    line-height: 1.5;
    padding-top: px2rpx(16);
  }

  .tip-star {
    color: #dc3545;
    margin-right: px2rpx(4);
  }

  .agree {
    margin-top: px2rpx(20);
  }

  .checkbox-agree {
    display: flex;
    align-items: flex-start;
    gap: px2rpx(8);
    :deep(.uni-checkbox-input){
      margin-top: px2rpx(3);
      width: px2rpx(18);
      height: px2rpx(18);
    }

    .agree-text {
      font-size: px2rpx(13);
      color: var(--bs-emphasis-color);
      line-height: 1.5;
      width: 100%;
      white-space: wrap;
      font-weight: normal;

      .a {
        color: #007bff;
        text-decoration: none;
        margin: 0 px2rpx(4);

        &:hover {
          color: #0056b3;
        }
      }
    }
  }

  .fllow-content {
    margin-bottom: px2rpx(16);

    .tit {
      font-size: px2rpx(14);
      font-weight: 500;
      color: var(--bs-body-color);
      margin-bottom: px2rpx(6);
      text-transform: uppercase;
      letter-spacing: px2rpx(0.5);
    }

    .con {
      font-size: px2rpx(16);
      font-weight: 400;
      color: var(--bs-emphasis-color);
      line-height: 1.4;
    }
  }

  .form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: px2rpx(20);
    margin-top: px2rpx(16);

    @media screen and (max-width: 768px) {
      grid-template-columns: 1fr;
    }
  }

  .form-item {
    display: flex;
    flex-direction: column;
    align-items: flex-start;

    text {
      font-size: px2rpx(14);
      font-weight: 500;
      color: var(--bs-body-color);
      margin-bottom: px2rpx(8);
      white-space: nowrap;
    }

    input,
    select,
    textarea {
      width: 100%;
      padding: px2rpx(10);
      border: 1px solid #ced4da;
      border-radius: px2rpx(4);
      font-size: px2rpx(14);
      transition: all 0.2s ease;

      &:focus {
        outline: none;
        border-color: #4dabf7;
        box-shadow: 0 0 0 2px rgba(77, 171, 247, 0.2);
      }
    }

    textarea {
      resize: vertical;
      min-height: px2rpx(100);
    }
  }

  .tip-red {
    color: #dc3545;
    font-size: px2rpx(14);
    margin: px2rpx(12) 0 px2rpx(24) 0;
  }

  .tip-text {
    margin-top: px2rpx(24);
    font-size: px2rpx(14);
    color: var(--bs-body-color);
    line-height: 1.5;
    padding: px2rpx(16);
    background-color: #e7f3ff;
    border-radius: px2rpx(4);
    border-left: 4px solid #4dabf7;
  }
}
</style>