<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="customerMergeSplitInfoBo">
            <el-row>
              <el-form-item label="主客户号" prop="fromSystem" label-width="100px">
                <el-input
                  v-model="customerMergeSplitInfoBo.customerNo"
                  placeholder="请输入主客户号"
                  style="width: 230px"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="子客户号" prop="primaryCustomerId" label-width="100px">
                <el-input
                  v-model="customerMergeSplitInfoBo.subCustomerNo"
                  placeholder="请输入子客户号"
                  style="width: 230px"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="姓名" prop="fromCustomerId" label-width="100px">
                <el-input
                  v-model="customerMergeSplitInfoBo.name"
                  placeholder="请输入姓名"
                  style="width: 230px"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="证件类型" prop="fromOperate" label-width="100px">
                <el-select v-model="customerMergeSplitInfoBo.identificationType" placeholder="请选择证件类型" style="width: 230px" clearable>
                  <el-option
                    v-for="dict in sys_id_type.filter((item) => item.value !== 'd' && item.value !== 'f')"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="证件号码" prop="fromOperate" label-width="100px">
                <el-input
                  v-model="customerMergeSplitInfoBo.identificationNumber"
                  placeholder="请输入证件号码"
                  style="width: 230px"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="操作时间" prop="dateValue" label-width="100px">
                <el-date-picker
                  v-model="dateValue"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 230px"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="类型" prop="errorMessage" label-width="100px">
                <el-select v-model="customerMergeSplitInfoBo.type" placeholder="请选择类型" style="width: 230px" clearable>
                  <el-option v-for="dict in merger_split" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item>
                <el-button type="primary" icon="Search" style="margin-left: 40px" @click="handleQueryCustomerMergeSplitInfo">查询</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">
      <span>客户信息列表</span>
      <el-table v-loading="loading" :data="customerMergeSplitInfo">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column label="姓名" align="center" prop="name" show-overflow-tooltip />
        <el-table-column label="性别" align="center" prop="gender">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
          </template>
        </el-table-column>
        <el-table-column label="出生日期" align="center" prop="birthday" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作时间" align="center" prop="operatingTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.operatingTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" prop="operatingType">
          <template #default="scope">
            <dict-tag :options="merger_split" :value="scope.row.operatingType" />
          </template>
        </el-table-column>
        <el-table-column label="发起系统" align="center" prop="formSystem">
          <template #default="scope">
            <dict-tag :options="sys_from_system" :value="scope.row.formSystem" />
          </template>
        </el-table-column>
        <el-table-column label="操作人" align="center" prop="operator" show-overflow-tooltip />
        <el-table-column label="被合并客户号" align="center" prop="beforeMerger" width="150" show-overflow-tooltip />
        <el-table-column label="合并后客户号" align="center" prop="afterMerger" width="150" />
        <el-table-column label="拆分客户号" align="center" prop="beforeSplit" width="150" />
        <el-table-column label="拆分后客户号" align="center" prop="afterSplit" width="150" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              v-hasPermi="['customer:customerMergeSplit:show']"
              link
              type="primary"
              icon="Edit"
              @click="viewCustomerMergeSplitInfo(scope.row)"
              >详情</el-button
            >
            <el-button v-hasPermi="['customer:customerInfo:list']" link type="primary" icon="View" @click="handleViewCustomer(scope.row)"
              >查看客户</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        v-model:page="customerMergeSplitInfoBo.pageNum"
        v-model:limit="customerMergeSplitInfoBo.pageSize"
        :total="total"
        @pagination="handleQueryCustomerMergeSplitInfo"
      />
      <el-button v-hasPermi="['customer:customerMergeSplit:export']" type="warning" plain icon="Download" @click="handleExport">下载</el-button>
    </el-card>
    <!-- 详情页面 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="90%" append-to-body>
      <el-form ref="customerMergeRecordFormRef" :model="customerNoMergeSplitDetailsForm" label-width="80%">
        <el-row>
          <el-form-item label="发起时间" prop="operationDate" label-width="60px">
            <el-date-picker
              v-model="customerNoMergeSplitDetailsForm.operationDate"
              clearable
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择发起时间"
              disabled
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="发起系统" prop="fromSystem" label-width="100px" style="margin-left: 10px">
            <el-select v-model="customerNoMergeSplitDetailsForm.fromSystem" placeholder="发起系统" style="width: 200px" disabled>
              <el-option v-for="dict in sys_from_system" :key="dict.value" :label="dict.label" :value="dict.value" :disabled="true"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="业务类型" prop="fromSystem" label-width="100px" style="margin-left: 10px">
            <el-select v-model="customerNoMergeSplitDetailsForm.type" placeholder="业务类型" style="width: 200px" disabled>
              <el-option v-for="dict in merger_split" :key="dict.value" :label="dict.label" :value="dict.value" :disabled="true"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否存在异常" prop="fromSystem" label-width="120px" style="margin-left: 10px">
            <el-input v-model="customerNoMergeSplitDetailsForm.isError" placeholder="是否存在异常" disabled />
          </el-form-item>
        </el-row>
      </el-form>
      <el-card shadow="never">
        <el-table v-loading="loading" :data="customerNoMergeSplitDetailsTable">
          <el-table-column label="发起时间" align="center" prop="operationDate" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.operationDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="系统" align="center" prop="fromSystem">
            <template #default="scope">
              <dict-tag :options="sys_from_system" :value="scope.row.fromSystem" />
            </template>
          </el-table-column>
          <el-table-column label="被合并客户号" align="center" prop="beforeMerger" />
          <el-table-column label="合并后客户号" align="center" prop="afterMerger" />
          <el-table-column label="拆分客户号" align="center" prop="beforeSplit" />
          <el-table-column label="拆分后客户号" align="center" prop="afterSplit" />
          <el-table-column label="处理完成时间" align="center" prop="completionDate" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.completionDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否存在异常" align="center" prop="isError" />
        </el-table>
      </el-card>
      <el-card shadow="hover">
        <el-steps :active="active" finish-status="finish">
          <el-step v-for="(step, index) in steps" :key="index" :title="step.title" :description="step.description" :icon="step.icon">
            <template v-if="step.subSteps" #description>
              <div>
                {{ step.description }}
                <div v-for="subStep in step.subSteps">
                  <el-steps :active="subStep.subActive" finish-status="finish" class="mt-2">
                    <el-step
                      v-for="(step, subIndex) in subStep.Steps"
                      :key="subIndex"
                      :title="step.title"
                      :description="step.description"
                      :icon="step.icon"
                      :status="subStep.status"
                    ></el-step>
                  </el-steps>
                </div>
              </div>
            </template>
          </el-step>
        </el-steps>
      </el-card>
    </el-dialog>
  </div>
</template>

<script setup name="CustomerMergeRecord" lang="ts">
import {
  listCustomerMergeRecord,
  getCustomerMergeRecord,
  delCustomerMergeRecord,
  addCustomerMergeRecord,
  updateCustomerMergeRecord,
  queryCustomerMergeSplitInfo,
  queryCustomerMergeSplitDetailsInfo
} from '@/api/customer/customerMergeSplit';
import {
  CustomerMergeRecordVO,
  CustomerMergeRecordQuery,
  CustomerMergeRecordForm,
  CustomerMergeSplitInfoBo,
  CustomerMergeSplitInfo,
  CustomerNoMergeSplitDetails
} from '@/api/customer/customerMergeSplit/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const customerMergeRecordList = ref<CustomerMergeRecordVO[]>([]);
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 initFormData: CustomerMergeRecordForm = {
  mergeId: undefined,
  fromSystem: undefined,
  primaryCustomerId: undefined,
  fromCustomerId: undefined,
  fromOperate: undefined,
  operationDate: undefined,
  completionDate: undefined,
  mergeStatus: undefined,
  errorMessage: undefined
};
const data = reactive<PageData<CustomerMergeRecordForm, CustomerMergeRecordQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    fromSystem: undefined,
    primaryCustomerId: undefined,
    fromCustomerId: undefined,
    fromOperate: undefined,
    operationDate: undefined,
    completionDate: undefined,
    mergeStatus: undefined,
    errorMessage: undefined,
    params: {}
  },
  rules: {
    mergeId: [{ required: true, message: '合并记录ID不能为空', trigger: 'blur' }],
    fromSystem: [{ required: true, message: '发起系统不能为空', trigger: 'blur' }],
    primaryCustomerId: [{ required: true, message: '合并向的客户号不能为空', trigger: 'blur' }],
    fromCustomerId: [{ required: true, message: '被合并客户号不能为空', trigger: 'blur' }],
    fromOperate: [{ required: true, message: '发起人不能为空', trigger: 'blur' }],
    operationDate: [{ required: true, message: '发起时间不能为空', trigger: 'blur' }],
    completionDate: [{ required: true, message: '完成时间不能为空', trigger: 'blur' }],
    mergeStatus: [{ required: true, message: '合并状态不能为空', trigger: 'change' }],
    errorMessage: [{ required: true, message: '错误信息不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
//字典转换
const {
  sys_id_type,
  sys_user_sex,
  verification_status,
  shareholder_sign,
  vip_customer,
  sys_from_system,
  customer_status,
  cont_status,
  merger_split
} = toRefs<any>(
  proxy?.useDict(
    'sys_id_type',
    'sys_user_sex',
    'verification_status',
    'shareholder_sign',
    'vip_customer',
    'sys_from_system',
    'customer_status',
    'cont_status',
    'merger_split'
  )
);
//查询客户合并拆分记录条件表单
const customerMergeSplitInfoBo: CustomerMergeSplitInfoBo = ref({
  customerNo: undefined,
  subCustomerNo: undefined,
  name: undefined,
  identificationType: undefined,
  identificationNumber: undefined,
  beforeTime: undefined,
  afterTime: undefined,
  type: undefined,
  pageNum: 1,
  pageSize: 10
});
const queryFormRef = ref<ElFormInstance>();
//查询条件，建立时间的数据
const dateValue = ref<DatePickerValueType | null>(null);
//监听dateValue的值变化
watch(dateValue, (newValue) => {
  if (newValue) {
    customerMergeSplitInfoBo.value.beforeTime = newValue[0];
    customerMergeSplitInfoBo.value.afterTime = newValue[1];
  } else {
    customerMergeSplitInfoBo.value.beforeTime = null;
    customerMergeSplitInfoBo.value.afterTime = null;
  }
});

function checkAtLeastOneFilled() {
  if (
    (customerMergeSplitInfoBo.value.customerNo !== undefined && customerMergeSplitInfoBo.value.customerNo !== '') ||
    (customerMergeSplitInfoBo.value.subCustomerNo !== undefined && customerMergeSplitInfoBo.value.subCustomerNo != '') ||
    (customerMergeSplitInfoBo.value.name !== undefined && customerMergeSplitInfoBo.value.name != '') ||
    (customerMergeSplitInfoBo.value.identificationType !== undefined && customerMergeSplitInfoBo.value.identificationType != '') ||
    (customerMergeSplitInfoBo.value.identificationNumber !== undefined && customerMergeSplitInfoBo.value.identificationNumber != '') ||
    (customerMergeSplitInfoBo.value.beforeTime !== undefined && customerMergeSplitInfoBo.value.beforeTime != '') ||
    (customerMergeSplitInfoBo.value.afterTime !== undefined && customerMergeSplitInfoBo.value.afterTime != '') ||
    (customerMergeSplitInfoBo.value.type !== undefined && customerMergeSplitInfoBo.value.type != '')
  ) {
    return true;
  } else {
    return false;
  }
}

//客户合并拆分记录对象
const customerMergeSplitInfo = ref<CustomerMergeSplitInfo>();
//查询相识客户合并拆分轨迹列表
const handleQueryCustomerMergeSplitInfo = () => {
  if (!checkAtLeastOneFilled()) {
    proxy?.$modal.alert('请至少录入一项查询条件');
    return; // 直接返回，不执行查询
  }
  loading.value = true;
  queryCustomerMergeSplitInfo(customerMergeSplitInfoBo.value)
    .then((res) => {
      customerMergeSplitInfo.value = res.rows;
      total.value = res.total;
      loading.value = false;
    })
    .catch((err) => {
      oading.value = false;
    });
};
//详情弹窗dialog
const dialog = reactive<DialogOption>({
  visible: false,
  title: '相似客户合并轨迹明细'
});
//详情对象
const customerNoMergeSplitDetailsTable = ref<CustomerNoMergeSplitDetails>();
const customerMergeRecordFormRef = ref<ElFormInstance>();
const customerNoMergeSplitDetailsForm: CustomerNoMergeSplitDetails = ref({
  operationDate: undefined,
  fromSystem: undefined,
  type: undefined,
  isError: undefined,
  completionDate: undefined
});
//是否存在异常字典转换
const isErrorMap = {
  'true': '存在',
  'false': '不存在'
};
//详情请求方法
const viewCustomerMergeSplitInfo = (row) => {
  dialog.visible = true;
  loading.value = true;
  queryCustomerMergeSplitDetailsInfo(row)
    .then((res) => {
      res.data.forEach((item) => {
        customerNoMergeSplitDetailsForm.value.operationDate = item.operationDate;
        customerNoMergeSplitDetailsForm.value.fromSystem = item.fromSystem;
        customerNoMergeSplitDetailsForm.value.type = item.type;
        item.isError = isErrorMap[item.isError];
        customerNoMergeSplitDetailsForm.value.isError = item.isError;
        customerNoMergeSplitDetailsForm.value.completionDate = item.completionDate;
      });
      customerNoMergeSplitDetailsTable.value = res.data;
      stepsValue();
      loading.value = false;
    })
    .catch((err) => {});
};
//步骤条设置
const active = ref(1);
const steps = ref([
  { title: '客户合并/拆分发起', description: '', icon: 'Edit' },
  {
    title: '各系统处理流程',
    description: '',
    icon: 'Upload',
    subSteps: []
  },
  { title: '处理结果', description: '', icon: 'Picture' }
]);
//步骤条设置值
const stepsValue = () => {
  steps.value[0].description = customerNoMergeSplitDetailsForm.value.operationDate;
  steps.value[1].subSteps = [];
  customerNoMergeSplitDetailsTable.value.forEach((table) => {
    table.systemMergeSplitDetails.forEach((row) => {
      const found = sys_from_system.value.find((option) => option.value === row.fromSystem);
      console.log(row);
      if (found) {
        const systemSubStep = {
          subActive: 1,
          Steps: [
            {
              title: found.label + '接收',
              description: row.operationDate,
              icon: 'Edit'
            },
            {
              title: found.label + '处理',
              description: row.actionTimestamp,
              icon: 'Upload'
            },
            {
              title: found.label + '返回',
              description: row.completionDate,
              icon: 'Picture'
            }
          ],
          status: '' // 可以设置状态：success, error, processing等
        };
        steps.value[1].subSteps.push(systemSubStep);
      }
    });
  });
  steps.value[2].description = customerNoMergeSplitDetailsForm.value.completionDate;
};
//查看客户信息
const handleViewCustomer = (row) => {
  // proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/customer/cus-info/customerInfo`,
    query: {
      customerNo: row.customerNo
    }
  });
};
/** 查看费用类型 */
const handleCostType = (row: CertificateTypeDefVO) => {
  // proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/bfs/config/fi-certificate-type/costTypeDef`,
    query: {
      certificateId: row.certificateId,
      certificateName: row.certificateName
    }
  });
};
/** 查询客户合并记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCustomerMergeRecord(queryParams.value);
  customerMergeRecordList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

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

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

/** 重置按钮操作 */
const resetQuery = () => {
  //重置表单字段
  customerMergeSplitInfoBo.value = {
    customerNo: undefined,
    subCustomerNo: undefined,
    name: undefined,
    identificationType: undefined,
    identificationNumber: undefined,
    beforeTime: undefined,
    afterTime: undefined,
    type: undefined,
    pageNum: 1,
    pageSize: 10
  };

  //重置日期选择器
  dateValue.value = null;

  //重置数据
  customerMergeSplitInfo.value = '';

  total.value = 0;
};

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加客户合并记录';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: CustomerMergeRecordVO) => {
  reset();
  const _mergeId = row?.mergeId || ids.value[0];
  const res = await getCustomerMergeRecord(_mergeId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改客户合并记录';
};

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

/** 删除按钮操作 */
const handleDelete = async (row?: CustomerMergeRecordVO) => {
  const _mergeIds = row?.mergeId || ids.value;
  await proxy?.$modal.confirm('是否确认删除客户合并记录编号为"' + _mergeIds + '"的数据项？').finally(() => (loading.value = false));
  await delCustomerMergeRecord(_mergeIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

//下载
const handleExport = () => {
  proxy?.download(
    'customer/customerMergeSplit/exportCustomerInfo',
    {
      ...customerMergeSplitInfoBo.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(() => {
//   handleQueryCustomerMergeSplitInfo();
// });
</script>
