<template>
  <div class="user-page flex-column card h-100 overflow-hidden">
    <div class="header-filter-form">
      <SearchForm
        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%"
    >
    </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 {
  getLogisticsWayList,
  addLogisticsWay,
  updateLogisticsWay,
  updateStatusLogisticsWay,
  deleteLogisticsWay,
  getWarehouseList,
  getRuleList,
  getPlatformList,
  getLogisticsLog,
  getLogisticsCompanyList,
  getUniuniList,
} from '@/api/logistics'
import { ISeachFormConfig } from '@/types/searchType'
import { TableColumn } from '@/components/VxeTable'
// import type { PromiseSettledResult } from 'types'
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 } from '@element-plus/icons-vue'
import { debounce } from 'lodash-es'

const [searchForm] = useValue({})
const [editForm, resetEditForm] = useValue<LogisticsMethod>({
  platformList: [{ platform: '', logisticsName: '', showPlatform: [] }],
  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 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 warehouseList = ref([])
const ruleNameList = ref([])
const uniuniList = ref([])
const logisticsCompanyList = ref([])
const formConfig = computed<IFormConfig[]>(() => [
  { title: '物流基础信息' },
  {
    prop: 'name',
    type: 'input',
    label: '物流名称',
    attrs: {
      placeholder: '请输入物流名称',
    },
    rules: [
      {
        required: true,
        message: '请输入物流名称',
      },
    ],
  },
  {
    prop: 'warehouseId',
    type: 'select',
    label: '仓库名称',
    attrs: {
      placeholder: '请选择仓库名称',
      label: 'name',
      value: 'id',
      options: [...(warehouseList.value || [])],
      onChange: (value: { name: string; id: string | number }) => {
        editForm.value.warehouseName = value.name
      },
    },
    rules: [
      {
        required: true,
        message: '请选择仓库名称',
      },
    ],
  },
  {
    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 {
          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: 'ruleId',
  //   type: 'select',
  //   label: '申报规则',
  //   fixed: 'last',
  //   attrs: {
  //     placeholder: '请选择申报规则',
  //     label: 'name',
  //     value: 'id',
  //     options: [...(ruleNameList.value || [])],
  //     onChange: (value: { name: string; id: string | number }) => {
  //       editForm.value.ruleRef.ruleId = value.id
  //       editForm.value.ruleRef.ruleName = value.name
  //     },
  //   },
  //   rules: [
  //     {
  //       required: true,
  //       message: '请选择申报规则',
  //     },
  //   ],
  // },
  {
    prop: 'serviceCode',
    type: 'input',
    label: '物流编码',
    fixed: 'last',
    attrs: {
      placeholder: '请输入物流编码',
    },
    rules: [
      {
        required: true,
        message: '请输入物流编码',
      },
    ],
  },
  {
    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: (item, formData) => {
      console.log(283, item, 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']}
              >
                {platformList.value?.map((el, idx) => (
                  <el-option label={el} value={el} key={idx}></el-option>
                ))}
              </el-select>
            </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:20%">
              {(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="primary"
                  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()
})

/**
 * @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
    if (item.uinuinWarehouseId) {
      nextTick(() => {
        editFormRef.value?.refashConfig(['uinuinWarehouseId'])
      })
    }
  } 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
    }
  }
}, 400)

/**
 * @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([
      getWarehouseList(),
      getRuleList(),
      getPlatformList(),
      getLogisticsCompanyList(),
      getUniuniList(),
    ])
    res.forEach(
      (item: PromiseSettledResult<{ code: number; data: never[] }>, index) => {
        if (item.status === 'fulfilled') {
          if (item.value.code === 200) {
            if (index == 0) {
              warehouseList.value = item.value.data || []
            } else if (index == 1) {
              console.log(758, item.value.data)

              ruleNameList.value = item.value.data || []
            } else if (index == 2) {
              platformList.value = item.value.data || []
            } else if (index == 3) {
              logisticsCompanyList.value = item.value.data || []
            } else if (index == 4) {
              uniuniList.value = item.value.data || []
            }
          }
        }
      },
    )

    console.log(545, res)
  } catch (error) {
    console.log(error)
  }
}

/**
 * @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>
