<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="70%">
    <div class="form-wrap">
      <div style="width: 1000px; margin-bottom: 20px">
        <el-descriptions :column="3" size="large" border>
          <el-descriptions-item>
            <template #label>
              <div>
                <el-icon color="green"><Money /></el-icon>
                <span> 余额：</span>
              </div>
            </template>
            <span>{{ userTaskInfo.balance }}</span>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div>
                <el-icon color="red"><Refrigerator /></el-icon>
                冻结：
              </div>
            </template>
            <span>{{ userTaskInfo.frozenBalance }}</span>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div>
                <el-icon color="red"><Refrigerator /></el-icon>
                可用佣金：
              </div>
            </template>
            <span>{{ userTaskInfo.availableCommission }}</span>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div>
                <el-icon color="blue"><Memo /></el-icon>
                今天完成单数
              </div>
            </template>
            <span>{{ userTaskInfo.completedTask }}</span>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div>
                <el-icon color="blue"><Memo /></el-icon>
                任务总数
              </div>
            </template>
            <span>{{ userTaskInfo.dailyTask }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div style="width: 1100px">
        <el-form
          label-position="left"
          label-width="100"
          ref="formRef"
          :rules="formRule"
          :model="formData"
          @validate="handleValidate"
        >
          <el-form-item label="第几单" prop="comboSequence">
            <el-input-number
              v-model="formData.comboSequence"
              :step="1"
              :max="userTaskInfo.dailyTask"
            />
            <div style="width: 30px"></div>
            <el-button type="primary" @click="calculateAmount" :loading="calcLoading">{{
              calcBalanceBtn
            }}</el-button>
          </el-form-item>
          <el-form-item v-if="showCalcReuslt">
            <span class="text-red-400"
              >预计余额在 {{ caleAmount.minBalance }} ~ {{ caleAmount.maxBalance }} 之间！
              只计算佣金奖励，其他奖励不包含。</span
            >
          </el-form-item>
          <el-form-item label="每单佣金" prop="multiplier">
            <el-input-number v-model="formData.multiplier" :step="1" />
            <div style="width: 30px"></div>
            <el-tag>原佣金的倍数</el-tag>
          </el-form-item>
          <el-row>
            <el-form-item label="任务金额" prop="taskAmount">
              <el-autocomplete v-model="formData.taskAmount" clearable :fetch-suggestions="querySearchTaskAmount"/>
            </el-form-item>
            <div style="width: 30px"></div>
            <el-form-item label="允许最大差值" prop="deviation">
              <el-input-number v-model="formData.deviation" />
            </el-form-item>
            <div style="width: 20px"></div>
            <el-form-item label="不允许重复" label-width="90">
              <el-tooltip class="box-item" content="勾选后搜索的商品不会重复出现" placement="top">
                <el-checkbox v-model="allowRepeat" />
              </el-tooltip>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="matchProduct" :disabled="searchDisable"
                >搜索</el-button
              >
            </el-form-item>
            <el-form-item prop="productList">
              <el-table :data="formData.productList" max-height="420px" v-loading="productLoading">
                <el-table-column type="index" label="序号" width="100px" />
                <el-table-column prop="id" label="商品ID" width="120px">
                  <template #default="scope">
                    <div class="table-column-wrap">
                      <span>{{ scope.row.id }}</span>
                      <el-button type="danger" @click="onClickDeleteProduct(scope)">删除</el-button>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="商品名称" />
                <el-table-column prop="price" label="价格" width="130px" />
                <el-table-column prop="quantity" label="数量" width="100px" />
                <el-table-column prop="totalPrice" label="总价" width="130px">
                  <template #default="{ row }">
                    <span>{{ row.price * row.quantity }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                  <template #default="scope">
                    <el-button type="primary" @click="onClickChange(scope)">换一个</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <div class="form-btn-wrap">
              <el-button type="primary" @click="onSubmit" :disabled="saveDisable">保存</el-button>
              <el-button @click="dialogVisible = false">关闭</el-button>
            </div>
          </el-row>
        </el-form>
      </div>
    </div>
    <div><span style="font-size: 18; font-weight: bold">当前连单</span></div>
    <div style="width: 100%">
      <el-table :data="combinationConfigList" max-height="420px" label-position="center">
        <el-table-column label="ID" prop="id" width="80" />
        <el-table-column label="会员编号" prop="username" width="180" />
        <el-table-column label="第几单" prop="comboSequence" width="100" />
        <el-table-column label="产品价格" prop="recordList" width="650">
          <template #default="{ row }">
            <el-descriptions :column="3" border size="small" v-for="item in row.recordList">
              <el-descriptions-item width="180">
                <template #label>
                  <span style="color: green">{{ item.productSort }}</span> 订单总额:
                </template>
                {{ item.totalPrice }}
              </el-descriptions-item>
              <el-descriptions-item width="100">
                <template #label> 佣金 </template>
                {{ ((item.totalPrice * row.multiplier) / 100).toFixed(2) }}
              </el-descriptions-item>
              <el-descriptions-item width="100">
                <template #label> 状态 </template>
                <dict-tag :type="DICT_TYPE.COMBO_RECORD_STATUS" :value="item.executeStatus" />
              </el-descriptions-item>
            </el-descriptions>
          </template>
        </el-table-column>
        <el-table-column label="本单佣金" prop="multiplier" width="150">
          <template #default="{ row }">
            <span>{{ row.multiplier }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="executeStatus" width="150">
          <template #default="{ row }">
            <dict-tag :type="DICT_TYPE.TASK_EXECUTE_STATUS" :value="row.executeStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              type="danger"
              @click="onClickDelete(row.id)"
              :disabled="deleteDisable || row.executeStatus === -1"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
  </Dialog>
</template>

<script setup lang="ts" name="CombinationConfigTable">
import { DICT_TYPE } from '@/utils/dict'
import { ElDescriptions, ElDescriptionsItem, ElMessage } from 'element-plus'
import { Money, Memo, Refrigerator } from '@element-plus/icons-vue'
import { getProductByPrice } from '@/api/member/product'
import { getConfigKey } from '@/api/infra/config'
import {
  createCombinationConfig,
  getCombinationConfigPage,
  updateCombinationExecuteStatus
} from '@/api/member/combinationConfig'
import { onMounted } from 'vue'
import { getUserTaskInfo, calcUserBalance } from '@/api/member/user'
import {useCache}  from "@/hooks/web/useCache"


defineOptions({ name: 'CombinationConfigTable' })

const userId = ref()
const { t } = useI18n() // 国际化
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
// 允许重复
const allowRepeat = ref(false)
// 搜索按钮是否可以点击
const searchDisable = ref(true)
// 保存按钮是否可以点击
const saveDisable = ref(true)
// 加载商品
const productLoading = ref(false)
// 显示计算结果
const showCalcReuslt = ref(false)
// 计算余额按钮
const calcBalanceBtn = ref('计算余额')
const calcLoading = ref(false)
// cache
const {wsCache} = useCache()
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  resetForm()
  userId.value = id
  dialogVisible.value = true
  searchDisable.value = true
  saveDisable.value = true
  dialogTitle.value = t('member.combinationConfig.' + type)
  showCalcReuslt.value = false
  await findUserTaskInfo()
  await pageCombinationConfig()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const userTaskInfo = ref({
  username: undefined,
  balance: undefined,
  frozenBalance: undefined,
  dailyTask: undefined,
  completedTask: undefined,
  id: undefined,
  availableCommission: undefined
})

// 获取用户余额
const findUserTaskInfo = async () => {
  let params = {
    id: userId.value
  }
  const data = await getUserTaskInfo(params)
  console.log(data)
  userTaskInfo.value = data
}
// 获取用户单数

// 表单
const formData = ref({
  comboSequence: undefined,
  multiplier: 3,
  productList: [],
  deviation: undefined,
  taskAmount: undefined
})
const searchLastIds = ref([-1])
const changeLastIds = ref({})

const resetForm = () => {
  formData.value.comboSequence = undefined
  formData.value.productList = []
  formData.value.multiplier = 3
  formData.value.taskAmount = undefined
  searchLastIds.value = [-1]
  changeLastIds.value = {}
}

// 表单校验
const formRef = ref()
const formRule = reactive({
  taskAmount: [{ required: true, message: '任务金额没有输入', trigger: 'change' }],
  comboSequence: [{ required: true, message: '请输入第几单', trigger: 'change' }],
  multiplier: [{ required: true, message: '佣金倍率必须填写', trigger: 'change' }]
})

const handleValidate = async (_prop: any, isValid: boolean) => {
  console.log('valid' + isValid)
  searchDisable.value = !isValid
}

watchEffect(() => {
  saveDisable.value = formData.value.productList.length > 0 ? false : true
})

const caleAmount = ref({
  minBalance: 0,
  maxBalance: 0
})
// 计算金额
const calculateAmount = async () => {
  calcBalanceBtn.value = '计算中'
  calcLoading.value = true
  const params = {
    userId: userId.value,
    comboSequence: formData.value.comboSequence
  }
  showCalcReuslt.value = true
  try {
    caleAmount.value = await calcUserBalance(params)
  } finally {
    calcBalanceBtn.value = '计算余额'
    calcLoading.value = false
  }
}

// 查询商品
const matchProduct = async () => {
  productLoading.value = true
  try {
    const data = await getProduct('search', searchLastIds.value)
    if (data) {
      formData.value.productList.push(data as never)
      if (allowRepeat.value) {
        searchLastIds.value.push(data.id)
      }
    }
  } finally {
    productLoading.value = false
  }
  console.log(formData.value.productList)
}

// 根据价格区间查询商品列表
const getProduct = async (type: string, lastIds: number[]) => {
  const queryParams = {
    price: formData.value.taskAmount,
    deviation: formData.value.deviation,
    lastIds: lastIds
  }
  const data = await getProductByPrice(queryParams)
  return data
}

// 点击换一个按钮
const onClickChange = async (scope: any) => {
  let lastIds = changeLastIds.value[scope.$index]
  if (!lastIds) {
    lastIds = [-1]
    changeLastIds.value[scope.$index] = lastIds
  }
  lastIds.push(scope.row.id)
  // 查询一个新的商品，把数组中的旧的商品替换掉
  const data = await getProduct('change', lastIds)
  formData.value.productList.splice(scope.$index, 1, data as never)
}

// 点击删除按钮
const onClickDeleteProduct = (scope: any) => {
  // 删除数组中的商品
  formData.value.productList.splice(scope.$index, 1)
}

// 保存任务记录
const onSubmit = async () => {
  saveDisable.value = false
  const valid = await formRef.value.validate()
  if (formData.value.productList.length == 0) {
    formRef.value.validator = false
  }
  if (!valid) return
  const data = {
    userId: userId.value,
    comboSequence: formData.value.comboSequence,
    taskAmount: formData.value.taskAmount,
    multiplier: formData.value.multiplier,
    productList: formData.value.productList
  }
  await createCombinationConfig(data)
  // 保存历史记录
  putTaskAmount()
  resetForm()
  await pageCombinationConfig()
  searchDisable.value = true
}

// 获取连单记录
const comboConfigQueryParams = ref({
  pageNo: 1,
  pageSize: 10,
  userId: userId.value
})
// 连单记录
const combinationConfigList = ref([])
const comboConfigLoading = ref(false)
const pageCombinationConfig = async () => {
  comboConfigLoading.value = true
  comboConfigQueryParams.value.userId = userId.value
  try {
    const res = await getCombinationConfigPage(comboConfigQueryParams.value)
    console.log(res)
    combinationConfigList.value = res.list
  } finally {
    comboConfigLoading.value = false
  }
}
const deleteDisable = ref(false)

// 删除连单记录
const onClickDelete = async (id: any) => {
  deleteDisable.value = true
  console.log('删除连单记录')
  let params = {
    id: id,
    executeStatus: -1
  }
  try {
    await updateCombinationExecuteStatus(params)
    ElMessage.success('删除成功')
    await pageCombinationConfig()
  } finally {
    deleteDisable.value = false
  }
}

// 卡单默认差值
const initDeviation = async () => {
  const res = await getConfigKey('defaultOrderDifference')
  formData.value.deviation = res
}

interface RestaurantItem {
  value: string
  link: string
}
// 显示历史任务金额
const restaurants = ref<RestaurantItem[]>([])
const querySearchTaskAmount = (queryString: string, cb: any) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value
  // call callback function to return suggestions
  cb(results)
}
const createFilter = (queryString: string) => {
  return (restaurant: RestaurantItem) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}
// 获取保存在store的金额
const loadAmount = () => {
  return wsCache.get('taskAmountStore') || []
}
// 最多保留10条记录
const putTaskAmount = () => {
  const taskAmount = formData.value.taskAmount
  if (taskAmount) {
    const index = restaurants.value.findIndex((item) => item.value === taskAmount)
    if (index !== -1) {
      restaurants.value.splice(index, 1)
    }
    restaurants.value.unshift({
      value: taskAmount,
      link: taskAmount
    })
    if (restaurants.value.length > 15) {
      restaurants.value.pop()
    }
    wsCache.set('taskAmountStore', restaurants.value)
  }
}
onMounted(async () => {
  await initDeviation()
  restaurants.value = loadAmount()
})
</script>

<style scoped lang="scss">
.form-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.table-column-wrap {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.form-btn-wrap {
  display: flex;
  width: 100%;
  margin-top: 20px;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
</style>
