<template>
  <div class="app-container">
    <el-row
      :gutter="10"
      class="mb8"
    >
      <el-form
        ref="queryRef"
        :model="queryParams"
        :inline="true"
        label-width="85px"
      >
        <el-form-item
          label="结算经办机构："
          prop="setlOptins"
          label-width="110px"
        >
          <el-input
            v-model="queryParams.setlOptins"
            placeholder="请输入结算经办机构"
            clearable
            style="width: 150px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="结算日期：">
          <el-date-picker
            v-model="occurrenceTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item
          label="清算类型："
          prop="clrType"
        >
          <el-select
            v-model="queryParams.clrType"
            placeholder="请选择清算类型"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="categoryCode in clrTypeOptions"
              :key="categoryCode.value"
              :label="categoryCode.label"
              :value="categoryCode.value"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="医院：" prop="orgId"  label-width="70px">
          <el-input
            v-model="queryParams.orgId"
            placeholder="请输入医院id"
            clearable
            style="width: 150px"
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->
        <el-form-item
          label="文件查询号："
          prop="fileQuryNo"
          label-width="100px"
        >
          <el-input
            v-model="queryParams.fileQuryNo"
            placeholder="请输入文件查询号"
            clearable
            style="width: 150px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="本地文件路径：" prop="filePath" label-width="110px">
          <el-input
            v-model="queryParams.filePath"
            placeholder="请输入本地文件路径"
            clearable
            style="width: 566px"
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->
        <el-form-item>
          <el-upload
            multiple
            ref="fileUpload"
            :action="uploadFileUrl"
            :before-upload="handleBeforeUpload"
            :file-list="fileList"
            limit="1"
            :on-error="handleUploadError"
            :on-exceed="handleExceed"
            :on-success="handleUploadSuccess"
            :show-file-list="false"
            :headers="headers"
            class="upload-file-uploader"
          >
            <el-button
              type="primary"
              plain
              icon="Edit"
            >
              上传文件
            </el-button>
          </el-upload>
          <div
            v-if="showTip"
            class="el-upload__tip"
          >
            请上传
            <template v-if="fileSize">
              大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
            </template>
            <template v-if="fileType">
              格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
            </template>
            的文件
          </div>
        </el-form-item>
      </el-form>
      <!-- <el-row :gutter="10" class="mb8"> -->
      <!-- <el-col :span="1.5"> -->
      <!-- v-hasPermi="['system:user:import']" -->
      <el-button
        type="primary"
        plain
        icon="Edit"
        @click="handleQuery"
      >
        统计
      </el-button>
      <el-button
        type="primary"
        plain
        icon="Edit"
        @click="handleExport"
      >
        生成txt文件
      </el-button>
      <!-- </el-col> -->
      <!-- <el-col :span="1.5"> -->
      <!-- v-hasPermi="['system:user:export']" -->
      <el-button
        type="primary"
        plain
        icon="Edit"
        @click="handleReconciliation"
      >
        开始明细对账
      </el-button>
      <el-button
        type="primary"
        plain
        icon="Edit"
        :disabled="ids.length == 0"
        @click="handleApplyForLiquidation"
      >
        申请清算
      </el-button>
      <!-- </el-col> -->
    </el-row>
    <div style="margin-bottom:5px">
      结算笔数：{{ counts }}（其中 总费用：{{ totalPrice1?totalPrice1.toFixed(2):0 }}元， 基金支付金额：{{ totalPrice2?totalPrice2.toFixed(2):0 }}元， 账户支付金额：{{ totalPrice3?totalPrice3.toFixed(2):0 }}元，现金支付金额：{{ totalPrice4?totalPrice4.toFixed(2):0 }}元）
    </div>
    <el-table
      v-loading="loading"
      :data="purchaseinventoryList"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
    >
      <el-table-column
        type="selection"
        width="50"
        align="center"
      />
      <el-table-column
        key="psnNo"
        label="个人编码"
        align="center"
        prop="psnNo"
        width="190"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        key="patientName"
        label="患者姓名"
        align="center"
        prop="patientName"
        width="100"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        key="mdtrtId"
        label="就诊ID"
        align="center"
        prop="mdtrtId"
        width="270"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        key="setlId"
        label="结算ID"
        align="center"
        prop="setlId"
        width="270"
        :show-overflow-tooltip="true"
      />
      <!-- <el-table-column
        label="姓名"
        align="center"
        key="locationName"
        prop="locationName"
         width="140"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="医保结算日期"
        align="center"
        key="productionDate"
        prop="productionDate"
        width="160"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.productionDate) }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        key="medfeeSumamt"
        label="总费用"
        align="center"
        prop="medfeeSumamt"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        key="fundPaySumamt"
        label="基金支付金额"
        align="center"
        prop="fundPaySumamt"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        key="acctPay"
        label="个人账户金额"
        align="center"
        prop="acctPay"
        :show-overflow-tooltip="true"
      />
      <!-- <el-table-column
        label="现金支付金额"
        align="center"
        key="unitCode_dictText"
        prop="unitCode_dictText"
        :show-overflow-tooltip="true"
      /> -->
      <!-- <el-table-column
        label="共计支付金额"
        align="center"
        key="quantity"
        prop="quantity"
        :show-overflow-tooltip="true"
      /> -->
      <el-table-column
        key="setlTime"
        label="结算时间"
        align="center"
        prop="setlTime"
      
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.setlTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        key="refdSetlFlag"
        label="是否退费"
        align="center"
        prop="refdSetlFlag"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{ scope.row.refdSetlFlag==1?'退费':'' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="报销类型"
        align="center"
        key="minUnitCode_dictText"
        prop="minUnitCode_dictText"
        :show-overflow-tooltip="true"
      />
       <el-table-column
        label="身份证"
        align="center"
        key="minUnitCode_dictText"
        prop="minUnitCode_dictText"
        :show-overflow-tooltip="true"
      />
       <el-table-column
        label="收据编号"
        align="center"
        key="busNo"
        prop="busNo"
        :show-overflow-tooltip="true"
      /> -->
    </el-table>
    <el-form
      :inline="true"
      label-width="90px"
      style="width: 100%; margin-top: 30px"
    >
      <el-form-item
        label="上传结果："
        style="width: 100%"
      >
        <el-input
          v-model="reconciliationDetail"
          :autosize="{ minRows: 4, maxRows: 10 }"
          type="textarea"
          disabled
          placeholder=""
        />
      </el-form-item>
    </el-form>
    <!-- <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    /> -->
    <!-- v-if="purchaseinventoryReturnList&&purchaseinventoryReturnList.length>0" -->
    <!-- <el-table
     v-if="purchaseinventoryList.length>0"
      style="height:190px;margin-top:32px;"
      v-loading="loadingReturn"
      :data="purchaseinventoryReturnList"
      @selection-change="handleSelectionChangeReturn"
    >
     <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        label="人员ID"
        align="center"
        key="busNo"
        prop="busNo"
         width="140"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="就诊ID"
        align="center"
        key="medicineName"
        prop="medicineName"
         width="140"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="结算ID"
        align="center"
        key="locationName"
        prop="locationName"
         width="140"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="对账结果"
        align="center"
        key="locationName"
        prop="locationName"
         width="140"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="备注"
        align="center"
        key="locationName"
        prop="locationName"
         width="140"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="总费用"
        align="center"
        key="manufacturerText"
        prop="manufacturerText"
        width="180px"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="医疗费总额"
        align="center"
        key="lotNumber"
        prop="lotNumber"
        width="120px"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="基金支付总额"
        align="center"
        key="quantityUnit"
        prop="quantityUnit"
         width="140px"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="个人账户支付总额"
        align="center"
        key="unitCode_dictText"
        prop="unitCode_dictText"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="发送方报文ID"
        align="center"
        key="quantity"
        prop="quantity"
        :show-overflow-tooltip="true"
      />
       <el-table-column
        label="退费结算标志"
        align="center"
        key="minUnitCode_dictText"
        prop="minUnitCode_dictText"
        :show-overflow-tooltip="true"
      />
    </el-table> -->
  </div>
</template>

<script setup name="reconciliationDetails">
import {
  applyFinancialClearing,
  reconcileDetailList,
  reconcileDetailTxt,
  reconcileGeneral,
  ybRequestFileUp
} from "./statisticalManagent";
import {getToken} from "@/utils/auth";
import {formatDate} from '@/utils/index';

const { proxy } = getCurrentInstance();
const purchaseinventoryList = ref([]);
const loading = ref(false);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const reconciliationDetail = ref("")
const occurrenceTime = ref([formatDate(new Date()),formatDate(new Date())]);
const clrTypeOptions = ref([]);
const filePath = ref("")
const purchaseinventoryReturnList = ref([])
const loadingReturn = ref(false)
const selectedRow = ref([])
const counts = ref(0)
const totalPrice1 = ref(0)
const totalPrice2 = ref(0)
const totalPrice3 = ref(0)
const totalPrice4 = ref(0)

const fileSize = ref(10)
const uploadList = ref([]);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/yb-request/file-up"); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const fileList = ref([]);
const fileType = ref(["zip","txt"]);
const data = reactive({
  form: {},
  queryParams: {
    // pageNo: 1,
    // pageSize: 10,
    setlOptins: '229900', 
    filePath: undefined, 
    orgId:undefined,
    clrType: undefined,
    fileQuryNo: undefined, 
    stmtBegnDate:undefined,
    stmtEndDate:undefined,
  },
  rules: {},
});

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

watch(
  () => purchaseinventoryList.value,
  (newVlaue) => {
    if(newVlaue&&newVlaue.length>0){
      handleTotalAmount()
    }
  },
  { immediate: true }
)
function handleBeforeUpload(file) {
  // 校检文件类型
  if (fileType.value.length) {
    const fileName = file.name.split('.');
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = fileType.value.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      proxy.$modal.msgError(`文件格式不正确, 请上传${fileType.value.join("/")}格式文件!`);
      return false;
    }
  }
  // 校检文件大小
  if (fileSize.value) {
    const isLt = file.size / 1024 / 1024 < fileSize.value;
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过10MB!`);
      return false;
    }
  }
  const formData = new FormData()
  formData.append('file', file)
  formData.append('filename', file.name)
  ybRequestFileUp(formData).then((res) => {
    if(res.code==200){
      proxy.$modal.msgSuccess("上传成功")
    }
    
  })
  // proxy.$modal.loading("正在上传文件，请稍候...");
  number.value++;
  return true;
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 1 个!`);
}

// 上传失败
function handleUploadError(err) {
  proxy.$modal.msgError("上传文件失败");
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    console.log(res,file,"file")
    uploadList.value.push({ name: res.fileName, url: res.fileName });
    uploadedSuccessfully();
  } else {
    number.value--;
    proxy.$modal.closeLoading();
    proxy.$modal.msgError(res.msg);
    proxy.$refs.fileUpload.handleRemove(file);
    uploadedSuccessfully();
  }
}
// function submitFileForm() {
//   proxy.$refs['fileUpload'].submit();
// }
// 上传结束处理
function uploadedSuccessfully() {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value);
    uploadList.value = [];
    number.value = 0;
    // proxy.$refs['fileUpload'].submit();
    emit("update:modelValue", listToString(fileList.value));
    proxy.$modal.closeLoading();
  }
}
// 删除文件
function handleDelete(index) {
  fileList.value.splice(index, 1);
  emit("update:modelValue", listToString(fileList.value));
}

// 获取文件名称
function getFileName(name) {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return name;
  }
}

// 对象转成指定字符串分隔
function listToString(list, separator) {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    if (list[i].url) {
      strs += list[i].url + separator;
    }
  }
  return strs != '' ? strs.substr(0, strs.length - 1) : '';
}
/**计算合计金额 */
function handleTotalAmount() {
  counts.value = purchaseinventoryList.value.length
  totalPrice1.value = purchaseinventoryList.value.reduce(
    (accumulator, currentRow) => {
      return (accumulator + (Number(currentRow.medfeeSumamt) || 0))
    },
    0
  );
  totalPrice2.value = purchaseinventoryList.value.reduce(
    (accumulator, currentRow) => {
      return (accumulator + (Number(currentRow.fundPaySumamt) || 0))
    },
    0
  );
  totalPrice3.value = purchaseinventoryList.value.reduce(
    (accumulator, currentRow) => {
      return (accumulator + (Number(currentRow.acctPay) || 0))
    },
    0
  );
  // 现金支付金额
  // totalPrice4.value = purchaseinventoryList.value.reduce(
  //   (accumulator, currentRow) => {
  //     return (accumulator + (Number(currentRow.profitAmount) || 0))
  //   },
  //   0
  // );
}
function getPharmacyCabinetLists() {
  clrTypeOptions.value = [
    { value: 11, label: '门诊' },
    { value: 21, label: '住院' },
  ];
}
function handleSelectionChangeReturn(selection) {
  idsReturn.value = selection.map((item) => item.id);
  singleReturn.value = selection.length != 1;
  multipleReturn.value = !selection.length;
}

function getList() {
  reconcileDetailList(queryParams.value).then((res) => {
    // console.log(res,"res----------------")
    // loading.value = false;
    // purchaseinventoryList.value = [{psnNo:"123",mdtrtId:"121",setlId:"1213",medfeeSumamt:"122",fundPaySumamt:"12",acctPay:"4.72",insutype:"410",clrType: 11,contractNo:"229900"},{psnNo:"123",mdtrtId:"121",setlId:"1213",medfeeSumamt:"122",fundPaySumamt:"12",acctPay:"7.43",insutype:"410",clrType: 11,contractNo:"229900"},{psnNo:"123",mdtrtId:"121",setlId:"1213",medfeeSumamt:"122",fundPaySumamt:"12",acctPay:"1",insutype:"410",clrType: 11,contractNo:"229900"},{psnNo:"123",mdtrtId:"121",setlId:"1213",medfeeSumamt:"122",fundPaySumamt:"12",acctPay:"-1",insutype:"410",clrType: 11,contractNo:"229900"}]
   purchaseinventoryList.value = res.data.record ? res.data.record : res.data;
    total.value = res.data.total;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.stmtBegnDate =
    occurrenceTime.value && occurrenceTime.value.length == 2
      ? occurrenceTime.value[0] + " 00:00:00"
      : "";
  queryParams.value.stmtEndDate =
    occurrenceTime.value && occurrenceTime.value.length == 2
      ? occurrenceTime.value[1] + " 23:59:59"
      : "";
  // queryParams.value.pageNo = 1;
  getList();
}

/** 按钮操作 */
function handleReconciliation() {
  // 调用接口返回值
  if(selectedRow.value.length==0){
    proxy.$message.error('请选择一行数据开始明细对账');
    return
  }
  loading.value = true;
  let queryParamsss = {
    settlementIdList:ids.value,
    filePath:queryParams.value.filePath?queryParams.value.filePath:"", 
    fileQuryNo:queryParams.value.fileQuryNo?queryParams.value.fileQuryNo:"", 
    setlOptins:queryParams.value.setlOptins?queryParams.value.setlOptins:"", 
    clrType:queryParams.value.clrType?queryParams.value.clrType:""
  }
  reconcileGeneral(queryParamsss).then((res) => {
    console.log(res.data, 'res----------------');
    loading.value = false;
  });
}
function handleApplyForLiquidation () {
  if (isAllSelected()) {
    let params = {}
    params.clrType = queryParams.value.clrType?queryParams.value.clrType:""
    params.clrOptins = queryParams.value.setlOptins?queryParams.value.setlOptins:""
    params.stmtBegnDate = occurrenceTime.value[0]
    params.stmtEndDate = occurrenceTime.value[1]
    params.settlementIdList = ids.value
    applyFinancialClearing(params).then((res) => {
      console.log(res.data,'res----------------');
      loading.value = false;
    });
  } else {
    proxy.$message.warning('当前未全选');
  }
}
function isAllSelected() {
  return selectedRow.value.length === purchaseinventoryList.value.length;
}
function handleExport(){
  if(selectedRow.value.length==0){
    proxy.$message.error('请选择一行数据进行生成txt文件');
    return
  }
  loading.value = true;
  reconcileDetailTxt({settlementIdList:ids.value}).then((res) => {
    console.log(res.data,'res----------------');
    let fileName = Date.now()+'.txt'; // 默认文件名
    // 2. 创建Blob对象
    const blob = new Blob([res], { type: 'application/octet-stream;charset=utf-8' });
    // 3. 创建临时下载链接
    const link = document.createElement('a');
    const url = window.URL.createObjectURL(blob);
    link.href = url;
    link.download = fileName; // 设置下载文件名
     // 4. 触发下载
    document.body.appendChild(link);
    link.click();
    // 5. 清理资源
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    loading.value = false;
    if(res.data){
      queryParams.value.filePath = res.data.split("生成txt文件成功，文件路径：")?res.data.split("生成txt文件成功，文件路径：")[1]:""
    }
  });
}

/** 选择条数  */
function handleSelectionChange(selection) {
  selectedRow.value = selection
  console.log(selectedRow.value,"selectedRow.value")
  ids.value = selection.map((item) => item.setlId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
//点击列表当前行
function handleRowClick(row) {
  // editRowTK.value = row
  console.log(row,"row")
  // if(row.returnStatus==1){
  //   loadingReturn.value = true
  //   generatedReturnDetail(row.supplyBusNo).then((response) => {
  //     purchaseinventoryReturnList.value = response.data
  //     purchaseinventoryReturnList.value.map(k=>{
  //       // k.returnStatus_text =  k.returnStatus==1?'已退库':''
  //       k.originalSupplyBusNo = k.originalSupplyBusNo?k.originalSupplyBusNo:row.supplyBusNo
  //     }) 
    
  //   })
  //   loadingReturn.value = false
  // }
}


getList();
getPharmacyCabinetLists()
</script>
<style scoped>
.custom-tree-node {
  display: flex;
  align-items: center;
}

.title {
  font-weight: bold;
  font-size: large;
  margin-bottom: 10px;
}
</style>