<template>
  <div class="table-box">
    <div class="table-inner">
      <ProTable :config="config" ref="caseLRef" :paramCallback="paramCallback" :api="getRepairRecord">
        <template #left_buttons>
          <div class="flex items-center justify-center h-8">
            <el-button
              v-permission="'repair_admin_export'"
              type="primary"
              @click="admindownload"
              class="mb-2 mr-2"
              >导出</el-button
            >
            <el-button
              v-permission="'repair_te_export'"
              type="primary"
              class="mb-2 mr-2"
              @click="download"
              >导出</el-button
            >
            <el-upload
              class="avatar-uploader"
              ref="uploadRef"
              :headers="{timeout:180000}"
              :action="upload.url"
              :disabled="upload.isUploading"
              accept=".xls, .xlsx"
              :limit="1"
              :on-success="handleFileSuccess"
              :on-remove="handleRemove"
              :auto-upload="true"
              :on-progress="uploadVideoProcess"
            >
              <el-button type="primary" plain :icon="Upload">批量修复上传</el-button>
            </el-upload>
          </div>
      </template>
      </ProTable>
    </div>
  </div>
</template>

<script setup name="case-manage" lang="jsx">
  import { useRouter } from 'vue-router';
  import { getAppEnvConfig } from '@/utils/env';
  import { reactive, ref } from 'vue';
  import { getRepairRecord, importExcel } from '@/api/property';
  import { Upload } from '@element-plus/icons-vue';
  import { ElMessage } from 'element-plus';
  import { getTenantPage } from '@/api/tenant';
  import citydata from '../../../assets/citydata';
  import { getPlatformPage } from '@/api/platform';
  import { VxeTextEllipsis, VxeTooltip } from 'vxe-pc-ui';

  const uploadRef = ref();

  const caseLRef = ref();
  import { onMounted } from 'vue';
  import { inject } from 'vue';
  const downloadfile = inject('download');
  const router = useRouter();
  const envs = getAppEnvConfig();
  import { useDict } from '@/hooks/useDict';
  const { PhoneResultStatus, ReduceType, FlowStatus, FollowStatus, AuditStatus, CaseStatus } = useDict("PhoneResultStatus","ReduceType", "FlowStatus", "FollowStatus","AuditStatus", "CaseStatus");
  const onCellClick = (row) => {
    router.push({
      path: '/property/case-detail',
      query: { id: row.id }, //这里不能直接写成 query: JSON.stringify(item)
    });
  };
  const paramCallback = (param) => {
    console.log('objobj', param)
    const obj = JSON.parse(JSON.stringify(param));
    if (obj.arealist && obj.arealist.length > 0) {
      const domicileProvince = []
      const domicileCity = []
      const area = []
      obj.arealist.forEach(item => {
        domicileProvince.push(item[0])
        if (item.length > 1) {
          domicileCity.push(item[1])
        }
        if (item.length > 2) {
          area.push(item[2])
        }
      })
      obj['domicileProvince'] = domicileProvince
      obj['domicileCity'] = domicileCity
      obj['area'] = area
      delete obj['arealist'];
    }
    if (obj['importTime']) {
      if (obj['importTime'][0]) obj['importTimeBegin'] = obj['importTime'][0];
      if (obj['importTime'][1]) obj['importTimeEnd'] = obj['importTime'][1];
      delete obj['importTime'];
    }
    return obj;
  };
  const upload = reactive({
    // 是否禁用上传
    isUploading: false,
    // 上传的地址
    url: envs.VITE_GLOB_API_URL_PREFIX + '/sys/upload',
  });
  console.log('upload', upload);
  const uploadVideoProcess = (event, file, fileList) => {
    upload.isUploading = true;
  };
  const download = () => {
    downloadfile('/RepairRecord/downloadByTenant', {}, '修复.xls');
  }
  const admindownload = () => {
    downloadfile('/RepairRecord/download', {}, '修复.xls');
  }
  const query = () => caseLRef.value?.search();

  const handleFileSuccess = (response, file, fileList) => {
    if (!response.success) {
      ElMessage.error({
        message: response.message || '检查失败',
        plain: true,
      });
      upload.isUploading = false;
      uploadRef.value.clearFiles();
    }
    if (response.success) {
      
      importExcel({
        fileUrl: response.message,
      }).then((res) => {
        ElMessage.success({
          message: '上传成功',
          plain: true,
        });
        uploadRef.value.clearFiles();
        query()
      }).catch(() => {
      })
      uploadRef.value.clearFiles();
      upload.isUploading = false;
    }
  };
  const handleRemove = () => {
    form.path = '';
  };

  const config = reactive({
    columns: [
      {
        field: 'borrower.name',
        title: '借款人姓名',
        showOverflow: 'tooltip',
        width: 120,
        // search: {
        //   el: 'input',
        //   key: 'name',
        //   props: { clearable: true },
        //   labelWidth: 105,
        // },
      },
      {
        field: 'borrower.idCard',
        title: '借款人身份证',
        showOverflow: 'tooltip',
        width: 140,
        // search: {
        //   el: 'input',
        //   props: { clearable: true },
        //   key: 'borrowerIdCard',
        //   labelWidth: 105,
        // },
      },
      {
        field: 'loanPlatform.name',
        showOverflow: 'tooltip',
        visible: false,
        enum: () => getPlatformPage({ current: 1, size: 999999999, status: 'enable' }),
        search: { el: 'select', props: { filterable: true }, key: 'loanPlatform', labelWidth: 105 },
        fieldNames: { label: 'name', value: 'id' },
        title: '借款平台',
        width: 100,
      },
      {
        field: 'commissionAmount',
        title: '委案金额',
        visible: false,
        showOverflow: 'tooltip',
        width: 80,
        search: { render: ({ searchParam }) => {
          return (
            <div class="flex">
              <el-input vModel_trim={searchParam.commissionAmountBegin} placeholder="" />
              <span class="mr-1 ml-1">-</span>
              <el-input vModel_trim={searchParam.commissionAmountEnd} placeholder="" />
            </div>
          );
        }, props: { clearable: true }, labelWidth: 105 },
      },
      {
        field: 'borrower.age',
        title: '年龄',
        showOverflow: 'tooltip',
        width: 80,
        search: { render: ({ searchParam }) => {
          return (
            <div class="flex">
              <el-input vModel_trim={searchParam.ageBegin} placeholder="" />
              <span class="mr-1 ml-1">-</span>
              <el-input vModel_trim={searchParam.ageEnd} placeholder="" />
            </div>
          );
        }, props: { clearable: true }, labelWidth: 105 },
      },
      {
        field: 'arealist',
        enum: citydata,
        title: '所属区域',
        showOverflow: 'tooltip',
        width: 160,
        fieldNames: { label: 'label', value: 'value' },
        search: { el: 'cascader', props: { clearable: true, checkStrictly: true, multiple: true, 'collapse-tags': true }, labelWidth: 105 },
        slots: {
          default: ({ row }) => {
            return (
              <VxeTooltip
                content={
                  row.borrower.domicileProvince +
                  (row.borrower.domicileCity ? '-' + row.borrower.domicileCity : '') +
                  (row.borrower.area ? '-' + row.borrower.area : '')
                }
              >
                <VxeTextEllipsis
                  content={
                    row.borrower.domicileProvince +
                    (row.borrower.domicileCity ? '-' + row.borrower.domicileCity : '') +
                    (row.borrower.area ? '-' + row.borrower.area : '')
                  }
                ></VxeTextEllipsis>
              </VxeTooltip>
            );
          },
        },
      },
      {
        field: 'importTime',
        title: '时间',
        showOverflow: 'tooltip',
        width: 130,
        visible: false,
        search: {
          el: 'date-picker',
          props: { type: 'daterange', valueFormat: 'YYYY-MM-DD' },
          labelWidth: 105,
        },
      },
      {
        field: 'oldPhone',
        title: '修复前联系方式',
        showOverflow: 'tooltip',
        // width: 140,
        search: {
          el: 'input',
          props: { clearable: true },
          key: 'oldPhone',
          labelWidth: 105,
        },
        default: ({ row }) => {
          return (
            <>
              {typeof row.oldPhone === 'object' ? row.oldPhone.join(',') : row.oldPhone}
            </>
          );
        },
      },
      {
        field: 'newPhone',
        title: '修复后联系方式',
        showOverflow: 'tooltip',
        // width: 140,
        search: {
          el: 'input',
          props: { clearable: true },
          key: 'newPhone',
          labelWidth: 105,
        },
        default: ({ row }) => {
          return (
            <>
              {typeof row.newPhone === 'object' ? row.newPhone.join(',') : row.newPhone}
            </>
          );
        },
      },
      // {
      //     title: 'CPE',
      //     showOverflow: 'tooltip',
      //     width: 60,
      //     slots: {
      //       default: ({ row }) => {
      //         return (
      //           <>{row.cpe?.username}</>
      //         );
      //       },
      //     },
      //     search: { el: 'input', props: { clearable: true }, key: 'cpeName', labelWidth: 105 },
      //   },
        {
          showOverflow: 'tooltip',
          slots: {
            default: ({ row }) => {
              return (
                <>{row.tenant?.name}</>
              );
            },
          },
          enum: () => getTenantPage({ current: 1, size: 999999999, status: 'enable' }),
          search: { el: 'select', props: { filterable: true }, key: 'tenantId', labelWidth: 105 },
          fieldNames: { label: 'name', value: 'id' },
          title: '调解中心',
          width: 100,
        },
      {
        field: 'repairStatus',
        title: '是否修复',
        showOverflow: 'tooltip',
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.repairStatus === 'Y' ? '是' : '否'}
              </>
            );
          },
        },
      },
      {
        field: 'kinship',
        title: '与债权人关系',
        showOverflow: 'tooltip',
        // width: 140,
        // search: {
        //   el: 'input',
        //   props: { clearable: true },
        //   key: 'newPhone',
        //   labelWidth: 105,
        // },
      },
      {
        field: 'flowStatus',
        showOverflow: 'tooltip',
        title: '审核状态',
        width: 95,
        enum: FlowStatus,
        search: { el: 'select', props: { filterable: true }, labelWidth: 105 },
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.flowStatus ? FlowStatus.value?.find((v) => v.value === row.flowStatus)?.label : ''}
              </>
            );
          },
        },
      },
    ],
  });


  onMounted(() => {
    query();
  });
</script>
<style lang="scss" scoped>
  .table-inner {
    width: 100%;
    :deep(.topgrp) {
      display: flex;
      margin-bottom: 8px;
      .topbox {
        margin-right: 10px;
        background: rgba(0, 0, 0, 0.02);
        border-radius: 16px;
        width: 146px;
        height: 97px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 24px;
        p:nth-child(1) {
          font-size: 14px;
          color: rgba(0, 0, 0, 0.45);
        }
      }
    }
  }
</style>
