<template>
  <a-card :bordered="false">
    <a-form
      :model="formModel"
      :label-col-props="{ span: 6 }"
      :wrapper-col-props="{ span: 18 }"
      label-align="left"
      @submit="handleSubmit"
    >
      <!-- 基础设置区域 -->
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item field="useHaozhuPlatform" label="豪猪平台">
            <a-switch
              v-model="formModel.useHaozhuPlatform"
              checked-text="启用"
              unchecked-text="禁用"
            >
              <template #checked-text>启用</template>
              <template #unchecked-text>禁用</template>
            </a-switch>
            <template #help>是否从豪猪平台获取手机号登录</template>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="haozhuUsername"
            label="豪猪用户名"
            :rules="[
              {
                required: formModel.useHaozhuPlatform,
                message: '启用豪猪平台时请输入用户名'
              }
            ]"
          >
            <a-input
              v-model="formModel.haozhuUsername"
              placeholder="请输入豪猪平台用户名"
              :disabled="!formModel.useHaozhuPlatform"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item
            field="haozhuPassword"
            label="豪猪密码"
            :rules="[
              {
                required: formModel.useHaozhuPlatform,
                message: '启用豪猪平台时请输入密码'
              }
            ]"
          >
            <a-input-password
              v-model="formModel.haozhuPassword"
              placeholder="请输入豪猪平台密码"
              :disabled="!formModel.useHaozhuPlatform"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="loginAccountCount"
            label="登录账号数量"
            :rules="[
              { required: true, message: '请输入登录账号数量' },
              {
                type: 'number',
                min: 1,
                max: 100,
                message: '请输入1-100之间的数字'
              }
            ]"
          >
            <a-input-number
              v-model="formModel.loginAccountCount"
              :min="1"
              :max="100"
              placeholder="请输入要登录的手机号数量"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item
            field="prefetchConcurrencyAccounts"
            label="并发账号数"
            :rules="[
              { required: true, message: '请输入并发账号数量' },
              {
                type: 'number',
                min: 1,
                max: 50,
                message: '请输入1-50之间的数字'
              }
            ]"
          >
            <a-input-number
              v-model="formModel.prefetchConcurrencyAccounts"
              :min="1"
              :max="50"
              placeholder="请输入提前拉单并发的账号数量"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="singleAccountConcurrency"
            label="单账号并发数"
            :rules="[
              { required: true, message: '请输入单账号并发数量' },
              {
                type: 'number',
                min: 1,
                max: 20,
                message: '请输入1-20之间的数字'
              }
            ]"
          >
            <a-input-number
              v-model="formModel.singleAccountConcurrency"
              :min="1"
              :max="20"
              placeholder="请输入单个账号的并发数量"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <div class="denominations-section">
        <div class="denominations-actions">
          <a-button type="primary" size="small" @click="addDenomination">
            <template #icon>
              <icon-plus />
            </template>
            添加面额
          </a-button>
        </div>

        <a-table
          v-if="
            formModel.targetDenominations &&
            formModel.targetDenominations.length > 0
          "
          :data="formModel.targetDenominations"
          :columns="columns"
          :pagination="false"
          :bordered="{ cell: true }"
          row-key="denomination"
        >
          <template #denomination="{ rowIndex }">
            <a-input-number
              v-model="formModel.targetDenominations[rowIndex].denomination"
              :min="1"
              placeholder="如100、200、500"
              style="width: 100%"
            />
          </template>
          <template #minCapacity="{ rowIndex }">
            <a-input-number
              v-model="formModel.targetDenominations[rowIndex].minCapacity"
              :min="0"
              placeholder="库存低于此值时触发补充"
              style="width: 100%"
            />
          </template>
          <template #targetCapacity="{ rowIndex }">
            <a-input-number
              v-model="formModel.targetDenominations[rowIndex].targetCapacity"
              :min="1"
              placeholder="补充时的目标数量"
              style="width: 100%"
            />
          </template>
          <template #actions="{ rowIndex }">
            <a-button
              type="text"
              status="danger"
              size="small"
              @click="removeDenomination(rowIndex)"
            >
              <template #icon>
                <icon-delete />
              </template>
              删除
            </a-button>
          </template>
        </a-table>

        <a-empty v-else description="暂无面额设置，请添加面额配置" />
      </div>

      <!-- 操作按钮区域 -->
      <div class="form-actions">
        <a-row justify="center">
          <a-col>
            <a-space :size="16">
              <a-button type="primary" html-type="submit" :loading="loading">
                <template #icon>
                  <icon-save />
                </template>
                保存设置
              </a-button>
              <a-button @click="resetForm">
                <template #icon>
                  <icon-refresh />
                </template>
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </div>
    </a-form>
  </a-card>
</template>

<script lang="ts" setup>
import { reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import type { KamiApiCamelOilV1DenominationSetting } from '@/api/generated/index.ts';
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
import { jdV2SettingsClient } from '@/api/index.ts';

const { loading, setLoading } = useLoading(false);

const formModel = reactive({
  useHaozhuPlatform: false,
  haozhuUsername: '',
  haozhuPassword: '',
  loginAccountCount: 5,
  prefetchConcurrencyAccounts: 2,
  singleAccountConcurrency: 3,
  targetDenominations: [] as KamiApiCamelOilV1DenominationSetting[]
});

// 表格列配置
const columns: TableColumnData[] = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 80,
    render: ({ rowIndex }) => rowIndex + 1
  },
  {
    title: '面额值',
    dataIndex: 'denomination',
    width: 150,
    slotName: 'denomination'
  },
  {
    title: '最小库存',
    dataIndex: 'minCapacity',
    width: 150,
    slotName: 'minCapacity'
  },
  {
    title: '目标库存',
    dataIndex: 'targetCapacity',
    width: 150,
    slotName: 'targetCapacity'
  },
  {
    title: '操作',
    dataIndex: 'actions',
    width: 100,
    slotName: 'actions'
  }
];

const addDenomination = () => {
  if (!formModel.targetDenominations) {
    formModel.targetDenominations = [];
  }
  formModel.targetDenominations.push({
    denomination: null,
    minCapacity: null,
    targetCapacity: null
  });
};

const removeDenomination = (index: number) => {
  formModel.targetDenominations.splice(index, 1);
};

const handleSubmit = async () => {
  try {
    // 验证豪猪平台设置
    if (formModel.useHaozhuPlatform) {
      if (!formModel.haozhuUsername || !formModel.haozhuPassword) {
        Message.warning({
          content: '启用豪猪平台时请填写用户名和密码',
          duration: 3000
        });
        return;
      }
    }

    // 验证面额设置
    if (
      formModel.targetDenominations &&
      formModel.targetDenominations.length > 0
    ) {
      for (let i = 0; i < formModel.targetDenominations.length; i++) {
        const item = formModel.targetDenominations[i];
        if (!item.denomination || !item.minCapacity || !item.targetCapacity) {
          Message.warning({
            content: `请完善第${i + 1}个面额设置的必填项`,
            duration: 3000
          });
          return;
        }
        if (item.minCapacity >= item.targetCapacity) {
          Message.warning({
            content: `第${i + 1}个面额设置的最小库存必须小于目标库存`,
            duration: 3000
          });
          return;
        }
      }
    }

    setLoading(true);
    await jdV2SettingsClient.apiJdV2SettingsUpdatePost({
      kamiApiCamelOilV1UpdateSettingsReq: { ...formModel }
    });

    Message.success({
      content: '设置保存成功',
      duration: 2000
    });
  } catch (error) {
    console.error('保存设置失败:', error);
    Message.error({
      content: '保存设置失败',
      duration: 2000
    });
  } finally {
    setLoading(false);
  }
};

const resetForm = () => {
  loadSettings();
};

// 加载设置数据
const loadSettings = async () => {
  setLoading(true);
  try {
    const { data } = await jdV2SettingsClient.apiJdV2SettingsGetGet();
    Object.assign(formModel, data);
    if (!formModel.targetDenominations) {
      formModel.targetDenominations = [];
    }
  } catch (error) {
    console.error('获取设置失败:', error);
    Message.error({
      content: '获取设置失败',
      duration: 2000
    });
  } finally {
    setLoading(false);
  }
};

// 组件挂载时加载设置
onMounted(() => {
  loadSettings();
});
</script>

<style scoped>
.denominations-section {
  margin-top: 20px;
}

.denominations-actions {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}

.section-title {
  font-weight: 500;
  color: var(--color-text-1);
  font-size: 14px;
}

.form-actions {
  margin-top: 32px;
  padding-top: 20px;
  border-top: 1px solid var(--color-border-2);
}

/* Arco Design 已经处理了大部分样式，只需要覆盖必要的布局样式 */
:deep(.arco-form-item-content-flex) {
  display: block;
}
</style>
