<script setup lang="tsx">
import { ref } from 'vue';
import { NDynamicInput, NInputNumber, NSelect } from 'naive-ui';
import { fetchGetAllChannelList } from '@/service/api/goods/store-goods';
import { fetchChannelList, fetchGetAddOrEditTransport, fetchGetTransport } from '@/service/api/common';
import { useTabStore } from '@/store/modules/tab';
import { useForm } from '@/components/zt/Form/hooks/useForm';
const isSubmit = ref(false);
const tabStore = useTabStore();
interface Options {
  value: any;
  index: number;
}
const ChannelOptions = ref<Api.goods.Channel[]>([]);
const [registerForm, { getFieldsValue, validate, setFieldsValue }] = useForm({
  schemas: [
    {
      field: 'id',
      component: 'NInput',
      label: 'false',
      show: false
    },
    {
      field: 'name',
      component: 'NDynamicInput',
      label: '配送费/运费',
      render({ model, field }) {
        return (
          <div class={'flex flex-wrap items-center'}>
            <div class={'h38px flex items-center'}>
              <div class={'w-200px text-center'}> 企业 </div>
              <div class={'ml-3 w-200px text-center'}> 费用(元) </div>
              <div class={'ml-3 w-200px text-center'}> 重量(kg) </div>
              <div class={'ml-3 w-200px text-center'}> 分单(km) </div>
            </div>
            <NDynamicInput
              value={model[field]}
              onUpdate:value={value => (model[field] = value)}
              v-slots={(row: Options) => handleCreatInput(model, field, row)}
              onCreate={() => handleAdd()}
              max={ChannelOptions.value.length}
            ></NDynamicInput>
          </div>
        );
      },
      required: true,
      defaultValue: []
    }
  ],
  labelWidth: 120,
  layout: 'horizontal',
  collapsedRows: 1,
  showActionButtonGroup: false,
  gridProps: {
    cols: '1',
    itemResponsive: true
  }
});
function handleCreatInput(model: any, field: any, row: Options) {
  return (
    <div class={'flex items-center'}>
      <div class={'w-200px'}>
        <NSelect
          value={model[field][row.index].channelId}
          labelField="channelName"
          valueField="id"
          options={ChannelOptions.value}
          onUpdate:value={vlaue => {
            ChannelOptions.value.map(it => {
              if (it.id == model[field][row.index].channelId) {
                it.disabled = false;
              }
              return it;
            });
            model[field][row.index].channelId = vlaue ? Number(vlaue) : undefined;
            handleGetChannelId(vlaue, row.index);
          }}
          onUpdate:show={value => {
            ChannelOptions.value.map(it => {
              if (it.id == model[field][row.index].channelId) {
                if (value) {
                  it.disabled = false;
                }
                if (!value) {
                  it.disabled = true;
                }
              }
              return it;
            });
          }}
        ></NSelect>
      </div>
      <div class={'ml-3 w-200px'}>
        <NInputNumber
          value={model[field][row.index].freightFee}
          min={1}
          onUpdate:value={value => {
            model[field][row.index].freightFee = value;
          }}
        ></NInputNumber>
      </div>
      <div class={'ml-3 w-200px'}>
        <NInputNumber
          value={model[field][row.index].weight}
          min={1}
          onUpdate:value={value => {
            model[field][row.index].weight = value;
          }}
          v-slots={{ prefix: () => '每', suffix: () => 'Kg' }}
        ></NInputNumber>
      </div>
      <div class={'ml-3 w-200px'}>
        <NInputNumber
          placeholder={'请输入配送距离'}
          value={model[field][row.index].distance}
          onUpdate:value={val => (model[field][row.index].distance = val)}
          v-slots={{ prefix: () => '大于', suffix: () => 'km' }}
        ></NInputNumber>
      </div>
    </div>
  );
}
function close() {
  tabStore.removeTab(tabStore.activeTabId);
}

async function getChannelList() {
  const { data } = await fetchGetAllChannelList();
  if (!data) return;
  ChannelOptions.value = data;
}
getChannelList();

async function getData() {
  const { data } = await fetchChannelList();
  if (data) {
    setFieldsValue({ name: data.records });
  }
}
getData();
function handleAdd() {
  return {
    channelId: null,
    freightFee: 1,
    distance: null,
    weight: 10
  };
}

async function save() {
  await validate();
  isSubmit.value = true;
  const form = getFieldsValue();
  await fetchGetAddOrEditTransport(form);
  isSubmit.value = false;
  getData();
}
async function handleGetChannelId(channelId: number, idx: number) {
  const res = await fetchGetTransport(channelId);
  const form = getFieldsValue();
  const newName = JSON.parse(JSON.stringify(form.name));
  newName[idx].distance = res.data?.distance;
  newName[idx].freightFee = res.data?.freightFee;
  newName[idx].weight = res.data?.weight;
  setFieldsValue({ name: newName });
}
</script>

<template>
  <LayoutTable>
    <NCard title="配送费&运费配置" :bordered="false" size="small" segmented class="card-wrapper">
      <NScrollbar x-scrollable>
        <BasicForm @register-form="registerForm"></BasicForm>
      </NScrollbar>
      <template #footer>
        <NSpace justify="end">
          <NButton size="small" @click="close">关闭</NButton>
          <NButton type="primary" size="small" :loading="isSubmit" @click="save">保存</NButton>
        </NSpace>
      </template>
    </NCard>
  </LayoutTable>
</template>

<style scoped></style>
