<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="22"><span>集团客户信息列表</span> </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['customer:groupCustomer:add']">新增</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="groupCustomerList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="企业ID" align="center" prop="topCustomerNo" />
        <el-table-column label="企业名称" align="center" prop="topCustomerName" />
        <el-table-column label="行业" align="center" prop="industryCategory" />
        <el-table-column label="到账" align="center" prop="accountPeriod" />
        <el-table-column label="客户等级" align="center" prop="customerLevel">
          <template #default="scope">
            <dict-tag :options="customer_level" :value="scope.row.customerLevel" />
          </template>
        </el-table-column>
        <el-table-column label="信用额" align="center" prop="creditAmount">
          <template #default="scope">
            <span>{{ scope.row.creditAmount || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="剩余额度" align="center" prop="remainingQuota">
          <template #default="scope">
            <span>{{ scope.row.remainingQuota || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="应收账款" align="center" prop="accountsReceivable">
          <template #default="scope">
            <span>{{ scope.row.accountsReceivable || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleDetail(scope.row)" v-hasPermi="['customer:groupCustomer:edit']">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改集团客户关系对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="900px" append-to-body>
      <el-form ref="groupCustomerFormRef" :model="form" :rules="rules" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="集团名称" prop="groupCustomerId">
              <el-select v-model="form.groupCustomerId" placeholder="请选择" clearable filterable style="width: 100%">
                <el-option v-for="item in customerList" :key="item.id" :label="item.customerName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="3">
            <div style="line-height: 32px; text-align: right; padding-right: 12px; color: #606266">
              <span>关联客户</span>
            </div>
          </el-col>
          <el-col :span="21">
            <div style="background-color: #f5f7fa; padding: 20px 16px; border-radius: 4px">
              <el-row :gutter="20">
                <el-col :span="8">
                  <div style="margin-bottom: 8px; color: #606266; font-size: 14px">上级客户</div>
                  <el-select v-model="form.topCustomerId" placeholder="请选择" clearable filterable style="width: 100%">
                    <el-option v-for="item in customerList" :key="item.id" :label="item.customerName" :value="item.id" />
                  </el-select>
                </el-col>
                <el-col :span="8">
                  <div style="margin-bottom: 8px; color: #606266; font-size: 14px">客户名称</div>
                  <el-select v-model="form.customerId" placeholder="请选择" clearable filterable style="width: 100%">
                    <el-option v-for="item in customerList" :key="item.id" :label="item.customerName" :value="item.id" />
                  </el-select>
                </el-col>
                <el-col :span="8">
                  <div style="margin-bottom: 8px; color: #606266; font-size: 14px">客户等级</div>
                  <el-select v-model="form.customerLevel" placeholder="请选择" clearable style="width: 100%">
                    <el-option v-for="dict in customer_level" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 认</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GroupCustomer" lang="ts">
import {
  listGroupCustomer,
  getGroupCustomer,
  delGroupCustomer,
  addGroupCustomer,
  updateGroupCustomer
} from '@/api/customer/customerFile/groupCustomer';
import { listCustomerInfo, getCustomerInfo } from '@/api/customer/customerFile/customerInfo';
import { CustomerInfoVO, CustomerInfoQuery, CustomerInfoForm } from '@/api/customer/customerFile/customerInfo/types';
import { GroupCustomerVO, GroupCustomerQuery, GroupCustomerForm } from '@/api/customer/customerFile/groupCustomer/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { customer_level } = toRefs<any>(proxy?.useDict('customer_level'));
const groupCustomerList = ref<GroupCustomerVO[]>([]);
const customerList = ref<CustomerInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
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 groupCustomerFormRef = ref<ElFormInstance>();

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

const initFormData: GroupCustomerForm = {
  id: undefined,
  groupCustomerId: undefined,
  customerId: undefined,
  customerLevel: undefined,
  topCustomerId: undefined,
  remark: undefined
};
const data = reactive<PageData<GroupCustomerForm, GroupCustomerQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    groupCustomerId: undefined,
    customerId: undefined,
    customerLevel: undefined,
    topCustomerId: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {}
});

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

/** 查询集团客户关系列表 */
const getList = async () => {
  loading.value = true;
  const res = await listGroupCustomer(queryParams.value);
  groupCustomerList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  groupCustomerFormRef.value?.resetFields();
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: GroupCustomerVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 加载客户列表 */
const loadCustomerList = async () => {
  const res = await listCustomerInfo({ pageNum: 1, pageSize: 10000 });
  customerList.value = res.rows;
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  await loadCustomerList();
  dialog.visible = true;
  dialog.title = '新增集团客户';
};

/** 修改按钮操作 */
const handleDetail = async (row?: GroupCustomerVO) => {
  reset();
  await loadCustomerList();
  const _id = row?.id || ids.value[0];
  const res = await getGroupCustomer(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '查看集团客户';
};

/** 提交按钮 */
const submitForm = () => {
  groupCustomerFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateGroupCustomer(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addGroupCustomer(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: GroupCustomerVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除集团客户关系编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delGroupCustomer(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'customer/groupCustomer/export',
    {
      ...queryParams.value
    },
    `groupCustomer_${new Date().getTime()}.xlsx`
  );
};

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