<template>
  <div class="p-4">
    <!-- ERP销售信息 -->
    <el-card shadow="never" class="mb-4">
      <template #header>
        <el-row :gutter="10" class="mb8" type="flex" justify="space-between" align="middle">
          <span style="font-size: 16px; font-weight: 500">ERP销售信息</span>
          <div style="display: flex; flex-wrap: nowrap; gap: 10px">
            <el-button v-if="!isViewMode" type="primary" plain icon="Plus" :loading="submitLoading" @click="handleSave">保存</el-button>
          </div>
        </el-row>
      </template>
      <el-form ref="salesFormRef" :model="salesForm" :rules="salesRules" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="业务人员" prop="salesPersonId" required>
              <el-select
                v-model="salesForm.salesPersonId"
                placeholder="请选择业务人员"
                class="w-full"
                filterable
                @change="handleSalesPersonChange"
                :disabled="isViewMode"
              >
                <el-option v-for="item in comStaffList" :key="item.staffId" :label="`${item.staffCode} , ${item.staffName}`" :value="item.staffId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客服人员" prop="serviceStaffId" required>
              <el-select v-model="salesForm.serviceStaffId" placeholder="请选择客服人员" class="w-full" filterable :disabled="isViewMode">
                <el-option v-for="item in comStaffList" :key="item.staffId" :label="`${item.staffCode} , ${item.staffName}`" :value="item.staffId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属部门" prop="belongingDepartmentId">
              <el-input v-model="deptName" placeholder="请选择所属部门" class="w-full" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="信用等级" prop="creditManagementId">
              <el-select v-model="salesForm.creditManagementId" placeholder="请选择信用等级" class="w-full" filterable :disabled="isViewMode">
                <el-option
                  v-for="item in creditLevelList"
                  :key="item.id"
                  :label="`${item.creditLevelNo} , ${item.creditLevelName}`"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="信用额度" prop="creditAmount">
              <el-input v-model="salesForm.creditAmount" :controls="false" class="w-full" placeholder="请输入信用额度" style="width: 100%" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="可用额度" prop="remainingQuota">
              <el-input
                v-model="salesForm.remainingQuota"
                :controls="false"
                class="w-full"
                placeholder="请输入可用额度"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="订单审核" prop="orderAudit">
              <el-select v-model="salesForm.orderAudit" placeholder="请选择" class="w-full" filterable :disabled="isViewMode">
                <el-option v-for="dict in order_check_way" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="支付密码" prop="creditPaymentPassword">
              <el-input v-model="salesForm.creditPaymentPassword" type="password" placeholder="请输入支付密码" show-password :disabled="isViewMode" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="结算方式" prop="settlementMethod">
              <el-select v-model="salesForm.settlementMethod" placeholder="请选择结算方式" class="w-full" filterable :disabled="isViewMode">
                <el-option v-for="item in settlementMethodList" :key="item.id" :label="item.settlementName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户来源" prop="customerSource">
              <el-select v-model="salesForm.customerSource" class="w-full" filterable :disabled="isViewMode">
                <el-option v-for="dict in customer_source" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售通路" prop="sellChannel">
              <el-select v-model="salesForm.sellChannel" class="w-full" filterable :disabled="isViewMode">
                <el-option v-for="dict in sell_channel" :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="rateId">
              <el-select v-model="salesForm.rateId" placeholder="税码" class="w-full" filterable :disabled="isViewMode">
                <el-option v-for="item in taxrateList" :key="item.id" :label="item.taxrateNo" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="交易币别" prop="dealCurrencyId">
              <el-select v-model="salesForm.dealCurrencyId" placeholder="请选择交易币别" class="w-full" filterable :disabled="isViewMode">
                <el-option v-for="item in currencyList" :key="item.id" :label="item.currencyName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="账款归属" prop="customerNo">
              <el-input :model-value="props.customerNo || ''" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="单价含税" prop="unitPrice">
              <el-select v-model="salesForm.unitPrice" placeholder="单价含税" class="w-full" filterable :disabled="isViewMode">
                <el-option v-for="item in unitPriceArr" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="账款额度超限" prop="creditLimit">
              <el-select v-model="salesForm.creditLimit" placeholder="请选择账款额度超限" class="w-full" filterable :disabled="isViewMode">
                <el-option v-for="dict in erp_is_enabled" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="账款超期" prop="creditTimeLimit">
              <el-select v-model="salesForm.creditTimeLimit" placeholder="请选择账款超期" class="w-full" filterable :disabled="isViewMode">
                <el-option v-for="dict in erp_is_enabled" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="ErpSaleInfo">
import { getCustomerInfo, updateCustomerInfo } from '@/api/customer/customerFile/customerInfo';
import type { SalesInfoForm } from '@/api/customer/customerFile/salesInfo/types';
import type { CustomerInfoForm } from '@/api/customer/customerFile/customerInfo/types';
import { listSettlementMethod } from '@/api/customer/settlementMethod';
import { SettlementMethodVO } from '@/api/customer/settlementMethod/types';
import { listCreditLevel } from '@/api/customer/creditLevel';
import { CreditLevelVO, CreditLevelQuery } from '@/api/customer/creditLevel/types';
import { listComStaff } from '@/api/company/comStaff';
import { listErpStaff } from '@/api/erpData/erpStaff';
import { listErpDept, getErpDept } from '@/api/erpData/erpDept';
import { listComCurrency } from '@/api/company/comCurrency';
import { listTaxrate } from '@/api/company/taxrate';
import { ComCurrencyVO } from '@/api/company/comCurrency/types';
import { ErpStaffVO } from '@/api/erpData/erpStaff/types';
import { ErpDeptVO } from '@/api/erpData/erpDept/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { order_check_way, customer_source, sell_channel, erp_is_enabled } = toRefs<any>(
  proxy?.useDict('order_check_way', 'customer_source', 'sell_channel', 'erp_is_enabled')
);

// 接收父组件传递的props
const props = defineProps<{
  customerId?: string | number;
  customerNo?: string;
}>();

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

// 查看模式
const isViewMode = computed(() => route.query.status === 'view');

const unitPriceArr = ref([
  { label: '含税', value: 'True' },
  { label: '不含税', value: 'False' }
]);

const salesFormRef = ref<any>(null);
const custId = ref<string | number>('');
const customerNumber = ref('');
const submitLoading = ref(false);

// 下拉框数据列表
const settlementMethodList = ref<SettlementMethodVO[]>([]);
const creditLevelList = ref<CreditLevelVO[]>([]);
const comStaffList = ref<ErpStaffVO[]>([]);
const comDeptList = ref<ErpDeptVO[]>([]);
const currencyList = ref<ComCurrencyVO[]>([]);
const taxrateList = ref<any[]>([]);

// 销售信息
const salesForm = reactive<SalesInfoForm>({
  salesPersonId: undefined,
  serviceStaffId: undefined,
  belongingDepartmentId: undefined,
  creditManagementId: undefined,
  creditAmount: undefined,
  remainingQuota: undefined,
  orderAudit: undefined,
  creditPaymentPassword: '',
  accountPeriod: '',
  payDays: undefined,
  customerSource: '1',
  unitPrice: 'True',
  sellChannel: '1',
  creditLimit: '1',
  creditTimeLimit: '1',
  dealCurrencyId: undefined,
  settlementMethod: undefined,
  status: '0'
});

// 销售信息表单验证规则
const salesRules = {
  salesPersonId: [{ required: true, message: '请选择业务人员', trigger: 'change' }],
  serviceStaffId: [{ required: true, message: '请选择客服人员', trigger: 'change' }]
};

// 部门名称（响应式）
const deptName = ref('');

// 加载币种列表
const loadCurrencyList = async () => {
  try {
    const res = await listComCurrency({
      isShow: '0',
      pageNum: 1,
      pageSize: 1000
    });
    currencyList.value = res.rows || [];
    if (res.rows && res.rows.length > 0) {
      salesForm.dealCurrencyId = res.rows[0].id;
    }
  } catch (error) {
    console.error('加载币种列表失败:', error);
    currencyList.value = [];
  }
};

// 加载税码列表
const loadTaxrateList = async () => {
  try {
    const res = await listTaxrate({
      isShow: '0',
      pageNum: 1,
      pageSize: 1000
    });
    taxrateList.value = res.rows || [];
    if (res.rows && res.rows.length > 0) {
      salesForm.rateId = res.rows[0].id;
    }
  } catch (error) {}
};

// 初始化
onMounted(async () => {
  // 加载下拉框数据
  await loadSettlementMethodList();
  await loadCreditLevelList();
  await loadComStaffList();
  await loadComDeptList();
  await loadCurrencyList();
  await loadTaxrateList();

  // 优先使用props传递的customerId，否则从路由获取
  const id = props.customerId || route.query.id;
  if (id) {
    custId.value = id as string;
    await loadCustomerData(id as any);
  }
});

// 加载结算方式列表
const loadSettlementMethodList = async () => {
  try {
    const query: any = { isShow: '0' };
    const res = await listSettlementMethod(query);
    settlementMethodList.value = res.rows || [];
  } catch (error) {
    console.error('加载结算方式列表失败:', error);
  }
};

// 加载信用等级列表
const loadCreditLevelList = async () => {
  try {
    const query: any = { dataSource: 'A10' };
    const res = await listCreditLevel(query);
    creditLevelList.value = res.rows || [];
  } catch (error) {
    console.error('加载信用等级列表失败:', error);
  }
};

// 加载员工列表
const loadComStaffList = async () => {
  try {
    const query: any = {};
    const res = await listErpStaff(query);
    comStaffList.value = res.rows || [];
  } catch (error) {
    console.error('加载员工列表失败:', error);
  }
};

// 加载部门列表
const loadComDeptList = async () => {
  try {
    const res = await listErpDept();
    // 处理可能的不同返回结构
    comDeptList.value = res.rows || res.data || [];
  } catch (error) {
    console.error('加载部门列表失败:', error);
  }
};

// 加载客户数据
const loadCustomerData = async (id: any) => {
  try {
    const res = await getCustomerInfo(id);
    const data = res.data;

    // 填充销售信息
    if (data.customerSalesInfoVo) {
      Object.assign(salesForm, data.customerSalesInfoVo);

      // 编辑时如果为空，使用默认值
      if (!salesForm.customerSource) salesForm.customerSource = '1';
      if (!salesForm.sellChannel) salesForm.sellChannel = '1';
      if (!salesForm.unitPrice) salesForm.unitPrice = 'True';
      if (!salesForm.creditLimit) salesForm.creditLimit = '1';
      if (!salesForm.creditTimeLimit) salesForm.creditTimeLimit = '1';

      // 如果有部门ID，且部门不在列表中，从API获取
      if (salesForm.belongingDepartmentId) {
        const deptExists = comDeptList.value.find((d) => String(d.deptId) === String(salesForm.belongingDepartmentId));
        if (!deptExists) {
          try {
            const deptRes = await getErpDept(salesForm.belongingDepartmentId);
            if (deptRes.data) {
              comDeptList.value.push(deptRes.data);
            }
          } catch (error) {
            console.error('获取部门信息失败:', error);
          }
        }
      }
    }
  } catch (error) {
    console.error('加载客户数据失败:', error);
    ElMessage.error('加载客户数据失败');
  }
};

// 监听props变化
watch(
  () => props.customerId,
  (newId) => {
    if (newId) {
      custId.value = newId;
      loadCustomerData(newId);
    }
  }
);

// 监听部门ID变化，自动加载部门名称
watch(
  () => salesForm.belongingDepartmentId,
  async (newDeptId) => {
    if (!newDeptId) {
      deptName.value = '';
      return;
    }

    // 先从列表中查找
    const dept = comDeptList.value.find((d) => String(d.deptId) === String(newDeptId));
    if (dept) {
      deptName.value = dept.deptName;
      return;
    }

    // 如果列表中没有，从API获取
    try {
      const res = await getErpDept(newDeptId);
      if (res.data) {
        deptName.value = res.data.deptName;
        comDeptList.value.push(res.data as any);
      }
    } catch (error) {
      console.error('获取部门信息失败:', error);
      deptName.value = String(newDeptId);
    }
  },
  { immediate: true }
);

// 处理业务人员选择变化
const handleSalesPersonChange = async (staffId: any) => {
  // 根据选中的业务人员ID，找到对应的部门ID
  const selectedStaff = comStaffList.value.find((staff) => staff.staffId === staffId);
  if (selectedStaff && selectedStaff.deptId) {
    // 确保 deptId 的类型一致
    salesForm.belongingDepartmentId = String(selectedStaff.deptId);

    // 如果部门不在列表中，从API获取
    const deptExists = comDeptList.value.find((d) => String(d.deptId) === String(selectedStaff.deptId));
    if (!deptExists) {
      try {
        const res = await getErpDept(selectedStaff.deptId);
        if (res.data) {
          comDeptList.value.push(res.data as any);
        }
      } catch (error) {
        console.error('获取部门信息失败:', error);
      }
    }
  }
};

// 保存按钮
const handleSave = async () => {
  try {
    await salesFormRef.value.validate();
    submitLoading.value = true;

    // 准备提交数据，包含销售信息
    const submitData: CustomerInfoForm = {
      id: custId.value,
      customerSalesInfoBo: { ...salesForm }
    };

    await updateCustomerInfo(submitData);

    ElMessage.success('保存成功');

    // 重新加载数据
    await loadCustomerData(custId.value);
  } catch (error) {
    const isValidationError = error && typeof error === 'object' && 'fields' in error;

    if (isValidationError) {
      console.warn('表单验证未通过', error);
      return;
    }

    ElMessage.error('保存失败，请稍后重试或联系管理员');
  } finally {
    submitLoading.value = false;
  }
};
</script>
