<template>
  <div class="table-box">
    <div class="table-inner">
      <ProTable :config="config" ref="caseLRef" :paramCallback="paramCallback"  :selectdList="selectdList" :api="getRepairRecord">
        <template #left_buttons>
          <div class="flex rounded w-full h-11 items-center pl-2 btn-grp mb-1">
            <el-dropdown  @command="(command) => dataValue = command">
              <span class="el-dropdown-link">
                  {{dataValue}}
                  <el-icon class="el-icon--right">
                  <arrow-down />
                  </el-icon>
              </span>
              <template #dropdown>
                  <el-dropdown-menu>
                      <el-dropdown-item v-for="item in dataOptions" :key="item.value" :command="item.value">{{item.label}}</el-dropdown-item>
                  </el-dropdown-menu>
              </template>
              </el-dropdown>
              <el-button
              type="primary"
              @click="repair"
              class="mr-3"
              >发起修复</el-button
              >
            <el-button
              v-permission="'repair_admin_export'"
              type="primary"
              @click="admindownload"
              class="mr-3"
              >导出全部</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" class="mt-2" 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, ElMessageBox } 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';
  import { sendRepairRecord } from '@/api/property';

  const uploadRef = ref();

  const caseLRef = ref();
  import { onMounted } from 'vue';
  import { inject } from 'vue';
  const downloadfile = inject('download');
  const selectdList = ref([]);
  const router = useRouter();
  const pageParams = ref({});

  const envs = getAppEnvConfig();
  import { useDict } from '@/hooks/useDict';
  const dataValue = ref('对查询结果操作');
  const dataOptions = [
      {
      label: '对查询结果操作',
      value: '对查询结果操作',
      },
      {
      label: '对选中项操作',
      value: '对选中项操作',
      }
  ];
  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 onCheckboxChange = (row) => {
    selectdList.value = row.records;
    dataValue.value = selectdList.value.length > 0 ? '对选中项操作' : '对查询结果操作'
  };
  const onCheckboxAll = (flag) => {
    if (flag.checked) {
      selectdList.value = flag.records;
    } else {
      selectdList.value = [];
    }
    dataValue.value = selectdList.value.length > 0 ? '对选中项操作' : '对查询结果操作'
  };
  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'];
    }
    pageParams.value = obj
    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 repair = async (row) => {
      const list = selectdList.value;
      if (dataValue.value === '对选中项操作' && (!selectdList.value || !selectdList.value.length)) {
        return ElMessage.warning({
            message: '请先选择操作对象!',
            plain: true,
        });
        }
      if (dataValue.value !== '对选中项操作') {
        const param = {...pageParams.value}
        delete param['current'];
        delete param['size'];
        await ElMessageBox.confirm('是否批量发起修复?', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        });
        await sendRepairRecord(param);
      } else {
        const ids = list.map((v) => v.id).join(',');
        await ElMessageBox.confirm('是否批量发起修复?', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        });
        await sendRepairRecord({recordIds: ids});
      }
      ElMessage({
        type: 'success',
        message: '修复申请发起成功！',
        plain: true,
      });
      query();
    };
  const config = reactive({
    columns: [
    { type: 'checkbox', title: '', width: 60, fixed: 'left' },
      {
        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,
        // },
      }
    ],
    onCheckboxChange: onCheckboxChange,
    onCheckboxAll: onCheckboxAll
  });


  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>
