<template>
  <view class="container" style="paddingBottom:1rpx;">
    <u-navbar
      leftIconSize="40rpx"
      leftIconColor="#333333"
      title="信用卡调额"
    >
    </u-navbar>
    <view class="section">
      <view class="section-title">{{ title }}</view>
      <view class="form-view">
        <u--form labelPosition="left" :model="form" :rules="rules" ref="uForm" label-width="auto"
          :labelStyle="{ color: '#333333', fontSize: '30rpx' }">
          
          <u-form-item label="调整前额度" prop="beforeLimit">
            <u--input v-model="form.beforeLimit" disabled disabledColor="#ffffff" placeholder="调整前额度"
              inputAlign="right" border="none">
              <template #suffix>
                <text style="color: #909399; font-size: 28rpx;">元</text>
              </template>
            </u--input>
          </u-form-item>
          
          <u-form-item label="调额类型" prop="limitTypeName" required @click="handleShowLimitType">
            <u--input v-model="form.limitTypeName" disabled disabledColor="#ffffff" placeholder="请选择调额类型"
              inputAlign="right" border="none"></u--input>
            <u-icon slot="right" name="arrow-down"></u-icon>
          </u-form-item>
          
          <u-form-item label="调整类型" prop="adjustTypeName" required @click="handleShowAdjustType">
            <u--input v-model="form.adjustTypeName" disabled disabledColor="#ffffff" placeholder="请选择调整类型"
              inputAlign="right" border="none"></u--input>
            <u-icon slot="right" name="arrow-down"></u-icon>
          </u-form-item>
                    <u-form-item label="调整后额度" prop="afterLimit" required>
            <u--input v-model="form.afterLimit" type="number" placeholder="请输入调整后额度"
              inputAlign="right" border="none">
              <template #suffix>
                <text style="color: #909399; font-size: 28rpx;">元</text>
              </template>
            </u--input>
          </u-form-item>
            <u-form-item label="调整额度" prop="adjustLimit">
            <u--input v-model="adjustLimitDisplay" disabled disabledColor="#ffffff" placeholder="自动计算"
              inputAlign="right" border="none" :style="{ color: adjustLimitColor }">
              <template #suffix>
                <text style="color: #909399; font-size: 28rpx;">元</text>
              </template>
            </u--input>
          </u-form-item>


          <u-form-item label="生效日期" prop="effectDate" required @click="selectEffectDate">
            <u--input v-model="form.effectDate" disabled disabledColor="#ffffff" placeholder="请选择生效日期" 
              inputAlign="right" border="none"></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          
          <u-form-item label="截止日期" prop="deadlineDate" :required="isTemporary" @click="selectDeadlineDate">
            <u--input v-model="form.deadlineDate" disabled disabledColor="#ffffff" :placeholder="isTemporary ? '请选择截止日期（必填）' : '请选择截止日期（可选）'" 
              inputAlign="right" border="none"></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          
          <u-form-item label="调整时间" prop="adjustTime" required @click="selectAdjustTime">
            <u--input v-model="form.adjustTime" disabled disabledColor="#ffffff" placeholder="请选择调整时间" 
              inputAlign="right" border="none"></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          
          <u-form-item label="备注" prop="remark" labelPosition="top">
            <u--textarea v-model="form.remark" placeholder="请填写备注" border="none" autoHeight inputAlign="right" count
              maxlength="500" style="padding:18rpx 0;"></u--textarea>
          </u-form-item>
        </u--form>
        <view class="form-btn">
          <u-button type="primary" text="提交" @click="submit"></u-button>
        </view>
      </view>
    </view>
    
    <u-toast ref="uToast"></u-toast>
    
    <!-- 调整类型选择器 -->
    <u-picker itemHeight="88" :show="showAdjustType" :columns="adjustTypeList" keyName="dictLabel" 
      @cancel="handleAdjustTypeCancel" @confirm="handleAdjustTypeConfirm"></u-picker>
    
    <!-- 调额类型选择器 -->
    <u-picker itemHeight="88" :show="showLimitType" :columns="limitTypeList" keyName="dictLabel" 
      @cancel="handleLimitTypeCancel" @confirm="handleLimitTypeConfirm"></u-picker>
    
    <!-- 生效日期选择器 -->
    <u-datetime-picker
      :show="effectDatePickShow"
      mode="date"
      :minDate="-2209017600000"
      ref="effectDateRef" 
      @cancel="effectDatePickShow=false"
      @confirm="effectDateConfirm"
      itemHeight="88"
    ></u-datetime-picker>
    
    <!-- 截止日期选择器 -->
    <u-datetime-picker
      :show="deadlineDatePickShow"
      mode="date"
      :minDate="-2209017600000"
      ref="deadlineDateRef" 
      @cancel="deadlineDatePickShow=false"
      @confirm="deadlineDateConfirm"
      itemHeight="88"
    ></u-datetime-picker>
    
    <!-- 调整时间选择器 -->
    <u-datetime-picker
      :show="adjustTimePickShow"
      mode="datetime"
      :minDate="-2209017600000"
      ref="adjustTimeRef" 
      @cancel="adjustTimePickShow=false"
      @confirm="adjustTimeConfirm"
      itemHeight="88"
    ></u-datetime-picker>
  </view>
</template>

<script setup>
import { getBankcardLend } from '@/api/invest/bankcardlend'
import { addLimitHistory, updateLimitHistory, getLimitHistory, listLimitHistory } from '@/api/invest/limitHistory'
import { getDicts } from '@/api/system/dict/data.js'
import { getCurrentInstance } from 'vue'
import { onLoad, onReady } from '@dcloudio/uni-app'
import { reactive, toRefs, ref, computed, watch } from 'vue'
import dayjs from 'dayjs'

const { proxy } = getCurrentInstance()

const title = ref('信用卡非柜调额')
const showAdjustType = ref(false)
const showLimitType = ref(false)
const effectDatePickShow = ref(false)
const deadlineDatePickShow = ref(false)
const adjustTimePickShow = ref(false)
const adjustTypeList = ref([])
const limitTypeList = ref([])

const data = reactive({
  form: {
    id: null,
    name: '',
    code: '',
    bankCardLendId: null,
    beforeLimit: '',
    afterLimit: '',
    adjustLimit: 0,
    adjustType: '',
    adjustTypeName: '',
    type: '',
    limitTypeName: '',
    effectDate: '',
    deadlineDate: '',
    adjustTime: '',
    remark: ''
  },
  rules: {
    afterLimit: [
      { type: 'number', required: true, message: '调整后额度不能为空', trigger: ['change', 'blur'] }
    ],
    adjustTypeName: [
      { type: 'string', required: true, message: '调整类型不能为空', trigger: ['change', 'blur'] }
    ],
    limitTypeName: [
      { type: 'string', required: true, message: '调额类型不能为空', trigger: ['change', 'blur'] }
    ],
    effectDate: [
      { type: 'string', required: true, message: '生效日期不能为空', trigger: ['change', 'blur'] }
    ],
    adjustTime: [
      { type: 'string', required: true, message: '调整时间不能为空', trigger: ['change', 'blur'] }
    ]
  }
})

const { form, rules } = toRefs(data)

// 计算调整额度
const adjustLimitDisplay = computed(() => {
  const before = parseFloat(form.value.beforeLimit) || 0
  const after = parseFloat(form.value.afterLimit) || 0
  const adjust = after - before
  form.value.adjustLimit = adjust
  return adjust > 0 ? `+${adjust}` : `${adjust}`
})

// 调整额度颜色
const adjustLimitColor = computed(() => {
  const adjust = form.value.adjustLimit
  if (adjust > 0) return '#52c41a'
  if (adjust < 0) return '#ff4d4f'
  return '#909399'
})

// 判断是否是临时额度
const isTemporary = computed(() => {
  return form.value.type === '1'
})

onLoad((option) => {
  form.value.id = option.id || null
  form.value.bankCardLendId = option.bankCardLendId
  form.value.name = option.name
  
  if (form.value.id) {
    title.value = '信用卡调额记录-修改'
  } else {
    title.value = '信用卡调额记录-新增'
  }
  
  getDict()
  
  if (form.value.id) {
    // 编辑模式：加载已有记录
    getLimitHistoryInfo()
  } else {
    // 新增模式：获取当前额度
    getCardInfo()
  }
})

onReady(() => {
  // 默认调整时间为当前时间
  form.value.adjustTime = dayjs(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss')
  // 默认生效日期为当前日期
  form.value.effectDate = dayjs(new Date().getTime()).format('YYYY-MM-DD')
})

function getDict() {
  // 调整类型
  getDicts('adjust_type').then(res => {
    adjustTypeList.value = [res.data]
    // 如果是新增模式，默认选中"调额"
    if (!form.value.id && res.data && res.data.length > 0) {
      const defaultItem = res.data.find(item => item.dictLabel === '调额')
      if (defaultItem) {
        form.value.adjustType = defaultItem.dictValue
        form.value.adjustTypeName = defaultItem.dictLabel
      }
    }
  })
  // 调额类型
  getDicts('limit_history_type').then(res => {
    limitTypeList.value = [res.data]
  })
}

function getLimitHistoryInfo() {
  getLimitHistory(form.value.id).then(res => {
    form.value = { ...form.value, ...res.data }
    // 获取字典显示名称
    if (form.value.adjustType) {
      getDicts('adjust_type').then(result => {
        form.value.adjustTypeName = dictStr(form.value.adjustType, result.data)
      })
    }
    if (form.value.type) {
      getDicts('limit_history_type').then(result => {
        form.value.limitTypeName = dictStr(form.value.type, result.data)
      })
    }
  })
}

function getCardInfo() {
  // 先获取该信用卡的最新一条调额记录
  listLimitHistory({ 
    pageSize: 1, 
    pageNum: 1, 
    bankCardLendId: form.value.bankCardLendId 
  }).then(res => {
    if (res.rows && res.rows.length > 0) {
      // 如果有调额记录，使用最新记录的调整后额度作为调整前额度
      const afterLimit = res.rows[0].afterLimit || 0
      form.value.beforeLimit = afterLimit
      // 默认调整后额度与调整前一致
      form.value.afterLimit = afterLimit
    } else {
      // 如果没有调额记录，使用信用卡的当前额度
      getBankcardLend(form.value.bankCardLendId).then(cardRes => {
        const limit = cardRes.data.creditLimit || 0
        form.value.beforeLimit = limit
        // 默认调整后额度与调整前一致
        form.value.afterLimit = limit
      })
    }
  }).catch(() => {
    // 查询失败时，使用信用卡的当前额度
    getBankcardLend(form.value.bankCardLendId).then(cardRes => {
      const limit = cardRes.data.creditLimit || 0
      form.value.beforeLimit = limit
      // 默认调整后额度与调整前一致
      form.value.afterLimit = limit
    })
  })
  
  // 获取信用卡账号
  getBankcardLend(form.value.bankCardLendId).then(res => {
    form.value.code = res.data.code || ''
  })
}

function dictStr(val, arr) {
  let str = ''
  arr.map(item => {
    if (item.dictValue === val) {
      str = item.dictLabel
    }
  })
  return str
}

// 调整类型选择
function handleShowAdjustType() {
  if (adjustTypeList.value[0].length === 0) {
    proxy.$refs['uToast'].show({
      message: '调整类型为空', 
      type: 'warning'
    })
  } else {
    showAdjustType.value = true
  }
}

function handleAdjustTypeConfirm(e) {
  form.value.adjustTypeName = e.value[0].dictLabel
  form.value.adjustType = e.value[0].dictValue
  showAdjustType.value = false
}

function handleAdjustTypeCancel() {
  showAdjustType.value = false
}

// 调额类型选择
function handleShowLimitType() {
  if (limitTypeList.value[0].length === 0) {
    proxy.$refs['uToast'].show({
      message: '调额类型为空', 
      type: 'warning'
    })
  } else {
    showLimitType.value = true
  }
}

function handleLimitTypeConfirm(e) {
  form.value.limitTypeName = e.value[0].dictLabel
  form.value.type = e.value[0].dictValue
  showLimitType.value = false
  
  // 如果不是临时额度，清空截止日期
  if (form.value.limitTypeName !== '临时额度') {
    form.value.deadlineDate = ''
  }
}

function handleLimitTypeCancel() {
  showLimitType.value = false
}

// 生效日期选择
function selectEffectDate() {
  effectDatePickShow.value = true
  proxy.$refs['effectDateRef'].innerValue = form.value.effectDate 
    ? new Date(form.value.effectDate).getTime() 
    : new Date().getTime()
}

function effectDateConfirm(e) {
  form.value.effectDate = dayjs(e.value).format('YYYY-MM-DD')
  effectDatePickShow.value = false
}

// 截止日期选择
function selectDeadlineDate() {
  deadlineDatePickShow.value = true
  proxy.$refs['deadlineDateRef'].innerValue = form.value.deadlineDate 
    ? new Date(form.value.deadlineDate).getTime() 
    : new Date().getTime()
}

function deadlineDateConfirm(e) {
  form.value.deadlineDate = dayjs(e.value).format('YYYY-MM-DD')
  deadlineDatePickShow.value = false
}

// 调整时间选择
function selectAdjustTime() {
  adjustTimePickShow.value = true
  proxy.$refs['adjustTimeRef'].innerValue = form.value.adjustTime 
    ? new Date(form.value.adjustTime).getTime() 
    : new Date().getTime()
}

function adjustTimeConfirm(e) {
  form.value.adjustTime = dayjs(e.value).format('YYYY-MM-DD HH:mm:ss')
  adjustTimePickShow.value = false
}

// 提交
function submit() {
  proxy.$refs['uForm'].validate().then(() => {
    // 如果是临时额度，检查截止日期是否填写
    if (isTemporary.value && !form.value.deadlineDate) {
      proxy.$refs['uToast'].show({
        message: '临时额度必须填写截止日期',
        type: 'error'
      })
      return
    }
    
    const submitData = { ...form.value }
    
    if (form.value.id) {
      // 修改
      updateLimitHistory(submitData).then(res => {
        proxy.$refs['uToast'].show({
          message: '修改成功',
          complete() {
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          }
        })
      })
    } else {
      // 新增
      addLimitHistory(submitData).then(res => {
        proxy.$refs['uToast'].show({
          message: '调额成功',
          complete() {
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          }
        })
      })
    }
  })
}
</script>

<style lang="scss" scoped>
.section {
  margin: 24rpx;
  padding: 0;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;

  .section-title {
    padding: 16rpx 24rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #ffffff;
    line-height: 1.2;
    font-size: 28rpx;
    font-weight: 600;
    display: flex;
    align-items: center;
    
    &::before {
      content: '';
      width: 6rpx;
      height: 28rpx;
      background: #ffffff;
      border-radius: 3rpx;
      margin-right: 12rpx;
    }
  }

  .form-view {
    padding: 24rpx;

    .form-btn {
      padding-top: 16rpx;
    }
  }
}
</style>

<style lang="scss">
.form-btn .u-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  border: none !important;
  border-radius: 24rpx !important;
  height: 80rpx !important;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4) !important;
}

.form-btn .u-button__text {
  font-size: 30rpx !important;
  font-weight: 500 !important;
  letter-spacing: 2rpx !important;
}
</style>
