<script setup lang="tsx">
import { ref } from 'vue';
import { NButton, NCollapse, NCollapseItem, NInput, NSelect, NTag, NTimePicker } from 'naive-ui';
import { commonStatus } from '@/constants/business';
import {
  fetchAddShop,
  fetchDelShop,
  fetchEditShop,
  fetchGetAreaList,
  fetchGetShopCity,
  fetchGetStoreList,
  fetchParseAddress
} from '@/service/api/xsb-manage/store-info';
import { useModalFrom } from '@/components/zt/ModalForm/hooks/useModalForm';
import { useTable } from '@/components/zt/Table/hooks/useTable';
import { $t } from '@/locales';
// 定义选项类型
interface AreaOption {
  label: string;
  value: string;
}

const columns: NaiveUI.TableColumn<Api.Store.ShopDetail>[] = [
  {
    key: 'hbStationNo',
    title: '商家门店编码',
    width: 250,
    render: row => {
      return (
        <NCollapse>
          <NCollapseItem title={row.hbStationNo} name={`${row.hbStationId}hbStationNo`}>
            <div class={'ml-6'}>
              联系电话：<span class={'text-gray'}>{row.tel} </span>
            </div>
            <div class={'ml-6'}>
              联系人：<span class={'text-gray'}>{row.shopOwner} </span>
            </div>
            <div class={'ml-6'}>
              门店经度：<span class={'text-gray'}>{row.shopLng} </span>
            </div>
            <div class={'ml-6'}>
              门店维度：<span class={'text-gray'}>{row.shopLat} </span>
            </div>
            {/* <div class={'ml-6'}>
              时段接单量: <span class={'text-gray'}>{row.shopOwner} </span>
            </div> */}
          </NCollapseItem>
        </NCollapse>
      );
    }
  },
  {
    key: 'shopName',
    title: '门店名称',
    align: 'center',
    width: 200
  },
  {
    key: 'address',
    title: '地址',
    align: 'center',
    width: 200,
    render: row => {
      return (
        <div>
          {row.province}
          {row.city}
          {row.shopAddress}
        </div>
      );
    }
  },
  {
    key: 'runStatus',
    title: '经营状态',
    align: 'center',
    render: row => {
      const tagMap: Record<Api.Common.commonStatus, NaiveUI.ThemeColor> = {
        1: 'success',
        0: 'warning'
      };
      const status = row.runStatus || 0;
      const label = $t(commonStatus[status]);
      return <NTag type={tagMap[status]}>{label}</NTag>;
    }
  },
  {
    key: 'shopStatus',
    title: '营业状态',
    align: 'center',
    render: row => {
      const tagMap: Record<Api.Common.commonStatus, NaiveUI.ThemeColor> = {
        1: 'success',
        0: 'error'
      };
      const labelArr = ['停业中', '营业中'];
      const status = row.shopStatus || 0;
      const label = labelArr[status];
      return <NTag type={tagMap[status]}>{label}</NTag>;
    }
  },
  {
    key: 'businessTime',
    title: '营业时间',
    align: 'center',
    width: 200,
    ellipsis: {
      tooltip: true
    }
  },
  {
    key: 'notice',
    title: '门店公告',
    align: 'center',
    render: row => {
      return <div>{row.notice || '--'}</div>;
    }
  }
];
const loading = ref(false);
const [registerTable, { refresh }] = useTable({
  searchFormConfig: {
    schemas: [
      {
        label: '门店名称',
        component: 'NInput',
        field: 'shopName'
      },
      {
        field: 'hbStationNo',
        label: '商家门店编码',
        component: 'NInput'
      },
      {
        field: 'city',
        label: '城市',
        component: 'ApiSelect',
        componentProps: {
          api: fetchGetShopCity,
          labelField: 'city',
          valueField: 'city'
        }
      },
      {
        field: 'runStatus',
        label: '经营状态',
        component: 'NSelect',
        componentProps: {
          options: [
            {
              label: '停业',
              value: 0
            },
            {
              label: '营业',
              value: 1
            }
          ]
        }
      }
    ],
    inline: false,
    size: 'small',
    labelPlacement: 'left',
    isFull: false
  },
  tableConfig: {
    keyField: 'id',
    title: '门店信息',
    opWdith: 160
  }
});

const areaOptions = ref<AreaOption[]>([]);

const businessTimeList = ref<any[]>([
  {
    startTime: '09:00',
    endTime: '18:00'
  }
]);
const [registerModalForm, { openModal, setFieldsValue, getFieldsValue, closeModal, setSubLoading }] = useModalFrom({
  modalConfig: {
    title: '门店',
    isShowHeaderText: true
  },
  formConfig: {
    schemas: [
      {
        field: 'shopId',
        component: 'NInput',
        label: 'shopId',
        show: false
      },

      {
        field: 'shopName',
        component: 'NInput',
        label: '门店名称',
        required: true
      },
      {
        field: 'shopLogo',
        component: 'zUpload',
        label: '封面图标',
        required: true,
        componentProps: {
          max: 1
        }
      },
      {
        label: '所属区域',
        field: 'area',
        required: true,
        component: 'NSelect',
        componentProps: {
          options: areaOptions.value,
          remote: true,
          filterable: true
        },
        render: ({ model }) => {
          return (
            <NSelect
              v-model:value={model.area}
              filterable
              placeholder=""
              options={areaOptions.value}
              clearable
              remote
            />
          );
        }
      },
      {
        field: 'shopAddress',
        component: 'NInput',
        label: '详细地址',
        required: true
      },
      {
        field: 'shopLng',
        component: 'NInput',
        label: '详细地址',
        required: true,
        show: false
      },
      {
        field: 'shopLat',
        label: '门店坐标',
        component: 'NInput',
        render: ({ model }) => {
          return (
            <div class={'flex items-center'}>
              <NInput v-model:value={model.shopLat} />
              <NInput class={'ml-10px'} v-model:value={model.shopLng} />
              <NButton class={'ml-10px'} text onClick={() => handleReverves()}>
                按地址生成
              </NButton>
            </div>
          );
        }
      },
      {
        field: 'tel',
        component: 'NInput',
        label: '客服电话',
        required: true
      },
      {
        field: 'runStatus',
        component: 'NSwitch',
        label: '经营状态',
        defaultValue: 1,
        required: true,
        componentProps: {
          checkedValue: 1,
          uncheckedValue: 0
        }
      },
      {
        field: 'businessTime',
        component: 'NInput',
        label: '营业时间',
        render: _row => {
          return (
            <div>
              {businessTimeList?.value.map((item: any, index) => {
                return (
                  <div class={'flex items-center'}>
                    <NTimePicker v-model:formatted-value={item.startTime} format="HH:mm" value-format="HH:mm" />
                    至
                    <NTimePicker v-model:formatted-value={item.endTime} format="HH:mm" value-format="HH:mm" />
                    <NButton class={'ml-10px'} type="primary" text onClick={() => addBusinessTime()}>
                      添加
                    </NButton>
                    <NButton class={'ml-10px'} text type="primary" onClick={() => removeBusinessTime(index)}>
                      删除
                    </NButton>
                  </div>
                );
              })}
            </div>
          );
        }
      }
    ],
    labelWidth: 120,
    layout: 'horizontal',
    gridProps: {
      cols: '1',
      itemResponsive: true
    }
  }
});

async function handleReverves() {
  const form = await getFieldsValue();
  if (!form.area || !form.shopAddress) {
    window.$message?.error('请先选择区域和地址');
    return;
  }
  if (loading.value) return;
  loading.value = true;
  const res = await fetchParseAddress({ address: form.area + form.shopAddress });
  loading.value = false;
  console.log(res);

  if (res.data.result) {
    setFieldsValue({ shopLat: res.data.result.location.lat, shopLng: res.data.result.location.lng });
  } else {
    window.$message?.error('请输入正确的地址');
  }
}
async function getArea() {
  const res = await fetchGetAreaList({});
  areaOptions.value =
    res.data?.map((item: any) => {
      return {
        label: item,
        value: item
      };
    }) || [];

  console.log(11111111, areaOptions.value);
}
getArea();
function addBusinessTime() {
  if (businessTimeList.value.length >= 3) {
    window.$message?.error('最多只能添加3条数据');
    return;
  }
  businessTimeList.value.push({
    startTime: '00:00',
    endTime: '23:00'
  });
}

function removeBusinessTime(index: number) {
  if (businessTimeList.value.length <= 1) return;
  businessTimeList.value.splice(index, 1);
}

function handleAdd() {
  openModal();
}
function handleEdit(record: any) {
  openModal(record);
  setFieldsValue(record);
  if (record.businessTime) {
    businessTimeList.value = record.businessTime.split(',');
    businessTimeList.value = businessTimeList.value.map((item: any) => {
      const time = item.split('-');
      return {
        startTime: time[0],
        endTime: time[1]
      };
    });
  }
}
function handleDelete(row: any) {
  window.$dialog?.info({
    title: '提示',
    content: `你确定要删除吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { error } = await fetchDelShop(row.shopId as string);
      if (!error) {
        refresh();
      }
    }
  });
}
async function handleSubmit() {
  const form = await getFieldsValue();
  setSubLoading(true);
  const businessTime: string[] = [];
  businessTimeList.value.forEach(i => {
    const item = `${i.startTime}-${i.endTime}`;
    businessTime.push(item);
  });
  form.businessTime = businessTime.join();
  form.province = form.area.split('-')[0];
  form.city = form.area.split('-')[1];
  console.log(form, '表单');
  let res;
  if (!form.shopId) {
    res = await fetchAddShop(form);
  } else {
    res = await fetchEditShop(form);
  }
  setSubLoading(false);

  if (res.response.data.code === '00000') {
    closeModal();
    refresh();
  }
}
</script>

<template>
  <LayoutTable>
    <ZTable :columns="columns" :api="fetchGetStoreList" @add="handleAdd" @register="registerTable">
      <template #op="{ row }">
        <NSpace v-if="row.isOperable">
          <NButton type="primary" ghost size="small" @click="handleEdit(row)">编辑</NButton>
          <NButton type="error" ghost size="small" @click="handleDelete(row)">删除</NButton>
        </NSpace>
      </template>
    </ZTable>

    <BasicModelForm @register-modal-form="registerModalForm" @submit-form="handleSubmit"></BasicModelForm>
  </LayoutTable>
</template>

<style scoped></style>
