<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="900"
    :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: 6 }"
      :wrapper-col="{ span: 18 }"
    >

      <!-- 客户信息 -->
      <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="dealerName">
            <a-input
              placeholder="请输入客户名称"
              v-model:value="form.dealerName"
              :disabled="form.applyStatus == 20"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="联系人" name="realName">
            <a-input
              placeholder="请输入联系人"
              v-model:value="form.realName"
              :disabled="form.applyStatus == 20"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="手机号码" name="mobile">
            <a-input
              placeholder="请输入手机号码"
              :disabled="form.applyStatus == 20"
              v-model:value="form.mobile"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="收益基数" name="rate">
            <a-input-number
              placeholder="0.007"
              :min="0"
              :max="1"
              step="0.01"
              :disabled="!hasRole('superAdmin')"
              v-model:value="form.rate"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 报备人信息 -->
      <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="报备人ID" name="userId">
            <a-input-number
              :min="1"
              placeholder="请输入报备人ID"
              :disabled="isUpdate"
              v-model:value="form.userId"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="报备人" name="nickName">
            <a-input-number
              :min="1"
              placeholder="请输入报备人名称"
              :disabled="isUpdate"
              v-model:value="form.nickName"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="推荐人ID" name="refereeId">
            <a-input-number
              :min="1"
              placeholder="请输入推荐人用户ID"
              :disabled="isUpdate"
              v-model:value="form.refereeId"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="推荐人名称" name="refereeName">
            <a-input-number
              :min="1"
              placeholder="请输入推荐人名称"
              :disabled="isUpdate"
              v-model:value="form.refereeName"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 审核信息 -->
      <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="applyStatus">
            <a-select v-model:value="form.applyStatus" placeholder="请选择审核状态" @change="handleStatusChange">
              <a-select-option :value="10">
                <a-tag color="orange">跟进中</a-tag>
                <span style="margin-left: 8px;">正在跟进中</span>
              </a-select-option>
              <a-select-option :value="20">
                <a-tag color="success">已签约</a-tag>
                <span style="margin-left: 8px;">客户已签约</span>
              </a-select-option>
              <a-select-option :value="30">
                <a-tag color="error">已取消</a-tag>
                <span style="margin-left: 8px;">客户已取消</span>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="form.applyStatus === 30">
          <a-form-item label="取消原因" name="rejectReason">
            <a-textarea
              v-model:value="form.rejectReason"
              placeholder="请输入取消原因"
              style="width: 100%"
              :rows="3"
              :maxlength="200"
              show-count
            />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 跟进情况 -->
      <a-divider orientation="left" v-if="form.applyStatus == 10">
        <span style="color: #1890ff; font-weight: 600;">跟进情况</span>
      </a-divider>

      <!-- 历史跟进记录 -->
      <div v-if="form.applyStatus == 10 && historyRecords.length > 0">
        <a-divider orientation="left" style="font-size: 14px; color: #666;">
          历史跟进记录
        </a-divider>
        <div v-for="(record, index) in historyRecords" :key="record.id" style="margin-bottom: 16px; padding: 12px; background-color: #f5f5f5; border-radius: 4px;">
          <div class="flex justify-between" style="font-weight: 500; margin-bottom: 8px;">
            <div>跟进 #{{ historyRecords.length - index }} <span class="text-gray-400 px-4">{{ record.createTime }}</span></div>
            <a-tag color="#f50" class="cursor-pointer" @click="remove(record)">删除</a-tag>
          </div>
          <div style="white-space: pre-wrap;">
            {{ record.content }}
          </div>
        </div>
      </div>

      <!-- 新增跟进记录 -->
      <div v-if="form.applyStatus == 10">
        <a-divider orientation="left" style="font-size: 14px; color: #666;">
          新增跟进记录
        </a-divider>
        <a-form-item :wrapper-col="{ span: 24 }">
          <div class="flex flex-col gap-2">
            <a-textarea
              v-model:value="newFollowUpContent"
              placeholder="请输入本次跟进内容"
              :rows="4"
              :maxlength="500"
              style="width: 80%"
              show-count
            />
            <div class="btn">
              <a-button
                type="primary"
                @click="saveFollowUpRecord"
                :loading="followUpLoading"
                :disabled="!newFollowUpContent.trim()"
              >
                保存跟进记录
              </a-button>
            </div>
          </div>
        </a-form-item>
      </div>

    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import dayjs from 'dayjs';
  import { assignObject } from 'ele-admin-pro';
  import { addShopDealerApply, updateShopDealerApply } from '@/api/shop/shopDealerApply';
  import {listShopDealerRecord, addShopDealerRecord, removeShopDealerRecord} from '@/api/shop/shopDealerRecord';
  import { ShopDealerApply } from '@/api/shop/shopDealerApply/model';
  import { ShopDealerRecord } from '@/api/shop/shopDealerRecord/model';
  import { FormInstance, RuleObject } from 'ant-design-vue/es/form';
  import { messageLoading } from 'ele-admin-pro';
  import {hasRole} from "@/utils/permission";

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

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

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

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

  // 历史跟进记录
  const historyRecords = ref<ShopDealerRecord[]>([]);

  // 新的跟进内容
  const newFollowUpContent = ref('');

  // 表单数据
  const form = reactive<ShopDealerApply>({
    applyId: undefined,
    userId: undefined,
    nickName: undefined,
    realName: '',
    mobile: '',
    dealerName: '',
    rate: 0.007,
    refereeId: undefined,
    refereeName: undefined,
    applyType: 10,
    applyTime: undefined,
    applyStatus: 10,
    auditTime: undefined,
    rejectReason: '',
    tenantId: undefined,
    createTime: undefined,
    updateTime: undefined
  });

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

  // 表单验证规则
  const rules = reactive({
    userId: [
      {
        required: true,
        message: '请输入用户ID',
        trigger: 'blur'
      } as RuleObject
    ],
    realName: [
      {
        required: true,
        message: '请输入客户名称',
        trigger: 'blur'
      } as RuleObject,
      {
        min: 2,
        max: 20,
        message: '姓名长度应在2-20个字符之间',
        trigger: 'blur'
      } as RuleObject
    ],
    rate: [
      {
        required: true,
        message: '请输入收益基数',
        trigger: 'blur'
      } as RuleObject
    ],
    mobile: [
      {
        required: true,
        message: '请输入手机号码',
        trigger: 'blur'
      } as RuleObject,
      {
        pattern: /^1[3-9]\d{9}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur'
      } as RuleObject
    ],
    applyType: [
      {
        required: true,
        message: '请选择申请方式',
        trigger: 'change'
      } as RuleObject
    ],
    applyStatus: [
      {
        required: true,
        message: '请选择审核状态',
        trigger: 'change'
      } as RuleObject
    ],
    rejectReason: [
      {
        required: true,
        message: '驳回时必须填写驳回原因',
        trigger: 'blur'
      } as RuleObject
    ],
    auditTime: [
      {
        required: true,
        message: '审核时请选择审核时间',
        trigger: 'change'
      } as RuleObject
    ]
  });

  /* 获取历史跟进记录 */
  const fetchHistoryRecords = async (dealerId: number) => {
    try {
      // 先通过list接口获取所有记录，然后过滤
      const allRecords = await listShopDealerRecord({});
      const records = allRecords.filter(record => record.dealerId === dealerId);

      // 按创建时间倒序排列（最新的在前面）
      historyRecords.value = records.sort((a, b) => {
        if (a.createTime && b.createTime) {
          return new Date(b.createTime).getTime() - new Date(a.createTime).getTime();
        }
        return 0;
      });
    } catch (error) {
      console.error('获取历史跟进记录失败:', error);
      message.error('获取历史跟进记录失败');
      historyRecords.value = [];
    }
  };

  /* 保存新的跟进记录 */
  const saveFollowUpRecord = async () => {
    // 检查是否有客户ID
    if (!form.applyId) {
      message.warning('请先保存客户信息');
      return;
    }

    // 检查是否有跟进内容
    if (!newFollowUpContent.value.trim()) {
      message.warning('请输入跟进内容');
      return;
    }

    try {
      followUpLoading.value = true;
      const recordData: any = {
        content: newFollowUpContent.value.trim(),
        dealerId: form.applyId,
        userId: form.userId,
        status: 1, // 默认设置为已完成
        sortNumber: 100
      };

      // 新增逻辑
      await addShopDealerRecord(recordData);
      message.success('跟进记录保存成功');
      // 保存最后跟进内容到主表
      await updateShopDealerApply({
        ...form,
        comments: newFollowUpContent.value.trim()
      })

      // 清空输入框
      newFollowUpContent.value = '';

      // 重新加载历史记录
      await fetchHistoryRecords(form.applyId);
    } catch (error) {
      console.error('保存跟进记录失败:', error);
      message.error('保存跟进记录失败');
    } finally {
      followUpLoading.value = false;
    }
  };

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

  /* 处理审核状态变化 */
  const handleStatusChange = (value: number) => {
    // 当状态改为审核通过或驳回时，自动设置审核时间为当前时间
    if ((value === 20 || value === 30) && !form.auditTime) {
      form.auditTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    }
    // 当状态改为待审核时，清空审核时间和驳回原因
    if (value === 10) {
      form.auditTime = undefined;
      form.rejectReason = '';
    }
  };

  /* 删除单个 */
  const remove = (row: ShopDealerRecord) => {
    const hide = messageLoading('请求中..', 0);
    removeShopDealerRecord(row.id)
      .then((msg) => {
        hide();
        message.success(msg);
        // 重新加载历史记录
        if(props.data?.applyId){
          fetchHistoryRecords(props.data?.applyId);
        }
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

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

    // 动态验证规则
    const validateFields: string[] = ['userId', 'realName', 'mobile', 'applyStatus'];

    // 如果是驳回状态，需要验证驳回原因
    if (form.applyStatus === 30) {
      validateFields.push('rejectReason');
    }

    // 如果是审核通过或驳回状态，需要验证审核时间
    if (form.applyStatus === 20 || form.applyStatus === 30) {
      validateFields.push('auditTime');
    }

    formRef.value
      .validate(validateFields)
      .then(async () => {
        loading.value = true;
        const formData = {
          ...form
        };

        // 处理时间字段转换 - 转换为ISO字符串格式
        if (formData.applyTime) {
          if (dayjs.isDayjs(formData.applyTime)) {
            formData.applyTime = formData.applyTime.format('YYYY-MM-DD HH:mm:ss');
          } else if (typeof formData.applyTime === 'number') {
            formData.applyTime = dayjs(formData.applyTime).format('YYYY-MM-DD HH:mm:ss');
          }
        }

        if (formData.auditTime) {
          if (dayjs.isDayjs(formData.auditTime)) {
            formData.auditTime = formData.auditTime.format('YYYY-MM-DD HH:mm:ss');
          } else if (typeof formData.auditTime === 'number') {
            formData.auditTime = dayjs(formData.auditTime).format('YYYY-MM-DD HH:mm:ss');
          }
        }

        // 当审核状态为通过或驳回时，确保有审核时间
        if ((formData.applyStatus === 20 || formData.applyStatus === 30) && !formData.auditTime) {
          formData.auditTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
        }

        // 当状态为待审核时，清空审核时间
        if (formData.applyStatus === 10) {
          formData.auditTime = undefined;
        }

        const saveOrUpdate = isUpdate.value ? updateShopDealerApply : addShopDealerApply;
        try {
          const msg = await saveOrUpdate(formData);
          message.success(msg);

          updateVisible(false);
          emit('done');
        } catch (e: any) {
          message.error(e.message);
        } finally {
          loading.value = false;
        }
      })
      .catch(() => {
        loading.value = false;
      });
  };

  watch(
    () => props.visible,
    async (visible) => {
      if (visible) {
        if (props.data) {
          assignObject(form, props.data);
          isUpdate.value = true;

          // 如果是修改且状态为跟进中，获取历史跟进记录
          if (props.data.applyId && props.data.applyStatus === 10) {
            await fetchHistoryRecords(props.data.applyId);
          }
        } else {
          // 重置为默认值
          Object.assign(form, {
            applyId: undefined,
            userId: undefined,
            realName: '',
            mobile: '',
            refereeId: undefined,
            applyType: 10,
            applyTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            applyStatus: 10,
            auditTime: undefined,
            rejectReason: '',
            tenantId: undefined,
            createTime: undefined,
            updateTime: undefined
          });
          isUpdate.value = false;

          // 重置历史记录和新内容
          historyRecords.value = [];
          newFollowUpContent.value = '';
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>

<style lang="less" scoped>
: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-radio) {
  display: flex;
  align-items: center;
  margin-bottom: 8px;

  .ant-radio-inner {
    margin-right: 8px;
  }
}

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