<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]">
        <div v-show="showSearch">
          <el-card shadow="hover">
            <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="100px">
              <el-form-item label="联系方式" prop="contact">
                <el-input v-model="queryParams.contact" clearable placeholder="请输入联系方式"
                          @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="身份证号" prop="idCard">
                <el-input v-model="queryParams.idCard" clearable placeholder="请输入身份证号"
                          @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item>
                <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>

        <el-card class="mt-[10px]" shadow="never">
          <el-table v-loading="loading" :data="parmentList">
            <el-table-column
              v-for="{ label, prop, align, minWidth, fixed } in headers"
              :key="prop"
              :align="align || 'center'"
              :fixed="fixed"
              :label="label"
              :min-width="minWidth || '120px'"
              prop="expertName"
            >
              <template #default="{ row }">
                <span v-if="prop == 'expertTypeMoneyFee'">{{ row.expertTypeMoneyFee || '0' }}元/次</span>
                <span v-else-if="prop == 'reviewCount'">{{ row.reviewCount || '0' }}次</span>
                <span v-else-if="prop == 'expertMoney'">{{ row.expertMoney || '0' }}元</span>
                <span v-else-if="prop == 'expertNoPayMoney'">{{ row.expertNoPayMoney || row.expertTypeMoneyFee }}元</span>
                <span v-else-if="prop == 'expertPayMoney'">{{ row.expertPayMoney || '0' }}元</span>
                <span v-else-if="prop == 'expertMoneyFlag'">{{ moneyStatusObj[row.expertMoneyFlag] }}</span>
                <span v-else>{{ row[prop] || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作"
                             min-width="120px">
              <template #default="{ row }">
                <el-button :disabled="row.expertMoneyFlag == 2" link type="primary" @click="openPaymentDialog(row)">支付
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="page.total > 0" v-model:limit="page.pageSize" v-model:page="page.pageNum"
                      :total="page.total" @pagination="getList" />
        </el-card>
        <el-dialog v-model="dialogVisible" :before-close="handleClose" title="支付" width="600px">
          <el-form ref="PaymentFormRef" :model="PaymentForm" :rules="rules" label-width="auto">
            <el-form-item label="支付金额" prop="money">
              <el-input-number v-model="PaymentForm.money" :max="maxMoney" :min="1" style="flex:1;">
              </el-input-number>
            </el-form-item>
            <el-form-item label="支付方式" prop="payMethod">
              <el-input v-model="PaymentForm.payMethod" placeholder="请输入支付方式" />
            </el-form-item>
            <el-form-item label="支付凭证" prop="expertMoneyFile">
              <el-upload
                ref="uploadPayRef"
                v-model:file-list="PaymentForm.expertMoneyFile"
                :action="uploadPay.url"
                :auto-upload="true"
                :headers="uploadPay.headers"
                :limit="1"
                :on-exceed="handleExceed"
                :on-success="handleSuccess"
                accept=".pdf"
                drag
                style="flex: 1"
              >
                <el-icon class="el-icon--upload">
                  <i-ep-upload-filled />
                </el-icon>
                <div class="el-upload__text">
                  <div>将文件拖到此处，或<em>点击上传</em></div>
                  <div>仅允许导入.pdf 格式文件。</div>
                </div>
              </el-upload>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="handleClose">取 消</el-button>
              <el-button type="primary" @click="Payment">确 定</el-button>
            </span>
          </template>
        </el-dialog>

        <!-- 专家费用支付导入对话框 -->
        <el-dialog v-model="upload.open" :title="upload.title" append-to-body width="400px">
          <el-upload
            ref="uploadRef"
            :action="upload.url"
            :auto-upload="false"
            :disabled="upload.isUploading"
            :headers="upload.headers"
            :limit="1"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            accept=".xlsx, .xls"
            drag
          >
            <el-icon class="el-icon--upload">
              <i-ep-upload-filled />
            </el-icon>
            <div class="el-upload__text">
              <div>将文件拖到此处，或<em>点击上传</em></div>
              <div>仅允许导入xls、xlsx格式文件。</div>
            </div>
          </el-upload>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitFileForm">确 定</el-button>
              <el-button @click="upload.open = false">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </transition>
  </div>
</template>

<script lang="ts" setup>
import { getTableList, paymentManage } from '@/api/expertMoneyConfig/payment';
import { globalHeaders } from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { money_status_flag } = toRefs<any>(proxy?.useDict('money_status_flag'));
const moneyStatusObj = computed(() => {
  return money_status_flag.value.reduce((acc: any, cur: any) => {
    acc[cur.value] = cur.label;
    return acc;
  }, {});
});

const parmentList = ref<any[]>([]);
const loading = ref(true);
const showSearch = ref(true);


const queryFormRef = ref<ElFormInstance>();

interface Header {
  label: string;
  prop: string;
  align?: 'center' | 'left' | 'right';
  minWidth?: string | number;
  fixed?: string;
}

const headers = ref<Header[]>([
  {
    label: '结算单号',
    prop: 'settlementSn',
    fixed: 'left'
  },
  {
    label: '专家名称',
    prop: 'expertName',
    fixed: 'left'
  },
  {
    label: '联系方式',
    prop: 'expertContact'
  },
  {
    label: '身份证号',
    prop: 'expertIdcard'
  },
  {
    label: '专家类别',
    prop: 'expertType'
  },
  {
    label: '费用标准',
    prop: 'expertTypeMoneyFee'
  },
  {
    label: '评审次数',
    prop: 'reviewCount'
  },
  {
    label: '项目名称',
    prop: 'productName'
  },
  {
    label: '服务日期',
    prop: 'reviewDate'
  },
  {
    label: '结算周期',
    prop: 'moneyCycle'
  },
  {
    label: '费用总额',
    prop: 'expertMoney'
  },
  {
    label: '待支付金额',
    prop: 'expertNoPayMoney'
  },
  {
    label: '已支付金额',
    prop: 'expertPayMoney'
  },
  {
    label: '支付状态',
    prop: 'expertMoneyFlag'
  },
  {
    label: '支付方式',
    prop: 'payMethod'
  },
  {
    label: '备注',
    prop: 'remark'
  },
  {
    label: '结算日期',
    prop: 'settlementDate'
  }
]);

const page = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});
const queryParams = ref<any>({
  contact: '',
  idCard: ''
});


const getList = async () => {
  loading.value = true;
  let params = {
    ...page.value,
    ...queryParams.value,
    status: 1
  };
  delete params.total;
  const res = await getTableList(params);
  parmentList.value = res.rows;
  loading.value = false;
  page.value.total = res.total;
};

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

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

/**
 * 支付
 */
const dialogVisible = ref(false);
const PaymentFormRef = ref();
const uploadPay = {
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload'
};
const handleExceed = () => {
  ElNotification({
    title: '提示',
    message: '最多只能上传一个文件',
    type: 'error'
  });
};
const uploadPayRef = ref();
const maxMoney = ref(0);
const handleSuccess = async (res: any, file: any) => {
  if (res.code != 200) {
    ElNotification({
      title: `${file.name}上传失败`,
      message: res.msg,
      type: 'error'
    });
    await proxy?.$nextTick();
    uploadPayRef.value!.clearFiles();
  }
  PaymentFormRef.value?.validateField('expertMoneyFile')
};
const PaymentForm = reactive({
  moneyId: undefined,
  money: 1,
  payMethod: '',
  expertMoneyFile: []
});
const rules = {
  money: [
    { required: true, message: '请输入支付金额', trigger: 'blur' }
  ],
  payMethod: [
    { required: true, message: '请输入支付方式', trigger: 'blur' }
  ],
  expertMoneyFile: [
    { required: true, message: '请上传支付凭证', trigger: 'change' }
  ]
};
const openPaymentDialog = (row: any) => {
  PaymentForm.moneyId = row.moneyId;
  PaymentForm.payMethod = row.payMethod;
  dialogVisible.value = true;
  maxMoney.value = +(row.expertNoPayMoney || row.expertTypeMoneyFee);
};
const handleClose = () => {
  PaymentFormRef.value?.resetFields();
  uploadPayRef.value!.clearFiles();
  dialogVisible.value = false;
};
const Payment = () => {
  PaymentFormRef.value?.validate(async (valid: any) => {
    if (!valid) return;
    ElMessageBox.confirm('是否确定支付？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      let params = {
        ...PaymentForm,
        expertMoneyFile: PaymentForm.expertMoneyFile?.[0]?.response.data.ossId || ''
      };
      let res = await paymentManage(params);
      if (res.code != 200) {
        ElNotification({
          title: '提示',
          message: res.msg,
          type: 'error'
        });
        return;
      }
      ElNotification({
        title: '提示',
        message: '支付成功！',
        type: 'success'
      });
      handleClose();
      await getList();
    });
  });
};

/**
 * 导入
 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/zjk-api/expertMoneyConfig/imports'
});
const exportList = () => {
  upload.title = '专家费用管理导入';
  upload.open = true;
};
const uploadRef = ref<ElUploadInstance>();
/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  if (response.code == 200) {
    ElNotification({
      title: '提示',
      message: '导入成功',
      type: 'success'
    });
  } else {
    ElNotification({
      title: '提示',
      message: response.msg,
      type: 'error'
    });
  }
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

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