<!-- 陈冠元 -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="个人编号" prop="personalId">
        <el-input
          v-model="queryParams.personalId"
          placeholder="请输入个人编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="证件号码" prop="idNumber">
        <el-input
          v-model="queryParams.idNumber"
          placeholder="请输入证件号码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="户籍地址" prop="registeredAddress">
        <el-input
          v-model="queryParams.registeredAddress"
          placeholder="请输入户籍地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="缴费年度" prop="paymentYear">
        <el-select
          v-model="queryParams.paymentYear"
          placeholder="请选择缴费年度"
          clearable
          @change="handleQuery"
          style="width: 180px"
        >
          <el-option
            v-for="year in years"
            :key="year"
            :label="year"
            :value="year"
          />
        </el-select>
      </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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['os:insurance:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['os:insurance:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['os:insurance:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['os:insurance:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
        type="warning" 
        plain icon="Upload" 
        @click="handleExcelImport"
        v-hasPermi="['os:insurance:add']"
        >excel表批量导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="insuranceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50px" align="center" prop="id" />
      <!-- <el-table-column label="个人编号" width="150" align="center" prop="personalId" />
      <el-table-column label="证件类型" width="120"  align="center" prop="idType" />
      <el-table-column label="证件号码" width="180" align="center" prop="idNumber" /> -->
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="出生日期" width="100" align="center" prop="birthdate">
        <template #default="scope">
          <span>{{ parseTime(scope.row.birthdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="gender" />
      <!-- <el-table-column label="联系电话" width="150" align="center" prop="contactPhone" />
      <el-table-column label="移动电话" width="150" align="center" prop="mobilePhone" />
      <el-table-column label="户籍地址" width="150" align="center" prop="registeredAddress" />
      <el-table-column label="居住地址" width="150" align="center" prop="residentialAddress" />
      <el-table-column label="缴费区划" width="100" align="center" prop="paymentDistrict" />
      <el-table-column label="缴费区划名称" width="120" align="center" prop="paymentDistrictName" />
      <el-table-column label="乡镇街道" width="120" align="center" prop="townshipStreet" />
      <el-table-column label="社区/行政村/学校" width="150" align="center" prop="communityVillageSchool" />
      <el-table-column label="单位编号" width="150" align="center" prop="unitId" />
      <el-table-column label="单位名称" width="150" align="center" prop="unitName" /> -->
      <el-table-column label="个人缴费金额" width="110" align="center" prop="personalPaymentAmount" />
      <el-table-column label="财政补助金额" width="110" align="center" prop="financialSubsidyAmount" />
      <el-table-column label="总金额" align="center" prop="totalAmount" />
      <el-table-column label="到账时间" align="center" prop="paymentTime" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.paymentTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="缴费年度" align="center" prop="paymentYear" />
      <el-table-column label="缴费人员身份类别" width="150" align="center" prop="payerCategory" />
      <el-table-column label="操作" width="150" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="viewDetail(scope.row)" v-hasPermi="['os:insurance:query']">查看详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['os:insurance:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['os:insurance:remove']">删除</el-button>
        </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-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="insuranceRef" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="个人编号" prop="personalId">
          <el-input v-model="form.personalId" placeholder="请输入个人编号" />
        </el-form-item>
        <el-form-item label="证件号码" prop="idNumber">
          <el-input v-model="form.idNumber" placeholder="请输入证件号码" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="出生日期" prop="birthdate">
          <el-date-picker clearable
            v-model="form.birthdate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择出生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="移动电话" prop="mobilePhone">
          <el-input v-model="form.mobilePhone" placeholder="请输入移动电话" />
        </el-form-item>
        <el-form-item label="户籍地址" prop="registeredAddress">
          <el-input v-model="form.registeredAddress" placeholder="请输入户籍地址" />
        </el-form-item>
        <el-form-item label="居住地址" prop="residentialAddress">
          <el-input v-model="form.residentialAddress" placeholder="请输入居住地址" />
        </el-form-item>
        <el-form-item label="缴费区划" prop="paymentDistrict">
          <el-input v-model="form.paymentDistrict" placeholder="请输入缴费区划" />
        </el-form-item>
        <el-form-item label="缴费区划名称" prop="paymentDistrictName">
          <el-input v-model="form.paymentDistrictName" placeholder="请输入缴费区划名称" />
        </el-form-item>
        <el-form-item label="乡镇街道" prop="townshipStreet">
          <el-input v-model="form.townshipStreet" placeholder="请输入乡镇街道" />
        </el-form-item>
        <el-form-item label="社区/行政村/学校" prop="communityVillageSchool">
          <el-input v-model="form.communityVillageSchool" placeholder="请输入社区/行政村/学校" />
        </el-form-item>
        <el-form-item label="单位编号" prop="unitId">
          <el-input v-model="form.unitId" placeholder="请输入单位编号" />
        </el-form-item>
        <el-form-item label="单位名称" prop="unitName">
          <el-input v-model="form.unitName" placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item label="个人缴费金额" prop="personalPaymentAmount">
          <el-input v-model="form.personalPaymentAmount" placeholder="请输入个人缴费金额" />
        </el-form-item>
        <el-form-item label="财政补助金额" prop="financialSubsidyAmount">
          <el-input v-model="form.financialSubsidyAmount" placeholder="请输入财政补助金额" />
        </el-form-item>
        <el-form-item label="总金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入总金额" />
        </el-form-item>
        <el-form-item label="到账时间" prop="paymentTime">
          <el-date-picker clearable
            v-model="form.paymentTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择到账时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="缴费年度" prop="paymentYear">
          <el-select
            v-model="form.paymentYear"
            placeholder="请选择缴费年度"
            clearable
            @change="handleQuery"
            style="width: 180px"
          >
            <el-option
              v-for="year in years"
              :key="year"
              :label="year"
              :value="year"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="缴费人员身份类别" prop="payerCategory">
          <el-input v-model="form.payerCategory" placeholder="请输入缴费人员身份类别" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看医保信息详情对话框 -->
    <el-dialog :title="detailTitle" v-model="detailDialogVisible" width="80%" append-to-body>
      <el-form :model="detailData" label-width="140px" disabled>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="个人编号">
              <el-input v-model="detailData.personalId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件类型">
              <el-input v-model="detailData.idType" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件号码">
              <el-input v-model="detailData.idNumber" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名">
              <el-input v-model="detailData.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期">
              <el-input v-model="detailData.birthdate" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-input v-model="detailData.gender" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话">
              <el-input v-model="detailData.contactPhone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="移动电话">
              <el-input v-model="detailData.mobilePhone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="户籍地址">
              <el-input v-model="detailData.registeredAddress" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="居住地址">
              <el-input v-model="detailData.residentialAddress" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="缴费区划">
              <el-input v-model="detailData.paymentDistrict" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="缴费区划名称">
              <el-input v-model="detailData.paymentDistrictName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="乡镇街道">
              <el-input v-model="detailData.townshipStreet" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="社区/行政村/学校">
              <el-input v-model="detailData.communityVillageSchool" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位编号">
              <el-input v-model="detailData.unitId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位名称">
              <el-input v-model="detailData.unitName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="个人缴费金额">
              <el-input v-model="detailData.personalPaymentAmount" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="财政补助金额">
              <el-input v-model="detailData.financialSubsidyAmount" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总金额">
              <el-input v-model="detailData.totalAmount" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到账时间">
              <el-input v-model="detailData.paymentTime" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="缴费年度">
              <el-input v-model="detailData.paymentYear" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="缴费人员身份类别">
              <el-input v-model="detailData.payerCategory" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 数据导入对话框 -->
    <el-dialog title="数据导入" v-model="excelOpen" width="400px" append-to-body>
      <el-upload ref="uploadRef" class="upload-demo" :action="uploadExcelUrl" :headers="headers"
        :on-success="handleUploadSuccess" :on-error="handleUploadError" :before-upload="handleBeforeUpload" :limit="1"
        :auto-upload="false">
        <template #trigger>
          <el-button type="primary">上传文件</el-button>&nbsp;&nbsp;&nbsp;
        </template>
        <el-button class="ml-3" type="success" @click="submitUpload">
          上传
        </el-button>
        <template #tip>
          <div class="el-upload__tip">
            上传文件仅支持，xls/xlsx格式，文件大小不得超过10M
          </div>
        </template>
      </el-upload>
    </el-dialog>

  </div>
</template>

<script setup name="Insurance">
import { listInsurance, getInsurance, delInsurance, addInsurance, updateInsurance } from "@/api/healthcare/outpatientService/insurance";
import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance();

const insuranceList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const detailDialogVisible = ref(false)
const detailTitle = ref("医保信息详情")
const detailData = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    personalId: null,
    idNumber: null,
    name: null,
    registeredAddress: null,
    paymentYear: null,
  },
  rules: {
    personalId: [
      { required: true, message: "个人编号不能为空", trigger: "blur" }
    ],
    idType: [
      { required: true, message: "证件类型不能为空", trigger: "change" }
    ],
    idNumber: [
      { required: true, message: "证件号码不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    birthdate: [
      { required: true, message: "出生日期不能为空", trigger: "blur" }
    ],
    gender: [
      { required: true, message: "性别不能为空", trigger: "blur" }
    ],
    paymentDistrict: [
      { required: true, message: "缴费区划不能为空", trigger: "blur" }
    ],
    paymentDistrictName: [
      { required: true, message: "缴费区划名称不能为空", trigger: "blur" }
    ],
    townshipStreet: [
      { required: true, message: "乡镇街道不能为空", trigger: "blur" }
    ],
    communityVillageSchool: [
      { required: true, message: "社区/行政村/学校不能为空", trigger: "blur" }
    ],
    unitId: [
      { required: true, message: "单位编号不能为空", trigger: "blur" }
    ],
    unitName: [
      { required: true, message: "单位名称不能为空", trigger: "blur" }
    ],
    personalPaymentAmount: [
      { required: true, message: "个人缴费金额不能为空", trigger: "blur" }
    ],
    financialSubsidyAmount: [
      { required: true, message: "财政补助金额不能为空", trigger: "blur" }
    ],
    totalAmount: [
      { required: true, message: "总金额不能为空", trigger: "blur" }
    ],
    paymentTime: [
      { required: true, message: "到账时间不能为空", trigger: "blur" }
    ],
    paymentYear: [
      { required: true, message: "缴费年度不能为空", trigger: "blur" }
    ]
  }
});

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

/** 查询患者医保信息列表 */
function getList() {
  loading.value = true;
  listInsurance(queryParams.value).then(response => {
    insuranceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 生成年份选项（最近10年 + 未来2年）
const currentYear = new Date().getFullYear()
const years = ref(
  Array.from({ length: 12 }, (_, index) => currentYear - 10 + index + 1)
    .reverse()
    .map(y => y.toString())
)

// 表单重置
function reset() {
  form.value = {
    id: null,
    personalId: null,
    idType: null,
    idNumber: null,
    name: null,
    birthdate: null,
    gender: null,
    contactPhone: null,
    mobilePhone: null,
    registeredAddress: null,
    residentialAddress: null,
    paymentDistrict: null,
    paymentDistrictName: null,
    townshipStreet: null,
    communityVillageSchool: null,
    unitId: null,
    unitName: null,
    personalPaymentAmount: null,
    financialSubsidyAmount: null,
    totalAmount: null,
    paymentTime: null,
    paymentYear: null,
    payerCategory: null
  };
  proxy.resetForm("insuranceRef");
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加患者医保信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getInsurance(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改患者医保信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["insuranceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateInsurance(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addInsurance(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除患者医保信息编号为"' + _ids + '"的数据项？').then(function() {
    return delInsurance(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('os/insurance/export', {
    ...queryParams.value
  }, `insurance_${new Date().getTime()}.xlsx`)
}


/* 打开数据导入对话框 */
const excelOpen = ref(false);
function handleExcelImport() {
  excelOpen.value = true;
}

/* 上传excel */
const uploadRef = ref({});
function submitUpload() {
  uploadRef.value.submit()
}

/* 上传地址 */
const uploadExcelUrl = ref(import.meta.env.VITE_APP_BASE_API + "/os/insurance/import"); // 上传excel文件地址
/* 上传请求头 */
const headers = ref({ Authorization: "Bearer " + getToken() });

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    proxy.$modal.msgSuccess("上传excel成功");
    excelOpen.value = false;
    getList();
  } else{
    proxy.$modal.msgError(res.msg);
  } 
  uploadRef.value.clearFiles();
  proxy.$modal.closeLoading();
}

// 上传失败
function handleUploadError() {
  proxy.$modal.msgError("上传excel失败");
  uploadRef.value.clearFiles();
  proxy.$modal.closeLoading();
}

//上传前校验
const props = defineProps({
  modelValue: [String, Object, Array],
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 10,
  },
  // 文件类型, 例如["xls", "xlsx"]
  fileType: {
    type: Array,
    default: () => ["xls", "xlsx"],
  },
});

// 上传前loading加载
function handleBeforeUpload(file) {
  let isExcel = false;
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isExcel = props.fileType.some(type => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  } 
  if (!isExcel) {
    proxy.$modal.msgError(
      `文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`
    );
    return false;
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传excel大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在上传excel，请稍候...");
}

function viewDetail(row) {
  // 获取详情数据
  getInsurance(row.id).then(response => {
    detailData.value = response.data
    detailDialogVisible.value = true
  })
}

getList();
</script>
