<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,
  fetchBatchOrderSplit,
  fetchOrderSplitList
} 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 openOptions = ref([
  { label: '是', value: 1 },
  { label: '否', value: 0 }
]);
const [registerForm, { getFieldsValue, validate, setFieldsValue }] = useForm({
  schemas: [
    {
      field: 'transportId',
      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={'ml-3 w-200px text-center'}> 是否启用</div>
              <div class={'w-200px text-center'}> 企业 </div>
              <div class={'ml-3 w-200px text-center'}> 重量(kg) </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}
              onRemove={handleRemove}
            ></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].autoSplit}
          options={openOptions.value}
          onUpdate:value={vlaue => {
            model[field][row.index].autoSplit = vlaue ? Number(vlaue) : undefined;
          }}
        ></NSelect>
      </div>
      <div class={'ml-3 w-200px'}>
        <NSelect
          value={model[field][row.index].id}
          labelField="channelName"
          valueField="id"
          options={ChannelOptions.value}
          onUpdate:value={vlaue => {
            ChannelOptions.value.map(it => {
              if (it.id == model[field][row.index].id) {
                it.disabled = false;
              }
              return it;
            });
            model[field][row.index].id = vlaue ? Number(vlaue) : undefined;
          }}
          onUpdate:show={value => {
            ChannelOptions.value.map(it => {
              if (it.id == model[field][row.index].id) {
                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].splitWeight}
          min={1}
          onUpdate:value={value => {
            model[field][row.index].splitWeight = value;
          }}
          v-slots={{ prefix: () => '每', suffix: () => 'Kg' }}
        ></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 fetchOrderSplitList({ splitRule: 1 });
  if (data) {
    setFieldsValue({
      name: data.map(it => {
        return {
          id: it.id,
          autoSplit: it.autoSplit,
          splitWeight: it.splitWeight,
          splitRule: it.splitRule
        };
      })
    });
    const dataKey = data.map(it => it.channelId);
    ChannelOptions.value.map(it => {
      if (dataKey.includes(Number(it.id))) {
        it.disabled = true;
      }
      return it;
    });
  }
}
getData();
function handleAdd() {
  return {
    id: null,
    autoSplit: null,
    splitWeight: null,
    splitRule: 1
  };
}

async function save() {
  await validate();
  isSubmit.value = true;
  const form = getFieldsValue();
  console.log(form);

  await fetchBatchOrderSplit(1, form.name);
  isSubmit.value = false;
  window.$message?.success('保存成功');
  getData();
}
function handleRemove() {
  const form = getFieldsValue();
  return console.log(form);
}
// async function handleGetChannelId(channelId: number, idx: number) {
//   const res = await fetchGetTransport(channelId);
//   console.log(res);

//   const form = getFieldsValue();
//   const newName = JSON.parse(JSON.stringify(form.name));
//   newName[idx].distance = res.data?.distance || null;
//   newName[idx].freightFee = res.data?.freightFee || null;
//   newName[idx].weight = res.data?.weight || null;
//   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>
