<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <div style="text-align: left; font-weight: bold; font-size: 24px">合同{{ form.contractId ? ' - 修改' : ' - 新增' }}</div>
      </template>
      <el-form ref="contractInfoFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="有无合同" prop="contractFlag">
              <el-radio-group v-model="form.contractFlag">
                <el-radio v-for="dict in contract_flag" :key="dict.value" :value="dict.value">{{ dict.label }} </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractCode" v-if="form.contractFlag === '1'">
              <el-input v-model="form.contractCode" placeholder="请输入合同编号">
                <template #append>
                  <el-button type="primary" @click="generateContractCode" :disabled="isCodeGenerated">生成合同编号</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="form.contractName" placeholder="请输入合同名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同大类" prop="contractCategory">
              <el-select v-model="form.contractCategory" placeholder="请选择合同大类">
                <el-option v-for="dict in contract_category" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同类型" prop="contractType">
              <el-select v-model="form.contractType" placeholder="请选择合同类型">
                <el-option v-for="dict in contract_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务方向" prop="businessDirection">
              <el-select v-model="form.businessDirection" placeholder="请选择业务方向">
                <el-option v-for="dict in business_direction" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="contractDeptId">
              <el-input v-model="form.contractDeptId" placeholder="请输入部门" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同时间" prop="contractDate">
              <el-date-picker clearable v-model="form.contractDate" type="date" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择合同时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同总价" prop="totalPrice">
              <el-input v-model="form.totalPrice" placeholder="根据合同物料自动计算" disabled>
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款方式" prop="paymentMethod">
              <el-input v-model="form.paymentMethod" placeholder="请输入付款方式" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方公司" prop="aCustomerId">
              <el-input v-model="form.aCustomerId" placeholder="请输入甲方公司" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="乙方公司" prop="bCustomerId">
              <el-input v-model="form.bCustomerId" placeholder="请输入乙方公司" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方授权代表" prop="aRepresent">
              <el-input v-model="form.aRepresent" placeholder="请输入甲方授权代表" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="乙方授权代表" prop="bRepresent">
              <el-input v-model="form.bRepresent" placeholder="请输入乙方授权代表" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方签字日期" prop="aDate">
              <el-date-picker clearable v-model="form.aDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择甲方签字日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="乙方签字日期" prop="bDate">
              <el-date-picker clearable v-model="form.bDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择乙方签字日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同状态" prop="contractStatus">
              <el-radio-group v-model="form.contractStatus" disabled>
                <el-radio v-for="dict in contract_status" :key="dict.value" :value="dict.value">{{ dict.label }} </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="流程状态" prop="flowStatus">-->
          <!--              <el-input v-model="form.flowStatus" placeholder="请输入流程状态" />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="合同模板ID" prop="templateId">
              <el-input v-model="form.templateId" placeholder="请输入合同模板ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="附件ID" prop="ossId">
              <el-input v-model="form.ossId" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 合同物料管理区域 -->
    <el-card shadow="never" style="margin-top: 20px">
      <template #header>
        <div style="text-align: left; font-weight: bold; font-size: 18px">合同物料管理</div>
      </template>

      <!-- 合同物料表格 -->
      <div style="margin-bottom: 16px">
        <el-button type="primary" icon="Plus" @click="handleAddMaterial">新增物料</el-button>
      </div>

      <el-table :data="contractMaterialList" border v-loading="materialLoading">
        <el-table-column label="产品名称" align="center" prop="productName" min-width="120" />
        <el-table-column label="规格描述" align="center" prop="specificationDescription" min-width="120" />
        <el-table-column label="物料ID" align="center" prop="materialId" width="100" />
        <el-table-column label="销售物料ID" align="center" prop="relationMaterialId" width="120" />
        <el-table-column label="数量" align="center" prop="amount" width="100">
          <template #default="scope">
            {{ scope.row.amount ? Number(scope.row.amount).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="单位ID" align="center" prop="unitId" width="100" />
        <el-table-column label="未税单价" align="center" prop="beforePrice" width="120">
          <template #default="scope">
            {{ scope.row.beforePrice ? Number(scope.row.beforePrice).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="税率(%)" align="center" prop="taxRate" width="100">
          <template #default="scope">
            {{ scope.row.taxRate ? Number(scope.row.taxRate).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="含税单价" align="center" prop="includingPrice" width="120">
          <template #default="scope">
            {{ scope.row.includingPrice ? Number(scope.row.includingPrice).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="小计" align="center" prop="subtotal" width="120">
          <template #default="scope">
            {{ scope.row.subtotal ? Number(scope.row.subtotal).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" min-width="100" />
        <el-table-column label="操作" align="center" fixed="right" width="150">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleEditMaterial(scope.row)">编辑</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDeleteMaterial(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-card shadow="never" style="margin-top: 20px">
        <el-col :span="24">
          <el-form-item>
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
            <el-button @click="goBack">返 回</el-button>
          </el-form-item>
        </el-col>
      </el-card>
    </el-card>

    <!-- 合同物料编辑对话框 -->
    <el-dialog :title="materialDialog.title" v-model="materialDialog.visible" width="800px" append-to-body>
      <el-form ref="materialFormRef" :model="materialForm" :rules="materialRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="materialForm.productName" placeholder="计划内请点击右侧图标检索物料">
                <template #suffix>
                  <el-icon style="cursor: pointer" @click="openMaterialSelect">
                    <Search />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格描述" prop="specificationDescription">
              <el-input v-model="materialForm.specificationDescription" placeholder="请输入规格描述" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料ID" prop="materialId">
              <el-input v-model="materialForm.materialId" placeholder="请输入物料ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售物料ID" prop="relationMaterialId">
              <el-input v-model="materialForm.relationMaterialId" placeholder="请输入销售物料ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="amount">
              <el-input-number
                v-model="materialForm.amount"
                placeholder="请输入数量"
                style="width: 100%"
                @change="calculateSubtotal"
                :precision="2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料单位" prop="unitId">
              <el-select v-model="materialForm.unitId" placeholder="请选择物料单位">
                <el-option v-for="item in unitInfoList" :key="item.unitId" :label="item.unitName" :value="item.unitId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税率(%)" prop="taxRate">
              <el-input-number
                v-model="materialForm.taxRate"
                placeholder="请输入税率"
                style="width: 100%"
                @change="calculateBeforePrice"
                :precision="2"
                :min="0"
                :max="100"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="未税单价" prop="beforePrice">
              <el-input-number
                v-model="materialForm.beforePrice"
                placeholder="自动计算"
                style="width: 100%"
                :precision="2"
                :controls="false"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="含税单价" prop="includingPrice">
              <el-input-number
                v-model="materialForm.includingPrice"
                placeholder="请输入含税单价"
                style="width: 100%"
                :precision="2"
                @change="calculateBeforePrice"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="小计" prop="subtotal">
              <el-input-number
                v-model="materialForm.subtotal"
                placeholder="自动计算"
                style="width: 100%"
                readonly
                :precision="2"
                :controls="false"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="materialForm.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="materialButtonLoading" type="primary" @click="submitMaterialForm">确 定</el-button>
          <el-button @click="cancelMaterial">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 物料选择 -->
    <MaterialSelect ref="materialSelectRef" :multiple="false" @confirm-call-back="materialSelectCallBack"></MaterialSelect>
  </div>
</template>

<script setup name="ContractInfoEdit" lang="ts">
import { addContractInfo, getContractInfo, updateContractInfo } from '@/api/oa/erp/contractInfo';
import { ContractInfoForm } from '@/api/oa/erp/contractInfo/types';
import { getErpContractMaterialList } from '@/api/oa/erp/contractMaterial';
import { ContractMaterialVO, ContractMaterialForm } from '@/api/oa/erp/contractMaterial/types';
import { getBaseUnitInfoList } from '@/api/oa/base/unitInfo';
import { getRuleGenerateCode } from '@/api/system/codeRule';
import MaterialSelect from '@/components/MaterialSelect/index.vue';
import { ref } from 'vue';

const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { contract_category, business_direction, active_flag, contract_flag, contract_type, contract_status } = toRefs<any>(
  proxy?.useDict('contract_category', 'business_direction', 'active_flag', 'contract_flag', 'contract_type', 'contract_status')
);

const buttonLoading = ref(false);
const contractInfoFormRef = ref<ElFormInstance>();

// 合同编号生成状态
const isCodeGenerated = ref(false);

// 合同物料相关
const materialLoading = ref(false);
const materialButtonLoading = ref(false);
const materialFormRef = ref<ElFormInstance>();

// 合同物料列表计算属性
const contractMaterialList = computed(() => {
  return (form.value as any).contractMaterialList || [];
});

/** 查询单位信息下拉框结构 */
const unitInfoList = ref([]);
const getUnitInfoListSelect = async () => {
  let res = await getBaseUnitInfoList(null);
  unitInfoList.value = res.data;
};

// 合同物料对话框
const materialDialog = reactive({
  visible: false,
  title: ''
});

// 合同物料表单数据
const initMaterialFormData: ContractMaterialForm = {
  contractMaterialId: undefined,
  contractId: undefined,
  productName: undefined,
  specificationDescription: undefined,
  materialId: undefined,
  relationMaterialId: undefined,
  amount: undefined,
  unitId: undefined,
  beforePrice: undefined,
  taxRate: undefined,
  includingPrice: undefined,
  subtotal: undefined,
  remark: undefined,
  activeFlag: '1'
};

const materialForm = ref<ContractMaterialForm>({ ...initMaterialFormData });

// 合同物料表单验证规则
const materialRules = {
  productName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
  amount: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
  taxRate: [{ required: true, message: '税率不能为空', trigger: 'blur' }]
};

const initFormData: ContractInfoForm = {
  contractId: undefined,
  contractFlag: '1',
  contractCode: undefined,
  contractName: undefined,
  contractCategory: '1',
  contractType: undefined,
  businessDirection: undefined,
  contractDeptId: undefined,
  contractDate: undefined,
  totalPrice: undefined,
  aCustomerId: undefined,
  aRepresent: undefined,
  aDate: undefined,
  bCustomerId: undefined,
  bRepresent: undefined,
  bDate: undefined,
  contractStatus: undefined,
  flowStatus: undefined,
  templateId: undefined,
  ossId: undefined,
  paymentMethod: undefined,
  signatureAppendix: undefined,
  taxRate: undefined,
  remark: undefined,
  activeFlag: undefined,
  contractMaterialList: []
} as any;

const data = reactive<{ form: ContractInfoForm; rules: any }>({
  form: { ...initFormData },
  rules: {
    contractId: [{ required: true, message: '合同ID不能为空', trigger: 'blur' }]
  }
});

const { form, rules } = toRefs(data);

const goBack = () => {
  proxy?.$tab.closePage();
};

// 监听contractFlag变化
watch(() => form.value.contractFlag, (newVal, oldVal) => {
  if (newVal === '2') {
    // 当选择"无合同"时，清空合同编号并重置生成状态
    form.value.contractCode = undefined;
    isCodeGenerated.value = false;
  }
});


// 生成合同编号
const generateContractCode = async () => {
  if (isCodeGenerated.value) return; // 如果已经生成过，直接返回

  try {
    const params = { codeRuleCode: '1001' } as any;
    const res = await getRuleGenerateCode(params);
    form.value.contractCode = res.msg;
    isCodeGenerated.value = true; // 标记为已生成
    proxy?.$modal.msgSuccess('合同编号生成成功');
  } catch (error) {
    console.error('生成合同编号失败:', error);
    proxy?.$modal.msgError('生成合同编号失败');
  }
};

const materialSelectRef = ref<InstanceType<typeof MaterialSelect>>();

//打开物料选择
const openMaterialSelect = () => {
  materialSelectRef.value.open();
};

//确认选择申请人
const materialSelectCallBack = (data) => {
  const materialList = data;
  if (materialList.length > 0) {
    materialForm.value.materialId = materialList[0].materialId;
    materialForm.value.productName = materialList[0].materialName;
  }
};

const submitForm = () => {
  contractInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.contractId) {
        await updateContractInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addContractInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      goBack();
    }
  });
};

// 获取合同物料列表
const getContractMaterialList = async () => {
  if (!form.value.contractId) return;
  materialLoading.value = true;
  try {
    const res = await getErpContractMaterialList({
      contractId: form.value.contractId
    });
    // 将获取到的数据存储到form中
    (form.value as any).contractMaterialList = res.data || [];
  } catch (error) {
    console.error('获取合同物料列表失败:', error);
  } finally {
    materialLoading.value = false;
  }
};

// 新增物料（新增合同时也可添加，不依赖contractId）
const handleAddMaterial = () => {
  resetMaterialForm();
  materialForm.value.contractId = form.value.contractId;
  materialDialog.visible = true;
  materialDialog.title = '新增合同物料';
};

// 编辑物料
const handleEditMaterial = (row: ContractMaterialVO) => {
  resetMaterialForm();
  materialForm.value = { ...row };
  materialDialog.visible = true;
  materialDialog.title = '编辑合同物料';
};

// 删除物料
const handleDeleteMaterial = async (row: ContractMaterialVO) => {
  await proxy?.$modal.confirm('是否确认删除该合同物料？');
  try {
    // 确保contractMaterialList存在
    if (!(form.value as any).contractMaterialList) {
      (form.value as any).contractMaterialList = [];
    }

    // 从本地数据中删除
    const index = (form.value as any).contractMaterialList.findIndex((item: any) => item.contractMaterialId === row.contractMaterialId);
    if (index !== -1) {
      (form.value as any).contractMaterialList.splice(index, 1);
    }

    // 更新合同总价
    calculateTotalPrice();

    proxy?.$modal.msgSuccess('删除成功');
  } catch (error) {
    console.error('删除合同物料失败:', error);
  }
};

// 重置物料表单
const resetMaterialForm = () => {
  materialForm.value = { ...initMaterialFormData };
  materialFormRef.value?.resetFields();
};

// 取消物料编辑
const cancelMaterial = () => {
  resetMaterialForm();
  materialDialog.visible = false;
};

// 计算未税单价（由含税与税率推未税）
const calculateBeforePrice = () => {
  const tax = Number(materialForm.value.taxRate);
  const including = Number(materialForm.value.includingPrice);
  if (!isNaN(tax) && !isNaN(including)) {
    const divisor = 1 + tax / 100;
    if (divisor > 0) {
      materialForm.value.beforePrice = Number((including / divisor).toFixed(2));
    }
  }
  // 未税变更后联动小计
  calculateSubtotal();
};

// 计算小计（数量 × 含税单价）
const calculateSubtotal = () => {
  const amount = Number(materialForm.value.amount);
  const including = Number(materialForm.value.includingPrice);
  if (!isNaN(amount) && !isNaN(including)) {
    materialForm.value.subtotal = Number((amount * including).toFixed(2));
  }
  // 计算小计后更新合同总价
  calculateTotalPrice();
};

// 计算合同总价（所有物料小计相加）
const calculateTotalPrice = () => {
  const materialList = (form.value as any).contractMaterialList || [];
  const total = materialList.reduce((sum: number, material: any) => {
    const subtotal = Number(material.subtotal) || 0;
    return sum + subtotal;
  }, 0);
  form.value.totalPrice = Number(total.toFixed(2));
};

// 提交物料表单
const submitMaterialForm = () => {
  materialFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      materialButtonLoading.value = true;
      try {
        // 确保contractMaterialList存在
        if (!(form.value as any).contractMaterialList) {
          (form.value as any).contractMaterialList = [];
        }

        if (materialForm.value.contractMaterialId) {
          // 编辑模式：更新现有物料
          const index = (form.value as any).contractMaterialList.findIndex(
            (item: any) => item.contractMaterialId === materialForm.value.contractMaterialId
          );
          if (index !== -1) {
            (form.value as any).contractMaterialList[index] = { ...materialForm.value };
          }
        } else {
          // 新增模式：添加新物料
          const newMaterial = {
            ...materialForm.value,
            contractMaterialId: Date.now() // 临时ID
          };
          (form.value as any).contractMaterialList.push(newMaterial);
        }

        // 更新合同总价
        calculateTotalPrice();

        proxy?.$modal.msgSuccess('操作成功');
        materialDialog.visible = false;
      } catch (error) {
        console.error('保存合同物料失败:', error);
      } finally {
        materialButtonLoading.value = false;
      }
    }
  });
};

onMounted(async () => {
  const id = (route.query.id || route.params.id) as string | number;
  if (id) {
    proxy?.$modal.loading('正在加载数据，请稍后...');
    const res = await getContractInfo(id);
    Object.assign(form.value, res.data);
    proxy?.$modal.closeLoading();

    // 编辑模式：如果已有合同编号，禁用生成按钮
    if (form.value.contractCode) {
      isCodeGenerated.value = true;
    } else if (form.value.contractFlag === '1') {
      // 如果有合同但没有编号，允许生成
      isCodeGenerated.value = false;
    }

    // 加载合同物料列表
    await getContractMaterialList();
  } else {
    // 新增模式：如果已有合同编号，禁用生成按钮
    if (form.value.contractCode) {
      isCodeGenerated.value = true;
    } else if (form.value.contractFlag === '1') {
      // 如果有合同但没有编号，允许生成
      isCodeGenerated.value = false;
    }
  }
  await getUnitInfoListSelect();
});
</script>
