<script setup lang="ts">
import { computed, nextTick, ref } from "vue";
import { ElForm, ElMessage } from "element-plus";
import { ModalTypes } from "/@/modules/modal";
import { useAsync } from "/@/hooks/core/useAsync";
import { useCompany } from "/@/hooks/core/useCompany";

import Platform from "./components/platform.vue";
import Company from "./components/company.vue";
import Customer from "./components/customer.vue";
import Supplier from "./components/supplier.vue";
import Category from "./components/category.vue";
import SaleUser from "./components/sale-user.vue";
import User from "./components/user.vue";

import {
  httpCreate,
  httpDetail,
  httpRatelist,
  httpUpdate
} from "/@/api/netOrderEnter/netOrderEntry";

import {
  defaultData,
  formRules,
  purchaseDepartOptions,
  saleDepartOptions
} from "./config/_options";

const emit = defineEmits(["reload"]);

const visible = ref(false);
const loading = ref(false);
const modalType = ref<ModalTypes>(ModalTypes.create);
const customerRef = ref<InstanceType<typeof Customer> | null>(null);
const supplierRef = ref<InstanceType<typeof Supplier> | null>(null);
const companyRef = ref<InstanceType<typeof Company> | null>(null);
const saleUserRef = ref<InstanceType<typeof User> | null>(null);
const buyerUserRef = ref<InstanceType<typeof User> | null>(null);
const categoryRef = ref<InstanceType<typeof Category> | null>(null);

const disabledDate = (time: Date) => time.getTime() > new Date().valueOf();

const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const formData = ref<Record<string, any>>({ ...defaultData });

const { currentCompany } = useCompany();

function onSuccess() {
  visible.value = false;
  emit("reload");
}

async function onRequestDetailSuccess(data: Record<string, string>) {
  const keys = Object.keys(data);
  const numberField = ["goodNum", "goodPrice", "cgd_tax"];

  keys.forEach(key => {
    formData.value[key] = numberField.includes(key)
      ? Number(data[key])
      : data[key];
  });

  const { companyNo, supplierNo, khNo, cat, sale_name, buyer } = formData.value;
  formData.value.platform_id = Number(formData.value.platform_id);

  const _cat = cat ? cat[cat.length - 1].id : "";
  formData.value.cat = _cat;
  await requsetRatelist();

  //回显数据
  companyRef.value.initalData({ companyNo });
  supplierRef.value.initalData({ companyNo: supplierNo });
  customerRef.value.initalData({ companyNo: khNo });
  categoryRef.value.initalData({ cat: _cat });

  await nextTick(() => {
    buyerUserRef.value.initalData({ nickname: buyer, companyNo });
    saleUserRef.value.initalData({ nickname: sale_name, companyNo });
  });
}

function onRequestRateSuccess(data: Array<Record<string, string>>) {
  const { tax } = formData.value;
  if (!data || !tax) return null;
  formData.value.tax = data.find(({ rate }) => rate === tax)?.id;
}

const {
  data: ratelist,
  run: runRatelist,
  loading: rateLoading
} = useAsync<Array<Record<string, any>>>({
  isList: false,
  initalData: [],
  success: data => onRequestRateSuccess(data)
});

const { run: runCreate, loading: createLoading } = useAsync({
  success: () => onSuccess()
});

const { run: runUpdate, loading: updateLoading } = useAsync({
  success: () => onSuccess()
});

const { run: runDetail, loading: detailLoading } = useAsync({
  initalData: {},
  success: data => onRequestDetailSuccess(data)
});

const title = computed(() => {
  const baseTitle = "销售订单";
  const isPreview = modalType.value === ModalTypes.preview;
  const isCreate = modalType.value === ModalTypes.create;
  if (isPreview) return `${baseTitle}详情`;
  return `${isCreate ? "创建" : "修改"}${baseTitle}`;
});

function handleUserChange(
  data: Record<string, string>,
  key: "sale_name" | "buyer"
) {
  if (!data) return null;
  const { nickname } = data;
  formData.value[key] = nickname;
}

const dialogloading = computed(() => rateLoading.value || detailLoading.value);
const actionLoading = computed(
  () => createLoading.value || updateLoading.value
);

const total = computed(() => {
  const { goodNum, goodPrice } = formData.value;
  return (Number(goodNum) * Number(goodPrice)).toFixed(2);
});

const requsetRatelist = () => runRatelist(httpRatelist());
const requsetCreateQrd = data => runCreate(httpCreate(data));
const requsetUpdateQrd = data => runUpdate(httpUpdate(data));
const requsetQrdDetail = data => runDetail(httpDetail(data));

function handleConfirm() {
  const { sale_id, buyerid, companyNo, supplierNo } = formData.value;

  if (sale_id === buyerid && sale_id && buyerid) {
    ElMessage.warning("采购员和销售员不能相同");
    return;
  }

  if (companyNo === supplierNo) {
    ElMessage.warning("销售方公司和供应商公司不能相同");
    return;
  }

  formRef.value.validate(isValid => {
    if (!isValid) return null;

    const isUpdate =
      modalType.value === ModalTypes.update ||
      modalType.value === ModalTypes.proUpdate;

    const requsetFunc = isUpdate ? requsetUpdateQrd : requsetCreateQrd;
    requsetFunc(formData.value);
  });
}

function onDisplay(_modalType: ModalTypes, id?: string) {
  const isUpdateOrPriview =
    _modalType === ModalTypes.update ||
    _modalType === ModalTypes.proUpdate ||
    _modalType === ModalTypes.preview;

  modalType.value = _modalType;
  visible.value = true;

  if (!isUpdateOrPriview && !currentCompany.value.companyNo) {
    ElMessage.warning("请在右上角选择一家公司");
    return;
  }

  if (isUpdateOrPriview) {
    requsetQrdDetail({ id });
    return;
  }

  requsetRatelist();
  formData.value.companyNo = currentCompany.value.companyNo;
  nextTick(() =>
    companyRef.value.initalData({ companyNo: currentCompany.value.companyNo })
  );
}

defineExpose({ onDisplay });
</script>

<template>
  <ElDialog
    v-model="visible"
    :title="title"
    destroy-on-close
    width="1040px"
    top="10vh"
    center
    @close="() => (formData = { ...defaultData })"
    :close-on-click-modal="false"
  >
    <ElForm
      v-loading="dialogloading"
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="70px"
      :disabled="modalType === ModalTypes.preview"
    >
      <ElRow :gutter="10">
        <ElCol :span="24" style="padding: 0 0 10px 0; margin-top: -5px">
          <ElDivider><ElTag>销售订单信息</ElTag></ElDivider>
        </ElCol>

        <ElCol :span="8">
          <ElFormItem label="所属平台" label-width="85px" prop="platform_id">
            <Platform
              :visible="visible"
              v-model="formData.platform_id"
              placeholder="所属平台"
              maxlength="200"
            />
          </ElFormItem>
        </ElCol>

        <!-- <ElCol :span="8">
          <ElFormItem label="销售员部门" prop="sale_depart">
            <ElSelect style="width: 100%" v-model="formData.sale_depart">
              <ElOption
                v-for="(deparment, index) in saleDepartOptions"
                :label="deparment.value"
                :value="deparment.value"
                :disabled="deparment.status !== '1'"
                :key="index"
              />
            </ElSelect>
          </ElFormItem>
        </ElCol> -->

        <ElCol :span="6">
          <ElFormItem label="采购毛利率" label-width="95px" prop="cgd_tax">
            <ElInputNumber
              v-model="formData.cgd_tax"
              style="width: 100%"
              controls-position="right"
              placeholder="采购毛利率"
              step-strictly
              :min="0"
              :precision="2"
              :step="0.01"
              :max="100"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="5">
          <ElFormItem label="销售员" prop="sale_id">
            <SaleUser
              ref="saleUserRef"
              :companyNo="formData.companyNo"
              v-model="formData.sale_id"
              @item-change="handleUserChange($event, 'sale_name')"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="5">
          <ElFormItem label="采购员" prop="buyerid">
            <User
              ref="buyerUserRef"
              v-model="formData.buyerid"
              :companyNo="formData.companyNo"
              @item-change="handleUserChange($event, 'buyer')"
            />
          </ElFormItem>
        </ElCol>

        <!-- <ElCol :span="8">
          <ElFormItem label="采购员部门" prop="cgd_depart">
            <ElSelect style="width: 100%" v-model="formData.cgd_depart">
              <ElOption
                v-for="(deparment, index) in purchaseDepartOptions"
                :label="deparment.value"
                :value="deparment.value"
                :disabled="deparment.status !== '1'"
                :key="index"
              />
            </ElSelect>
          </ElFormItem>
        </ElCol> -->

        <ElCol :span="12">
          <ElFormItem label="单据号" prop="workCode">
            <ElInput
              v-model="formData.workCode"
              placeholder="单据号"
              maxlength="200"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="平台订单编码" prop="poCode" label-width="110px">
            <ElInput
              v-model="formData.poCode"
              placeholder="平台订单编码"
              maxlength="200"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="购买方公司" prop="khNo" label-width="95px">
            <Customer ref="customerRef" v-model="formData.khNo" />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="销售方公司" prop="companyNo" label-width="95px">
            <Company
              ref="companyRef"
              v-model="formData.companyNo"
              :disabled="modalType !== ModalTypes.proUpdate"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="24" style="padding: 0 0 10px 0; margin-top: -5px">
          <ElDivider><ElTag>收货信息</ElTag></ElDivider>
        </ElCol>

        <ElCol :span="8">
          <ElFormItem label="收货人" prop="contactor">
            <ElInput
              v-model="formData.contactor"
              placeholder="收货人"
              maxlength="200"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="8">
          <ElFormItem label="联系电话" prop="mobile" label-width="80px">
            <ElInput
              v-model="formData.mobile"
              placeholder="联系电话"
              maxlength="11"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="发货时间" prop="sendtime" label-width="80px">
            <ElDatePicker
              v-model="formData.sendtime"
              :disabled-date="disabledDate"
              :editable="false"
              :clearable="true"
              placeholder="发货时间"
              style="width: 100%; margin: 0"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="24">
          <ElFormItem label="联系地址" prop="addr" label-width="80px">
            <ElInput
              v-model="formData.addr"
              placeholder="联系地址"
              maxlength="200"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="24" style="padding: 0 0 10px 0; margin-top: -5px">
          <ElDivider><ElTag>商品信息</ElTag></ElDivider>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="供应商公司" prop="supplierNo" label-width="95px">
            <Supplier ref="supplierRef" v-model="formData.supplierNo" />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="商品分类" prop="cat" label-width="80px">
            <Category
              v-model="formData.cat"
              style="width: 100%"
              ref="categoryRef"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="商品名称" prop="goodName" label-width="80px">
            <ElInput
              v-model="formData.goodName"
              placeholder="商品名称"
              maxlength="200"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="6">
          <ElFormItem label="数量" prop="goodNum">
            <ElInputNumber
              v-model="formData.goodNum"
              style="width: 100%"
              controls-position="right"
              placeholder="数量"
              :min="0"
              :precision="0"
              step-strictly
              :step="1"
              :max="9999999"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="6">
          <ElFormItem label="单价" label-width="55px" prop="goodPrice">
            <ElInputNumber
              v-model="formData.goodPrice"
              controls-position="right"
              placeholder="单价"
              style="width: 100%"
              :min="0"
              :precision="2"
              step-strictly
              :step="0.01"
              :max="9999999"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="6">
          <ElFormItem label="货款总额">
            <ElInput :value="total" placeholder="货款总额" disabled>
              <template #append>元</template>
            </ElInput>
          </ElFormItem>
        </ElCol>
        <ElCol :span="6">
          <ElFormItem label="税率" prop="tax">
            <ElSelect style="width: 100%" v-model="formData.tax">
              <ElOption
                v-for="rate in ratelist"
                :key="rate.id"
                :label="rate.rate + '%'"
                :value="rate.id"
              />
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12" style="text-align: right; padding: 5px 0 0 0">
          <ElButton
            type="primary"
            @click="handleConfirm"
            :loading="actionLoading || loading"
            >保存</ElButton
          >
          <ElButton @click="() => (visible = false)">关闭</ElButton>
        </ElCol>
      </ElRow>
    </ElForm>
  </ElDialog>
</template>
