<template>
  <div style="padding: 0.5rem">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" style="margin-bottom: 10px">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100">
            <el-form-item label="职称等级" prop="expertTitleLevel">
              <el-select v-model="queryParams.expertTitleLevel" placeholder="请选择职称等级" clearable>
                <el-option v-for="dict in positionList" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="专家名称" prop="expertName">
              <el-input v-model="queryParams.expertName" placeholder="请输入专家名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="联系电话" prop="expertPhone">
              <el-input v-model="queryParams.expertPhone" placeholder="请输入联系电话" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="专家身份证号" prop="expertIdNumber">
              <el-input v-model="queryParams.expertIdNumber" placeholder="请输入专家身份证号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" style="margin-bottom: 2rem">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Upload" @click="handleImport">导入</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="invoiceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="发票号码" align="center" prop="invoiceNumber" />
        <el-table-column label="发票金额" align="center" prop="invoiceMoney" />
        <el-table-column label="开票日期" align="center" prop="startDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="专家名称" align="center" prop="expertName" />
        <el-table-column label="联系电话" align="center" prop="expertPhone" />
        <el-table-column label="专家身份证号" align="center" prop="expertIdNumber" />
        <el-table-column label="职称等级" align="center" prop="expertTitleLevel" />
        <el-table-column label="电子发票" align="center" prop="invoiceAddr">
          <template #default="scope">
            <a :href="scope.row.url || ''" :download="scope.row.invoiceAttachedName" class="download" target="_blank">{{
              scope.row.invoiceAttachedName
            }}</a>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button link type="primary" icon="Edit" :disabled="scope.row.checkStatus == 1" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" :disabled="scope.row.checkStatus == 1" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
            <!-- 校验完整性按钮 -->
            <el-tooltip content="校验完整性" placement="top">
              <el-button link type="success" icon="Check" @click="handleVerify(scope.row)" />
            </el-tooltip>
            <!-- 校验完整性按钮 -->
            <el-tooltip content="审核" placement="top">
              <el-button link type="success" icon="CircleCheck" :disabled="scope.row.checkStatus == 1" @click="handleAudit(scope.row)" />
            </el-tooltip>
          </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="1000px" append-to-body>
      <el-form ref="invoiceFormRef" :model="form" :rules="rules" label-width="auto">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发票号码" prop="invoiceNumber">
              <el-input v-model="form.invoiceNumber" placeholder="请输入发票号码" />
            </el-form-item>
            <el-form-item label="发票金额" prop="invoiceMoney">
              <el-input v-model="form.invoiceMoney" placeholder="请输入发票金额" />
            </el-form-item>
            <el-form-item label="开票日期" prop="startDate">
              <el-date-picker
                clearable
                style="width: 400px"
                v-model="form.startDate"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="请选择开票日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="电子发票" prop="invoiceAttached">
              <el-upload
                ref="invoiceUploadRef"
                style="width: 100%"
                v-model:file-list="fileList"
                :limit="1"
                accept=".pdf"
                :headers="invoiceAddrUpload.headers"
                :action="invoiceAddrUpload.url"
                :disabled="invoiceAddrUpload.isUploading"
                :on-progress="invoiceAddrHandleFileUploadProgress"
                :on-success="invoiceAddrHandleFileSuccess"
                :on-exceed="invoiceAddrHandleExceed"
                :auto-upload="true"
                drag
              >
                <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-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="productId">
              <el-select v-model="form.productId" placeholder="请选择项目名称" @change="getExpertLists(false)">
                <el-option v-for="project in projectLists" :key="project.productId" :label="project.productName" :value="project.productId" />
              </el-select>
            </el-form-item>
            <el-form-item label="项目阶段" prop="reviewSn">
              <el-select v-model="form.reviewSn" placeholder="请选择项目阶段" @change="getExpertLists(false)">
                <el-option v-for="item in item_stage" :key="item.value" :label="`${item.label}阶段`" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="专家名称" prop="expertName">
              <el-select
                :disabled="!form.productId || !form.reviewSn"
                v-model="form.expertName"
                filterable
                placeholder="请选择专家"
                style="flex: 1"
                @change="getSettlementLists(false)"
              >
                <el-option
                  v-for="item in expertOptions"
                  :key="item.expertId"
                  :label="`${item.workUnit} - ${item.expertName}（${item.contact}）`"
                  :value="item.expertId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="结算单选择" prop="settleId">
              <el-select :disabled="!form.expertName" v-model="form.settleId" placeholder="请选择结算单">
                <el-option v-for="item in settlementLists" :key="item.moneyId" :label="item.settlementSn" :value="item.moneyId"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="联系电话" prop="expertPhone">
              <el-input v-model="form.expertPhone" placeholder="请输入联系电话" />
            </el-form-item>
            <el-form-item label="专家身份证号" prop="expertIdNumber">
              <el-input v-model="form.expertIdNumber" placeholder="请输入专家身份证号" />
            </el-form-item>
            <el-form-item label="职称等级" prop="expertTitleLevel">
              <el-select v-model="form.expertTitleLevel" placeholder="请选择职称等级">
                <el-option v-for="dict in positionList" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </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>
    <!-- 导入发票弹框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="true"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { listProject } from '@/api/project/review';
import {
  listInvoice,
  getInvoice,
  delInvoice,
  addInvoice,
  updateInvoice,
  auditInvoices,
  getSettlement,
  getExpertList
} from '@/api/expertMoneyConfig/expertMoneyInfo';
import { InvoiceVO, InvoiceQuery, InvoiceForm } from '@/api/expertMoneyConfig/expertMoneyInfo/types';
import { genFileId } from 'element-plus';
import type { UploadUserFile, UploadRawFile } from 'element-plus';
import { listPosition } from '@/api/expert/person';
import { globalHeaders } from '@/utils/request';
import { verifyHmac } from '@/api/project/maintain';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { item_stage } = toRefs<any>(proxy?.useDict('item_stage'));

const positionList = ref<any>([]);
const invoiceList = ref<InvoiceVO[]>([]);
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 invoiceFormRef = ref<ElFormInstance>();
const uploadRef = ref<ElUploadInstance>();
const invoiceUploadRef = ref<ElUploadInstance>();

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

/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/zjk-api/invoice/imports'
});

const invoiceAddrUpload = reactive({
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload'
});

const fileList = ref<UploadUserFile[]>([]);
const initFormData: InvoiceForm = {
  id: undefined,
  invoiceNumber: undefined,
  invoiceMoney: undefined,
  startDate: undefined,
  expertName: undefined,
  expertPhone: undefined,
  expertIdNumber: undefined,
  expertTitleLevel: undefined,
  invoiceAttached: undefined,
  invoiceAttachedAddr: undefined,
  invoiceAttachedName: undefined,
  productId: undefined,
  reviewSn: undefined,
  settleId: undefined
};
const projectLists = ref([]);
const getProjectLists = async () => {
  const res = await listProject({
    pageNum: 1,
    pageSize: 100000000
  });
  projectLists.value = [...new Map(res.rows.map((item) => [item.productId, item])).values()];
};

const settlementLists = ref([]);
const getSettlementLists = async (isEdit = false) => {
  if (!isEdit) {
    form.value.settleId = '';
  }
  settlementLists.value = [];
  if (!form.value.expertName) return;
  const res = await getSettlement({
    productId: form.value.productId,
    reviewSn: form.value.reviewSn,
    expertId: form.value.expertName
  });
  settlementLists.value = res.data;
};

const contactValidator = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入联系方式'));
  }
  if (value.toString().indexOf(' ') != -1) {
    return callback(new Error('不允许输入空格!'));
  }
  if (value.toString().length != 11) {
    return callback(new Error('请输入11位手机号!'));
  }
  if (/^1([3]|[5]|[8])\d{9}/.test(value) || /^1([45]|[47]\d{9})/.test(value) || /^17[0-8]{9}/.test(value)) {
    callback();
  } else {
    callback(new Error('请检查手机号格式!'));
  }
};
const idCardValidator = (rule: any, value: any, callback: any) => {
  if (value) {
    if (!value.trim()) {
      return callback(new Error('请输入身份证号'));
    }
    if (value.toString().indexOf(' ') != -1) {
      return callback(new Error('不允许输入空格!'));
    }
    if (value.toString().length != 18) {
      return callback(new Error('请输入18位身份证号!'));
    }
    if (/^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[0-9Xx]$/.test(value)) {
      callback();
    } else {
      callback(new Error('请检查身份证号格式!'));
    }
  } else {
    callback(new Error('请输入身份证号!'));
  }
};
const invoiceNumberValidator = (rule: any, value: any, callback: any) => {
  if (value) {
    if (/^[0-9]*[1-9][0-9]*$/.test(value)) {
      form.value.invoiceNumber = Number(value);
      callback();
    } else {
      callback(new Error('请输入正确发票号码!'));
    }
  } else {
    callback(new Error('请输入发票号码!'));
  }
};
const invoiceMoneyValidator = (rule: any, value: any, callback: any) => {
  if (value) {
    if (/^([1-9]\d{0,9}|0)([.]?|(\.\d{1,2})?)$/.test(value)) {
      form.value.invoiceMoney = Number(value);
      callback();
    } else {
      callback(new Error('请输入正确发票金额!'));
    }
  } else {
    callback(new Error('请输入发票金额!'));
  }
};
const data = reactive<PageData<InvoiceForm, InvoiceQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    expertName: undefined,
    expertPhone: undefined,
    expertIdNumber: undefined,
    expertTitleLevel: undefined,
    params: {}
  },
  rules: {
    invoiceNumber: [{ required: true, validator: invoiceNumberValidator, trigger: 'blur' }],
    invoiceMoney: [{ required: true, validator: invoiceMoneyValidator, trigger: 'blur' }],
    startDate: [{ required: true, message: '开票日期不能为空', trigger: 'blur' }],
    expertName: [{ required: true, message: '专家名称不能为空', trigger: 'blur' }],
    expertPhone: [{ required: true, validator: contactValidator, trigger: 'blur' }],
    expertIdNumber: [{ required: true, validator: idCardValidator, trigger: 'blur' }],
    expertTitleLevel: [{ required: true, message: '职称等级不能为空', trigger: 'change' }],
    invoiceAttached: [{ required: true, message: '电子发票不能为空', trigger: 'change' }],
    productId: [
      {
        required: true,
        message: '项目不能为空',
        trigger: 'change'
      }
    ],
    reviewSn: [
      {
        required: true,
        message: '项目阶段不能为空',
        trigger: 'change'
      }
    ],
    settleId: [
      {
        required: true,
        message: '结算单不能为空',
        trigger: 'change'
      }
    ]
  }
});

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

/** 查询发票列表 */
const getList = async () => {
  loading.value = true;
  const res = await listInvoice(queryParams.value);
  invoiceList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 职称等级列表 */
const getPositionList = async () => {
  const res = await listPosition();
  positionList.value = res.data;
};

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加发票';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: InvoiceVO) => {
  fileList.value = [];
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getInvoice(_id);
  // 1. 找到对应职称等级在 positionList 里的 moneyId
  const matched = positionList.value.find((item) => item.label === res.data.expertTitleLevel);
  if (matched) {
    res.data.expertTitleLevel = matched.value; // 替换成 moneyId
  }
  if (row.invoiceAttached) {
    fileList.value.push({
      name: row.invoiceAttachedName,
      url: row.invoiceAttachedAddr
    });
  }
  Object.assign(form.value, res.data, {reviewSn: `${res.data.reviewSn}`});
  getExpertLists(true);
  getSettlementLists(true);
  dialog.visible = true;
  dialog.title = '修改发票';
};

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

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

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '发票导入';
  upload.open = true;
};

/** 下载模板操作 */
const importTemplate = () => {
  proxy?.download('/zjk-api/invoice/downloadExcel', {}, `invoice_template_${new Date().getTime()}.xlsx`);
};

/** 导入文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 导入文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/**文件上传中处理 */
const invoiceAddrHandleFileUploadProgress = () => {
  invoiceAddrUpload.isUploading = true;
};
/** 文件上传成功处理 */
const invoiceAddrHandleFileSuccess = (response: any, file: UploadFile) => {
  fileList.value.push({
    name: response.data.fileName,
    url: response.data.url
  });
  form.value.invoiceAttached = response.data.ossId;
  if (form.value.id) {
    form.value.invoiceAttachedAddr = response.data.url;
    form.value.invoiceAttachedName = response.data.fileName;
  }
  invoiceAddrUpload.isUploading = false;
  invoiceUploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
};
const invoiceAddrHandleExceed = (files) => {
  invoiceUploadRef.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  invoiceUploadRef.value!.handleStart(file);
};

/**hmac校验*/
function handleVerify(row: any) {
  verifyHmac({
    bizType: 'invoice',
    id: row.id,
    fields: []
  })
    .then((result: any) => {
      if (result.match) {
        ElMessage.success('校验通过');
      } else {
        ElMessage.error(`校验失败，该信息被篡改`);
      }
    })
    .catch((err) => {
      ElMessage.error('接口请求失败: ' + (err.response?.data?.msg || err.message));
    });
}

const handleAudit = (row: any) => {
  auditInvoices(row.id)
    .then((res) => {
      if (res.code !== 200) {
        ElNotification({
          type: 'error',
          title: '提示',
          message: res.msg
        });
        return;
      }
      ElNotification({
        title: '提示',
        message: '审核完成',
        type: 'success'
      });
      getList()
    })
    .catch((e) => {
      console.log(e);
    });
};
const expertOptions = ref([]);
const getExpertLists = async (isEdit = false) => {
  if (!isEdit) {
    form.value.expertName = '';
    form.value.settleId = '';
  }
  expertOptions.value = [];
  settlementLists.value = [];
  if (!form.value.productId || !form.value.reviewSn) return;
  let res = await getExpertList({
    productId: form.value.productId,
    reviewSn: form.value.reviewSn
  });
  expertOptions.value = res.data || [];
};

onMounted(() => {
  //获取职称等级列表
  getPositionList();
  getList();
  getProjectLists();
});
onActivated(() => {
  getPositionList();
  getList();
  getProjectLists();
});
</script>

<style scoped lang="scss">
.download {
  color: #409eff;
}
:deep(.el-upload-dragger){
  padding:0 10px;
}
</style>
