<script setup lang="tsx">
import { onMounted, reactive, ref } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import {
  ElInput,
  FormInstance,
  ElTabPane,
  ElTabs,
  ElForm,
  ElFormItem,
  ElMessage,
  ElSelect,
  ElOption,
  ElTableColumn,
  ElTable,
  ElDrawer,
  ElRadioGroup,
  ElRadio,
  ElMessageBox,
  ElCard
} from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { getStoreList, getStoreUser, getOutGood, getStoreGood, addWareAdjust } from '@/api/erp'
const pageTitle = ref('添加')
const { params } = useRoute()
const { push } = useRouter()
const actinoTabIndex = ref(1)
const selfBuild = reactive<{ [key: string]: any }>({
  type: 1,
  store_id: '',
  wid: '',
  create_admin_id: '',
  up_store_id: '',
  up_wid: '',
  product_list: [],
  rate: ''
})

const hzBuild = reactive<{ [key: string]: any }>({
  create_admin_id: '',
  store_id: '',
  up_store_id: '',
  product_list: [],
  type: 1,
  rate: ''
})

const rules = reactive({
  rate: [{ required: true, message: '请输入调价比例', trigger: 'change' }],
  create_admin_id: [{ required: true, message: '请选择创建人', trigger: 'change' }],
  wid: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  store_id: [{ required: true, message: '请选择门店', trigger: 'change' }]
})
const formRef = ref<FormInstance>()
const formRefs = ref<FormInstance>()
const checkGoodss = ref<any[]>([])
const goSuccess = () => {
  ElMessage.success('保存成功')
  ElMessageBox.confirm(`创建成功是否返回调价列表`, '提示', {
    confirmButtonText: '返回列表',
    cancelButtonText: `继续创建`,
    type: 'warning'
  })
    .then(() => {
      backList()
    })
    .catch(() => {
      checkGoods.value = []
      checkGoodss.value = []
    })
}

/**
 * 保存表单数据
 * 此函数在用户提交表单时被触发，它首先验证表单数据的有效性，如果有效则处理数据并调用相应的API进行保存
 * @param {FormInstance | undefined} formEl - 表单实例，用于表单验证和获取表单数据
 * @returns {Promise<Array>} - 返回一个空数组，当前函数没有实际返回值，但为了保持接口一致性，返回了空数组
 */
const save = async (formEl: FormInstance | undefined) => {
  // 检查表单实例是否存在，如果不存在则返回空数组
  if (!formEl) return []
  // 验证表单数据，如果验证失败，则显示错误消息并中断保存流程
  const valid = await formEl.validate((valid, fields) => {
    if (valid) {
    } else {
      for (const key in fields) {
        ElMessage.error(fields[key][0].message)
        return
      }
      console.log('error submit!', fields)
    }
  })
  if (valid) {
    if (actinoTabIndex.value == 1) {
      let good: any[] = []
      try {
        console.log(checkGoods.value, 'checkGoods.value')

        checkGoods.value.forEach((item) => {
          console.log(item, 'item')

          let obj = {
            ot_price: item.out_price || 0,
            price: selfBuild.type == 1 ? item.price : showPrice(item.out_price || 0),
            product_id: item.product_id,
            product_name: item.product_name
          }
          if (selfBuild.type == 0) {
            Object.assign(obj, { scale: selfBuild.rate })
          }
          good.push(obj)
        })
        console.log(good, 'good')

        const res = await addWareAdjust({
          body: good,
          create_admin_id: selfBuild.create_admin_id,
          wid: selfBuild.wid,
          type: selfBuild.type == 1 ? 0 : 1,
          adjust_type: actinoTabIndex.value == 1 ? 1 : 0
        })
        if (res?.status == 200) {
          goSuccess()
        }
      } catch (error) {
        console.log(error, 'error')
      }
    } else if (actinoTabIndex.value == 2) {
      console.log(checkGoodss.value)

      let good: any[] = []
      try {
        checkGoodss.value.forEach((item) => {
          item.specs = item.specs.map((i) => {
            i.price = hzBuild.type == 1 ? i.price : showPrices(i.prices)
            i.price_1 = hzBuild.type == 1 ? i.price_1 : showPrices(i.prices_1)
            i.price_2 = hzBuild.type == 1 ? i.price_2 : showPrices(i.prices_2)
            i.price_3 = hzBuild.type == 1 ? i.price_3 : showPrices(i.prices_3)
            return i
          })
          let obj = {
            price: hzBuild.type == 1 ? item.price : showPrices(item.prices),
            product_id: item.id,
            product_name: item.store_name,
            specs: item.specs.map(items => {
              delete items.prices
              delete items.prices_1
              delete items.prices_2
              delete items.prices_3
              return items
            })
          }
          if (hzBuild.type == 0) {
            Object.assign(obj, { scale: hzBuild.rate })
          }
          good.push(obj)
        })
        console.log(good, 'dd')
        //   if (!ok) {
        //     return
        //   }


        const res = await addWareAdjust({
          body: good,
          create_admin_id: hzBuild.create_admin_id,
          store_id: hzBuild.store_id,
          type: hzBuild.type == 1 ? 0 : 1,
          adjust_type: 0
        })
        if (res.status == 200) {
          goSuccess()
        }
      } catch (error) {
        console.log(error, 'error')
      }
    }
  }
}

const loadingData = ref(false)
onMounted(async () => {
  if (params.type == 'add') {
    pageTitle.value = '添加调价'
  } else if (params.type == 'edit') {
    pageTitle.value = '编辑调价'
  }
})
const backList = () => {
  push('/erp/adjust')
}
const storeLoading = ref(false)
const storeOptions = 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 widOptions = ref<any[]>([])
const adminOptions = ref<any[]>([])
const wareLoading = ref(false)
const adminLoading = ref(false)
const checkGoods = ref<any[]>([])

const getWid = async (query = '', id = '') => {
  try {
    wareLoading.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 {
    wareLoading.value = false
  }
}
const getAdmin = async () => {
  console.log(actinoTabIndex.value, 'actinoTabIndex')
  let id: any = 0
  if (actinoTabIndex.value == 1) {
    id = selfBuild.wid
  } else if (actinoTabIndex.value == 2) {
    id = hzBuild.store_id
  }
  const res = await getStoreUser({ page: 1, limit: 20, relation_id: 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 fristCheck = ref<any[]>([])

const changeSw = () => {
  selfBuild.create_admin_id = ''
  checkGoods.value = []
  checkGoodss.value = []
  hzBuild.create_admin_id = ''
}
const handleSelectionChange = (e) => {
  fristCheck.value = e
}
const handleCurrentChange = (e: number) => {
  getPurgood(e, '')
}

const cancelClick = () => {
  dialogVisible.value = false
}

const unique = (arr) => {
  return arr.filter((item, index, arr) => arr.findIndex((t) => t.id === item.id) === index)
}
type iitem = {
  [key: string]: any
}
const confirmClick = () => {
  // 关闭弹窗
  dialogVisible.value = false
  //合并选中去重
  fristCheck.value = fristCheck.value.map((item: iitem) => {
    if (actinoTabIndex.value == 1) {
      item.price = +item.out_price || 0
    } else {
      // item.prices = item.price
      // item.prices_3 = item.price_3
      // item.prices_2 = item.price_2
      // item.prices_1 = item.price_1
      item.specs.map((items) => {
        items.prices = items.price
        items.prices_3 = items.price_3
        items.prices_2 = items.price_2
        items.prices_1 = items.price_1
        return items
      })
    }
    console.log(item, 'item----------')
    return item
  })
  if (actinoTabIndex.value == 1) {
    checkGoods.value = unique(checkGoods.value.concat(fristCheck.value))
  } else if (actinoTabIndex.value == 2) {
    checkGoodss.value = unique(checkGoodss.value.concat(fristCheck.value))
  }
}

const goods = ref([])
const count = ref(0)
const keyword = ref('')
const currentPage = ref(0)
const pageSize = ref(10)
const dialogVisible = ref(false)
const getPurgood = async (page = 1, key = '') => {
  if (key == 're') {
    keyword.value = ''
  }
  let qData: {
    key: string
    page: number
    limit: number
    store_id?: any
    wid?: any
    type: any
    up_wid?: any
  } = {
    type: '',
    store_id: '',
    wid: '',
    key: keyword.value,
    page: page,
    limit: 10,
    up_wid: ''
  }
  if (actinoTabIndex.value == 1) {
    if (!selfBuild.wid) {
      return ElMessage.error('请选仓库')
    }
    qData.up_wid = selfBuild.wid
    qData.type = 0
    const res = await getOutGood(qData)
    goods.value = res.data.data
    count.value = res.data.count
    dialogVisible.value = true
  } else if (actinoTabIndex.value == 2) {
    if (!hzBuild.store_id) {
      return ElMessage.error('请选门店')
    }
    qData.store_id = hzBuild.store_id

    // const res = await getProduct(qData)
    const res = await getStoreGood(qData)
    goods.value = res.data.data
    count.value = res.data.count
    dialogVisible.value = true
  }
}
const delCheckGoods = (row) => {
  console.log(row)
  let set1 = new Set(checkGoods.value)
  let set2 = new Set([row])
  checkGoods.value = Array.from(set1.difference(set2))
}
const showPrice = (price) => {
  if (!price) {
    return 0 + ''
  }
  if (!selfBuild.rate) {
    return price + ''
  } else {
    return ((price * (100 + selfBuild.rate * 1)) / 100).toFixed(2) + ''
  }
}
const showPrices = (price) => {
  console.log('price:', price)
  if (!price) {
    console.log('zhe')

    return '0'
  } else if (!hzBuild.rate) {
    console.log('na', hzBuild.rate)
    return price
  } else {
    console.log('hh', ((price * (100 + hzBuild.rate * 1)) / 100).toFixed(2) + '')

    return ((price * (100 + hzBuild.rate * 1)) / 100).toFixed(2) + ''
  }
}
const delCheckGoodss = (index: number) => {
  checkGoodss.value.splice(index, 1)
}
</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>
    <ElTabs v-model="actinoTabIndex" type="border-card">
      <ElTabPane label="仓库调价" :name="1">
        <ElForm
          v-loading="loadingData"
          ref="formRef"
          :model="selfBuild"
          :rules="rules"
          label-width="100px"
        >
          <ElFormItem label="仓库" prop="wid">
            <ElSelect
              filterable
              remote
              reserve-keyword
              v-model="selfBuild.wid"
              :remote-method="getWid"
              :loading="wareLoading"
              remote-show-suffix
              placeholder="请选择仓库"
              @change="changeSw"
            >
              <ElOption
                v-for="item in widOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </ElSelect>
          </ElFormItem>
          <ElFormItem label="调整方式" v-if="selfBuild.wid">
            <ElRadioGroup v-model="selfBuild.type" class="ml-4">
              <ElRadio :label="1" size="large">价格调整</ElRadio>
              <ElRadio :label="0" size="large">比例调整</ElRadio>
            </ElRadioGroup>
          </ElFormItem>
          <ElFormItem label="比例" v-if="selfBuild.type == 0" prop="rate">
            <ElInput type="number" v-model="selfBuild.rate" />
          </ElFormItem>
          <ElFormItem label="创建人员" prop="create_admin_id" v-if="selfBuild.wid">
            <ElSelect
              filterable
              remote
              reserve-keyword
              :disabled="params.type == 'edit'"
              v-model="selfBuild.create_admin_id"
              :remote-method="getAdmin"
              :loading="adminLoading"
              remote-show-suffix
              placeholder="请选择创建人员"
            >
              <ElOption
                v-for="item in adminOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </ElSelect>
          </ElFormItem>
          <ElFormItem label="商品">
            <BaseButton type="primary" style="margin-bottom: 20px" @click="getPurgood(1, '')">
              选择商品
            </BaseButton>
            <ElTable
              header-cell-class-name="bg-gray-100!"
              :data="checkGoods"
              class="w-100%"
              :border="true"
              stripe
            >
              <ElTableColumn prop="product_id" label="ID"> </ElTableColumn>
              <ElTableColumn prop="product_name" label="名称"> </ElTableColumn>
              <ElTableColumn prop="suk" label="单位"></ElTableColumn>
              <ElTableColumn prop="out_price" label="原价"></ElTableColumn>
              <ElTableColumn prop="price" label="价格" v-if="selfBuild.type == 1">
                <template #header> <span>价格</span><span class="text-red">*</span> </template>
                <template #default="{ row }">
                  <ElInput type="number" v-model="row.price" />
                </template>
              </ElTableColumn>
              <ElTableColumn prop="price" label="价格" v-if="selfBuild.type == 0">
                <template #header> <span>价格</span><span class="text-red">*</span> </template>
                <template #default="{ row }">
                  {{ showPrice(row.out_price) || 0 }}
                </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>
      </ElTabPane>
      <ElTabPane label="门店调价" :name="2">
        <ElForm
          v-loading="loadingData"
          ref="formRefs"
          :model="hzBuild"
          :rules="rules"
          label-width="100px"
        >
          <ElFormItem label="门店" prop="store_id">
            <ElSelect
              filterable
              remote
              reserve-keyword
              :disabled="params.type == 'edit'"
              v-model="hzBuild.store_id"
              :remote-method="getStore"
              :loading="storeLoading"
              remote-show-suffix
              placeholder="请选择门店"
              @change="changeSw"
            >
              <ElOption
                v-for="item in storeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </ElSelect>
          </ElFormItem>
          <ElFormItem label="调整方式">
            <ElRadioGroup v-model="hzBuild.type" class="ml-4">
              <ElRadio :label="1" size="large">价格调整</ElRadio>
              <ElRadio :label="0" size="large">比例调整</ElRadio>
            </ElRadioGroup>
          </ElFormItem>
          <ElFormItem label="比例 (%)" v-if="hzBuild.type == 0" prop="rate">
            <ElInput type="number" v-model="hzBuild.rate" />
          </ElFormItem>
          <ElFormItem label="创建人员" prop="create_admin_id" v-if="hzBuild.store_id">
            <ElSelect
              filterable
              remote
              reserve-keyword
              :disabled="params.type == 'edit'"
              v-model="hzBuild.create_admin_id"
              :remote-method="getAdmin"
              :loading="adminLoading"
              remote-show-suffix
              placeholder="请选择创建人员"
            >
              <ElOption
                v-for="item in adminOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </ElSelect>
          </ElFormItem>
          <ElFormItem label="调价商品">
            <BaseButton type="primary" style="margin-bottom: 20px" @click="getPurgood(1, '')">
              调价商品
            </BaseButton>
          </ElFormItem>
          <ElFormItem label="">
            <div style="display: flex; flex-wrap: wrap; justify-content: space-between">
              <ElCard
                v-for="(item, index) in checkGoodss"
                :key="index"
                class="mb5"
                style="width: 48%; min-width: 700px"
              >
                <template #header>
                  <div class="card-header">
                    <span>{{ item.store_name }}</span>
                  </div>
                </template>
                <ElTable
                  header-cell-class-name="bg-gray-100!"
                  :data="item.specs"
                  class="w-100%"
                  :border="true"
                  stripe
                >
                  <ElTableColumn prop="name" label="规格"> </ElTableColumn>
                  <template v-if="hzBuild.type == 1">
                    <ElTableColumn prop="price" label="价格">
                      <template #header>
                        <span>价格</span><span class="text-red">*</span>
                      </template>
                      <template #default="{ row }">
                        <ElInput type="number" v-model="row.price" />
                      </template>
                    </ElTableColumn>
                    <ElTableColumn prop="price_1" label="VIP价格">
                      <template #header>
                        <span>VIP价格</span><span class="text-red">*</span>
                      </template>
                      <template #default="{ row }">
                        <ElInput type="number" v-model="row.price_1" />
                      </template>
                    </ElTableColumn>
                    <ElTableColumn prop="price_2" label="金卡价格">
                      <template #header>
                        <span>金卡价格</span><span class="text-red">*</span>
                      </template>
                      <template #default="{ row }">
                        <ElInput type="number" v-model="row.price_2" />
                      </template>
                    </ElTableColumn>
                    <ElTableColumn prop="price_3" label="钻卡价格">
                      <template #header>
                        <span>钻卡价格</span><span class="text-red">*</span>
                      </template>
                      <template #default="{ row }">
                        <ElInput type="number" v-model="row.price_3" />
                      </template>
                    </ElTableColumn>
                  </template>
                  <template v-else>
                    <ElTableColumn prop="price" label="价格">
                      <template #header>
                        <span>价格</span><span class="text-red">*</span>
                      </template>
                      <template #default="{ row }">
                        {{ showPrices(row.prices) || 0 }}
                      </template>
                    </ElTableColumn>
                    <ElTableColumn prop="price_1" label="VIP价格">
                      <template #header>
                        <span>VIP价格</span><span class="text-red">*</span>
                      </template>
                      <template #default="{ row }">
                        {{ showPrices(row.prices_1) || 0 }}
                      </template>
                    </ElTableColumn>
                    <ElTableColumn prop="price_2" label="金卡价格">
                      <template #header>
                        <span>金卡价格</span><span class="text-red">*</span>
                      </template>
                      <template #default="{ row }">
                        {{ showPrices(row.prices_2) || 0 }}
                      </template>
                    </ElTableColumn>
                    <ElTableColumn prop="price_3" label="钻卡价格">
                      <template #header>
                        <span>钻卡价格</span><span class="text-red">*</span>
                      </template>
                      <template #default="{ row }">
                        {{ showPrices(row.prices_3) || 0 }}
                      </template>
                    </ElTableColumn>
                  </template>
                </ElTable>
                <template #footer>
                  <BaseButton type="primary" link style="margin-bottom: 20px" @click="delCheckGoodss(index)"> 删除 </BaseButton>
                </template>
              </ElCard>
            </div>
          </ElFormItem>
        </ElForm>
      </ElTabPane>
    </ElTabs>
    <ElDrawer v-model="dialogVisible" title="选择商品" size="700px">
      <div class="mb5">
        <ElInput v-model="keyword" style="width: 200px" placeholder="输入商品名称搜索" />
        <BaseButton type="primary" class="ml2" @click="getPurgood(1, '')"> 搜索 </BaseButton>
        <BaseButton @click="getPurgood(1, 're')"> 重置 </BaseButton>
      </div>

      <ElTable
        header-cell-class-name="bg-gray-100!"
        :data="goods"
        class="w-100%"
        :border="true"
        stripe
        @selection-change="handleSelectionChange"
      >
        <template v-if="actinoTabIndex == 1">
          <ElTableColumn type="selection" width="55" />
          <ElTableColumn prop="product_name" label="名称"> </ElTableColumn>
          <ElTableColumn prop="suk" label="单位"></ElTableColumn>
          <ElTableColumn prop="product_num" label="库存"></ElTableColumn>
        </template>
        <template v-if="actinoTabIndex == 2">
          <ElTableColumn type="selection" width="55" />
          <ElTableColumn prop="store_name" label="名称"> </ElTableColumn>
          <ElTableColumn prop="specs[0].name" label="单位"></ElTableColumn>
          <ElTableColumn prop="stock" label="库存"></ElTableColumn>
        </template>
      </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>
  </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 v-if="params.type == 'add' && actinoTabIndex == 1" @click="save(formRef)">
      保存</BaseButton
    >
    <BaseButton v-if="params.type == 'add' && actinoTabIndex == 2" @click="save(formRefs)">
      保存</BaseButton
    >
  </div>
</template>
