<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
              <el-form-item label="企业客户号" prop="customerId" label-width="120px">
                <el-input v-model="queryParams.customerId" placeholder="请输入企业客户号" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="企业名称" prop="companyName" label-width="120px">
                <el-input v-model="queryParams.companyName" placeholder="请输入企业名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="统一社会信用代码" prop="businessLicenseCode" label-width="120px">
                <el-input v-model="queryParams.businessLicenseCode" placeholder="请输入统一社会信用代码" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="客户来源" prop="system" label-width="120px">
                <el-select v-model="queryParams.system" placeholder="客户来源" clearable>
                  <el-option
                    v-for="dict in sys_from_system.filter((item) => item.value !== 'CMS' && item.value !== 'Shared')"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="单位性质" prop="companyType" label-width="120px">
                <el-select v-model="queryParams.companyType" placeholder="单位性质" style="width: 240px" clearable>
                  <el-option v-for="dict in unit_nature" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="创建日期" prop="dateRange" label-width="120px">
                <el-date-picker
                  v-model="dateRange"
                  clearable
                  type="daterange"
                  range-separator="至"
                  start-placeholder="创建起期"
                  end-placeholder="创建止期"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                  style="width: 240px"
                />
              </el-form-item>
            <el-row>
              <el-form-item>
                <el-button type="primary" icon="Search" style="margin-left: 50px" @click="handleQuery">查询</el-button>
                <el-button icon="Refresh" style="margin-left: 50px" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table v-loading="loading" :data="corpList">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column v-if="true" label="企业客户号" align="center" prop="customerId" width="200" />
        <el-table-column label="企业名称" align="center" prop="companyName" width="200" />
        <el-table-column label="统一社会信用代码" align="center" prop="businessLicenseCode" width="200" />
        <el-table-column label="证件有效期" align="center" prop="businessLicenseExpiry" width="200">
          <template #default="scope">
            <span>{{ parseTime(scope.row.businessLicenseExpiry, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="员工总数" align="center" prop="employeeCount" />
        <el-table-column label="单位性质" align="center" prop="companyType" width="200">
          <template #default="scope">
            <dict-tag :options="unit_nature" :value="scope.row.companyType" />
          </template>
        </el-table-column>
        <el-table-column label="来源" align="center" prop="system">
          <template #default="scope">
            <dict-tag :options="sys_from_system" :value="scope.row.system" />
          </template>
        </el-table-column>
        <el-table-column label="法人代表" align="center" prop="representativeName" />
        <el-table-column label="创建日期" align="center" prop="createTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="110">
          <template #default="scope">
            <el-tooltip content="客户信息查询" placement="top">
              <el-button v-hasPermi="['customer:corp:view']" link type="primary" icon="View" @click="handleView(scope.row)">查看详情</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
      <el-button v-hasPermi="['customer:corp:export']" type="warning" plain icon="Download" @click="handleExport"> 下载 </el-button>
    </el-card>
    <!-- 添加或修改企业客户基础信息对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="1250px" append-to-body>
      <el-form ref="corpFormRef" :model="form" label-width="80px">
        <el-divider>客户基本信息</el-divider>
        <el-row :gutter="0">
          <el-form-item label="企业名称" prop="companyName" label-width="100px">
            <el-input v-model="form.companyName" placeholder="企业名称" style="width: 230px" disabled />
          </el-form-item>
          <el-form-item label="统一社会信用代码" prop="businessLicenseCode" label-width="150px">
            <el-input v-model="form.businessLicenseCode" placeholder="统一社会信用代码" style="width: 230px" disabled />
          </el-form-item>
          <el-form-item label="证件有效期" prop="businessLicenseExpiry" style="flex: 1" label-width="150px">
            <el-date-picker
              v-model="form.businessLicenseExpiry"
              clearable
              type="date"
              value-format="YYYY-MM-DD"
              style="width: 230px"
              disabled
            ></el-date-picker>
          </el-form-item>
        </el-row>
        <el-row :gutter="0">
          <el-form-item label="员工总数" prop="employeeCount" label-width="100px">
            <el-input v-model="form.employeeCount" placeholder="员工总数" style="width: 230px" disabled />
          </el-form-item>
          <el-form-item label="单位性质" prop="companyType" label-width="150px">
            <el-select v-model="form.companyType" placeholder="单位性质" style="width: 230px" disabled>
              <el-option v-for="dict in unit_nature" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="社保登记号" prop="socialSecurityNo" label-width="150px">
            <el-input v-model="form.socialSecurityNo" placeholder="社保登记号" style="width: 230px" disabled />
          </el-form-item>
        </el-row>

        <el-form-item label="经营范围" prop="businessScope" label-width="100px">
          <el-input v-model="form.businessScope" type="textarea" placeholder="内容" style="width: 1000px" disabled />
        </el-form-item>

        <el-row :gutter="0">
          <el-form-item label="行业分类" prop="industryCategory" label-width="100px">
            <el-select v-model="form.industryCategory" placeholder="行业分类" style="width: 230px" disabled>
              <el-option v-for="dict in industry_category" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="传真" prop="fax" label-width="150px">
            <el-input v-model="form.fax" placeholder="传真" style="width: 230px" disabled />
          </el-form-item>
          <el-form-item label="联系电话" prop="phoneNumber" label-width="150px">
            <el-input v-model="form.phoneNumber" placeholder="联系电话" style="width: 230px" disabled />
          </el-form-item>
        </el-row>
        <el-row :gutter="0">
          <el-form-item label="机构类别" prop="organizationType" label-width="100px">
            <el-input v-model="form.organizationType" style="width: 230px" disabled />
          </el-form-item>
          <el-form-item label="控制人税收居民类型" prop="controllerTaxResidency" label-width="150px">
            <el-input v-model="form.controllerTaxResidency" style="width: 230px" disabled />
          </el-form-item>
          <el-form-item label="机构税收居民类型" prop="organizationTaxResidency" label-width="150px">
            <el-input v-model="form.organizationTaxResidency" style="width: 230px" disabled />
          </el-form-item>
        </el-row>
      </el-form>
      <el-form ref="LegalFormRef" :model="formLegal" label-width="80px">
        <el-row :gutter="0">
          <el-form-item label="法人代表" prop="representativeName" label-width="100px">
            <el-input v-model="formLegal.representativeName" placeholder="法人代表" style="width: 230px" disabled />
          </el-form-item>

          <el-form-item label="法人证件类型" prop="idType" label-width="150px">
            <el-select v-model="formLegal.idType" placeholder="法人证件类型" style="width: 230px" disabled>
              <el-option v-for="dict in sys_id_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="法人证件号码" prop="idNumber" label-width="150px">
            <el-input v-model="formLegal.idNumber" style="width: 230px" disabled />
          </el-form-item>
        </el-row>
        <el-row :gutter="0">
          <el-form-item label="证件有效期起期" prop="idValidFrom" label-width="100px">
            <el-date-picker
              v-model="formLegal.idValidFrom"
              clearable
              type="date"
              value-format="YYYY-MM-DD"
              style="width: 230px"
              disabled
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="证件有效期止期" prop="idValidTo" label-width="150px">
            <el-date-picker
              v-model="formLegal.idValidTo"
              clearable
              type="date"
              value-format="YYYY-MM-DD"
              style="width: 230px"
              disabled
            ></el-date-picker>
          </el-form-item>
        </el-row>
        <el-row :gutter="0">
          <el-form-item label="省" prop="province" label-width="100px">
            <el-select v-model="formLegal.province" placeholder="省" style="width: 230px" disabled>
              <el-option v-for="dict in sys_province" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="市" prop="city" label-width="150px">
            <el-select v-model="formLegal.city" placeholder="市" style="width: 230px" disabled>
              <el-option v-for="dict in sys_city" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="区县" prop="district" label-width="150px">
            <el-select v-model="formLegal.district" placeholder="市" style="width: 230px" disabled>
              <el-option v-for="dict in sys_district" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="详细地址" prop="address" label-width="100px">
            <el-input v-model="formLegal.address" style="width: 1000px" disabled />
          </el-form-item>
        </el-row>
      </el-form>
      <el-collapse v-model="activeNames">
        <el-divider>客户其他信息</el-divider>
        <el-collapse-item title="证件信息" name="1">
          <el-table v-loading="loading" :data="documentList">
            <el-table-column v-if="false" label="证件ID" align="center" prop="documentId" />
            <el-table-column label="证件类型" align="center" prop="documentType">
              <template #default="scope">
                <dict-tag :options="corp_id_type" :value="scope.row.documentType" />
              </template>
            </el-table-column>
            <el-table-column label="证件号码" align="center" prop="documentNumber" />
            <el-table-column label="证件有效期起期" align="center" prop="documentValidFrom">
              <template #default="scope">
                <span>{{ parseTime(scope.row.documentValidFrom, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="证件有效期止期" align="center" prop="documentValidTo">
              <template #default="scope">
                <span>{{ parseTime(scope.row.documentValidTo, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
        <el-collapse-item title="联系人信息" name="2">
          <el-table v-loading="loading" :data="contactList">
            <el-table-column label="联系人姓名" align="center" prop="contactName" />
            <el-table-column label="联系人固定电话" align="center" prop="phoneNumber" />
            <el-table-column label="联系人手机" align="center" prop="mobileNumber" />
            <el-table-column label="联系人Email" align="center" prop="email" />
            <el-table-column label="联系人部门" align="center" prop="department" />
            <el-table-column label="证件类型" align="center" prop="idType">
              <template #default="scope">
                <dict-tag :options="sys_id_type" :value="scope.row.idType" />
              </template>
            </el-table-column>
            <el-table-column label="证件号码" align="center" prop="idNumber" />
            <el-table-column label="证件有效期起期" align="center" prop="idValidFrom">
              <template #default="scope">
                <span>{{ parseTime(scope.row.idValidFrom, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="证件有效期止期" align="center" prop="idValidTo">
              <template #default="scope">
                <span>{{ parseTime(scope.row.idValidTo, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
        <el-collapse-item title="银行信息" name="3">
          <el-form ref="formBankRef" :model="formBank" label-width="80px">
            <el-row :gutter="0">
              <el-form-item label="开户银行" prop="bankName">
                <el-select v-model="formBank.bankName" placeholder="开户银行" style="width: 230px" disabled>
                  <el-option v-for="dict in sys_bank_code" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="银行账号" prop="bankAccount" label-width="150px">
                <el-input v-model="formBank.bankAccount" disabled />
              </el-form-item>
              <el-form-item label="开户行所在省市" prop="bankProvince" label-width="200px">
                <el-input v-model="formBank.bankProvince" disabled />
              </el-form-item>
            </el-row>
            <el-row :gutter="0">
              <el-form-item label="开户名" prop="accountHolder">
                <el-input v-model="formBank.accountHolder" style="width: 575px" disabled />
              </el-form-item>
            </el-row>
          </el-form>
        </el-collapse-item>
        <el-collapse-item title="其他信息" name="4">
          <el-form ref="additionalFormRef" :model="formAdditional" label-width="80px">
            <el-form-item label="特别说明" prop="additionalInfo">
              <el-input v-model="formAdditional.additionalInfo" type="textarea" disabled />
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="toggleAll">{{ buttonText }}</el-button>
          <el-button @click="cancel">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Corp" lang="ts">
import { listCorp, queryInfo } from '@/api/customer/corp';
import {
  CorpVO,
  CorpQuery,
  CorpForm,
  CorpCustomerDocumentVO,
  CorpCustomerContactVO,
  CorpLegalRepresentativeForm,
  CorpLegalRepresentativeQuery,
  CorpCustomerBankInfoForm,
  CorpCustomerBankInfoQuery,
  CorpCustomerAdditionalInfoForm,
  CorpCustomerAdditionalInfoQuery
} from '@/api/customer/corp/types';
import { parseTime } from '../../../utils/ruoyi';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_from_system, unit_nature, sys_id_type, sys_bank_code, corp_id_type, industry_category } = toRefs<any>(
  proxy?.useDict('sys_from_system', 'unit_nature', 'sys_id_type', 'sys_bank_code', 'corp_id_type', 'industry_category')
);
const { sys_province, sys_city, sys_district } = toRefs<any>(proxy?.useDict('sys_province', 'sys_city', 'sys_district'));

const corpList = ref<CorpVO[]>([]);
const documentList = ref<CorpCustomerDocumentVO[]>([]);
const contactList = ref<CorpCustomerContactVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const corpFormRef = ref<ElFormInstance>();
const LegalFormRef = ref<ElFormInstance>();
const formBankRef = ref<ElFormInstance>();
const additionalFormRef = ref<ElFormInstance>();
const c = ref<ElFormInstance>();
const activeNames = ref([]);
const items = ref(['1', '2', '3', '4']);
const buttonText = ref('查看全部');
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
//客户基本信息
const initFormData: CorpForm = {
  customerId: undefined,
  companyName: undefined,
  businessLicenseCode: undefined,
  businessLicenseExpiry: undefined,
  employeeCount: undefined,
  companyType: undefined,
  socialSecurityNo: undefined,
  businessScope: undefined,
  industryCategory: undefined,
  fax: undefined,
  phoneNumber: undefined,
  organizationType: undefined,
  system: undefined,
  controllerTaxResidency: undefined,
  organizationTaxResidency: undefined,
  province: undefined,
  city: undefined,
  county: undefined,
  postalAddress: undefined
};
const data = reactive<PageData<CorpForm, CorpQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerId: undefined,
    companyName: undefined,
    businessLicenseCode: undefined,
    businessLicenseExpiry: undefined,
    employeeCount: undefined,
    companyType: undefined,
    socialSecurityNo: undefined,
    businessScope: undefined,
    industryCategory: undefined,
    fax: undefined,
    phoneNumber: undefined,
    organizationType: undefined,
    system: undefined,
    controllerTaxResidency: undefined,
    organizationTaxResidency: undefined,
    params: {}
  },
  rules: {}
});

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

//法人信息
const initFormDataLegal: CorpLegalRepresentativeForm = {
  representativeId: null,
  customerId: null,
  representativeName: '',
  idType: '',
  idNumber: '',
  idValidFrom: null,
  idValidTo: null,
  province: '',
  city: '',
  district: '',
  address: ''
};
const formLegal = ref({ ...initFormDataLegal });

//其他信息
const initFormDataAdditional: CorpCustomerAdditionalInfoForm = {
  representativeId: null,
  customerId: null,
  representativeName: '',
  idType: '',
  idNumber: '',
  idValidFrom: null,
  idValidTo: null,
  province: '',
  city: '',
  district: '',
  address: ''
};
const formAdditional = ref({ ...initFormDataAdditional });

//银行信息
const initFormBank: CorpCustomerBankInfoForm = {
  bankInfoId: null,
  customerId: null,
  bankName: '',
  accountHolder: '',
  bankAccount: '',
  bankProvince: '',
  bankCity: '',
  paymentMethod: ''
};
const formBank = ref({ ...initFormBank });

/** 查询企业客户基础信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCorp(proxy?.addDateRange(queryParams.value, dateRange.value));
  corpList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  corpFormRef.value?.resetFields();
  LegalFormRef.value?.resetFields();
  formBankRef.value?.resetFields();
  additionalFormRef.value?.resetFields();
  activeNames.value = [];
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  dateRange.value = ['', ''];
  corpList.value = [];
  total.value = 0;
};

/** 修改按钮操作 */
const handleView = async (row?: CorpVO) => {
  reset();
  const _customerId = row?.customerId || ids.value[0];
  const res = await queryInfo(_customerId);
  Object.assign(form.value, res.data.corpCustomerInfo);
  Object.assign(formLegal.value, res.data.legalRepresentative);
  formLegal.value.province = form.value.province;
  formLegal.value.city = form.value.city;
  formLegal.value.district = form.value.county;
  formLegal.value.address = form.value.postalAddress;
  documentList.value = res.data.document;
  contactList.value = res.data.contact;
  Object.assign(formBank.value, res.data.bankInfo);
  Object.assign(formAdditional.value, res.data.additional);
  dialog.visible = true;
  // dialog.title = '修改企业客户基础信息';
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'customer/corp/export',
    {
      ...queryParams.value
    },
    `企业客户管理_${new Date().toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      fractionalSecondDigits: 3,
      hour12: false
    })}.xlsx`
  );
};

// onMounted(() => {
//   getList();
// });

const toggleAll = () => {
  if (activeNames.value.length === items.value.length) {
    activeNames.value = [];
    buttonText.value = '查看全部';
  } else {
    activeNames.value = items.value;
    buttonText.value = '折叠全部';
  }
};
// 监听弹窗显示/隐藏
watch(
  () => dialog.visible,
  (newVal) => {
    if (!newVal) {
      // 弹窗关闭时
      activeNames.value = []; // 折叠所有面板
      buttonText.value = '查看全部'; // 重置按钮文字
    }
  }
);
</script>

<style scoped>
.dialog-footer {
  text-align: left; /* 将按钮左对齐 */
  margin-bottom: 10px;
}
</style>
