<script setup lang="ts">
import { ElForm } from "element-plus";
import { computed, ref, watch } from "vue";
import { UnitInput } from "/@/components/Input";
import { financeRules_JS, financeRules_NoJS } from "./../config/_rules";
import { useCompany } from "/@/hooks/core/useCompany";
import { useAsync } from "/@/hooks/core/useAsync";
import { ModalTypes } from "./../types";
import { httpList } from "/@/api/parameter/supplierPay";
import { useUserInfo } from "/@/hooks/core/useUser";
import Super from "/@/layout/components/company/super.vue";
import { httpAdd, httpUpdate } from "/@/api/parameter/finance";
import { xs_inv_type_list } from "/@/utils/status";

const emit = defineEmits(["finance-save"]);

const visible = ref(false);
const modalType = ref<ModalTypes>(ModalTypes.create);
const formRef = ref<InstanceType<typeof ElForm>>(null);
const selectCompany = ref<any>();
const initalRef = ref(true);

const { run, data } = useAsync<Record<string, string>[]>({
  initalData: [],
  isList: true,
  success: () => {
    const { address, name, registercode } = data.value[0];
    if (modalType.value !== ModalTypes.create) return;
    formData.value.company_name = name;
    formData.value.company_address = address;
    formData.value.company_license = registercode;
  }
});

const defaultData = {
  company_name: "",
  invoice_title: "",
  company_address: "",
  company_license: "",
  bank_name: "",
  bankNo: "",
  mobile: "",
  input_ticket: "",
  out_ticket: "",
  voider: "",
  reviewer: "",
  drawer: "",
  payee: "",
  ownerPlace: "",
  denomination: "",
  invoiceType: []
};

const { companyList } = useCompany();
const { isSuperUser } = useUserInfo();
const formData = ref<Record<string, any>>({ ...defaultData });
const rules = ref(financeRules_JS);

const isUpdate = computed(() => modalType.value === ModalTypes.update);

const companys = computed(() => {
  const allListItemIndex = companyList.value.findIndex(
    ({ companyNo }) => companyNo === ""
  );

  if (allListItemIndex >= 0) {
    return companyList.value.slice(allListItemIndex + 1);
  }

  return companyList.value;
});

const title = computed(() => {
  const baseName = "公司财务设置";
  switch (modalType.value) {
    case ModalTypes.create:
      return "创建" + baseName;
    case ModalTypes.preview:
      return "查看" + baseName;
    default:
      return "修改" + baseName;
  }
});

const formDataTransform = _data => {
  Object.keys(formData.value).forEach(key => {
    switch (key) {
      case "invoiceType":
        formData.value[key] = _data[key].split(",");
        break;
      default:
        formData.value[key] = _data[key];
        break;
    }
  });

  console.log(formData.value);
};

const { run: create, loading } = useAsync({
  success: () => {
    visible.value = false;
    emit("finance-save");
  }
});

const { run: update, loading: _loading } = useAsync({
  success: () => {
    visible.value = false;
    emit("finance-save");
  }
});

function handleSave() {
  formRef.value.validate(isValid => {
    if (!isValid) return;
    const param = {
      companyNo: selectCompany.value,
      ...(isSuperUser.value ? {} : { relaComNo: selectCompany.value }),
      ...formData.value
    };

    switch (modalType.value) {
      case ModalTypes.create:
        create(httpAdd(param));
        break;
      case ModalTypes.update:
        update(httpUpdate(param));
        break;
    }
  });
}

const requsetCompany = companyNo =>
  run(
    httpList({
      companyNo
    })
  );

watch(
  () => formData.value,
  ({ out_ticket }) => {
    const current =
      Number(out_ticket) === 1 ? financeRules_JS : financeRules_NoJS;
    rules.value = current;
    formRef.value && formRef.value.clearValidate();
  },
  {
    deep: true,
    immediate: true
  }
);

watch(
  () => selectCompany.value,
  companyNo => {
    if (modalType.value === ModalTypes.create && companyNo) {
      requsetCompany(companyNo);
    }
  }
);

defineExpose({
  onDisplay: (_data?: any, type?: ModalTypes) => {
    formData.value = { ...defaultData };
    visible.value = true;
    modalType.value = type;
    selectCompany.value = "";

    if (_data) {
      formDataTransform(_data);
      selectCompany.value = _data.companyNo;
      requsetCompany(_data.companyNo);
    }
  }
});
</script>

<template>
  <ElDialog
    center
    v-model="visible"
    :title="title"
    destroy-on-close
    @close="initalRef = true"
    width="1040px"
    :close-on-click-modal="false"
  >
    <ElForm
      ref="formRef"
      labelWidth="110px"
      :model="formData"
      :rules="rules"
      :disabled="modalType === ModalTypes.preview"
    >
      <h1 class="text-xl font-[600] mb-2 text-[#000]">公司财务设置</h1>
      <ElRow :gutter="12">
        <ElCol :span="12">
          <ElFormItem label="公司" prop="company_name">
            <ElSelect
              v-if="!isSuperUser"
              style="width: 100%"
              v-model="selectCompany"
              placeholder="请选择公司"
              :disabled="isUpdate"
            >
              <ElOption
                v-for="c in companys"
                :key="c.companyNo"
                :label="c.companyName"
                :value="c.companyNo"
              />
            </ElSelect>

            <Super
              v-else
              v-model:code="selectCompany"
              noAll
              noSet
              @change="value => (selectCompany = value.code)"
              :disabled="isUpdate"
            />
          </ElFormItem>

          <ElFormItem label="纳税号" prop="company_license">
            <ElInput
              v-model="formData.company_license"
              placeholder="纳税号"
              disabled
            />
          </ElFormItem>

          <ElFormItem label="抬头" prop="invoice_title">
            <ElInput
              disabled
              v-model="formData.invoice_title"
              placeholder="请输入抬头"
            />
          </ElFormItem>

          <ElFormItem label="地址" prop="company_address">
            <ElInput
              v-model="formData.company_address"
              placeholder="请输入地址"
              :disabled="isUpdate"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="联系电话" prop="mobile">
            <ElInput
              placeholder="联系电话"
              v-model="formData.mobile"
              :disabled="isUpdate"
            />
          </ElFormItem>

          <ElFormItem label="银行名称" prop="bank_name">
            <ElInput
              placeholder="银行名称"
              v-model="formData.bank_name"
              :disabled="isUpdate"
            />
          </ElFormItem>

          <ElFormItem label="银行卡号" prop="bankNo">
            <ElInput
              v-model="formData.bankNo"
              placeholder="银行卡号"
              :disabled="isUpdate"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <h1 class="text-xl font-[600] mb-2 text-[#000]">进项票设置</h1>
      <ElFormItem label="进项票设置" prop="input_ticket">
        <ElRadioGroup v-model="formData.input_ticket">
          <ElRadio label="1">金税验票</ElRadio>
          <ElRadio label="2">人工验票</ElRadio>
        </ElRadioGroup>
      </ElFormItem>

      <h1 class="text-xl font-[600] mb-2 text-[#000]">销项票设置</h1>
      <ElRow :gutter="10">
        <ElCol :span="12">
          <ElFormItem label="金税开票" prop="out_ticket">
            <ElRadioGroup v-model="formData.out_ticket">
              <ElRadio label="1">支持</ElRadio>
              <ElRadio label="2">不支持</ElRadio>
            </ElRadioGroup>
          </ElFormItem>

          <ElFormItem label="作废人" prop="voider">
            <ElInput placeholder="请输入作废人" v-model="formData.voider" />
          </ElFormItem>

          <ElFormItem label="开票人" prop="drawer">
            <ElInput placeholder="请输入开票人" v-model="formData.drawer" />
          </ElFormItem>

          <ElFormItem label="收款人" prop="payee">
            <ElInput placeholder="请输入收款人" v-model="formData.payee" />
          </ElFormItem>

          <ElFormItem label="复核人" prop="reviewer">
            <ElInput placeholder="请输入复核人" v-model="formData.reviewer" />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="发票归属地" prop="ownerPlace">
            <ElInput
              placeholder="请选择发票归属地"
              v-model="formData.ownerPlace"
            />
          </ElFormItem>

          <ElFormItem label="发票面额" prop="denomination">
            <UnitInput
              unit="万元"
              placeholder="请输入发票面额"
              v-model="formData.denomination"
            />
          </ElFormItem>

          <ElFormItem label="支持发票类型" prop="invoiceType">
            <ElCheckboxGroup v-model="formData.invoiceType">
              <template v-for="inv in xs_inv_type_list" :key="inv.value">
                <ElCheckbox :label="inv.value">{{ inv.label }}</ElCheckbox>
                <br />
              </template>
            </ElCheckboxGroup>
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElFormItem>
        <div class="flex w-full justify-end">
          <ElButton type="取消" @click="() => (visible = false)">取消</ElButton>
          <ElButton
            :loading="loading || _loading"
            type="primary"
            @click="() => handleSave()"
            >保存</ElButton
          >
        </div>
      </ElFormItem>
    </ElForm>
  </ElDialog>
</template>
