<template>
  <!-- 六小金刚 -->
  <SearchList :showSearch="showSearch"
    :queryParams="params"
    @change="getTableList" />
  <CustomTable :tableData="tableData"
    :baseColumns="baseColumns"
    :total="total"
    :params="params"
    :isLoading="isLoading"
    @getTableList="getTableList"
    @updateShowSearch="v => showSearch.value = v" />
</template>

<script setup
  lang="jsx">
  import CustomTable from '../components/Table'
  import SearchList from '../components/SearchList'
  import { getSixLittleDiamondsPlanList, submitSixLittleDiamondsPlan } from '@/api'
  import { getSixLittleDiamondsConfig } from './data.jsx'
  import { parseTime } from '@/utils'

  const { proxy } = getCurrentInstance()
  /*************** 搜索列表 ***************/
  const showSearch = ref(true)

  /*************** 表格 ***************/
  // 提交变更
  const submitChange = async (row, col) => {

    let requestObj = {}
    if (col.requestKey) {
      // 关联的公式计算列，需要特殊处理
      for (const str of col.requestKey) {
        const obj = getSixLittleDiamondsConfig().flatMap(item => {
          if (item.children) {
            return item.children.filter(child => !child.onlyFill);
          }
          return [];
        }).find(item => item.prop === str)
        if (obj && obj.type === 'formula') {
          obj.func(row)
        }
      }
      requestObj = col.requestKey.reduce((acc, key) => ({ ...acc, [key]: row[key] }), {})
    }

    await submitSixLittleDiamondsPlan({
      id: row.sadjId,
      [col.prop]: row[col.prop], // 当前修改列的值
      ...requestObj
    })

  }
  // 全部列
  const baseColumns = ref(getSixLittleDiamondsConfig(submitChange));

  const tableData = ref([])
  const isLoading = ref(false)
  const total = ref(0)

  const params = ref({
    pageNum: 1,
    pageSize: 50,
    salesMonth: new Date(),
    deptName: '',
    dealerCN: '',
    lineNameLike: '',
    storeCN: ''
  })
  const getTableList = () => {
    isLoading.value = true
    getSixLittleDiamondsPlanList({
      ...params.value,
      salesMonth: parseTime(params.value.salesMonth, '{y}-{m}')
    }).then(res => {
      isLoading.value = false
      tableData.value = res.data.rows.map(item => {
        // 计划月份
        item.salesMonth = proxy.parseTime(item.salesMonth, '{y}-{m}')
        return item
      }) || []
      total.value = res.data.total || 0
    })
  }
  getTableList()
</script>

<style scoped></style>