<template>
  <!-- 档期计划 -->
  <!-- 隐藏门店搜索 -->
  <SearchList :showSearch="showSearch"
    :queryParams="params"
    @change="getTableList"
    :showStoreSearch="false" />
  <CustomTable :tableData="tableData"
    :baseColumns="baseColumns"
    :total="total"
    :params="params"
    :isLoading="isLoading"
    :formatter="formatterFn"
    tabsType="档期计划"
    @getTableList="getTableList"
    @updateShowSearch="v => showSearch = v" />
  <!-- 弹窗：实际与计划不一致，让用户补充实际内容 -->
  <el-dialog v-model="showPromotionDialog"
    title="请输入实际促销机制内容"
    width="500%"
    :before-close="handleDialogClose">
    <el-form :model="dialogForm"
      label-width="80px">
      <el-form-item label="实际内容">
        <el-input v-model="dialogForm.actualPromotionContent"
          type="textarea"
          :rows="4"
          placeholder="请输入实际促销机制内容" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary"
          @click="handleDialogConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

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

  const { proxy } = getCurrentInstance()
  /*************** 操作类型 ***************/

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

    let requestObj = {}
    if (col.requestKey) {
      // 关联的公式计算列，需要特殊处理
      for (const str of col.requestKey) {
        const obj = getSchedulePlanConfig().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 submitDisplaySchedulePlan({
      id: row.sapId,
      [col.prop]: row[col.prop], // 当前修改列的值
      ...requestObj,
      actualPromotionFlavor: Array.isArray(row.actualPromotionFlavor) ? row.actualPromotionFlavor.join(',') : '-', // 档期执行-促销口味，为数组时，转成字符串
      actualPromotionStartDate: row.actualPromotionStartDate ? parseTime(row.actualPromotionStartDate, '{y}-{m}-{d}') : '', // 档期执行-促销开始日期，为字符串时，转成日期格式
    })
  }
  // 基础列配置
  const baseColumns = ref(getSchedulePlanConfig(submitChange));

  // 表格数据
  const tableData = ref([])
  const isLoading = ref(true)
  const params = ref({
    pageNum: 1,
    pageSize: 50,
    salesMonth: new Date(),
    deptName: '',
    dealerCN: '',
    lineNameLike: '',
    storeCN: ''
  })
  const total = ref(0)

  // 获取表格数据
  const getTableList = async () => {
    isLoading.value = true
    const res = await getDisplayScheduleList({
      ...params.value,
      rqStatus: params.value.rqStatus === '全部' ? '' : params.value.rqStatus,
      salesMonth: parseTime(params.value.salesMonth, '{y}-{m}')
    })
    // 处理日期格式
    res.data.rows.forEach(item => {
      item.salesMonth = parseTime(item.salesMonth, '{y}-{m}')
      item.openingDate = parseTime(item.openingDate, '{y}-{m}-{d}')
      item.plannedAdjustmentStartDate = parseTime(item.plannedAdjustmentStartDate, '{y}-{m}-{d}')
      item.plannedAdjustmentEndDate = parseTime(item.plannedAdjustmentEndDate, '{y}-{m}-{d}')
      item.plannedPromotionStartDate = parseTime(item.plannedPromotionStartDate, '{y}-{m}-{d}')
      item.actualPromotionStartDate = parseTime(item.actualPromotionStartDate, '{y}-{m}-{d}')
      item.plannedPromotionEndDate = parseTime(item.plannedPromotionEndDate, '{y}-{m}-{d}')
      item.actualPromotionEndDate = parseTime(item.actualPromotionEndDate, '{y}-{m}-{d}')
      item.totalCostRate = item.totalCostRate ? `${(item.totalCostRate).toFixed(2)}%` : '-'
      item.adjustmentCostRatio = item.adjustmentCostRatio ? `${(item.adjustmentCostRatio).toFixed(2)}%` : '-'
      // 档期执行-促销口味从字符串转成数组（回显用）
      item.actualPromotionFlavor = item.actualPromotionFlavor ? item.actualPromotionFlavor.split(',') : []
      // 修改时间
      item.updateTime = parseTime(item.updateTime, '{y}-{m}-{d} {h}:{i}:{s}')
    })
    tableData.value = res.data.rows
    total.value = res.data.total
    isLoading.value = false
  }

  // 表格格式化指定列的数据内容
  const formatterFn = (row, col, cellValue) => {
    if (col.prop === 'actualPromotionFlavor') {
      // 对数组内容格式化，为空时，显示'-'
      return cellValue.length ? cellValue.join(',') : '-'
    }
    return cellValue
  }

  onMounted(() => {
    getTableList()
  })
  const showSearch = ref(true)

  /*************** 弹窗 ***************/
  const showPromotionDialog = ref(false)
  const nowEnterRow = ref({}) // 当前弹窗弹出时，要填写哪行的数据对象
  const nowEnterRowProp = ref('') // 当前弹窗弹出时，要填写哪行的数据对象的属性
  const dialogForm = reactive({
    actualPromotionContent: '',
  })
  // 弹窗关闭时，清空表单数据
  const handleDialogClose = () => {
    showPromotionDialog.value = false
    dialogForm.actualPromotionContent = ''
    nowEnterRow.value = {}
    nowEnterRowProp.value = ''
  }
  // 确定
  const handleDialogConfirm = async () => {
    if (!dialogForm.actualPromotionContent) {
      proxy.$modal.msgError('请输入实际促销机制内容')
      return
    }
    // 赋值
    nowEnterRow.value[nowEnterRowProp.value] = dialogForm.actualPromotionContent
    showPromotionDialog.value = false
  }

</script>
