<script setup lang="tsx">
import { computed, nextTick, ref, useTemplateRef } from 'vue';
import { NButton, NInputNumber, NSelect } from 'naive-ui';
import dayjs from 'dayjs';
import { fetchGetStoreList, fetchImportLogList } from '@/service/api/xsb-manage/store-info';
// import {
// fetchGetAllChannelList
// fetchImportGoods,
// fetchSetUpChannels
// } from '@/service/api/goods/store-goods';
import { fetchGetDictDataList } from '@/service/api/system-manage';
import {
  // fetchGetAllChannelList,
  fetchGetChannelList,
  fetchGetShopCategories,
  fetchImportGoods,
  fetchProductList,
  fetchReset,
  fetchSetUpChannels
} from '@/service/api/goods-center/store-goods';
import { useAuth } from '@/hooks/business/auth';
import { areAllItemsAllFieldsFilled } from '@/utils/zt';
import { commonExport } from '@/utils/common';
import { useTable } from '@/components/zt/Table/hooks/useTable';
import { useModalFrom } from '@/components/zt/ModalForm/hooks/useModalForm';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { useModal } from '@/components/zt/Modal/hooks/useModal';
// import { businessType } from '../../order-manage/normal-order/normal-order';
type Price = { channelId: number | undefined; channelProdPrice: number; id: number; channelName?: string };
const importTemplateRef = useTemplateRef('importTemplateRef');
const loading = ref(false);

const options = ref<Api.goods.Channel[]>([]);
const typeOptions = ref([]);
const loadingCategories = ref(false);
// const TypeName = ['企业用户', 'B端用户', 'C端用户'];
const statusList = ['商家下架', '上架', '违规下架', '平台审核'];
const businessType = ref<Record<string, string>>({});
const failColumns: NaiveUI.TableColumn<Api.government.PointsFailureRecordVO>[] = [
  {
    key: 'index',
    title: '序号',
    align: 'center',
    width: 80,
    render(_, rowIndex) {
      return rowIndex + 1;
    }
  },
  {
    key: 'name',
    title: '任务名称',
    align: 'center'
  },
  {
    key: 'createTime',
    title: '时间',
    align: 'center',
    width: 300,
    render(row) {
      return (
        <div>
          <div>创建时间：{row.createTime}</div>
          <div>完成时间：{row.createTime}</div>
        </div>
      );
    }
  },
  {
    key: 'totalUserCount',
    title: '操作人',
    align: 'center',
    width: 120,
    render(row) {
      return (
        <div>
          <div>{row.createByRole}</div>
          <div>({row.createByName})</div>
        </div>
      );
    }
  },
  {
    key: 'successStatus',
    title: '状态',
    align: 'center',
    width: 240,
    render(row) {
      return (
        <div class={'flex items-center'}>
          共{Number(row.recordCount)}条，成功：{row.successCount}，
          <span class={'flex items-center text-red-500'}>
            失败：
            {row.failCount}
            {row.failCount != 0 && (
              <div onClick={() => hanleExportFailure(row.code)}>
                <SvgIcon
                  icon={'tdesign:download'}
                  class={'ml-1 cursor-pointer text-20px'}
                  style={'color:red'}
                ></SvgIcon>
              </div>
            )}
          </span>
        </div>
      );
    }
  }
];
const columns: NaiveUI.TableColumn<Api.goods.ShopSku>[] = [
  {
    type: 'selection',
    align: 'center',
    width: 48,
    fixed: 'left'
  },
  {
    key: 'supId',
    title: '商品ID',
    align: 'left',
    width: 200,
    render: (row: any) => {
      return (
        <div>
          <div>统一ID:</div>
          <div>
            {/* {row.businessType} */}
            {row.supId}
          </div>
          <div>业务系统商品ID：</div>
          <div>{row.hbSkuId}</div>
        </div>
      );
    }
  },
  {
    key: 'skuCode',
    title: '商品编码',
    align: 'center',
    width: 120,
    ellipsis: {
      tooltip: true
    }
  },

  {
    key: 'pic',
    title: '商品图片',
    align: 'center',
    width: 120,
    render: (row: any) => {
      return <n-image src={row.pic} width={60} height={60}></n-image>;
    }
  },

  {
    key: 'prodName',
    title: '商品名称',
    align: 'center',
    width: 120,
    ellipsis: {
      tooltip: true
    }
  },
  {
    key: 'businessType',
    title: '业务类型',
    align: 'center',
    width: 120,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => {
      return <div>{businessType.value[row.businessType] || row.businessType}</div>;
    }
  },
  {
    key: 'shopName',
    title: '商户',
    align: 'center',
    width: 120,
    ellipsis: {
      tooltip: true
    }
  },
  {
    key: 'channelVOS',
    title: '价格',
    align: 'center',
    width: 120,
    render: (row: any) => {
      return (
        <div>
          {row.channelVOS.map((it: Api.government.ChannelVO) => {
            return (
              <div>
                {it.channelName}：￥{it.price}
              </div>
            );
          })}
        </div>
      );
    }
  },
  {
    key: 'shopSkuStocks',
    title: '库存',
    align: 'center',
    width: 120,
    ellipsis: {
      tooltip: true
    }
  },
  {
    key: 'status',
    title: '状态',
    align: 'center',
    width: 120,
    render: (row: any) => {
      return (
        <div class="flex items-center justify-center">
          <n-badge color={row.status == 1 ? 'green' : 'red'} value={row.status} dot />
          <span class="ml-2">{statusList[row.status]}</span>
        </div>
      );
    }
  },
  {
    key: 'updateTime',
    title: '更新时间',
    align: 'center',
    width: 120,
    ellipsis: {
      tooltip: true
    }
  }
];

const PriceColumns: NaiveUI.TableColumn<Price>[] = [
  {
    title: '销售渠道',
    key: 'channelId',
    align: 'center',
    width: 250,
    render: row => {
      return (
        <NSelect
          options={options.value}
          labelField="channelName"
          valueField="id"
          value={row.channelId}
          clearable
          onUpdate:value={value => {
            options.value.map(it => {
              if (it.id == row.channelId) {
                it.disabled = false;
              }
              return it;
            });
            row.channelId = value ? Number(value) : undefined;
            row.channelName = options.value.find(it => it.id == row.channelId)?.channelName;
          }}
          onUpdate:show={value => {
            console.log('show', value);
            options.value.map(it => {
              if (it.id == row.channelId) {
                if (value) {
                  it.disabled = false;
                }
                if (!value) {
                  it.disabled = true;
                }
              }
              return it;
            });
          }}
        ></NSelect>
      );
    }
  },
  {
    title: '售价(元)',
    key: 'channelProdPrice',
    align: 'center',
    width: 250,
    render: row => {
      return (
        <NInputNumber
          value={row.channelProdPrice}
          precision={2}
          onUpdate:value={value => {
            row.channelProdPrice = Number(value);
          }}
          min={0}
        />
      );
    }
  },
  {
    title: () => {
      return (
        <div onClick={() => handleAddPrice()} class={'w-full flex items-center justify-center'}>
          <SvgIcon
            icon={'proicons:add-square'}
            class={'cursor-pointer text-24px'}
            style={'color:var(--n-color)'}
          ></SvgIcon>
        </div>
      );
    },
    key: 'action',
    width: 80,
    align: 'center',
    render: (_row, index) => {
      return (
        <div onClick={() => handleDelPrice(index)} class={'w-full flex items-center justify-center'}>
          <SvgIcon
            icon={'proicons:subtract-square'}
            class={'cursor-pointer text-24px'}
            style={'color:#f5222d'}
          ></SvgIcon>
        </div>
      );
    }
  }
];
const PriceData = ref<Price[]>([]);
const selectData = ref<Api.goods.ShopSku>();
const [registerTable, { getTableCheckedRowKeys, refresh, getTableData, getSeachForm, setTableLoading }] = useTable({
  searchFormConfig: {
    schemas: [
      {
        label: '门店名称',
        component: 'ApiSelect',
        field: 'shopId',
        componentProps: {
          api: fetchGetStoreList,
          resultFeild: 'data.list',
          labelFeild: 'shopName',
          valueFeild: 'shopId'
        }
      },
      {
        label: '关键词',
        component: 'NInput',
        field: 'keywords',
        componentProps: {
          placeholder: '请输入商品名称/海博商品ID'
        }
      },
      {
        label: '业务类型',
        field: 'channelCode',
        component: 'ApiSelect',
        componentProps: {
          api: fetchGetDictDataList,
          labelFeild: 'name',
          valueFeild: 'value',
          resultFeild: 'data.list',
          params: {
            typeCode: 'sys_business_type'
          }
        }
      },
      {
        label: '状态',
        field: 'status',
        component: 'NSelect',
        componentProps: {
          options: [
            {
              label: '上架',
              value: 1
            },
            {
              label: '商家下架',
              value: 0
            },
            {
              label: '违规下架',
              value: 2
            },
            {
              label: '平台审核',
              value: 3
            }
          ]
        }
      },
      // {
      //   label: '分类',
      //   component: 'NCascader',
      //   field: 'skuName',
      //   componentProps: {}
      // },
      {
        label: '更新时间',
        component: 'NDatePicker',
        field: 'createTime',
        componentProps: {
          type: 'datetimerange',
          defaultTime: ['00:00:00', '23:59:59']
        }
      },
      {
        label: '价格范围',
        component: 'NInput',
        field: 'price',
        componentProps: {
          separator: '-',
          pair: true,
          placeholder: ['最低价', '最高价'],
          allowInput: (value: string) => !value || /^\d+$/.test(value)
        }
      },
      {
        label: '海博商品ID',
        component: 'NInput',
        field: 'hbSkuId'
      },
      {
        label: '商品编码',
        component: 'NInput',
        field: 'skuCode'
      }
    ],
    inline: false,
    size: 'small',
    labelPlacement: 'left',
    isFull: false
  },
  tableConfig: {
    keyField: 'skuId',
    title: '商品列表',
    showAddButton: false,
    scrollX: 1800,
    fieldMapToTime: [
      ['price', ['minPrice', 'maxPrice']],
      ['createTime', ['startTime', 'endTime']]
    ]
  }
});
const [registerLogTable, { refresh: refreshLog, setTableLoading: setLogTableLoading }] = useTable({
  tableConfig: {
    keyField: 'skuId',
    title: '',
    minHeight: 200,
    showAddButton: false,
    showSearch: false
  }
});

const [
  registerModalPrice,
  { openModal: openPriceModal, setSubLoading: setSubModalLoding, closeModal: closePriceModal }
] = useModal({
  title: '设置渠道及价格',
  width: 800,
  height: 300
});

const [registerModalFail, { openModal: openModalFail }] = useModal({
  title: '导入记录',
  height: 400,
  width: 1200,
  showFooter: false
});

const [
  registerModalForm,
  {
    openModal: openModalForm,
    setFieldsValue: setModalFormValue,
    getFieldsValue: getModalFormValue,
    closeModal: closeModalForm,
    setSubLoading
  }
] = useModalFrom({
  modalConfig: {
    title: '重置渠道价格',
    isShowHeaderText: false
  },
  formConfig: {
    schemas: [
      {
        label: '门店名称',
        component: 'ApiSelect',
        field: 'shopId',
        required: true,
        componentProps: {
          api: fetchGetStoreList,
          resultFeild: 'data.list',
          labelFeild: 'shopName',
          valueFeild: 'shopId',
          onUpdateValue: e => {
            console.log(e, '门店名称');
            if (e) {
              getShopCategories(e);
            } else {
              typeOptions.value = [];
            }
          }
        }
      },
      {
        field: 'categoryCodes',
        label: '分类',
        component: 'NInput',
        required: true,
        render({ model }) {
          return (
            <div>
              <NSelect
                v-model:value={model.categoryCodes}
                class={'w-400px'}
                multiple
                loading={loadingCategories.value}
                label-field="name"
                value-field="code"
                placeholder="请先选择门店再选择分类"
                options={typeOptions.value}
              />
            </div>
          );
        },
        ifShow({ model }) {
          return model.shopId;
        }
      },
      {
        field: 'channelId',
        component: 'ApiSelect',
        label: '渠道',
        componentProps: {
          api: fetchGetChannelList,
          labelField: 'channelName',
          valueField: 'id',
          clearable: true
        },
        required: true
      }
    ],
    labelWidth: 120,
    layout: 'horizontal',
    gridProps: {
      cols: '1',
      itemResponsive: true
    }
  }
});

const isDisabledExport = computed(() => {
  return !getTableCheckedRowKeys().length;
});
const tableData = computed(() => {
  return getTableData();
});

async function openImportLogModal() {
  openModalFail();
  await nextTick();
  refreshLog();
}

async function hanleExportFailure(code: string) {
  if (loading.value) {
    window.$message?.error('正在导出，请勿重复点击');
    return;
  }
  loading.value = true;
  setLogTableLoading(true);
  try {
    await commonExport('/smqjh-pms/api/v1/channelProdRecord/exportError', { code }, '失败的记录.xlsx');
  } finally {
    loading.value = false;
    setLogTableLoading(false);
  }
}

async function getrDic() {
  const res = (await fetchGetDictDataList({ typeCode: 'sys_business_type' })) as any;
  if (!res.error) {
    res.data.list.forEach((item: any) => {
      businessType.value[item.value] = item.name;
    });
  }
}

getrDic();
async function handleSubmitImport(file: File) {
  const res = await fetchImportGoods({ file });
  console.log(res);

  if (!res.error) {
    importTemplateRef.value?.closeModal();
  }
  window.$message?.success(res.data);
  importTemplateRef.value?.setSubLoading(false);
}
function openImportModal() {
  importTemplateRef.value?.openModal();
}
function handleModalPrice(row: Api.goods.ShopSku) {
  selectData.value = row;

  if (row.channelVOS) {
    PriceData.value = row.channelVOS?.map((it: Api.government.ChannelVO) => {
      options.value.map(its => {
        if (its.id == it.channelId) {
          its.disabled = true;
        }
        return its;
      });

      return {
        channelName: it.channelName,
        channelId: Number(it.channelId),
        channelProdPrice: Number(it.price)
        // id: Number(it.id)
      };
    });
  }

  openPriceModal();
}
function handleAddPrice() {
  // if (PriceData.value.length == 3) {
  //   window.$message?.error('最多只能添加3条数据');
  //   return;
  // }
  PriceData.value.push({
    channelName: '',
    channelId: undefined,
    channelProdPrice: 1,
    id: dayjs().valueOf()
  });
  console.log(PriceData.value);
}
function handleDelPrice(index: number) {
  // PriceData.value = PriceData.value.filter(item => item.id != id);
  PriceData.value.splice(index, 1);
  console.log('删除', index, PriceData.value);
}

async function handleSubmitPrice() {
  // if (!PriceData.value.length) {
  //   window.$message?.error('最少填写一条数据');
  //   return;
  // }
  if (!areAllItemsAllFieldsFilled(PriceData.value)) {
    window.$message?.error('请填写完整数据');
    return;
  }
  setSubModalLoding(true);
  const form = {
    shopId: selectData.value?.shopId,
    skuId: selectData.value?.skuId,
    // purchasePrice: selectData.value?.channelProdList?.length ? selectData.value.channelProdList[0].purchasePrice : null,
    // deliveryPrice: selectData.value?.channelProdList?.length ? selectData.value.channelProdList[0].deliveryPrice : null,
    purchasePrice: selectData.value?.channelVOS?.length ? selectData.value.channelVOS[0].purchasePrice : null,
    deliveryPrice: selectData.value?.channelVOS?.length ? selectData.value.channelVOS[0].deliveryPrice : null,
    setChannelPriceFormList: PriceData.value.map(item => {
      return {
        channelName: item.channelName,
        channelId: item.channelId,
        channelProdPrice: item.channelProdPrice
      };
    })
  };
  const { error } = await fetchSetUpChannels(form);
  if (!error) {
    closePriceModal();
    refresh();
    PriceData.value = [];
    options.value.map(it => (it.disabled = false));
  } else {
    setSubModalLoding(false);
  }
}
async function getData() {
  const { data, error } = await fetchGetChannelList();
  if (!error) {
    options.value = data;
  }
}
getData();

async function getShopCategories(shopId: any) {
  loadingCategories.value = true;
  const { data, error } = await fetchGetShopCategories({ shopId });
  const categoryCodes = data.map((item: any) => item.code);
  setModalFormValue({ categoryCodes });
  loadingCategories.value = false;
  if (!error) {
    typeOptions.value = data;
  }
}

async function handleExport() {
  setTableLoading(true);
  try {
    await commonExport('/smqjh-pms/api/v1/shopSku/export', getSeachForm(), '商品列表.xlsx');
  } finally {
    setTableLoading(false);
  }
}

async function handleSubmit() {
  const form = await getModalFormValue();
  console.log(form, '表单');
  const { error } = await fetchReset(form);
  if (!error) {
    window.$message?.success('保存成功');
  }
  setSubLoading(false);
  closeModalForm();
  refresh();
}
</script>

<template>
  <LayoutTable>
    <ZTable :columns="columns" :api="fetchProductList" @register="registerTable">
      <template #op="{ row }">
        <NButton v-if="row.businessType !== 'JY'" size="small" ghost type="primary" @click="handleModalPrice(row)">
          设置渠道及价格
        </NButton>
      </template>
      <template #prefix="{ loading }">
        <NSpace>
          <NButton v-if="useAuth().hasAuth('goods:reset-btn')" size="small" @click="openModalForm">
            渠道价格重置
          </NButton>
          <NButton size="small" @click="openImportLogModal">导入记录</NButton>
          <NButton size="small" @click="openImportModal">导入商品销售渠道及价格</NButton>
          <NButton size="small" :disabled="tableData.length == 0" :loading="loading" @click="handleExport">
            导出全部
          </NButton>
          <NButton size="small" :disabled="isDisabledExport">导出选中数据</NButton>
          <!-- <NButton size="small">修改记录</NButton> -->
        </NSpace>
      </template>
    </ZTable>
    <ZImportTemplate
      ref="importTemplateRef"
      url="/smqjh-pms/api/v1/channelProd/template/download"
      template-text="商品渠道及价格导入模版.xlsx"
      modal-text="导入商品销售渠道及价格"
      @submit="handleSubmitImport"
    ></ZImportTemplate>
    <BasicModal @register="registerModalPrice" @ok="handleSubmitPrice">
      <NDataTable :columns="PriceColumns" :data="PriceData" :row-key="row => row.channelId" />
    </BasicModal>

    <BasicModal @register="registerModalFail">
      <ZTable
        :columns="failColumns"
        :immediate="false"
        :show-table-action="false"
        :api="fetchImportLogList"
        @register="registerLogTable"
      ></ZTable>
    </BasicModal>

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

<style scoped></style>
