<template>
  <div class="p-4">
    <!-- 页面标题和按钮 -->
    <div class="flex justify-between items-center mb-4">
      <div class="flex items-center gap-2">
        <el-button icon="ArrowLeft" @click="router.back()">返回</el-button>
        <span class="text-lg font-medium">{{ isEdit ? '编辑' : '新增' }}维保</span>
      </div>
    </div>

    <!-- 企业基本信息 -->
    <el-card shadow="never" class="mb-4">
      <template #header>
        <span class="font-medium">企业基本信息</span>
      </template>
      <el-form :model="form" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="企业名称" prop="customerId">
              <el-select v-model="form.customerId" placeholder="请选择企业" class="w-full" filterable @change="handleCustomerChange">
                <el-option v-for="customer in customerList" :key="customer.id" :label="customer.companyName" :value="customer.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="企业规模">
              <el-input v-model="customerInfo.enterpriseScale" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属行业">
              <el-input v-model="customerInfo.industryCategory" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合作等级">
              <el-input v-model="customerInfo.cooperationLevel" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="会员等级">
              <el-input v-model="customerInfo.memberLevel" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="固定电话">
              <el-input v-model="customerInfo.phone" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="办公地址">
              <el-input v-model="customerInfo.provincialCityCounty" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-input v-model="customerInfo.address" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 销售信息 -->
    <el-card shadow="never" class="mb-4">
      <template #header>
        <span class="font-medium">销售信息</span>
      </template>
      <el-form :model="form" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="业务员">
              <el-input v-model="customerInfo.salesPerson" disabled placeholder="请选择" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客服人员">
              <el-input v-model="customerInfo.servicePerson" disabled placeholder="请选择" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 维保信息 -->
    <el-card shadow="never" class="mb-4">
      <template #header>
        <span class="font-medium">维保信息</span>
      </template>
      <el-form ref="maintainFormRef" :model="form" :rules="rules" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="申请人名称" prop="applicantName">
              <el-input v-model="form.applicantName" placeholder="请输入申请人名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请人手机号" prop="applicantPhone">
              <el-input v-model="form.applicantPhone" placeholder="请输入申请人手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务时间(月)" prop="serviceTime">
              <el-select v-model="form.serviceTime" placeholder="请选择服务时间" class="w-full" filterable>
                <el-option v-for="dict in service_time_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="月度维保次数" prop="monthMainten">
              <el-input-number
                v-model="form.monthMainten"
                :min="0"
                :controls="false"
                class="w-full"
                placeholder="请输入月度维保次数"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="剩余维保次数" prop="remainingMainten">
              <el-input
                v-model="form.remainingMainten"
                :min="0"
                :controls="false"
                class="w-full"
                placeholder="请输入剩余维保次数"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="维保次数限制" prop="maintenLimit">
              <el-input v-model="form.maintenLimit" :min="0" class="w-full" :controls="false" placeholder="请输入维保次数限制" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="服务工程师" prop="serviceEngineer">
              <el-select v-model="form.serviceEngineer" placeholder="请选择" class="w-full" filterable>
                <el-option label="工程师A" value="工程师A" />
                <el-option label="工程师B" value="工程师B" />
                <el-option label="工程师C" value="工程师C" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工程师电话" prop="engineerPhone">
              <el-input v-model="form.engineerPhone" placeholder="请输入工程师电话" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开始时间" prop="serviceStartTime">
              <el-date-picker
                v-model="form.serviceStartTime"
                type="date"
                placeholder="请选择"
                class="w-full"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="结束时间" prop="serviceEndTime">
              <el-date-picker
                v-model="form.serviceEndTime"
                type="date"
                placeholder="请选择"
                class="w-full"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="维保类型" prop="maintainType">
              <el-select v-model="form.maintainType" placeholder="请选择" class="w-full" filterable>
                <el-option v-for="dict in maintenance_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="服务内容" prop="serviceContent">
              <el-checkbox-group v-model="form.serviceContent">
                <el-checkbox v-for="item in serviceContentList" :key="item.id" :value="item.id">{{ item.itemName }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="维保合同" prop="maintainFile">
              <el-upload action="#" :auto-upload="false" :file-list="fileList" :on-change="handleFileChange">
                <el-button type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="其他服务" prop="otherService">
              <el-input v-model="form.otherService" type="textarea" :rows="3" placeholder="请输入其他服务" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">提交</el-button>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="MaintainInfoAdd">
import { addMaintainInfo, updateMaintainInfo, getMaintainInfo } from '@/api/customer/maintainInfo';
import { listCustomerInfo, getCustomerInfo } from '@/api/customer/customerFile/customerInfo';
import { getEnterpriseScale } from '@/api/customer/customerCategory/enterpriseScale';
import { getIndustryCategory } from '@/api/customer/customerCategory/industryCategory';
import { listServerItem } from '@/api/customer/serverItem';
import { CustomerInfoVO } from '@/api/customer/customerFile/customerInfo/types';
import type { ServerItemVO } from '@/api/customer/serverItem/types';
import type { MaintainInfoForm } from '@/api/customer/maintainInfo/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { service_time_type, maintenance_type } = toRefs<any>(proxy?.useDict('service_time_type', 'maintenance_type'));

const route = useRoute();
const router = useRouter();

const formRef = ref<any>(null);
const maintainFormRef = ref<any>(null);
const submitLoading = ref(false);
const isEdit = ref(false);
const fileList = ref<any[]>([]);
const customerList = ref<CustomerInfoVO[]>([]);
const serviceContentList = ref<ServerItemVO[]>([]);

// 客户信息（选择企业后自动带出）
const customerInfo = reactive({
  customerNo: '',
  enterpriseScale: '',
  industryCategory: '',
  cooperationLevel: '',
  memberLevel: '',
  phone: '',
  address: '',
  provincialCityCounty: '',
  salesPerson: '',
  servicePerson: ''
});

// 表单数据
const form = reactive<any>({
  customerId: undefined,
  applicantName: '',
  applicantPhone: '',
  serviceTime: '',
  monthMainten: undefined,
  remainingMainten: undefined,
  maintenLimit: undefined,
  serviceEngineer: '',
  engineerPhone: '',
  serviceStartTime: '',
  serviceEndTime: '',
  maintainType: '',
  serviceContent: [],
  maintainFile: '',
  otherService: '',
  status: '0'
});

// 表单验证规则
const rules = {
  customerId: [{ required: true, message: '请选择企业名称', trigger: 'change' }],
  applicantName: [{ required: true, message: '请输入申请人名称', trigger: 'blur' }],
  applicantPhone: [
    { required: true, message: '请输入申请人手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  serviceEngineer: [{ required: true, message: '请选择服务工程师', trigger: 'change' }]
};

// 初始化
onMounted(async () => {
  // 加载客户列表
  await loadCustomerList();
  // 加载服务内容列表
  await loadServiceContentList();
  const _id = route.query.id;
  if (_id) {
    isEdit.value = true;
    await loadMaintainData(_id as any);
  }
});

// 加载客户列表
const loadCustomerList = async () => {
  try {
    const res = await listCustomerInfo();
    customerList.value = res.rows || [];
  } catch (error) {
    console.error('加载客户列表失败:', error);
    ElMessage.error('加载客户列表失败');
  }
};

// 加载服务内容列表
const loadServiceContentList = async () => {
  try {
    const res = await listServerItem();
    serviceContentList.value = res.rows || [];
  } catch (error) {
    console.error('加载服务内容列表失败:', error);
    ElMessage.error('加载服务内容列表失败');
  }
};

// 选择企业后加载企业信息
const handleCustomerChange = async (customerId: string | number) => {
  if (!customerId) return;

  try {
    const res = await getCustomerInfo(customerId);
    const data = res.data;

    // 填充企业基本信息 - 使用API获取真实数据
    customerInfo.customerNo = data.customerNo;
    // customerInfo.memberLevel = getCustomerLevelName(data.customerLevelId);
    customerInfo.phone = data.landline || '';
    customerInfo.address = data.address || '';
    customerInfo.provincialCityCounty = data.provincialCityCounty || '';
    customerInfo.industryCategory = data.industryCategory || '-';
    customerInfo.enterpriseScale = data.enterpriseScale || '-';

    // 填充销售信息
    if (data.customerSalesInfoVo) {
      customerInfo.salesPerson = res.data.customerSalesInfoVo?.salesPerson;
      customerInfo.servicePerson = res.data.customerSalesInfoVo?.serviceStaff;
    }
  } catch (error) {
    ElMessage.error('加载企业信息失败');
  }
};

// 加载维保数据
const loadMaintainData = async (id: string | number) => {
  try {
    const res = await getMaintainInfo(id);
    const data = res.data;

    // 将服务内容字符串（ID列表）转换为数组
    if (data.serviceContent && typeof data.serviceContent === 'string') {
      data.serviceContent = data.serviceContent.split(',').filter((item: string) => item.trim());
    }

    Object.assign(form, data);

    // 如果有客户ID，加载客户信息
    if (form.customerId) {
      await handleCustomerChange(form.customerId);
    }
  } catch (error) {
    ElMessage.error('加载维保数据失败');
  }
};

// 文件变化
const handleFileChange = (file: any, uploadFileList: any[]) => {
  fileList.value = uploadFileList;
  console.log('文件变化:', file, uploadFileList);
};

// 提交表单
const handleSubmit = async () => {
  try {
    await maintainFormRef.value?.validate();
    submitLoading.value = true;

    // 准备提交数据，将 serviceContent 数组（ID列表）转换为逗号分隔的字符串
    const submitData = {
      ...form,
      serviceContent: Array.isArray(form.serviceContent) ? form.serviceContent.join(',') : form.serviceContent
    };

    if (isEdit.value) {
      await updateMaintainInfo(submitData);
      ElMessage.success('修改成功');
    } else {
      await addMaintainInfo(submitData);
      ElMessage.success('添加成功');
    }
    router.back();
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败，请重试');
  } finally {
    submitLoading.value = false;
  }
};
</script>
