<template>
  <div class="company-add-container">
    <!-- 页面标题和按钮 -->
    <div class="flex justify-between items-center mb-4">
      <div class="flex items-center gap-2">
        <el-button icon="ArrowLeft" @click="goBack">返回</el-button>
        <span class="text-lg font-medium">{{ form.id ? '编辑公司' : '新增公司' }}</span>
      </div>
    </div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">公司基本信息</span>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </template>

      <el-form ref="companyFormRef" :model="form" :rules="rules" label-width="150px">
        <!-- 第一行：企业名称（全宽） -->
        <div class="form-row three-columns">
          <el-form-item label="企业名称：" prop="companyName">
            <el-input v-model="form.companyName" placeholder="请输入企业名称" />
          </el-form-item>
        </div>

        <!-- 第二行：一行三列 -->
        <div class="form-row three-columns">
          <el-form-item label="开户银行：" prop="accBnId">
            <el-select v-model="form.accBnId" placeholder="请选择开户银行">
              <el-option v-for="bank in bankList" :key="bank.id" :label="bank.bnName" :value="bank.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="开户银行帐号：" prop="accBnNo">
            <el-input v-model="form.accBnNo" placeholder="请输入开户银行帐号" />
          </el-form-item>
          <el-form-item label="营业期限(开始)：" prop="begDate">
            <el-date-picker v-model="form.begDate" type="date" placeholder="请选择日期" :disabledDate="disabledDate" />
          </el-form-item>
        </div>

        <!-- 第三行：一行三列 -->
        <div class="form-row three-columns">
          <el-form-item label="经营范围：" prop="busScp">
            <el-input v-model="form.busScp" placeholder="请输入经营范围" />
          </el-form-item>
          <el-form-item label="注册资本：" prop="capAmt">
            <el-input v-model="form.capAmt" placeholder="请输入注册资本" />
          </el-form-item>
          <el-form-item label="法定代表人：" prop="lelPer">
            <el-input v-model="form.lelPer" placeholder="请输入法定代表人" />
          </el-form-item>
        </div>

        <!-- 第四行：一行三列 -->
        <div class="form-row three-columns">
          <el-form-item label="E-Mail：" prop="email">
            <el-input v-model="form.email" placeholder="请输入E-Mail" />
          </el-form-item>
          <el-form-item label="营业期限(结束)：" prop="endDate">
            <el-date-picker v-model="form.endDate" type="date" placeholder="请选择日期" :disabledDate="disabledDate" />
          </el-form-item>
          <el-form-item label="成立日期：" prop="foundDate">
            <el-date-picker v-model="form.foundDate" type="date" placeholder="请选择日期" />
          </el-form-item>
        </div>

        <!-- 第五行：一行三列 -->
        <div class="form-row three-columns">
          <el-form-item label="内部交易客户：" prop="inCustId">
            <el-input v-model="form.inCustId" placeholder="请输入内部交易客户" />
          </el-form-item>
          <el-form-item label="内部交易供应商：" prop="inSupId">
            <el-input v-model="form.inSupId" placeholder="请输入内部交易供应商" />
          </el-form-item>
          <el-form-item label="法人代表：" prop="corporation">
            <el-input v-model="form.corporation" placeholder="请输入法人代表" />
          </el-form-item>
        </div>

        <!-- 第六行：一行三列 -->
        <div class="form-row three-columns">
          <el-form-item label="办公电话：" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入办公电话" />
          </el-form-item>
          <el-form-item label="负责人：" prop="principal">
            <el-input v-model="form.principal" placeholder="请输入负责人" />
          </el-form-item>
          <el-form-item label="登记日期：" prop="regDate">
            <el-date-picker v-model="form.regDate" type="date" placeholder="请选择" />
          </el-form-item>
        </div>

        <!-- 第七行：一行三列 -->
        <div class="form-row three-columns">
          <el-form-item label="登记机关：" prop="regOrg">
            <el-input v-model="form.regOrg" placeholder="请输入登记机关" />
          </el-form-item>
          <el-form-item label="统一社会信用代码：" prop="taxNo">
            <el-input v-model="form.taxNo" placeholder="请输入统一社会信用代码" />
          </el-form-item>
          <el-form-item label="是否启用：" prop="isShow">
            <el-radio-group v-model="form.isShow">
              <el-radio v-for="dict in sys_platform_yes_no" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <!-- 最后一行：一行两列 -->
        <div class="form-row three-columns">
          <el-form-item label="地址信息：" prop="address">
            <el-input v-model="form.address" type="textarea" :rows="3" placeholder="请输入地址" />
          </el-form-item>
          <el-form-item label="备注：" prop="remark">
            <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
          </el-form-item>
        </div>
      </el-form>
    </el-card>
  </div>
</template>
<script setup name="Company" lang="ts">
import { addCompany, updateCompany, getCompany } from '@/api/company/company';
import { CompanyVO, CompanyQuery, CompanyForm } from '@/api/company/company/types';
import { listBank } from '@/api/company/bank';
import { BankVO } from '@/api/company/bank/types';
const router = useRouter();
const route = useRoute();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_platform_yes_no } = toRefs<any>(proxy?.useDict('sys_platform_yes_no'));

const companyList = ref<CompanyVO[]>([]);
const buttonLoading = ref(false);
const bankList = ref<BankVO[]>([]);

const companyFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: CompanyForm = {
  id: undefined,
  accBnId: undefined,
  accBnNo: undefined,
  address: undefined,
  begDate: undefined,
  busScp: undefined,
  capAmt: undefined,
  companyFullName: undefined,
  corporation: undefined,
  email: undefined,
  endDate: undefined,
  foundDate: undefined,
  inCustId: undefined,
  inSupId: undefined,
  lelPer: undefined,
  phone: undefined,
  principal: undefined,
  regAddr: undefined,
  regDate: undefined,
  regOrg: undefined,
  taxNo: undefined,
  companyCode: undefined,
  companyName: undefined,
  isShow: '0',
  dataSource: undefined,
  status: undefined,
  remark: undefined
};
const data = reactive<PageData<CompanyForm, CompanyQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    accBnId: undefined,
    accBnNo: undefined,
    address: undefined,
    begDate: undefined,
    busScp: undefined,
    capAmt: undefined,
    companyFullName: undefined,
    corporation: undefined,
    email: undefined,
    endDate: undefined,
    foundDate: undefined,
    inCustId: undefined,
    inSupId: undefined,
    lelPer: undefined,
    phone: undefined,
    principal: undefined,
    regAddr: undefined,
    regDate: undefined,
    regOrg: undefined,
    taxNo: undefined,
    companyCode: undefined,
    companyName: undefined,
    isShow: undefined,
    dataSource: undefined,
    status: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {
    begDate: [{ required: true, message: '经营开始日期不能为空', trigger: 'blur' }],
    endDate: [{ required: true, message: '经营结束日期不能为空', trigger: 'blur' }],
    foundDate: [{ required: true, message: '成立日期不能为空', trigger: 'blur' }],
    regDate: [{ required: true, message: '注册日期不能为空', trigger: 'blur' }],
    companyName: [{ required: true, message: '公司名称不能为空', trigger: 'blur' }],
    isShow: [{ required: true, message: '是否显示不能为空', trigger: 'change' }]
  }
});

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

// 返回上一页
const goBack = () => {
  router.back();
};

// 获取银行列表
const getBankList = async () => {
  try {
    const res = await listBank({ pageNum: 1, pageSize: 9999, isShow: '0' });
    bankList.value = res.rows || [];
  } catch (error) {
    console.error('获取银行列表失败', error);
  }
};

// 禁用过去的日期
const disabledDate = (time: Date) => {
  return time.getTime() < new Date().setHours(0, 0, 0, 0);
};

// 获取公司详情
const getCompanyDetail = async (id: string | number) => {
  try {
    const res = await getCompany(id);
    console.log(res);

    Object.assign(form.value, res.data);
  } catch (error) {
    console.error('获取公司详情失败', error);
  }
};

// 提交表单
const submitForm = async () => {
  if (!companyFormRef.value) return;

  await companyFormRef.value.validate(async (valid) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        if (form.value.id) {
          await updateCompany(form.value);
          proxy?.$modal.msgSuccess('修改成功');
        } else {
          await addCompany(form.value);
          proxy?.$modal.msgSuccess('新增成功');
        }
        router.back();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

// 页面挂载
onMounted(() => {
  getBankList();
  const id = route.query.id;
  if (id) {
    getCompanyDetail(id);
  }
});
</script>

<style scoped lang="scss">
.company-add-container {
  padding: 20px;

  .header-wrapper {
    display: flex;
    align-items: center;
    gap: 24px;
    margin-bottom: 20px;

    .el-button {
      font-size: 16px;
    }

    .title-text {
      font-size: 18px;
      font-weight: 600;
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 16px;
      font-weight: 600;
    }
  }

  .form-row {
    display: grid;
    gap: 20px;
    margin-bottom: 24px;

    &.three-columns {
      grid-template-columns: repeat(3, 1fr);
    }

    &.two-columns {
      grid-template-columns: repeat(2, 1fr);
    }

    .full-width {
      grid-column: 1 / -1;
    }

    .two-col {
      width: 100%;
    }

    :deep(.el-form-item) {
      margin-bottom: 0;
    }

    :deep(.el-form-item__label) {
      width: auto;
    }

    :deep(.el-input),
    :deep(.el-select),
    :deep(.el-date-picker) {
      width: 100%;
    }
  }
}
</style>
