<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"
            @change="handleQuery"
          >
            <el-option
              v-for="categoryCode in clrTypeOptions"
              :key="categoryCode.value"
              :label="categoryCode.label"
              :value="categoryCode.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        plain
        icon="Edit"
        @click="handleQuery"
      >
        统计
      </el-button>
      <el-button
        type="primary"
        plain
        icon="Edit"
        @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
        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
        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
          label="是否退费"
          align="center"
          key="refdSetlFlag"
          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"
            width="150"
            class-name="small-padding fixed-width"
            fixed="right"
          >
            <template #default="scope">
              <el-button
                type="danger"
                link
                icon="revoked-filled"
                :disabled="scope.row.id == ''"
                @click="revokedSelectedRows(scope.row)"
              >
                撤销
              </el-button>
            </template>
          </el-table-column> -->
    </el-table>
  </div>
</template>
  
  <script setup name="reconciliationDetails">
  import {applyUnClearing, autoApplyFinancialClearing, reconcileDetailList} from "./statisticalManagent";
  import {formatDateStr} 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 occurrenceTime = ref([
    formatDateStr(getFirstDayOfMonth(new Date()), 'YYYY-MM-DD'), // 当前月份的第一天
    formatDateStr(new Date(), 'YYYY-MM-DD') // 当天
  ])
  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 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 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 getFirstDayOfMonth(date) {
  return new Date(date.getFullYear(), date.getMonth(), 1);
}
  
  // 对象转成指定字符串分隔
  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.records ? res.data.records : res.data;
      total.value = res.data.total;
    });
  }
  
  function handleApplyForLiquidation () {
    let params = {}
    params.clrType = queryParams.value.clrType?queryParams.value.clrType:""
    params.setlOptins = queryParams.value.setlOptins?queryParams.value.setlOptins:""
    params.stmtBegnDate = queryParams.value.stmtBegnDate?queryParams.value.stmtBegnDate:""
    params.stmtEndDate = queryParams.value.stmtEndDate?queryParams.value.stmtEndDate:""
    autoApplyFinancialClearing(params).then((res) => {
    console.log(res.data,'res----------------');
    loading.value = false;
    });
  }
  function isAllSelected() {
    return selectedRow.value.length === purchaseinventoryList.value.length;
  }

  function revokedSelectedRows(row) {
    let queryParamsss = {
        clrAppyEvtId:row.outResult,
        clroptins:queryParams.value.setlOptins?queryParams.value.setlOptins:"", 
    }
    applyUnClearing(queryParamsss).then(res => {
        proxy.$message.success('撤销成功')
        getList()
    }).catch(err => {
        proxy.$message.error('撤销失败')
    })
  }
  
  /** 选择条数  */
  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>