<script setup lang="ts">
import { ref, watchEffect, unref } from "vue";
import { ElForm, ElMessage } from "element-plus";
import { projectFormConfig } from "../config/_details";
import { projectFormRules } from "../config/_rules";
import { httpCateDetail } from "/@/api/operate/setComGood";
import { BasicForm } from "/@/components/BasicForm";
import LadderModal from "./ladder-modal.vue";
import LadderTable from "./ladder-table.vue";

import SearchTerrace from "/@/components/SearchTerrace";
import SearchWorkCompany from "/@/components/SearchWorkCompany";
import { transform, createDefaultData } from "/@/components/BasicForm";
import { Customer } from "/@/components/RemoteSelect";
import { AmountInput } from "/@/components/Input";
import { useResponseHandle } from "/@/hooks/useAsync";

const config = {
  name: "project_name",
  platform: "platform_name"
};

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

const props = defineProps<{
  data: Record<string, string>;
  readonly: boolean;
  id?: string;
}>();

const loading = ref(false);
const { formItems } = projectFormConfig;

const responseHandle = useResponseHandle();
const basicFormRef = ref<InstanceType<typeof ElForm>>(null);
const formData = ref<Record<string, any>>(createDefaultData(formItems));
const ladderModalRef = ref<InstanceType<typeof LadderModal>>(null);

function requesetCategoryById(id: string) {
  const transform = ({ cat_name, ...rest }: any) => ({
    ...rest,
    name: cat_name
  });
  return new Promise(resolve => {
    httpCateDetail({ id }).then(({ code, message, data }) => {
      responseHandle({
        code,
        message,
        handler: () => resolve(transform(data))
      });
    });
  });
}

async function ladderTransform(ladder) {
  loading.value = true;
  const { ladder: _ladder } = formData.value;
  const tasks = ladder.cat_info.map(async id => await requesetCategoryById(id));
  ladder.cat_info = await Promise.all(tasks);
  loading.value = false;
  return ladder;
}

async function handlePush(_ladder) {
  const ladder = await ladderTransform(_ladder);
  if (!Array.isArray(formData.value.ladder)) {
    formData.value.ladder = [];
  }
  formData.value.ladder.push(ladder);
}

async function handleUpdate(_ladder, index) {
  const ladder = await ladderTransform(_ladder);
  formData.value.ladder[index] = ladder;
}

function disabledDate(date) {
  return date.getTime() < new Date().getTime() - 86400000;
}

function handleDateChange(prop: string) {
  const { arrtime, endtime } = formData.value;
  const start = new Date(arrtime).valueOf();
  const end = new Date(endtime).valueOf();
  if (start > end) {
    formData.value[prop] = "";
    ElMessage.warning(`竞价截止时间不能大于要求到货时间！`);
  }
}

function handleCreate() {
  basicFormRef.value.validate(isValid => {
    if (!isValid) return;
    const { ladder, ...rest } = unref(formData);
    const transform = ladder => {
      return {
        ...(ladder.good_img ? { good_img: ladder.good_img } : {}),
        ...{
          budget_price: ladder.budget_price,
          good_name: ladder.good_name,
          good_type: ladder.good_type,
          num: ladder.num
        }
      };
    };

    const params = {
      ...rest,
      ladder: ladder.map(transform)
    };

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

watchEffect(() => {
  const { readonly, data } = props;
  if (readonly && !data) {
    return;
  }

  formData.value = transform(formItems, data, config);
});
</script>

<template>
  <ElScrollbar>
    <BasicForm
      ref="basicFormRef"
      v-bind="projectFormConfig"
      :form-data="formData"
      :rules="projectFormRules"
      :disabled="readonly"
      label-width="120px"
    >
      <template #platform>
        <SearchTerrace v-model="formData.platform" placeholder="所属平台" />
      </template>

      <template #companyNo>
        <SearchWorkCompany v-model="formData.companyNo" placeholder="销售方" />
      </template>

      <template #arrtime>
        <ElDatePicker
          v-model="formData.arrtime"
          style="width: 100%"
          :disabled-date="disabledDate"
          @change="e => handleDateChange('arrtime')"
          placeholder="竞价截止时间"
        />
      </template>

      <template #endtime>
        <ElDatePicker
          v-model="formData.endtime"
          style="width: 100%"
          :disabled-date="disabledDate"
          @change="e => handleDateChange('endtime')"
          placeholder="竞价截止时间"
        />
      </template>

      <template #khNo>
        <Customer
          v-model="formData.khNo"
          :companyNo="formData.khNo"
          placeholder="购买方"
        />
      </template>

      <template #budget_total>
        <AmountInput v-model="formData.budget_total" placeholder="项目总预算" />
      </template>

      <template #ladder>
        <LadderTable
          :readonly="readonly"
          :ladder="formData.ladder"
          @choose="() => ladderModalRef.onDisplay()"
          @update="({ data, index }) => ladderModalRef.onDisplay(data, index)"
          @delete="index => formData.ladder.splice(index, 1)"
        />
      </template>

      <template #footer>
        <div class="w-full flex justify-end" v-if="!readonly">
          <ElButton type="primary" @click="handleCreate">保存</ElButton>
        </div>
      </template>
    </BasicForm>

    <LadderModal
      ref="ladderModalRef"
      @update="handleUpdate"
      @push="handlePush"
    />
  </ElScrollbar>
</template>
