<template>
  <div class="app-container">
    <el-tabs
      v-model="activeTabName"
      type="card"
      class="inOut-tabs"
      @tab-click="hendleTabChange"
    >
      <el-tab-pane
        label="对账"
        name="first"
      >
        <el-row :guutter="15">
          <el-form
            ref="priceRef"
            :model="totalPrice"
            :inline="true"
          >
            <el-row :guutter="15">
              <el-form-item
                label="结算经办机构："
                prop="setlOptins"
                label-width="160px"
              >
                <el-input
                  v-model="totalPrice.setlOptins"
                  placeholder="请输入结算经办机构"
                  clearable
                  style="width: 150px"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item
                label="结算日期："
                label-width="130px"
              >
                <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"
                label-width="160px"
              >
                <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="insutype"
                label-width="160px"
              >
                <el-select
                  v-model="queryParams.insutype"
                  placeholder="请选择险种类型"
                  clearable
                  style="width: 150px"
                >
                  <el-option
                    v-for="categoryCode in insutypeOptions"
                    :key="categoryCode.value"
                    :label="categoryCode.label"
                    :value="categoryCode.value"
                  />
                </el-select>
              </el-form-item>
            </el-row>
            <el-row :guutter="15">
              <el-form-item
                label="医疗费总额："
                prop="medfeeSumamt"
                label-width="160px"
              >
                <el-input
                  v-model="totalPrice.medfeeSumamt"
                  placeholder="请输入医疗费总额"
                  clearable
                  style="width: 150px"
                />
              </el-form-item>
              <el-form-item
                label="基金支付总额："
                prop="fundAppySum"
                label-width="160px"
              >
                <el-input
                  v-model="totalPrice.fundAppySum"
                  placeholder="请输入基金支付总额"
                  clearable
                  style="width: 150px"
                />
              </el-form-item>
              <el-form-item
                label="个人账户支付金额："
                prop="acctPay"
                label-width="160px"
              >
                <el-input
                  v-model="totalPrice.acctPay"
                  placeholder="请输入个人账户支付金额"
                  clearable
                  style="width: 150px"
                />
              </el-form-item>
              <el-form-item
                label="现金支付金额："
                prop="cashPayamt"
                label-width="160px"
              >
                <el-input
                  v-model="totalPrice.cashPayamt"
                  placeholder="请输入现金支付金额"
                  clearable
                  style="width: 150px"
                />
              </el-form-item>
              <el-form-item
                label="结算笔数："
                prop="setlCnt"
                label-width="160px"
              >
                <el-input
                  v-model="totalPrice.setlCnt"
                  placeholder="请输入结算笔数"
                  clearable
                  style="width: 150px"
                />
              </el-form-item>
              <!-- <el-button type="primary" plain icon="Edit" @click="handOperatedApply">手动清算</el-button> -->
              <el-button
                type="primary"
                plain
                icon="Edit"
                @click="handOperatedReconcileAccounts"
              >
                手动对账
              </el-button>
            </el-row>
          </el-form>
        </el-row>

        <!-- </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="outResult"
            label="申请清算ID"
            align="center"
            prop="outResult"
            width="270"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="begndate"
            label="开始时间"
            align="center"
            prop="begndate"
            width="150"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="enddate"
            label="结束时间"
            align="center"
            prop="enddate"
            width="150"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="clrType"
            label="清算类别"
            align="center"
            prop="clrType"
            width="100"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="medfeeSumamt"
            label="总费用"
            align="center"
            prop="medfeeSumamt"
            width="170"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="medSumfee"
            label="医保认可总费用"
            align="center"
            prop="medSumfee"
            width="170"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="fundAppySum"
            label="基金申报金额"
            align="center"
            prop="fundAppySum"
            width="170"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="cashPayamt"
            label="现金支付总额"
            align="center"
            prop="cashPayamt"
            width="170"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="acctPay"
            label="个人账户金额"
            align="center"
            prop="acctPay"
            width="170"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="status"
            label="状态"
            align="center"
            prop="status"
            width="170"
            :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="300"
            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>
        <span class="descriptions-item-label">对账结果：</span>
        <div
          style="
            background: #f5f7fa;
            border: solid 1px;
            border-color: #e4e7ed;
            width: 50%;
            height: 100px;
            margin-top: 20px;
          "
        >
          <span>{{ reconciliation }}</span>
        </div>
      </el-tab-pane>
      <el-tab-pane
        label="清算"
        name="second"
      >
        <el-row :guutter="15">
          <el-form
            ref="priceRef"
            :model="totalPrice"
            :inline="true"
          >
            <el-row :guutter="15">
              <el-form-item
                label="结算经办机构："
                prop="setlOptins"
                label-width="160px"
              >
                <el-input
                  v-model="totalPrice.setlOptins"
                  placeholder="请输入结算经办机构"
                  clearable
                  style="width: 150px"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item
                label="结算日期："
                label-width="130px"
              >
                <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"
                label-width="160px"
              >
                <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="insutype" label-width="160px">
                <el-select v-model="queryParams.insutype" placeholder="请选择险种类型" clearable style="width: 150px">
                  <el-option v-for="categoryCode in insutypeOptions" :key="categoryCode.value" :label="categoryCode.label"
                    :value="categoryCode.value" />
                </el-select>
              </el-form-item> -->
            </el-row>
            <el-row :guutter="15">
              <el-form-item
                label="医疗费总额："
                prop="medfeeSumamt"
                label-width="160px"
              >
                <el-input
                  v-model="totalPrice.medfeeSumamt"
                  placeholder="请输入医疗费总额"
                  clearable
                  style="width: 150px"
                />
              </el-form-item>
              <el-form-item
                label="基金支付总额："
                prop="fundAppySum"
                label-width="160px"
              >
                <el-input
                  v-model="totalPrice.fundAppySum"
                  placeholder="请输入基金支付总额"
                  clearable
                  style="width: 150px"
                />
              </el-form-item>
              <el-form-item
                label="个人账户支付金额："
                prop="acctPay"
                label-width="160px"
              >
                <el-input
                  v-model="totalPrice.acctPay"
                  placeholder="请输入个人账户支付金额"
                  clearable
                  style="width: 150px"
                />
              </el-form-item>
              <el-form-item
                label="现金支付金额："
                prop="cashPayamt"
                label-width="160px"
              >
                <el-input
                  v-model="totalPrice.cashPayamt"
                  placeholder="请输入现金支付金额"
                  clearable
                  style="width: 150px"
                />
              </el-form-item>
              <!-- <el-form-item label="结算笔数：" prop="setlCnt" label-width="160px">
                <el-input v-model="totalPrice.setlCnt" placeholder="请输入结算笔数" clearable style="width: 150px" />
              </el-form-item> -->
              <el-button
                type="primary"
                plain
                icon="Edit"
                @click="handOperatedApply"
              >
                手动清算
              </el-button>
              <!-- <el-button type="primary" plain icon="Edit" @click="handOperatedReconcileAccounts">手动对账</el-button> -->
            </el-row>
          </el-form>
        </el-row>

        <!-- </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="outResult"
            label="申请清算ID"
            align="center"
            prop="outResult"
            width="270"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="begndate"
            label="开始时间"
            align="center"
            prop="begndate"
            width="150"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="enddate"
            label="结束时间"
            align="center"
            prop="enddate"
            width="150"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="clrType"
            label="清算类别"
            align="center"
            prop="clrType"
            width="100"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="medfeeSumamt"
            label="总费用"
            align="center"
            prop="medfeeSumamt"
            width="170"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="medSumfee"
            label="医保认可总费用"
            align="center"
            prop="medSumfee"
            width="170"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="fundAppySum"
            label="基金申报金额"
            align="center"
            prop="fundAppySum"
            width="170"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="cashPayamt"
            label="现金支付总额"
            align="center"
            prop="cashPayamt"
            width="170"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="acctPay"
            label="个人账户金额"
            align="center"
            prop="acctPay"
            width="170"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="status"
            label="状态"
            align="center"
            prop="status"
            width="170"
            :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="300"
            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>
        <span class="descriptions-item-label">清算结果：</span>
        <div
          style="
            background: #f5f7fa;
            border: solid 1px;
            border-color: #e4e7ed;
            width: 50%;
            height: 100px;
            margin-top: 20px;
          "
        >
          <span>{{ reconciliation }}</span>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup name="LiquidationRecords">
import {
  applyFinancialClearingList,
  applyUnClearing,
  autoApplyFinancialClearing,
  handOperatedApplyFinancialClearing,
  handOperatedApplyReconcileAccounts,
} from './statisticalManagent';
import {formatDateStr} from '@/utils/index';
import {ref} from 'vue';

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 activeTabName = ref('first');
const clrTypeOptions = ref([]);
const insutypeOptions = ref([]);
const filePath = ref('');
const purchaseinventoryReturnList = ref([]);
const loadingReturn = ref(false);
const selectedRow = ref([]);

const fileSize = ref(10);
const uploadList = ref([]);
const reconciliation = 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: 11,
    fileQuryNo: undefined,
    stmtBegnDate: undefined,
    stmtEndDate: undefined,
  },
  rules: {},
});

const totalPrice = reactive({
  medfeeSumamt: 0,
  fundAppySum: 0,
  acctPay: 0,
  cashPayamt: 0,
  counts: 0,
  setlCnt: 0,
  medSumfee: 0.0,
});

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

// 接收路由参数
const route = useRoute();

// 监听路由变化
watch(
  () => route.query,
  (newQuery) => {
    // 当路由 query 参数变化时执行
    if (newQuery.currentRow) {
      try {
        const currentRow = JSON.parse(newQuery.currentRow);
        console.log('接收到的currentRow参数:', currentRow);

        // 处理接收到的参数
        if (currentRow) {
          totalPrice.medfeeSumamt = currentRow.medFeeSumAmt || 0;
          totalPrice.fundAppySum = currentRow.fundPaySumAmt || 0;
          totalPrice.acctPay = currentRow.acctPay || 0;
          totalPrice.cashPayamt = currentRow.acctGjPay || 0;
          totalPrice.counts = currentRow.fixMedInsSetlCnt || 0;
          queryParams.insutype = currentRow.insutype;

          // 如果有传递时间参数也一并处理
          if (newQuery.occurrenceTime) {
            occurrenceTime.value = newQuery.occurrenceTime;
          }
          console.log('已更新参数:', currentRow);
        }
      } catch (error) {
        console.error('解析currentRow参数失败:', error);
      }
    }
  },
  { immediate: true } // 立即执行一次，处理首次加载的情况
);

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() {
  totalPrice.counts = purchaseinventoryList.value.length;
  totalPrice.medfeeSumamt = purchaseinventoryList.value.reduce((accumulator, currentRow) => {
    return Number((accumulator + Number(currentRow.medfeeSumamt || 0)).toFixed(2));
  }, 0);
  totalPrice.fundAppySum = purchaseinventoryList.value.reduce((accumulator, currentRow) => {
    return Number((accumulator + Number(currentRow.fundPaySumamt || 0)).toFixed(2));
  }, 0);
  totalPrice.acctPay = purchaseinventoryList.value.reduce((accumulator, currentRow) => {
    return Number((accumulator + Number(currentRow.acctPay || 0)).toFixed(2));
  }, 0);
  // 现金支付金额
  // cashPayamt.value = purchaseinventoryList.value.reduce(
  //   (accumulator, currentRow) => {
  //     return (accumulator + (Number(currentRow.profitAmount) || 0))
  //   },
  //   0
  // );
}
function getPharmacyCabinetLists() {
  clrTypeOptions.value = [
    { value: 11, label: '门诊' },
    { value: 21, label: '住院' },
  ];
  insutypeOptions.value = [
    { value: 310, label: '职工基本医疗保险' },
    { value: 390, label: '城乡居民基本医疗保险' },
    { value: 320, label: '公务员医疗补助' },
    { value: 330, label: '大额医疗费用补助' },
    { value: 340, label: '离休人员医疗保障' },
    { value: 350, label: '一至六级残废军人医疗补助' },
    { value: 360, label: '老红军医疗保障' },
    { value: 370, label: '企业补充医疗保险' },
    { value: 380, label: '新型农村合作医疗' },
    { value: 391, label: '城镇居民基本医疗保险' },
    { value: 392, label: '城乡居民大病医疗保险' },
  ];
}

function handleSelectionChangeReturn(selection) {
  idsReturn.value = selection.map((item) => item.id);
  singleReturn.value = selection.length != 1;
  multipleReturn.value = !selection.length;
}

function getList() {
  applyFinancialClearingList(queryParams.value).then((res) => {
    // console.log(res,"res----------------")
    // loading.value = false;
    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 handOperatedApply() {
  const params = { ...totalPrice };
  params.clrOptins = totalPrice.setlOptins ? totalPrice.setlOptins : '';
  params.begndate = occurrenceTime.value[0] ? occurrenceTime.value[0] + ' 00:00:00' : '';
  params.enddate = occurrenceTime.value[1] ? occurrenceTime.value[1] + ' 23:59:59' : '';
  params.clrType = queryParams.value.clrType ? queryParams.value.clrType : '';
  handOperatedApplyFinancialClearing(params)
    .then((res) => {
      reconciliation.value = res.data;
    })
    .catch((err) => {
      proxy.$message.error('申请失败');
    });
}

function hendleTabChange() {
  totalPrice.medfeeSumamt = 0;
  totalPrice.fundAppySum = 0;
  totalPrice.acctPay = 0;
  totalPrice.cashPayamt = 0;
  totalPrice.counts = 0;
  totalPrice.setlCnt = 0;
  totalPrice.medSumfee = 0.0;
  occurrenceTime.value = [
    formatDateStr(getFirstDayOfMonth(new Date()), 'YYYY-MM-DD'), // 当前月份的第一天
    formatDateStr(new Date(), 'YYYY-MM-DD'), // 当天
  ];
  purchaseinventoryList.value = [];
  queryParams.value = {
    setlOptins: undefined,
    filePath: undefined,
    orgId: undefined,
    clrType: undefined,
    fileQuryNo: undefined,
    stmtBegnDate: undefined,
    stmtEndDate: undefined,
  };
  reconciliation.value = '';
}

function handOperatedReconcileAccounts() {
  const params = { ...totalPrice };
  params.clrOptins = totalPrice.setlOptins ? totalPrice.setlOptins : '';
  params.begndate = occurrenceTime.value[0] ? occurrenceTime.value[0] + ' 00:00:00' : '';
  params.enddate = occurrenceTime.value[1] ? occurrenceTime.value[1] + ' 23:59:59' : '';
  params.clrType = queryParams.value.clrType ? queryParams.value.clrType : '';
  params.insutype = queryParams.value.insutype ? queryParams.value.insutype : '';
  handOperatedApplyReconcileAccounts(params)
    .then((res) => {
      reconciliation.value = res.data;
    })
    .catch((err) => {
      proxy.$message.error('对账失败');
    });
}
//点击列表当前行
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>