<template>
  <!-- 档期陈列 -->
  <el-form :inline="true"
    :model="queryParams"
    class="demo-form-inline">
    <el-form-item label="计划月份">
      <el-date-picker v-model="queryParams.salesMonth"
        type="month"
        placeholder="选择计划月份"
        @change="getTableList"
        clearable />
    </el-form-item>
  </el-form>
  <CustomTable :tableData="tableData"
    :baseColumns="baseColumns"
    :isLoading="isLoading"
    @getTableList="getTableList"
    @updateShowSearch="v => showSearch.value = v" />
</template>

<script setup
  lang="jsx">
  import CustomTable from '../components/Table'
  import { getDisplayScheduleDashboardList, getDisplayScheduleDashboardListArea } from '@/api'
  import { parseTime } from '@/utils'
  import { getScheduleDisConfig } from './data'

  /*************** 表格数据 ***************/
  // 提交变更
  const submitChange = async (row, col) => {
    // 需要特殊处理的
    // 1. 实际主货架-形式，为空时，置空实际主货架-数量
    if (col.prop === 'actualMainShelfType' && !row.actualMainShelfType) {
      row.actualMainShelfQty = 0
    }

    // 关联的公式计算列，需要特殊处理
    for (const str of col.requestKey) {
      const obj = getScheduleDisConfig().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)
      }
    }

    await submitDisplayScheduleDetail({
      id: row.sapdId,
      [col.prop]: row[col.prop], // 当前修改列的值
      ...col.requestKey.reduce((acc, key) => ({ ...acc, [key]: row[key] }), {}), // 额外携带影响的列字段值
      // 特殊类型字段处理
      // 端架数量实际
      actualEndCapQty: row.actualEndCapQty || 0,
      // 地堆平米数实际
      actualFloorStackArea: row.actualFloorStackArea || 0,
    })
  }
  // 全部列
  const baseColumns = ref(getScheduleDisConfig(submitChange));

  // 表格数据
  const queryParams = reactive({
    salesMonth: new Date(),
  })
  const tableData = ref([])
  const isLoading = ref(true)
  const total = ref(0)

  // 筛选列表数据
  const getTableList = async (operation) => {
    isLoading.value = true
    const res = await (operation === '大区战区-分析' ? getDisplayScheduleDashboardList : getDisplayScheduleDashboardListArea)({
      ...queryParams,
      salesMonth: parseTime(queryParams.salesMonth, '{y}-{m}')
    })
    if (operation === '大区战区-分析') {
      // 合并战区大区结构为扁平化
      const { zq, dq } = res.data
      tableData.value = [...zq, ...dq]
    } else {
      // 合并城市经理结构为扁平化
      tableData.value = res.data
    }
    isLoading.value = false
  }
  const { proxy } = getCurrentInstance()
  const isDaQuZQ = proxy.checkPermi(['promotion:dashboard:list-show'])
  getTableList(isDaQuZQ ? '大区战区-分析' : '城市经理-分析')

</script>