<template>
  <div class="user-page flex-column card h-100 overflow-hidden">
    <div class="header-filter-form">
      <SearchForm
        :callback="search"
        v-model="searchForm"
        :config="searchConfig"
        @search="search"
        @add="addDialog"
        @delete="deleteFn"
      ></SearchForm>
    </div>
    <div class="user-content flex-1 flex-column overflow-hidden">
      <div v-loading="loading" class="user-list flex-1 overflow-hidden">
        <CustomizeTable
          v-model="tableData"
          :config="tableConfig"
          @get-checkbox-records="handleCheckboxRecords"
        ></CustomizeTable>
      </div>
      <ElPagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[100, 200, 300, 400, 500]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin: 10px auto 0; text-align: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></ElPagination>
    </div>
  </div>

  <LogDialog
    v-model="dialogVisible"
    :title="editForm.id ? '编辑物流方式' : '新增物流方式'"
    dialog-width="1000px"
    @close="cancelFn"
  >
    <CustomizeForm
      ref="editFormRef"
      v-model="editForm"
      :config="formConfig"
      form-item-width="100%"
      label-width="110"
    >
    </CustomizeForm>

    <template #footer>
      <div style="text-align: center">
        <ElButton @click="cancelFn">取消</ElButton>

        <ElButton type="primary" @click="save">保存</ElButton>
      </div>
    </template>
  </LogDialog>
  <LogDialog
    v-model="logDialogVisible"
    title="操作日志"
    @close="logDialogVisible = false"
  >
    <div v-for="item in logList" :key="item.id" style="margin-bottom: 8px">
      <span style="margin-right: 10px">{{ item.createTime }}</span>
      <span>{{ item.description }}</span>
    </div>
  </LogDialog>
</template>

<script setup lang="tsx">
defineOptions({
  name: 'LogisticsMethod',
})
import LogisticsWaySelect from './components/LogisticsWaySelect.tsx'
import {
  getLogisticsWayList,
  addLogisticsWay,
  updateLogisticsWay,
  updateStatusLogisticsWay,
  deleteLogisticsWay,
  getRuleList,
  getPlatformList,
  getLogisticsLog,
  getLogisticsCompanyList,
  getUniuniList,
  getTiktokCarrier,
} from '@/api/logistics'
import type { FormItemRule } from 'element-plus'
import { WarehouseListData } from '@/types'
import { ISeachFormConfig } from '@/types/searchType'
import { TableColumn } from '@/components/VxeTable'
import { loadWarehouseListApi } from '@/api/common'
import type {
  LogisticsMethod,
  platformObj,
} from '@/views/logistics/types/logistics.ts'
import SearchForm from '@/components/SearchForm.tsx'
import LogDialog from './components/LogDialog.tsx'
import CustomizeForm from '@/components/CustomizeForm.tsx'
import CustomizeTable from '@/components/VxeTable.tsx'
import { IFormConfig } from '@/components/CustomizeForm.tsx'
import usePageList from '@/utils/hooks/usePageList'
import { useValue } from './hooks/useValue'
import { showConfirm } from '@/utils/ui'
import { Edit, Delete, List, WarningFilled } from '@element-plus/icons-vue'
import { debounce } from 'lodash-es'
import UPARCELImage from '@/assets/images/UPARCEL物流编码.png'

const [searchForm] = useValue({})
const [editForm, resetEditForm] = useValue<LogisticsMethod>({
  platformList: [
    { platform: '', logisticsName: '', showPlatform: ['default'] },
  ],
  ruleRef: { ruleId: '', ruleName: '' },
  status: 1,
})

const {
  loading,
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh: search,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList({
  query: (page, pageSize) =>
    getLogisticsWayList({
      ...searchForm.value,
      pageSize: pageSize,
      currentPage: page,
    }).then(({ data }) => {
      return data
    }),
})
const dialogVisible = ref(false)
const logDialogVisible = ref(false)
const editFormRef = ref<InstanceType<typeof CustomizeForm> | null>(null)
const selection = ref([])
const warehouseList = ref<WarehouseListData[]>([])

interface ImageList {
  [key: string]: string
}

const imgeList = ref<ImageList>({
  UPARCEL: UPARCELImage,
})
const searchConfig = ref<ISeachFormConfig[]>([
  {
    prop: 'name',
    type: 'input',
    label: '物流方式',

    attrs: {
      clearable: true,
      placeholder: '请输入物流方式',
    },
  },
  {
    prop: 'status',
    type: 'select',
    label: '启用状态',
    attrs: {
      clearable: true,
      placeholder: '请选择启用状态',
      options: [
        { label: '启用', value: 1 },
        { label: '禁用', value: 0 },
      ],
    },
  },
  {
    prop: 'serviceCode',
    type: 'input',
    label: '物流编码',
    attrs: {
      clearable: true,
      placeholder: '请输入物流编码',
    },
  },
])
const platformList = ref([])

const ruleNameList = ref([])
const uniuniList = ref([])
const logisticsCompanyList = ref([])

watch(
  () => JSON.parse(JSON.stringify(editForm.value.platformList)),
  (newValue, oldValue) => {
    if (oldValue.length && newValue.length) {
      // 遍历旧值数组
      oldValue.forEach(
        (
          oldItem: { logisticsName: string; showPlatform: string[] },
          index: number,
        ) => {
          // 检查旧值项是否符合条件
          if (
            oldItem.showPlatform.length === 1 &&
            oldItem.showPlatform[0] === 'TIKTOK' &&
            oldItem.logisticsName
          ) {
            // 获取对应的新值项
            const newItem = newValue[index]

            // 检查新值项是否不再满足条件
            if (
              newItem &&
              (!Array.isArray(newItem.showPlatform) ||
                newItem.showPlatform.length === 0 ||
                !newItem.showPlatform.includes('TIKTOK') ||
                newItem.showPlatform.length > 1)
            ) {
              // 清除 logisticsName
              editForm.value.platformList[index].logisticsName = ''
            }
          }
        },
      )
    }
  },
  { deep: true },
)
const formConfig = computed<IFormConfig[]>(() => [
  { title: '物流基础信息' },
  {
    prop: 'companyId',
    type: 'select',
    label: '物流公司',
    attrs: {
      placeholder: '请选择物流公司',
      label: 'name',
      value: 'id',
      options: [...(logisticsCompanyList.value || [])],
      onChange: (value: {
        code: string
        name: string
        id: string | number
      }) => {
        editForm.value.company = value.name
        if (value.code === 'UINUIN') {
          editFormRef.value?.refashConfig(['uinuinWarehouseId'])
          editFormRef.value?.clearValidate()
        } else if (value.code === 'YW') {
          editFormRef.value?.refashConfig(['companyWarehouseCode'])
          editFormRef.value?.clearValidate()
        } else {
          editFormRef.value?.refashConfig([])
          editFormRef.value?.clearValidate()
          editForm.value.uinuinWarehouseId = null
        }
      },
    },
    rules: [
      {
        required: true,
        message: '请选择物流公司',
      },
    ],
  },
  {
    prop: 'uinuinWarehouseId',
    type: 'select',
    label: 'uniuni仓库',
    isIncludeProp: true,
    attrs: {
      placeholder: '请选择uniuni仓库',
      label: 'warehouseName',
      value: 'warehouseId',
      options: [...(uniuniList.value || [])],
    },
    rules: [
      {
        required: true,
        message: '请选择uniuni仓库',
      },
    ],
  },
  {
    prop: 'companyWarehouseCode',
    type: 'select',
    label: '物流仓库编码',
    isIncludeProp: true,
    attrs: {
      placeholder: '请选择物流仓库编码',
      options: [
        { label: 'LAX01', value: 'LAX01' },
        { label: 'NJC01', value: 'NJC01' },
        { label: 'ORD01', value: 'ORD01' },
        { label: 'MIA01', value: 'MIA01' },
        { label: 'DFW01', value: 'DFW01' },
      ],
    },
    rules: [
      {
        required: true,
        message: '请选择物流仓库编码',
      },
    ],
  },
  {
    prop: 'serviceCode',

    label: '物流编码',
    fixed: 'last',
    render: () => {
      const company = editForm.value.company
      return (
        <div style="display: flex; width:100%;height: 100%">
          <el-input
            v-model={editForm.value.serviceCode}
            placeholder="请输入物流编码"
          />
          <el-popover
            placement="bottom-end"
            width={1050}
            v-slots={{
              default: () => (
                <div style="width: 100%; height: 100%;">
                  <div style="font-size: 20px; font-weight: bold;margin-bottom: 10px;">
                    {company ? `${company}物流编码来源图:` : '请先选择物流公司'}
                  </div>
                  {company && imgeList.value[company] && (
                    <img
                      src={imgeList.value[company]}
                      style={{ width: '100%' }}
                      alt={`${company}物流编码图`}
                    />
                  )}
                </div>
              ),
              reference: () => (
                <el-icon
                  style={{ marginLeft: '10px', height: '100%' }}
                  size={25}
                >
                  <WarningFilled />
                </el-icon>
              ),
            }}
          ></el-popover>
        </div>
      )
    },

    rules: [
      {
        required: true,
        message: '请输入物流编码',
      },
    ],
  },
  {
    prop: 'name',
    type: 'input',
    label: '物流名称',
    fixed: 'last',
    attrs: {
      placeholder: '请输入物流名称',
    },
    rules: [
      {
        required: true,
        message: '请输入物流名称',
      },
    ],
  },
  {
    prop: 'warehouseId',
    type: 'select',
    label: '仓库名称',
    fixed: 'last',
    attrs: {
      placeholder: '请选择仓库名称',
      label: 'name',
      value: 'id',
      options: [...(warehouseList.value || [])],
      onChange: (item: WarehouseListData) => {
        editForm.value.warehouseName = item.name
      },
    },
  },

  {
    prop: 'siteUrl',
    type: 'input',
    label: '查询网址',
    fixed: 'last',
    attrs: {
      placeholder: '请输入查询网址',
    },
    rules: [
      {
        required: true,
        message: '请输入物流编码',
      },
    ],
  },
  {
    prop: 'status',
    type: 'switch',
    label: '启用状态',
    fixed: 'last',
    attrs: {
      activeValue: 1,
      inactiveValue: 0,
    },
  },
  {
    title: '平台物流名称',
    fixed: 'last',
    render: (_, formData) => {
      return (formData?.platformList as platformObj[])?.map(
        (item: platformObj, index: number) => (
          <div style="display: flex; width:100%">
            <el-form-item
              key={index}
              class="renderItem"
              label="平台名称"
              style="flex:50%"
              prop={`platformList.${index}.showPlatform`}
              rules={[
                {
                  required: true,
                  message: '请选择平台名称',
                  trigger: 'blur',
                },
              ]}
            >
              <el-select
                multiple
                collapse-tags
                collapse-tags-tooltip
                v-model={item['showPlatform']}
                disabled={index === 0}
              >
                {platformList.value?.map((el, idx) => (
                  <el-option label={el} value={el} key={idx}></el-option>
                ))}
              </el-select>
            </el-form-item>
            {item['showPlatform'].length === 1 &&
            item['showPlatform'][0] === 'TIKTOK' ? (
              <el-form-item
                key={index}
                class="renderItem"
                label="物流名称"
                style="display: flex;flex:50%"
                prop={`platformList.${index}.logisticsName`}
                rules={[
                  {
                    required: true,
                    message: '请输入物流名称',
                    trigger: 'blur',
                    validator: (
                      _: FormItemRule,
                      value: string,
                      callback: (error?: string) => void,
                    ) => {
                      if (value) callback()
                    },
                  },
                ]}
              >
                <LogisticsWaySelect
                  v-model={item.logisticsName as string | number}
                  isRadio={true}
                  companyList={tiktokCarriers.value as ICompanyList[]}
                  valueKey="name"
                ></LogisticsWaySelect>
              </el-form-item>
            ) : (
              <el-form-item
                key={index}
                class="renderItem"
                label="物流名称"
                style="display: flex;flex:50%"
                prop={`platformList.${index}.logisticsName`}
                rules={[
                  {
                    required: true,
                    message: '请输入物流名称',
                    trigger: 'blur',
                  },
                ]}
              >
                <el-input
                  v-model={item.logisticsName}
                  placeholder="请输入物流名称"
                />
              </el-form-item>
            )}
            <div style="display: flex;flex:17%">
              {(formData?.platformList as platformObj[])?.length - 1 ===
                index && (
                <el-button
                  style="margin-left: 10px"
                  type="primary"
                  onClick={() => addCol()}
                >
                  新增
                </el-button>
              )}
              {index >= 1 && (
                <el-button
                  style="margin-left: 10px"
                  type="danger"
                  onClick={() => deleteCol(index)}
                >
                  删除
                </el-button>
              )}
            </div>
          </div>
        ),
      )
    },
  },
])

const tableConfig = ref<TableColumn[]>([
  {
    prop: 'name',
    label: '物流名称',
  },
  {
    prop: 'warehouseName',
    label: '发货仓库',
  },

  {
    prop: 'serviceCode',
    label: '物流编码',
  },
  {
    prop: 'company',
    label: '物流公司',
  },

  {
    prop: 'status',
    label: '状态',
    render: {
      default: ({ row }) => (
        <div>
          <el-switch
            v-model={row.status}
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            inline-prompt
            active-text="启用"
            inactive-text="禁用"
            active-value={1}
            inactive-value={0}
            onClick={() => changeStatus(row as unknown as LogisticsMethod)}
          />
        </div>
      ),
    },
  },
  {
    prop: 'status1',
    label: '平台物流名称',
    attrs: { width: '400px', align: 'center' },

    render: {
      default: ({ row }) =>
        (row.platformList as platformObj[])?.map((el: platformObj) => (
          <div>
            <span style="margin-right:18px;">
              <span>{'平台:'}</span>
              <span class="logistics-name">{el.platform}</span>
            </span>
            <span>
              <span>{'物流名称:'}</span>
              <span class="logistics-name">{el.logisticsName}</span>
            </span>
          </div>
        )),
    },
  },
  // {
  //   prop: 'status2',
  //   label: '申报规则',
  //   render: {
  //     default: ({ row }) => (
  //       <div>{(row.ruleList as { ruleName: string }[])?.[0]?.ruleName}</div>
  //     ),
  //   },
  // },
  {
    prop: 'siteUrl',
    label: '查询网址',
    attrs: { width: '200px', align: 'center' },
    render: {
      default: ({ row }) => (
        <div>
          <el-link href={row.siteUrl} target="_blank">
            {row.siteUrl}
          </el-link>
        </div>
      ),
    },
  },
  {
    prop: 'opeare',
    label: '操作',
    attrs: {
      align: 'center',
    },
    render: {
      default: ({ row }) => (
        <div>
          <el-icon
            size="24"
            title="编辑"
            color="#EF6C00"
            style="cursor: pointer; vertical-align: middle"
            onclick={() => editWay(row as unknown as LogisticsMethod)}
          >
            <Edit />
          </el-icon>
          <el-icon
            size="24"
            title="删除"
            color="#f56c6c"
            style="cursor: pointer; vertical-align: middle"
            onclick={() => deleteWay(row as unknown as LogisticsMethod)}
          >
            <Delete />
          </el-icon>
          <el-icon
            size="24"
            title="日志"
            color="#008aff"
            style="cursor: pointer; vertical-align: middle"
            onclick={() => showLog(row as unknown as LogisticsMethod)}
          >
            <List />
          </el-icon>
        </div>
      ),
    },
  },
])

onMounted(() => {
  getAllList()
  getTiktokCarriers()
})

/**
 * @description: 更改状态
 */
async function changeStatus(data: LogisticsMethod) {
  loading.value = true
  try {
    const params = {
      id: data.id,
      status: data.status,
    }
    await updateStatusLogisticsWay(params)
    ElMessage({
      message: '更改状态成功',
      type: 'success',
    })
    search()
  } catch (error) {
    console.log(error)
  }
}

/**
 * @description: 取消按钮
 */
function cancelFn() {
  dialogVisible.value = false
  editFormRef.value?.resetFields()
  resetEditForm()
}

/**
 * @description: 删除按钮
 */
async function deleteWay(item: LogisticsMethod) {
  try {
    await showConfirm('是否删除物流方式', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  try {
    const ids = [item.id].join(',')
    await deleteLogisticsWay(ids)
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
    search()
  } catch (e) {
    search()
    // showError(e)
  }
}

/**
 * @description: 编辑按钮
 */
async function editWay(item: LogisticsMethod) {
  try {
    editForm.value = { ...item }
    editForm.value.ruleId = item.ruleList?.[0]?.ruleId || ''
    editForm.value.platformList =
      item.platformList?.map((el) => {
        el.showPlatform = el.platform.split(',')
        return el
      }) || []
    console.log(493, editForm.value)

    dialogVisible.value = true
    nextTick(() => {
      if (item.uinuinWarehouseId) {
        editFormRef.value?.refashConfig(['uinuinWarehouseId'])
      } else if (item.companyWarehouseCode) {
        editFormRef.value?.refashConfig(['companyWarehouseCode'])
      }
    })
  } catch (e) {
    console.log(e)
  }
}

/**
 * @description: 检查数据
 */
async function checkData() {
  const [isValid, postData] = await Promise.all([
    new Promise<boolean>((resolve) => {
      editFormRef.value
        ?.validate()
        .then(() => resolve(true))
        .catch((err) => {
          resolve(false)
          console.log(err)
        })
    }),
    new Promise<LogisticsMethod>((resolve) => {
      const params = { ...editForm.value }
      if (params.platformList?.length) {
        params.platformList.forEach((el) => {
          el.platform = el.showPlatform.join()
        })
      }
      resolve(params)
    }),
  ])
  console.log(isValid, postData)

  return { isValid, postData }
}

/**
 * @description: 保存按钮
 */
const save = debounce(async () => {
  const { isValid, postData } = await checkData()
  if (isValid) {
    try {
      if (!postData.id) {
        await addLogisticsWay({
          ...postData,
        })
      } else {
        await updateLogisticsWay({
          ...postData,
        })
      }
      ElMessage({
        message: '保存成功',
        type: 'success',
        offset: window.innerHeight / 2,
      })

      cancelFn()
      search()
    } catch (e) {
      return
    }
  }
}, 200)

/**
 * @description: 新增按钮打开弹窗
 */
function addDialog() {
  dialogVisible.value = true
  // nextTick(() => {
  //   editFormRef.value?.refashConfig()
  // })
}

/**
 * @description: 多选删除按钮
 */
async function deleteFn() {
  if (!selection.value.length) {
    return ElMessage({
      message: '请选择物流方式',
      type: 'warning',
    })
  }
  try {
    await showConfirm('是否删除物流方式', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  try {
    const ids = selection.value.map((item: { id: number }) => item.id).join(',')
    await deleteLogisticsWay(ids)
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
    search()
  } catch (e) {
    search()
    // showError(e)
  }
}

/**
 * @description: 获取选中数据
 */
function handleCheckboxRecords(value: never[]) {
  console.log(351, value)
  selection.value = value
}

/**
 * @description: 新增平台物流行
 */
function addCol() {
  editForm.value.platformList?.push({
    platform: '',
    logisticsName: '',
    showPlatform: [],
  })
}

/**
 * @description: 删除平台物流行
 */
function deleteCol(index: number) {
  editForm.value.platformList?.splice(index, 1)
}

/**
 * @description: 获取列表数据
 */
async function getAllList() {
  try {
    const res = await Promise.allSettled([
      loadWarehouseListApi(),
      getRuleList(),
      getPlatformList(),
      getLogisticsCompanyList(),
      getUniuniList(),
    ])
    res.forEach(
      (
        item: PromiseSettledResult<{
          code: number
          data: WarehouseListData[] | never[]
        }>,
        index,
      ) => {
        if (item.status === 'fulfilled') {
          if (item.value.code === 200) {
            if (index == 0) {
              warehouseList.value = item.value.data || []
            } else if (index == 1) {
              ruleNameList.value = (item.value.data as never[]) || []
            } else if (index == 2) {
              platformList.value = (item.value.data as never[]) || []
            } else if (index == 3) {
              logisticsCompanyList.value = (item.value.data as never[]) || []
            } else if (index == 4) {
              uniuniList.value = (item.value.data as never[]) || []
            }
          }
        }
      },
    )
  } catch (error) {
    console.log(error)
  }
}

interface ICompanyList {
  warehouseName: string
  wayList: IwayList[]
}

interface IwayList {
  name: string
  id: string
}

const tiktokCarriers = ref<ICompanyList[]>([])

/**
 * @description: 获取tictok物流承运商
 */
async function getTiktokCarriers() {
  const { data } = await getTiktokCarrier()
  const labelTypeList = Array.from(new Set(data.map((e) => e.label)))
  const result: ICompanyList[] = []
  labelTypeList.forEach((label) => {
    result.push({
      warehouseName: label,
      wayList: data.filter((e) => e.label === label),
    })
  })
  tiktokCarriers.value = result
}

/**
 * @description: 日志弹窗
 */
interface LogList {
  id?: number
  createTime?: string
  description?: string
}

const logList = ref<LogList[]>([])

async function showLog(row: LogisticsMethod) {
  logDialogVisible.value = true
  try {
    const { data } = await getLogisticsLog({
      logType: 'logistics_way',
      relaId: row.id as number,
    })
    logList.value = data
  } catch (error) {
    console.log(error)
  }
}
</script>

<style lang="scss" scoped>
.header-filter-form {
  margin-bottom: 20px;

  :deep(.el-form-item) {
    margin-right: 14px;
    margin-bottom: 10px;
  }
}

.user-operate-btn {
  margin-bottom: 10px;
}

.dialog-footer {
  text-align: center;
}
</style>
