<script setup lang="tsx">
import { onMounted, reactive, ref} from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import {
  ElInput,
  FormInstance,
  // ElSwitch,
  ElForm,
  ElFormItem,
  ElMessage,
  ElMessageBox,
  ElSelect,
  ElOption,
  ElRadioGroup,
  ElRadio,
  ElTableColumn,
  ElTable,
  ElDrawer,
  ElPagination
} from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { attrsValue } from '@/api/goods/types'
import {  getProductDetail } from '@/api/goods'
import { AttrBaseItem } from '@/api/goods/types'
import { UpImgButtom } from '@/components/UpFile'
import { getStoreDetail } from '@/api/store'
import { getStoreList, getWantGoods,createWant,getStoreUser } from '@/api/erp'
import { wantGood, wantDate } from '@/api/erp/types'
// import { Dialog } from '@/components/Dialog'

const pageTitle = ref('添加')
const { params } = useRoute()
const { push } = useRouter()

const formData = reactive<any>({
  // bar_code: '',
  type: 1, //要货渠道
  up_store_id: '',
  product_type: 0,
  store_id: '',
  id: 0,
  store_name: '',
  video_open: 0,
  video_link: '',
  slider_image: [],
  image: [],
  store_info: '',
  keyword: [],
  cate_id: [],
  sales: 0,
  ficti: 0,
  spec_type: 0,
  is_show: 1,
  limit_num: 0,
  is_limit: 0,
  limit_type: 0,
  is_police: 0,
  shelf_life: 0,
  attrs: [],
  attrs_value: [], // 初始化为空数组
  sort: 0,
  description: '',
  show_type: 0,
  is_verify: 0,
  pay_qudou: 0,
  is_vip_product: 0,
  is_weigh: 0,
  specs: []
})
const attrs_value = reactive<
  attrsValue & {
    image: string[]
  }
>({
  suk: '默认',
  image: [],
  stock: 0,
  detail: {},
  price: 0,
  ot_price: 0,
  cost: 0
})


const rules = reactive({
  store_id: [{ required: true, message: '请选择门店', trigger: 'change' }],
  wid: [{ required: true, message: '请选择来源仓库', trigger: 'change' }],
  up_store_id: [{ required: true, message: '请选择来源门店', trigger: 'change' }],
  auth_admin_id: [{ required: true, message: '请选择审核人员', trigger: 'change' }],
  create_admin_id: [{ required: true, message: '请选择创建人员', trigger: 'change' }],

})
const formRef = ref<FormInstance>()

/**
 * 保存表单数据
 * 此函数在用户提交表单时被触发，它首先验证表单数据的有效性，如果有效则处理数据并调用相应的API进行保存
 * @param {FormInstance | undefined} formEl - 表单实例，用于表单验证和获取表单数据
 * @returns {Promise<Array>} - 返回一个空数组，当前函数没有实际返回值，但为了保持接口一致性，返回了空数组
 */
const save = async () => {
  console.log(checkGoods.value)
  //
  if (!formData.store_id) {
    return ElMessage.error('请选择要货门店')
  }
  if (formData.type == 1 && !formData.wid) {
    return ElMessage.error('请选择来源仓库')
  }
  if (formData.type == 2 && !formData.up_store_id) {
    return ElMessage.error('请选择来源门店')
  }
  if (checkGoods.value.length == 0) {
    return ElMessage.error('请选择商品')
  }
  if (!formData.create_admin_id) {
    return ElMessage.error('请选择创建人员')
    
  }
  // 校验要货商品是否为空
  let goods: Array<wantGood> = []
  let pData: wantDate = {
    type: 1,
    store_id: 0,
    up_wid: 0,
    up_store_id: 0,
    create_admin_id: 0,
    goods: []
  }

  checkGoods.value.forEach(
    (item: {
      id: number
      store_name: string
      bar_code: string
      specs: { name: string }
      want_product_num: number
      is_weigh: number
    }) => {
      if (!item['want_product_num'] || item['want_product_num'] < 0) {
        return ElMessage.error('请填写正确的要货商品数量')
      } else {
        goods.push({
          product_id: item.id,
          product_name: item.store_name,
          bar_code: item.bar_code,
          suk: item.specs.name,
          want_product_num: item.want_product_num,
          is_weigh: item.is_weigh
        })
      }
    }
  )
  pData = {
    type: formData.type,
    store_id: formData.store_id,
    up_wid: formData.wid,
    up_store_id: formData.up_store_id,
    create_admin_id: formData.create_admin_id,
    goods: goods,
  }
  console.log(goods, 'goods', pData)
  const res = await createWant(pData)
  if (res?.status == 200) {
    ElMessage.success('保存成功')
        ElMessageBox.confirm(`创建成功是否返回要货列表`, '提示', {
          confirmButtonText: '返回列表',
          cancelButtonText: `继续创建`,
          type: 'warning'
        }).then(() => {
          backList()
        })
  }
  
}

const loadingData = ref(false)
onMounted(async () => {
  //加载商品规格
  // ruleList()
  if (params.type == 'add') {
    pageTitle.value = '添加要货'
  } else if (params.type == 'edit') {
    pageTitle.value = '编辑要货'
    try {
      const res = await getProductDetail(params.id)
      const data = res.data
      formData.id = data.id
      formData.is_weigh = data.is_weigh
      formData.store_id = data.store_id
      formData.store_name = data.store_name
      formData.store_info = data.store_info
      formData.video_open = data.video_open
      formData.video_link = data.video_link
      formData.slider_image = data.slider_image || []
      formData.image = [data.image]
      // formData.bar_code = data.bar_code
      formData.recommend_image = data.recommend_image
      formData.keyword = data.keyword ? data.keyword.split(',') : []
      formData.cate_id = data.cate_id.split(',').map((re) => parseInt(re))
      formData.sales = data.sales
      formData.ficti = data.ficti
      formData.spec_type = data.spec_type
      formData.is_show = data.is_show
      formData.is_vip_product = data.is_vip_product
      formData.is_limit = data.is_limit
      formData.limit_type = data.limit_type
      formData.limit_num = data.limit_num
      formData.is_police = data.is_police
      formData.shelf_life = data.shelf_life
      formData.pay_qudou = data.pay_qudou
      formData.show_type = data.show_type
      formData.attrs = data.attrs
      formData.sort = data.sort
      formData.description = data.description
      formData.is_verify = data.is_verify
      // formData.specs = data.specs
      attrBase = reactive(
        data.specs.map((item) => {
          let obj = JSON.parse(JSON.stringify(item))
          obj.img = [item.img]
          return obj
        })
      )
      //加载门店
      getStore('', data.store_id)
      getStore('', data.up_store_id)
      getWid('', data.up_wid)
      console.log('z')
    } catch (error) {
      console.log(error, 'error')
    }
  }
})
const backList = () => {
  push('/erp/want')
}
const storeLoading = ref(false)
const storeOptions = ref<any[]>([])
const widOptions = ref<any[]>([])
  const adminOptions = ref<any[]>([])
const getStore = async (query = '', id = '') => {
  try {
    storeLoading.value = true
    const res = await getStoreList({ page: 1, limit: 1000, name: query, id, store: 1 })
    if (res) {
      storeOptions.value = res.data.data.map((item) => {
        return {
          value: item.id,
          label: item.name
        }
      })
    } else {
      return []
    }
  } catch (error) {
    console.log(error)
  } finally {
    storeLoading.value = false
  }
}
const getAdmin = async () => {
  const res = await getStoreUser({ page: 1, limit: 20, relation_id: storeInfo.value.id })
  // adminOptions.value = res.data.list
  if (res) {
    adminOptions.value = res.data.map((item) => {
        return {
          value: item.id,
          label: item.real_name
        }
      })
    } else {
      return []
    }
}
const getWid = async (query = '', id = '') => {
  try {
    storeLoading.value = true
    const res = await getStoreList({ page: 1, limit: 1000, name: query, id, type: 3 })
    if (res) {
      widOptions.value = res.data.data.map((item) => {
        return {
          value: item.id,
          label: item.name
        }
      })
    } else {
      return []
    }
  } catch (error) {
    console.log(error)
  } finally {
    storeLoading.value = false
  }
}

let attrBase = reactive<AttrBaseItem[]>([
  {
    img: [], //图片
    bar_code: '', //产品编号
    price: 0, //售价
    num: 0,
    is_default: 0,
    price_1: 0,
    price_2: 0,
    price_3: 0,
    name: '',
    is_del: 0,
    rate: 0
  }
])


const selectPic = ref<string[]>([]) //选中的图片
const selectPicIndex = ref(0) //上传图片选择对象
const selectPicObj = ref('header') //上传图片类型


/**
 * 根据不同的图片选择对象类型，更新相应的图片数组
 * @param {string[]} pic - 要更新的图片数组
 */
const changePic = (pic: string[]) => {
  console.log(pic, 'pic')
  // 根据选中的图片对象类型，更新对应的图片数组
  switch (selectPicObj.value) {
    case 'header':
      // 更新产品属性列表中的图片数组
      attrBase[selectPicIndex.value].img = pic
      break
    case 'attrBase':
      // 更新基础属性中的图片数组
      attrBase[0].img = pic
      break
    case 'banner':
      // 更新表单数据中的图片数组
      formData.image = pic
      break
    case 'attrOne':
      // 更新单规格的图片数组
      attrs_value.image = pic
      break
    default:
      // 其他情况不做处理
      break
  }
}


const storeInfo = ref({ wid: 0, id: 0 })
const storeChange = async (e) => {
  const res = await getStoreDetail(e)
  storeInfo.value = res.data
  // 清空选择的商品和选择的门店仓库
  formData.wid = ''
  formData.up_store_id = ''
  checkGoods.value = []
  formData.create_admin_id = ''
  getAdmin()
  // 判断是否有上级仓库
  if (!storeInfo.value?.wid) {
    formData.type = 2
  } else {
    formData.wid = storeInfo.value.wid
    getWid('', formData.wid)
  }
}
const upStoreChange = async (e) => {
  if (e == storeInfo.value.id) {
    formData.up_store_id = ''
    ElMessage.error('要货门店和来源门店不能一致')
  }
}

const goods = ref([])
const dialogVisible = ref(false)
const count = ref(0)
const currentPage = ref(0)
const pageSize = ref(15)
const keyword = ref('')
const fristCheck = ref([])
const checkGoods = ref([])

const getWantgood = async (page = 1, type = '') => {
  // getWantGoods
  if (!storeInfo.value.id) {
    return ElMessage.error('请选择要货门店')
  }
  if (type == 're') {
    keyword.value = ''
  }
  let qdata = {
    store_id: storeInfo.value.id,
    type: formData.type,
    wid: 0,
    up_store_id: 0,
    page: page,
    limit: pageSize.value,
    key: keyword.value
  }
  if (formData.type == 1) {
    qdata.wid = storeInfo.value.wid
    if (!qdata.wid) {
      return ElMessage.error('请选择来源仓库')
    }
  } else {
    qdata.up_store_id = formData.up_store_id
    if (!qdata.up_store_id) {
      return ElMessage.error('请选择来源门店')
    }
  }
  const res = await getWantGoods(qdata)
  goods.value = res.data.data
  count.value = res.data.count
  dialogVisible.value = true
}
const handleSelectionChange = (e) => {
  fristCheck.value = e
}
const handleCurrentChange = (e:number) => {
  getWantgood(e, '')
}
const cancelClick = () => {
  dialogVisible.value = false
}
const confirmClick = () => {
  // 关闭弹窗
  dialogVisible.value = false
  //合并选中去重
  fristCheck.value = fristCheck.value.map((item) => {
    Object.assign(item, { want_product_num: '' })
    return item
  })
  checkGoods.value = unique(checkGoods.value.concat(fristCheck.value))
}

const unique = (arr) => {
  return arr.filter((item, index, arr) => arr.findIndex((t) => t.id === item.id) === index)
}
const delCheckGoods = (row) => {
  console.log(row)
  let set1 = new Set(checkGoods.value)
  let set2 = new Set([row])
  checkGoods.value = Array.from(set1.difference(set2))
}
</script>
<template>
  <ContentWrap
    :title="pageTitle"
    class="!min-h-[calc(100vh-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height)-var(--app-content-padding))]"
  >
    <template #header>
      <BaseButton size="small" @click="backList"> 返回列表 </BaseButton>
    </template>
    <ElForm
      v-loading="loadingData"
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
    >
      <ElFormItem label="要货门店" prop="store_id">
        <ElSelect
          filterable
          remote
          reserve-keyword
          :disabled="params.type == 'edit'"
          v-model="formData.store_id"
          :remote-method="getStore"
          :loading="storeLoading"
          remote-show-suffix
          placeholder="请选择门店"
          @change="storeChange"
        >
          <ElOption
            v-for="item in storeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="要货渠道" v-if="storeInfo.id">
        <ElRadioGroup v-model="formData.type" class="ml-4">
          <ElRadio :label="1" size="large" :disabled="storeInfo.wid == 0">仓库</ElRadio>
          <ElRadio :label="2" size="large">门店</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
      <template v-if="storeInfo.id">
        <ElFormItem label="来源仓库" v-if="formData.type == 1" prop="wid">
          <ElSelect
            filterable
            remote
            reserve-keyword
            disabled
            v-model="formData.wid"
            :remote-method="getWid"
            :loading="storeLoading"
            remote-show-suffix
            placeholder="请选择仓库"
          >
            <ElOption
              v-for="item in widOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="来源门店" v-else prop="up_store_id">
          <ElSelect
            filterable
            remote
            reserve-keyword
            :disabled="params.type == 'edit'"
            v-model="formData.up_store_id"
            :remote-method="getStore"
            :loading="storeLoading"
            remote-show-suffix
            placeholder="请选择门店"
            @change="upStoreChange"
          >
            <ElOption
              v-for="item in storeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="创建人员" prop="create_admin_id">
          <ElSelect
            filterable
            remote
            reserve-keyword
            :disabled="params.type == 'edit'"
            v-model="formData.create_admin_id"
            :remote-method="getAdmin"
            :loading="storeLoading"
            remote-show-suffix
            placeholder="请选择创建人员"
          >
            <ElOption
              v-for="item in adminOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
        <!-- <ElFormItem label="审核人员" prop="auth_admin_id">
          <ElSelect
            filterable
            remote
            reserve-keyword
            :disabled="params.type == 'edit'"
            v-model="formData.auth_admin_id"
            :remote-method="getAdmin"
            :loading="storeLoading"
            remote-show-suffix
            placeholder="请选择审核人员"
          >
            <ElOption
              v-for="item in adminOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem> -->
      </template>
      <ElFormItem label="要货商品">
        <BaseButton type="primary" style="margin-bottom: 20px" @click="getWantgood(1, '')">
          选择商品
        </BaseButton>
        <ElTable
          header-cell-class-name="bg-gray-100!"
          :data="checkGoods"
          class="w-100%"
          :border="true"
          stripe
        >
          <ElTableColumn prop="store_name" label="规格名称"> </ElTableColumn>
          <ElTableColumn prop="unit_name" label="单位">
            <template #default="{ row }">
              <div type="text">{{ row.specs.name || 0 }}</div>
            </template></ElTableColumn
          >
          <ElTableColumn prop="my_stock" label="本地库存">
            <template #default="{ row }">
              <div type="text">{{ row.my_stock || 0 }}</div>
            </template></ElTableColumn
          >
          
          <ElTableColumn prop="want_product_num" label="要货数量">
            <template #header> <span>要货数量</span><span class="text-red">*</span> </template>
            <template #default="{ row }">
              <ElInput type="number" v-model="row.want_product_num" />
            </template>
          </ElTableColumn>
          <ElTableColumn prop="action" label="操作">
                <template #default="{ row }">
                  <!-- <div type="text">{{ row.specs.num || 0 }}</div> -->
                   <BaseButton link size="small" type="primary" @click="delCheckGoods(row)">删除</BaseButton>
                </template></ElTableColumn
              >
        </ElTable>
      </ElFormItem>
    </ElForm>
    <UpImgButtom
      class="pos-absolute left-[-200px]"
      ref="upImageButtomRef"
      v-model="selectPic"
      @change="changePic"
    />
  </ContentWrap>
  <div
    class="text-center border-t-1px border-solid border-gray-200 py-10px mt-10px position-sticky bottom-0 left-0 right-0 bg-white"
  >
    <BaseButton @click="save()"> 保存 </BaseButton>
  </div>
  <ElDrawer v-model="dialogVisible" title="选择商品" size="700px">
    <div class="mb5">
      <ElInput v-model="keyword" style="width: 200px" placeholder="输入商品名称搜索" />
      <BaseButton type="primary" class="ml2" @click="getWantgood(1, '')"> 搜索 </BaseButton>
      <BaseButton @click="getWantgood(1, 're')"> 重置 </BaseButton>
    </div>

    <ElTable
      header-cell-class-name="bg-gray-100!"
      :data="goods"
      class="w-100%"
      :border="true"
      stripe
      @selection-change="handleSelectionChange"
    >
      <ElTableColumn type="selection" width="55" />
      <ElTableColumn prop="store_name" label="规格名称"> </ElTableColumn>
      <ElTableColumn prop="unit_name" label="单位">
        <template #default="{ row }">
          <div type="text">{{ row.specs.name || 0 }}</div>
        </template></ElTableColumn
      >
      <ElTableColumn prop="my_stock" label="本地库存">
        <template #default="{ row }">
          <div type="text">{{ row.my_stock || 0 }}</div>
        </template></ElTableColumn
      >
      <!-- <ElTableColumn prop="my_stock" label="仓库/门店库存">
        <template #default="{ row }">
          <div type="text">{{ row.specs.num || 0 }}</div>
        </template></ElTableColumn
      > -->
    </ElTable>
    <div style="height: 20px"></div>
    <ElPagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[2, 3, 4, 5]"
      layout="total, prev, pager, next, jumper"
      :total="count"
      @current-change="handleCurrentChange"
    />
    <template #footer>
      <div style="flex: auto">
        <BaseButton @click="cancelClick">取消</BaseButton>
        <BaseButton type="primary" @click="confirmClick">确认</BaseButton>
      </div>
    </template>
  </ElDrawer>
</template>
