<template>
  <Mask :is-show="show" :height="600" :width="400" @close="close" title="手动对账" :show-footer="true">
    <template #default>
      <div class="form">
        <el-form :model="formData" label-width="130" :rules="rules" ref="formRef">
          <el-form-item label="对账日期" prop="date">
            <el-date-picker
                v-model="selectDate"
                type="daterange"
                @change="changeDate"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="height: 100%"
            />
          </el-form-item>
          <el-form-item label="清算类别" prop="reconciliationType">
            <el-select v-model="formData.reconciliationType" placeholder="请选择">
              <el-option
                  v-for="item in clrTypeOptions"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="险种类型" prop="insuranceType">
            <el-select v-model="formData.insuranceType" placeholder="请选择">
              <el-option
                  v-for="item in insutypesOptions"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="经办机构" prop="handlingInstitution">
            <el-input v-model="formData.handlingInstitution"></el-input>
          </el-form-item>
          <el-form-item label="医疗费用总额" prop="totalMedicalCost">
            <el-input v-model.number="formData.totalMedicalCost" type="number"></el-input>
          </el-form-item>
          <el-form-item label="基金支付总额" prop="totalFundPayment">
            <el-input v-model.number="formData.totalFundPayment" type="number"></el-input>
          </el-form-item>
          <el-form-item label="个账支付总额" prop="totalPersonalAccountPayment">
            <el-input v-model.number="formData.totalPersonalAccountPayment" type="number"></el-input>
          </el-form-item>
          <el-form-item label="结算笔数" prop="settlementCount">
            <el-input v-model.number="formData.settlementCount" type="number"></el-input>
          </el-form-item>
          <el-form-item>

          </el-form-item>
        </el-form>
      </div>
    </template>
    <template #footer>
      <div class="footer">
        <span class="default-btn" @click="submitForm">对账</span>
        <span class="default-btn" @click="close" style="margin-left: 24px">取消</span>
      </div>
    </template>
  </Mask>
</template>
<script setup lang="ts">

import Mask from "@/components/common/Mask.vue";
import {reactive, ref} from "vue";
import {post} from "@/utils/request.ts";
import {ElMessage} from "element-plus";
import {formatDateArray, getEndOfDay} from "@/utils/dateUtils.ts";
import clrType from "@/assets/config/directory/clrType.json"
import insutypes from "@/assets/config/directory/insutypes.json"

interface ClrType {
  [key: string]: string;
}

const clrTypeOptions = Object.entries(clrType as ClrType).map(([key, value]) => ({
  key: key,
  value: value
}))

interface Insutypes {
  [key: string]: string;
}

const insutypesOptions = Object.entries(insutypes as Insutypes).map(([key, value]) => ({
  key: key,
  value: value
}))
const init = (data: any) => {
  formData.value = data;
  selectDate.value = formatDateArray([data.beginTime, data.endTime]);
  show.value = true;
};
defineExpose({init})
const show = ref(false);
const close = () => {
  show.value = false;
};
const formData = ref<any>({})
const changeDate = (val: any) => {
  selectDate.value = formatDateArray(val);
  formData.value.beginTime = selectDate.value[0];
  formData.value.endTime = getEndOfDay(selectDate.value[1]);
}
const selectDate = ref<any>([])
const submitForm = () => {
  // 假设你给 el-form 设置了 ref="formRef"
  formRef.value.validate((valid: any) => {
    if (valid) {
      accountRecordDo()
    } else {
      ElMessage.error('请完善表单');
      return false;
    }
  });
};

const accountRecordDo = () => {
  let data = {...formData.value};
  post("social/reconciliation/totalDo", {data: data}).then((res: any) => {
    let msg = res.stmtinfo.stmt_rslt_dscr;
    if (res.stmtinfo.stmt_rslt == 0) {
      msg = "对平"
    }
    ElMessage.success({
      message: msg,
      duration: 8000
    });
  })
}
const formRef = ref();
const rules = reactive({
  // 对账日期（date）需要手动校验，因为 el-date-picker 不直接支持 prop 校验
  date: [
    {validator: validateDate, trigger: 'change'}
  ],
  reconciliationType: [
    {required: true, message: '清算类别不能为空', trigger: 'change'}
  ],
  insuranceType: [
    {required: true, message: '险种类型不能为空', trigger: 'change'}
  ],
  handlingInstitution: [
    {required: true, message: '经办机构不能为空', trigger: 'blur'}
  ],
  totalMedicalCost: [
    {required: true, message: '医疗费用总额不能为空', trigger: 'blur'},
    {type: 'number', message: '必须为数字', trigger: 'blur'}
  ],
  totalFundPayment: [
    {required: true, message: '基金支付总额不能为空', trigger: 'blur'},
    {type: 'number', message: '必须为数字', trigger: 'blur'}
  ],
  totalPersonalAccountPayment: [
    {required: true, message: '个账支付总额不能为空', trigger: 'blur'},
    {type: 'number', message: '必须为数字', trigger: 'blur'}
  ],
  settlementCount: [
    {required: true, message: '结算笔数不能为空', trigger: 'blur'},
    {type: 'number', message: '必须为数字', trigger: 'blur'}
  ]
});

function validateDate(rule: any, value: any, callback: any) {
  if (!selectDate.value || selectDate.value.length < 2) {
    callback(new Error('请选择完整的对账日期范围'));
  } else {
    callback();
  }
}

</script>
<style scoped lang="scss">
.form {
  padding: 20px;
}

.footer {
  height: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 0 24px;
}
</style>