<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="1000"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑分销商设置' : '新增分销商设置'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
    >
      <!-- 基本信息 -->
      <a-divider orientation="left">
        <span style="color: #1890ff; font-weight: 600;">基本信息</span>
      </a-divider>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="设置标识" name="key">
            <a-select
              v-model:value="form.key"
              placeholder="请选择设置标识"
              @change="onSettingKeyChange"
            >
              <a-select-option value="commission_rate">
                <div class="setting-option">
                  <a-tag color="blue">佣金比例</a-tag>
                  <span>分销佣金比例设置</span>
                </div>
              </a-select-option>
              <a-select-option value="withdraw_config">
                <div class="setting-option">
                  <a-tag color="green">提现配置</a-tag>
                  <span>提现相关参数设置</span>
                </div>
              </a-select-option>
              <a-select-option value="level_config">
                <div class="setting-option">
                  <a-tag color="orange">等级配置</a-tag>
                  <span>分销商等级设置</span>
                </div>
              </a-select-option>
              <a-select-option value="reward_config">
                <div class="setting-option">
                  <a-tag color="purple">奖励配置</a-tag>
                  <span>推广奖励设置</span>
                </div>
              </a-select-option>
              <a-select-option value="other">
                <div class="setting-option">
                  <a-tag color="default">其他设置</a-tag>
                  <span>自定义设置项</span>
                </div>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="设置描述" name="describe">
            <a-input
              placeholder="请输入设置项描述"
              v-model:value="form.describe"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 设置内容 -->
      <a-divider orientation="left">
        <span style="color: #1890ff; font-weight: 600;">设置内容</span>
      </a-divider>

      <!-- 预设配置模板 -->
      <div v-if="form.key && form.key !== 'other'" class="config-template">
        <a-alert
          :message="getTemplateTitle()"
          :description="getTemplateDescription()"
          type="info"
          show-icon
          style="margin-bottom: 16px"
        />

        <!-- 佣金比例配置 -->
        <div v-if="form.key === 'commission_rate'" class="commission-config">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item label="一级佣金比例">
                <a-input-number
                  v-model:value="configData.firstRate"
                  :min="0"
                  :max="100"
                  :precision="2"
                  placeholder="0.00"
                  style="width: 100%"
                >
                  <template #addonAfter>%</template>
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="二级佣金比例">
                <a-input-number
                  v-model:value="configData.secondRate"
                  :min="0"
                  :max="100"
                  :precision="2"
                  placeholder="0.00"
                  style="width: 100%"
                >
                  <template #addonAfter>%</template>
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="三级佣金比例">
                <a-input-number
                  v-model:value="configData.thirdRate"
                  :min="0"
                  :max="100"
                  :precision="2"
                  placeholder="0.00"
                  style="width: 100%"
                >
                  <template #addonAfter>%</template>
                </a-input-number>
              </a-form-item>
            </a-col>
          </a-row>
        </div>

        <!-- 提现配置 -->
        <div v-if="form.key === 'withdraw_config'" class="withdraw-config">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item label="最小提现金额">
                <a-input-number
                  v-model:value="configData.minAmount"
                  :min="0"
                  :precision="2"
                  placeholder="0.00"
                  style="width: 100%"
                >
                  <template #addonAfter>元</template>
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="手续费比例">
                <a-input-number
                  v-model:value="configData.feeRate"
                  :min="0"
                  :max="100"
                  :precision="2"
                  placeholder="0.00"
                  style="width: 100%"
                >
                  <template #addonAfter>%</template>
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="审核方式">
                <a-select v-model:value="configData.auditType" style="width: 100%">
                  <a-select-option :value="1">自动审核</a-select-option>
                  <a-select-option :value="2">人工审核</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </div>

        <!-- 等级配置 -->
        <div v-if="form.key === 'level_config'" class="level-config">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="升级条件">
                <a-select v-model:value="configData.upgradeType" style="width: 100%">
                  <a-select-option :value="1">按推广人数</a-select-option>
                  <a-select-option :value="2">按累计佣金</a-select-option>
                  <a-select-option :value="3">按订单数量</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="升级阈值">
                <a-input-number
                  v-model:value="configData.upgradeThreshold"
                  :min="0"
                  placeholder="0"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </div>

        <!-- 奖励配置 -->
        <div v-if="form.key === 'reward_config'" class="reward-config">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item label="推广奖励">
                <a-input-number
                  v-model:value="configData.promotionReward"
                  :min="0"
                  :precision="2"
                  placeholder="0.00"
                  style="width: 100%"
                >
                  <template #addonAfter>元</template>
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="首单奖励">
                <a-input-number
                  v-model:value="configData.firstOrderReward"
                  :min="0"
                  :precision="2"
                  placeholder="0.00"
                  style="width: 100%"
                >
                  <template #addonAfter>元</template>
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="月度奖励">
                <a-input-number
                  v-model:value="configData.monthlyReward"
                  :min="0"
                  :precision="2"
                  placeholder="0.00"
                  style="width: 100%"
                >
                  <template #addonAfter>元</template>
                </a-input-number>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
      </div>

      <!-- JSON 编辑器 -->
      <a-form-item label="配置内容" name="values">
        <div class="json-editor-container">
          <div class="json-editor-header">
            <span>JSON 配置</span>
            <a-space>
              <a-button size="small" @click="formatJson">
                <template #icon>
                  <FormatPainterOutlined />
                </template>
                格式化
              </a-button>
              <a-button size="small" @click="validateJson">
                <template #icon>
                  <CheckCircleOutlined />
                </template>
                验证
              </a-button>
              <a-button size="small" @click="resetToTemplate" v-if="form.key && form.key !== 'other'">
                <template #icon>
                  <ReloadOutlined />
                </template>
                重置为模板
              </a-button>
            </a-space>
          </div>
          <a-textarea
            v-model:value="form.values"
            placeholder="请输入JSON格式的配置内容"
            :rows="12"
            class="json-editor"
            @blur="onJsonBlur"
          />
          <div class="json-status" v-if="jsonStatus">
            <a-alert
              :type="jsonStatus.type"
              :message="jsonStatus.message"
              show-icon
              :closable="false"
            />
          </div>
        </div>
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import {
    FormatPainterOutlined,
    CheckCircleOutlined,
    ReloadOutlined
  } from '@ant-design/icons-vue';
  import { assignObject } from 'ele-admin-pro';
  import { addShopDealerSetting, updateShopDealerSetting } from '@/api/shop/shopDealerSetting';
  import { ShopDealerSetting } from '@/api/shop/shopDealerSetting/model';
  import { FormInstance } from 'ant-design-vue/es/form';

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: ShopDealerSetting | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  // 表格选中数据
  const formRef = ref<FormInstance | null>(null);

  // 表单数据
  const form = reactive<ShopDealerSetting>({
    key: undefined,
    describe: '',
    values: '',
    tenantId: undefined,
    updateTime: undefined
  });

  // 配置数据（用于模板配置）
  const configData = reactive<any>({
    // 佣金比例配置
    firstRate: 0,
    secondRate: 0,
    thirdRate: 0,
    // 提现配置
    minAmount: 0,
    feeRate: 0,
    auditType: 1,
    // 等级配置
    upgradeType: 1,
    upgradeThreshold: 0,
    // 奖励配置
    promotionReward: 0,
    firstOrderReward: 0,
    monthlyReward: 0
  });

  // JSON状态
  const jsonStatus = ref<any>(null);

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单验证规则
  const rules = reactive({
    key: [
      {
        required: true,
        message: '请选择设置标识',
        trigger: 'change'
      }
    ],
    describe: [
      {
        required: true,
        message: '请输入设置描述',
        trigger: 'blur'
      },
      {
        min: 2,
        max: 100,
        message: '描述长度应在2-100个字符之间',
        trigger: 'blur'
      }
    ],
    values: [
      {
        required: true,
        message: '请输入配置内容',
        trigger: 'blur'
      },
      {
        validator: (rule: any, value: any) => {
          if (value) {
            try {
              JSON.parse(value);
              return Promise.resolve();
            } catch (e) {
              return Promise.reject('配置内容必须是有效的JSON格式');
            }
          }
          return Promise.resolve();
        },
        trigger: 'blur'
      }
    ]
  });

  /* 获取模板标题 */
  const getTemplateTitle = () => {
    const titleMap = {
      commission_rate: '佣金比例配置模板',
      withdraw_config: '提现配置模板',
      level_config: '等级配置模板',
      reward_config: '奖励配置模板'
    };
    return titleMap[form.key] || '配置模板';
  };

  /* 获取模板描述 */
  const getTemplateDescription = () => {
    const descMap = {
      commission_rate: '设置一级、二级、三级分销商的佣金比例，支持小数点后两位',
      withdraw_config: '配置提现的最小金额、手续费比例和审核方式',
      level_config: '设置分销商等级升级的条件和阈值',
      reward_config: '配置推广奖励、首单奖励和月度奖励金额'
    };
    return descMap[form.key] || '请根据业务需求配置相关参数';
  };

  /* 设置标识改变时的处理 */
  const onSettingKeyChange = (value: string) => {
    // 重置配置数据
    Object.keys(configData).forEach(key => {
      configData[key] = typeof configData[key] === 'number' ? 0 : '';
    });

    // 设置默认描述
    const descMap = {
      commission_rate: '分销佣金比例设置',
      withdraw_config: '提现相关参数配置',
      level_config: '分销商等级配置',
      reward_config: '推广奖励配置',
      other: '自定义设置项'
    };

    if (!form.describe) {
      form.describe = descMap[value] || '';
    }

    // 生成默认JSON
    resetToTemplate();
  };

  /* 重置为模板 */
  const resetToTemplate = () => {
    if (!form.key || form.key === 'other') {
      form.values = '{}';
      return;
    }

    let template = {};

    switch (form.key) {
      case 'commission_rate':
        template = {
          firstRate: configData.firstRate || 10,
          secondRate: configData.secondRate || 5,
          thirdRate: configData.thirdRate || 2,
          description: '分销佣金比例配置'
        };
        break;
      case 'withdraw_config':
        template = {
          minAmount: configData.minAmount || 100,
          feeRate: configData.feeRate || 1,
          auditType: configData.auditType || 1,
          description: '提现配置参数'
        };
        break;
      case 'level_config':
        template = {
          upgradeType: configData.upgradeType || 1,
          upgradeThreshold: configData.upgradeThreshold || 10,
          description: '分销商等级配置'
        };
        break;
      case 'reward_config':
        template = {
          promotionReward: configData.promotionReward || 10,
          firstOrderReward: configData.firstOrderReward || 5,
          monthlyReward: configData.monthlyReward || 50,
          description: '推广奖励配置'
        };
        break;
    }

    form.values = JSON.stringify(template, null, 2);
    validateJson();
  };

  /* 格式化JSON */
  const formatJson = () => {
    try {
      const parsed = JSON.parse(form.values);
      form.values = JSON.stringify(parsed, null, 2);
      jsonStatus.value = {
        type: 'success',
        message: 'JSON格式化成功'
      };
    } catch (e) {
      jsonStatus.value = {
        type: 'error',
        message: 'JSON格式错误，无法格式化'
      };
    }
  };

  /* 验证JSON */
  const validateJson = () => {
    try {
      JSON.parse(form.values);
      jsonStatus.value = {
        type: 'success',
        message: 'JSON格式正确'
      };
    } catch (e) {
      jsonStatus.value = {
        type: 'error',
        message: `JSON格式错误: ${e.message}`
      };
    }
  };

  /* JSON失焦时验证 */
  const onJsonBlur = () => {
    if (form.values) {
      validateJson();
    }
  };

  const { resetFields } = useForm(form, rules);

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }

    // 先验证JSON格式
    if (form.values) {
      try {
        JSON.parse(form.values);
      } catch (e) {
        message.error('配置内容JSON格式错误，请检查后重试');
        return;
      }
    }

    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form,
          updateTime: Date.now()
        };

        const saveOrUpdate = isUpdate.value ? updateShopDealerSetting : addShopDealerSetting;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        jsonStatus.value = null;
        if (props.data) {
          assignObject(form, props.data);

          // 解析配置数据到模板
          if (props.data.values) {
            try {
              const parsed = JSON.parse(props.data.values);
              Object.keys(configData).forEach(key => {
                if (parsed[key] !== undefined) {
                  configData[key] = parsed[key];
                }
              });
            } catch (e) {
              console.warn('解析配置数据失败:', e);
            }
          }

          isUpdate.value = true;
        } else {
          // 重置为默认值
          Object.assign(form, {
            key: undefined,
            describe: '',
            values: '{}',
            tenantId: undefined,
            updateTime: undefined
          });

          // 重置配置数据
          Object.keys(configData).forEach(key => {
            configData[key] = typeof configData[key] === 'number' ? 0 : '';
          });

          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );

  // 监听配置数据变化，自动更新JSON
  watch(
    () => configData,
    () => {
      if (form.key && form.key !== 'other') {
        resetToTemplate();
      }
    },
    { deep: true }
  );
</script>

<style lang="less" scoped>
.setting-option {
  display: flex;
  align-items: center;

  .ant-tag {
    margin-right: 8px;
  }

  span {
    color: #666;
    font-size: 12px;
  }
}

.config-template {
  background: #fafafa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 16px;

  .commission-config,
  .withdraw-config,
  .level-config,
  .reward-config {
    margin-top: 16px;
  }
}

.json-editor-container {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  overflow: hidden;

  .json-editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    background: #fafafa;
    border-bottom: 1px solid #d9d9d9;

    span {
      font-weight: 600;
      color: #333;
    }
  }

  .json-editor {
    border: none;
    border-radius: 0;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 12px;
    line-height: 1.5;

    &:focus {
      box-shadow: none;
    }
  }

  .json-status {
    padding: 8px 12px;
    border-top: 1px solid #d9d9d9;
    background: #fff;
  }
}

:deep(.ant-divider-horizontal.ant-divider-with-text-left) {
  margin: 24px 0 16px 0;

  .ant-divider-inner-text {
    padding: 0 16px 0 0;
  }
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-select-selection-item) {
  display: flex;
  align-items: center;
}

:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-alert) {
  .ant-alert-message {
    font-weight: 600;
  }
}
</style>
</script>
