<script setup lang="ts">
import { ElMessage, dayjs, ElForm } from "element-plus";
import { computed, reactive, ref, watchEffect } from "vue";
import { input_type_list } from "../../../status";

import { upload_invoice_rules } from "../../../config/configs";
import { xs_inv_type_list } from "/@/utils/status";

const map = {
  "10": "electronic", //电子普通发票
  "20": "special_electronic", //电子专用发票
  "01": "special", //普通专用发票
  "04": "normal", //普通发票
  '31': 'fully_digitalized_special_electronic',
  '32': 'fully_digitalized_normal_electronic',
};

const props = defineProps<{
  isElectronic: boolean;
  isSupport: boolean;
  isSpecialTicket: boolean;
  isPlain: boolean;
  invType: string;
}>();

const formRef = ref<InstanceType<typeof ElForm>>(null);
const emit = defineEmits(["changeStatus"]);
const rules = reactive({ ...upload_invoice_rules });
const scanInvType = ref("");

const disabled = computed(() => formData.input_type === "1");

const scanInputValue = ref("");

const formData = reactive({
  input_type: "1",
  remark: "",
  invCode: "",
  invNum: "",
  open_date: null,
  subtotal_fee: 0,
  checkCode: ""
});


const isFull = computed(() => {
  return Number(scanInvType.value) === 31 || Number(scanInvType.value) === 32
});


function handleSaveStatus() {
  formRef.value.validate(isValid => {
    if (!isValid) return;
    const { input_type: _, subtotal_fee, checkCode, ...otherParams } = formData;

    const now = dayjs(new Date()).format('YYYY-MM-DD');
    if (formData.open_date && !dayjs(formData.open_date).isSame(dayjs(now)) && !dayjs(formData.open_date).isBefore(dayjs(now))) {
      return ElMessage.error("开票日期不能超过当前日期");
    }

    let params: Record<string, string> | null = null;

    const type = map[scanInvType.value];

    if (scanInvType.value && String(props.invType) !== String(type)) {
      return ElMessage.error("扫描识别的发票类型与开票类型不一致");
    }

    //线下开票
    params = {
      status: "3",
      // subtotal_fee: subtotal_fee.toFixed(2),
      ...(isFull.value ? { total_fee: subtotal_fee.toFixed(2) } : { subtotal_fee: subtotal_fee.toFixed(2) }),
      ...(checkCode ? { checkCode } : {}),
      ...otherParams
    };

    emit("changeStatus", params);
  });
}

function handleScanKeydown(evt: KeyboardEvent) {
  const { keyCode } = evt;
  if (keyCode !== 13) return;

  //校验扫描枪值是否含有中文逗号
  if (scanInputValue.value.indexOf("，") >= 0) {
    ElMessage.error("不能包含中文逗号");
    return (scanInputValue.value = "");
  }

  const result = scanInputValue.value.split(",");

  if (result.length !== 9 && result.length !== 8) {
    ElMessage.error("扫码枪识别数据格式不正确,请重新扫描。");
    return;
  }

  const [_1, invoiceType, ...chunks] = result;
  const [invCode, invNum, subtotal_amount, open_time, checkCode] = chunks;

  scanInvType.value = invoiceType;
  const year = open_time.slice(0, 4);
  const month = open_time.slice(4, 6);
  const day = open_time.slice(6);

  formData.invCode = invCode;
  formData.checkCode = checkCode;
  formData.invNum = invNum;
  formData.subtotal_fee = Number(subtotal_amount);
  formData.open_date = dayjs(`${year}-${month}-${day}`).format("YYYY-MM-DD HH:mm:ss");

  scanInputValue.value = "";
}

watchEffect(() => {
  rules.checkCode[0].required =
    props.invType === "normal" || props.invType === "electronic";
});

watchEffect(() => {
  const { input_type } = formData;

  if (input_type === "2") {
    const source = xs_inv_type_list.find(
      ({ value }) => value === props.invType
    );

    if (source) {
      scanInvType.value = source.scanValue;
    }
  }
});
</script>

<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="90px" class="demo-ruleForm" size="small"
    status-icon>
    <el-row>
      <el-col :span="12">
        <el-form-item label="输入类型" prop="input_type">
          <el-select v-model="formData.input_type" style="width: 100%" placeholder="菜单类型">
            <el-option v-for="(si, sii) in input_type_list" :key="'type' + si.value + sii" :label="si.label"
              :value="si.value" />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="24" style="padding: 12px 12px 12px 16px" v-if="formData.input_type === '1'">
        <el-input clearable v-model="scanInputValue" :rows="3" type="textarea" placeholder="扫码枪输入处"
          @keydown="handleScanKeydown" />
      </el-col>

      <el-col :span="8">
        <el-form-item label="发票类型">
          <el-select style="width: 100%" v-model="scanInvType" disabled>
            <el-option v-for="inv in xs_inv_type_list" :key="inv.scanValue" :value="inv.scanValue" :label="inv.label" />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="发票号码" prop="invNum">
          <el-input v-model="formData.invNum" placeholder="发票号码" :disabled="disabled" />
        </el-form-item>
      </el-col>

      <el-col :span="8" v-if="!isFull">
        <el-form-item label="发票代码" prop="invCode">
          <el-input v-model="formData.invCode" placeholder="发票代码" :disabled="disabled" />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="开票日期" prop="open_date">
          <el-date-picker style="width:100%" value-format="YYYY-MM-DD HH:mm:ss" v-model="formData.open_date"
            :disabled="disabled" />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item :label="isFull ? '税后金额' : '税前金额'" prop="subtotal_fee">
          <el-input-number v-model="formData.subtotal_fee" :precision="2" style="width: 100%" :max="100000000" :min="0"
            :disabled="disabled" />
        </el-form-item>
      </el-col>

      <el-col :span="8" v-if="!isFull">
        <el-form-item label="校验码" prop="checkCode">
          <el-input placeholde="请输入校验码" v-model="formData.checkCode" :disabled="disabled" />
        </el-form-item>
      </el-col>
    </el-row>
    <div class="flex justify-end">
      <el-button type="primary" @click="handleSaveStatus">保存</el-button>
    </div>
  </el-form>
</template>
