<template>
  <!-- 档期计划 -->
  <!-- 隐藏门店搜索 -->
  <SearchList :showSearch="showSearch"
    @change="searchChange"
    :showStoreSearch="false" />
  <CustomTable :tableData="tableData"
    :isLoading="isLoading"
    :total="total"
    :tableColumns="tableColumns"
    :chooseColumns="chooseColumns"
    :visibleProps="visibleProps"
    :params="params"
    :showFill="showFill"
    :formatter="formatterFn"
    @updateColumns="updateColumns"
    @getTableList="getTableList"
    @updateShowSearch="updateShowSearch" />
  <!-- 弹窗：实际与计划不一致，让用户补充实际内容 -->
  <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 '@/views/promotion/components/Table'
  import SearchList from '@/views/promotion/components/SearchList'
  import { getDisplayScheduleList, submitDisplaySchedulePlan } from '@/api'
  import { parseTime } from '@/utils'
  import userStore from '@/store/modules/user'
  import { ElMessageBox } from 'element-plus'

  const { proxy } = getCurrentInstance()

  // 是否启用填报模式
  const showFill = userStore().hasQcMarketEmpInfo

  /*************** 操作类型 ***************/
  function splitAndFilter(str) {
    // 分割字符串并处理空值
    return str.split(/[,，]/)
      .map(item => item.trim())       // 去除前后空格
      .filter(item => item.length > 0); // 过滤空字符串
  }
  // 基础列配置
  const baseColumns = ref([
    {
      label: "基础信息",
      children: [
        // {
        //   label: '操作提示',
        //   prop: 'operationTip', // 列属性
        //   visible: true, // 是否显示
        //   type: 'string', // 列类型
        //   fill: true, // 是否为填报列
        //   fixed: 'left', // 是否固定在左侧
        //   width: 100,
        //   onlyFill: true, // 只在填报列显示
        //   render: (_, row, col) => {
        //     return (
        //       <div class="operation_tip_cell">
        //         <p>计划</p>
        //         <p>实际</p>
        //       </div>
        //     )
        //   }
        // },
        {
          label: '计划月份',
          prop: 'salesMonth',
          visible: true,
          type: 'string',
          fill: false,
          width: 100
        },
        {
          label: "销售大区",
          prop: "regionName",
          visible: true,
          type: "string",
          fill: false,
          width: 100
        },
        {
          label: "销售战区",
          prop: "districtName",
          visible: true,
          type: "string",
          fill: false,
          width: 100
        },
        {
          label: "经销商-省份",
          prop: "dealerProvince",
          visible: true,
          type: "string",
          fill: false,
          width: 100
        },
        {
          label: "经销商-城市",
          prop: "dealerCity",
          visible: true,
          type: "string",
          fill: false,
          width: 100
        },
        {
          label: "经销商-代码",
          prop: "dealerCode",
          visible: true,
          type: "string",
          fill: false,
          width: 100
        },
        {
          label: "经销商名称",
          prop: "dealerName",
          visible: true,
          showOverflowTooltip: true,
          type: "string",
          fill: true,
          fixed: 'left',
          width: 200
        },
        {
          label: "经销商类型",
          prop: "dealerType",
          visible: true,
          showOverflowTooltip: true,
          type: "string",
          fill: false,
          width: 100
        },
        {
          label: "开户日期",
          prop: "openingDate",
          visible: true,
          type: "string",
          fill: false,
          width: 100
        },
        {
          label: "闭户日期",
          prop: "closingDate",
          visible: true,
          type: "string",
          fill: false,
          width: 100
        },
        {
          label: "大区总监",
          prop: "regionManager",
          visible: true,
          type: "string",
          fill: false,
          width: 100
        },
        {
          label: "战区经理",
          prop: "districtManager",
          visible: true,
          type: "string",
          fill: false,
          width: 100
        },
        {
          label: "城市经理",
          prop: "cityManager",
          visible: true,
          type: "string",
          fill: false,
          width: 100
        },
        {
          label: "系统名称",
          prop: "lineName",
          visible: true,
          type: "string",
          fill: true,
          // fixed: 'left',
          width: 100
        },
        {
          label: "系统类型",
          prop: "lineType",
          visible: true,
          type: "string",
          fill: false,
          width: 100
        },
        {
          label: "渠道大类",
          showOverflowTooltip: true,
          prop: "channelDl",
          visible: true,
          type: "string",
          fill: false,
          width: 100
        },
        {
          label: "渠道小类",
          prop: "channelXl",
          showOverflowTooltip: true,
          visible: true,
          type: "string",
          fill: false,
          width: 100
        },
        {
          label: "系统业态",
          showOverflowTooltip: true,
          prop: "lineLf",
          visible: true,
          type: "string",
          fill: false,
          width: 100
        },
        {
          label: "门店数",
          prop: "storeCount",
          visible: true,
          type: "string",
          fill: false,
          width: 100
        }
      ],
      prop: 'baseColumns',
      visible: true
    },
    {
      label: "档期基础信息",
      children: [
        {
          label: "档期执行月份",
          prop: "promotionExecutionMonth",
          visible: true,
          type: "string",
          fill: false,
          width: 100
        },
        {
          label: "档期促销规格",
          subLabel: '计划',
          prop: "plannedPromotionSpec",
          showOverflowTooltip: true,
          visible: true,
          type: "string",
          fill: true,
          width: 150
        },
        {
          label: "档期促销规格",
          subLabel: '实际',
          prop: "actualPromotionSpec",
          visible: true,
          type: 'select',
          options: [
            // {
            //   label: '虎皮105g',
            //   value: '虎皮105g'
            // },
            // {
            //   label: '虎皮210g',
            //   value: '虎皮210g'
            // },
            // {
            //   label: '去骨72g',
            //   value: '去骨72g'
            // },
            // {
            //   label: '去骨138g',
            //   value: '去骨138g'
            // },
            // {
            //   label: '小鸡腿80g',
            //   value: '小鸡腿80g'
            // },
            // {
            //   label: '老卤95g',
            //   value: '老卤95g'
            // },
            // {
            //   label: '鸡肉豆堡',
            //   value: '鸡肉豆堡'
            // },
            // {
            //   label: '牛肉豆堡',
            //   value: '牛肉豆堡'
            // }
          ],
          referenceKey: "plannedPromotionSpec",
          fill: true,
          width: 150,
          render: (_, row, col) => {
            let list = splitAndFilter(row[col.referenceKey])
            list = list.map(item => ({
              label: item,
              value: item
            })).concat([{
              label: '其他',
              value: '其他'
            }])
            return (
              <div>
                {/* <span>{row[col.referenceKey] || '-'}</span> */}
                <el-select modelValue={row[col.prop]}
                  onUpdate:modelValue={async (value) => {
                    row[col.prop] = value;
                    await submitChange(row, col);
                    col.checkFn(row)
                  }}
                  disabled={!row[col.referenceKey]}
                  class={{ 'no-disabled': row[col.referenceKey] }}
                  placeholder=""
                  clearable
                >
                  {list.map(item => (
                    <el-option
                      key={item.value}
                      label={item.label}
                      value={item.value}
                    />
                  ))}
                </el-select>
              </div>
            )
          },
          checkFn(row) {
            // 检查点击选项并决定是否弹窗
            if (row.actualPromotionSpec && row.actualPromotionSpec.includes('其他')) {
              // 直接使用 ElMessageBox.prompt() 方法
              ElMessageBox.prompt('请输入实际执行规格', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputType: 'textarea',
                inputPlaceholder: '请输入实际执行规格',
                // 可以设置输入框的行数
                inputValidator: (value) => {
                  if (!value || !value.trim()) {
                    return '请输入实际执行规格'
                  }
                  return true
                }
              }).then(({ value }) => {
                // 用户点击确定后，直接将输入的值赋予给 row 对象的指定属性
                row.actualPromotionSpecRe = value
                // 这里可以直接调用 submitChange 函数提交修改
                submitChange(row, { prop: 'actualPromotionSpecRe' })
              }).catch(() => {
                // 用户点击取消或关闭弹窗
              })
            } else {
              // 没选其他，则清空实际执行规格
              row.actualPromotionSpecRe = ''
              // 这里可以直接调用 submitChange 函数提交修改
              submitChange(row, { prop: 'actualPromotionSpecRe' })
            }
          },
          // 请求时需要额外携带影响的列字段值
          requestKey: ["specExecutionStatus", "promotionExecutionStatus"]
        },
        {
          label: "实际执行规格",
          prop: "actualPromotionSpecRe",
          visible: true,
          type: "input",
          render: (_, row, col) => {
            return (
              <div>
                {
                  row.actualPromotionSpec !== '其他' ? (<div style="width: 100%; text-align: center;">-</div>) : (
                    <el-input modelValue={row[col.prop]}
                      onUpdate:modelValue={(value) => {
                        row[col.prop] = value;
                        submitChange(row, col);
                      }}
                      class='no-disabled'
                      placeholder="">
                    </el-input>
                  )
                }
              </div>
            )
          },
          fill: true,
          width: 150
        },
        {
          label: "档期规格是否",
          subLabel: '按计划执行',
          prop: "specExecutionStatus",
          visible: true,
          type: 'formula',
          func: (row) => {
            // 如果参考值是空则返回 '-'
            if (!row.plannedPromotionSpec) {
              row.specExecutionStatus = '-';
              return '-';
            }
            row.specExecutionStatus = row.plannedPromotionSpec === row.actualPromotionSpec ? '执行' : '未执行';
            return row.specExecutionStatus;
          },
          formulaStr: '公式：（档期计划促销规格 = 档期执行促销规格）',
          fill: true,
          width: 150
        },
        {
          label: "档期促销口味",
          subLabel: '计划',
          prop: "plannedPromotionFlavor",
          visible: true,
          type: "string",
          fill: true,
          width: 150
        },
        {
          label: "档期促销口味",
          subLabel: '实际',
          prop: "actualPromotionFlavor",
          visible: true,
          type: 'select',
          options: [],
          referenceKey: "plannedPromotionFlavor",
          fill: true,
          width: 150,
          render: (_, row, col) => {
            // options 根据参考属性值来决定（计划值）
            let list = splitAndFilter(row[col.referenceKey])
            let isFullFlavor = false
            // 如果数组里有"全系列"/"全口味"则修改数组
            if (list.includes('全口味')) {
              list = [
                {
                  label: '全口味',
                  value: '全口味'
                },
                {
                  label: '部分口味',
                  value: '部分口味'
                }
              ]
              isFullFlavor = true
            } else {
              list = list.map(item => ({
                label: item,
                value: item
              })).concat([{
                label: '其他',
                value: '其他'
              }])
              isFullFlavor = false
            }
            // span 标签超出宽度时显示省略号
            return (
              <div>
                {/* <el-tooltip placement="top" content={row[col.referenceKey] || '-'} disabled={!isContentOverflow(col.referenceKey, row[col.referenceKey], col)}>
                  <span >
                    {row[col.referenceKey] || '-'}
                  </span>
                </el-tooltip> */}
                <el-select modelValue={row[col.prop]}
                  onUpdate:modelValue={async (value) => {
                    row[col.prop] = value;
                    await submitChange(row, col);
                    {/* 检查一下未执行/部分执行时，填写实际执行内容 */ }
                    col.checkFn(row)
                  }}
                  disabled={!row[col.referenceKey]}
                  class={{ 'no-disabled': row[col.referenceKey] }}
                  placeholder=""
                  clearable
                  multiple={!isFullFlavor}
                  collapse-tags={!isFullFlavor}
                  collapse-tags-tooltip={!isFullFlavor}>
                  {list.map(item => (
                    <el-option
                      key={item.value}
                      label={item.label}
                      value={item.value}
                    />
                  ))}
                </el-select>
              </div >
            )
          },
          checkFn(row) {
            // 检查点击选项并决定是否弹窗
            if (row.actualPromotionFlavor && row.actualPromotionFlavor.includes('其他')) {
              // 直接使用 ElMessageBox.prompt() 方法
              ElMessageBox.prompt('请输入实际执行口味', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputType: 'textarea',
                inputPlaceholder: '请输入实际执行口味',
                // 可以设置输入框的行数
                inputValidator: (value) => {
                  if (!value || !value.trim()) {
                    return '请输入实际执行口味'
                  }
                  return true
                }
              }).then(({ value }) => {
                // 用户点击确定后，直接将输入的值赋予给 row 对象的指定属性
                row.actualPromotionFlavorRe = value
                // 这里可以直接调用 submitChange 函数提交修改
                submitChange(row, { prop: 'actualPromotionFlavorRe' })
              }).catch(() => {
                // 用户点击取消或关闭弹窗
              })
            } else {
              // 没选其他，则清空实际执行口味
              row.actualPromotionFlavorRe = ''
              // 这里可以直接调用 submitChange 函数提交修改
              submitChange(row, { prop: 'actualPromotionFlavorRe' })
            }
          },
          // 请求时需要额外携带影响的列字段值
          requestKey: ["flavorExecutionStatus", "promotionExecutionStatus"]
        },
        {
          label: "实际执行口味",
          prop: "actualPromotionFlavorRe",
          visible: true,
          type: "input",
          render: (_, row, col) => {
            return (
              <div>
                {
                  row.actualPromotionFlavor.includes('其他') ? (
                    <el-input modelValue={row[col.prop]}
                      onUpdate:modelValue={(value) => {
                        row[col.prop] = value;
                        submitChange(row, col);
                      }}
                      class='no-disabled'
                      placeholder="">
                    </el-input>
                  ) : (<div style="width: 100%; text-align: center;">-</div>)
                }
              </div>
            )
          },
          fill: true,
          width: 150,
        },
        {
          label: "档期口味是否",
          subLabel: '按计划执行',
          prop: "flavorExecutionStatus",
          visible: true,
          type: 'formula',
          func: (row) => {
            // 如果参考值是空则返回 '-'
            if (!row.plannedPromotionFlavor) {
              row.flavorExecutionStatus = '-';
              return '-';
            }
            // 处理逗号的口味形成数组
            let ppromotionFlavor = splitAndFilter(row.plannedPromotionFlavor)
            if (!row.actualPromotionFlavor) {
              // 判断空字符串
              row.flavorExecutionStatus = '未执行';
            } else if (row.actualPromotionFlavor?.length === 0) {
              // 空数组
              row.flavorExecutionStatus = '未执行';
            } else if (row.actualPromotionFlavor?.length === 1 && row.actualPromotionFlavor[0] === '其他') {
              // 数组里只有其他，则是未执行
              row.flavorExecutionStatus = '未执行';
            } else if (row.actualPromotionFlavor.includes('其他')) {
              // 数组里包含其他，就是部分执行
              row.flavorExecutionStatus = '部分执行';
            } else if (row.actualPromotionFlavor?.length !== ppromotionFlavor?.length) {
              // 计划的个数和实际选择的不一致，则也是部分执行
              row.flavorExecutionStatus = '部分执行';
            } else if (row.actualPromotionFlavor?.length === 1 && row.actualPromotionFlavor[0] === '全口味') {
              // 有且只有一个，并且是全口味，则执行
              row.flavorExecutionStatus = '执行';
            } else if (row.actualPromotionFlavor?.length === ppromotionFlavor.length && row.actualPromotionFlavor.every(item => ppromotionFlavor.includes(item))) {
              row.flavorExecutionStatus = '执行';
            }
            return row.flavorExecutionStatus;
          },
          formulaStr: '公式：（档期计划促销口味 = 档期执行促销口味）',
          fill: true,
          width: 150,
        },
      ],
      prop: 'scheduleInfo',
      visible: true
    },
    {
      label: "合计费用",
      prop: 'totalCostParent',
      children: [
        {
          label: "合计费用",
          prop: "totalCost",
          visible: true,
          type: "string",
          fill: false,
          width: 105
        },
        {
          label: "合计费率",
          prop: "totalCostRate",
          visible: true,
          type: "string",
          fill: false,
          width: 85
        }
      ],
      visible: true
    },
    {
      label: "促销计划",
      prop: 'promotionPlan',
      children: [
        {
          label: "计划-档期形式",
          prop: "plannedPromotionFormat",
          visible: true,
          type: "string",
          fill: false,
          width: 115
        },
        {
          label: "计划-核销方式",
          prop: "plannedVerificationMethod",
          visible: true,
          type: "string",
          fill: false,
          width: 115
        },
        {
          label: "计划-档期规则",
          prop: "plannedPromotionRules",
          visible: true,
          type: "string",
          fill: false,
          width: 115
        },
        {
          label: "计划-档期前补差天数",
          prop: "plannedPrePromotionAdjustDays",
          visible: true,
          type: "string",
          fill: false,
          width: 155
        },
        {
          label: "计划-档期后补差天数",
          prop: "plannedPostPromotionAdjustDays",
          visible: true,
          type: "string",
          fill: false,
          width: 155
        },
        {
          label: "档期开始时间",
          subLabel: '计划',
          prop: "plannedPromotionStartDate",
          visible: true,
          type: "string",
          fill: true,
          width: 150
        },
        {
          label: "计划-补差开始时间",
          prop: "plannedAdjustmentStartDate",
          visible: true,
          type: "string",
          fill: false,
          width: 140
        },
        {
          label: "档期开始时间",
          subLabel: '实际',
          prop: "actualPromotionStartDate",
          visible: true,
          type: 'date',
          referenceKey: "plannedPromotionStartDate",
          fill: true,
          width: 150,
          render: (_, row, col) => {
            return (
              <div>
                {/* <span>{row[col.referenceKey] || '-'}</span> */}
                <div class={['date-picker', { 'no-disabled': row[col.referenceKey] }]}>
                  <el-date-picker modelValue={row[col.prop]}
                    onUpdate:modelValue={(value) => {
                      row[col.prop] = value;
                      submitChange(row, col);
                    }}
                    disabled={!row[col.referenceKey]}
                    placeholder=""
                    clearable
                    type="date"
                  />
                </div>
              </div>
            )
          },
          requestKey: ["timeExecutionStatus", 'promotionImplementationStatus']
        },
        {
          label: "档期结束时间",
          subLabel: '计划',
          prop: "plannedPromotionEndDate",
          visible: true,
          type: "string",
          fill: true,
          width: 150,
        },
        {
          label: "计划-补差结束时间",
          prop: "plannedAdjustmentEndDate",
          visible: true,
          type: "string",
          fill: false,
          width: 140
        },
        {
          label: "档期结束时间",
          subLabel: '实际',
          prop: "actualPromotionEndDate",
          visible: true,
          type: 'date',
          fill: true,
          referenceKey: "plannedPromotionEndDate",
          width: 150,
          render: (_, row, col) => {
            return (
              <div>
                {/* <span>{row[col.referenceKey] || '-'}</span> */}
                <div class={['date-picker', { 'no-disabled': row[col.referenceKey] }]}>
                  <el-date-picker modelValue={row[col.prop]}
                    onUpdate:modelValue={(value) => {
                      row[col.prop] = value;
                      submitChange(row, col);
                    }}
                    disabled={!row[col.referenceKey]}
                    placeholder=""
                    clearable
                    type="date"
                  />
                </div>
              </div>
            )
          },
          requestKey: ["timeExecutionStatus", 'promotionImplementationStatus']
        },
        {
          label: "档期是否",
          subLabel: '按计划执行',
          prop: "promotionImplementationStatus",
          visible: true,
          type: 'formula',
          func: (row) => {
            // 如果参考值是空则返回 '-'
            if (!row.plannedPromotionStartDate || !row.plannedPromotionEndDate) {
              row.promotionImplementationStatus = '-';
              return '-';
            }
            row.promotionImplementationStatus = row.actualPromotionStartDate && row.actualPromotionEndDate ? '执行' : '未执行';
            return row.promotionImplementationStatus;
          },
          formulaStr: '公式：（实际档期开始时间不为空，并且实际档期结束时间不为空）',
          fill: true,
          width: 150
        },
        {
          label: "时间是否",
          subLabel: '按计划执行',
          prop: "timeExecutionStatus",
          visible: true,
          type: 'formula',
          func: (row) => {
            // 如果参考值是空则返回 '-'
            if (!row.plannedPromotionStartDate || !row.plannedPromotionEndDate) {
              row.timeExecutionStatus = '-';
              return '-';
            }
            row.timeExecutionStatus = (parseTime(row.actualPromotionStartDate) === parseTime(row.plannedPromotionStartDate)) && parseTime(row.actualPromotionEndDate) === parseTime(row.plannedPromotionEndDate) ? '执行' : '未执行';
            return row.timeExecutionStatus;
          },
          formulaStr: '公式：（实际档期开始时间 = 计划档期开始时间，并且实际档期结束时间 = 计划档期结束时间）',
          fill: true,
          width: 150
        },
        {
          label: "促销机制",
          subLabel: '计划',
          prop: "plannedPromotionMechanism",
          visible: true,
          type: "string",
          fill: true,
          width: 150
        },
        {
          label: "促销机制",
          subLabel: '实际',
          prop: "actualPromotionMechanism",
          visible: true,
          type: 'select',
          referenceKey: "plannedPromotionMechanism",
          fill: true,
          width: 190,
          options: [
            {
              label: '执行与计划一致',
              value: '执行与计划一致'
            },
            {
              label: '执行与计划不一致',
              value: '执行与计划不一致'
            }
          ],
          render: (_, row, col) => {
            return (
              <div>
                {/* <span>{row[col.referenceKey] || '-'}</span> */}
                <div style="width: 100%">
                  <el-select modelValue={row[col.prop]}
                    onUpdate:modelValue={async (value) => {
                      row[col.prop] = value;
                      await submitChange(row, col);
                      col.checkFn(row)
                    }}
                    disabled={!row[col.referenceKey]}
                    class={{ 'no-disabled': row[col.referenceKey] }}
                    placeholder=""
                    clearable
                  >
                    {col.options.map(item => (
                      <el-option key={item.value} label={item.label} value={item.value} />
                    ))}
                  </el-select>
                </div>
              </div>
            )
          },
          checkFn(row) {
            // 检查点击选项并决定是否弹窗
            if (row.actualPromotionMechanism === '执行与计划不一致') {
              // 直接使用 ElMessageBox.prompt() 方法
              ElMessageBox.prompt('请输入实际执行价格', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputType: 'textarea',
                inputPlaceholder: '请输入实际执行价格',
                // 可以设置输入框的行数
                inputValidator: (value) => {
                  if (!value || !value.trim()) {
                    return '请输入实际执行价格'
                  }
                  return true
                }
              }).then(({ value }) => {
                // 用户点击确定后，直接将输入的值赋予给 row 对象的指定属性
                row.actualPromotionPriceRe = value
                // 这里可以直接调用 submitChange 函数提交修改
                submitChange(row, { prop: 'actualPromotionPriceRe' })
              }).catch(() => {
                // 用户点击取消或关闭弹窗
              })
            } else {
              // 没选其他，则清空实际执行价格
              row.actualPromotionPriceRe = ''
              // 这里可以直接调用 submitChange 函数提交修改
              submitChange(row, { prop: 'actualPromotionPriceRe' })
            }
          }
        },
        {
          label: "实际执行价格",
          prop: "actualPromotionPriceRe",
          visible: true,
          type: "input",
          render: (_, row, col) => {
            return (
              <div>
                {
                  row.actualPromotionMechanism !== '执行与计划不一致' ? (<div style="width: 100%; text-align: center;">-</div>) : (
                    <el-input modelValue={row[col.prop]}
                      onUpdate:modelValue={(value) => {
                        row[col.prop] = value;
                        submitChange(row, col);
                      }}
                      class='no-disabled'
                      placeholder="">
                    </el-input>
                  )
                }
              </div>
            )
          },
          fill: true,
          width: 150
        },
        // {
        //   label: "促销机制是否执行",
        //   prop: "promotionMechanismExecutionStatus",
        //   visible: true,
        //   type: 'formula',
        //   func: (row) => {
        //     // 如果参考值是空则返回 '-'
        //     if (!row.plannedPromotionMechanism) {
        //       row.promotionMechanismExecutionStatus = '-';
        //       return '-';
        //     }
        //     row.promotionMechanismExecutionStatus = row.actualPromotionMechanism === '执行与计划一致' ? '执行' : '未执行';
        //     return row.promotionMechanismExecutionStatus;
        //   },
        //   formulaStr: '公式：实际促销机制，是否有值',
        //   fill: true,
        //   width: 150,
        // },
        {
          label: "预估袋数",
          prop: "estimatedBagCount",
          visible: true,
          type: "string",
          fill: false,
          width: 90
        },
        // {
        //   label: "档期备货量（袋）",
        //   prop: "promotionStockQuantity",
        //   visible: true,
        //   type: 'input',
        //   format: 'number',
        //   referenceKey: "estimatedBagCount",
        //   fill: true,
        //   width: 135,
        //   render: (_, row, col) => {
        //     return (
        //       <div>
        //         <span>{row[col.referenceKey] || '-'}</span>
        //         <div>
        //           <el-input modelValue={row[col.prop]}
        //             onUpdate:modelValue={(value) => {
        //               row[col.prop] = value;
        //               submitChange(row, col);
        //             }}
        //             disabled={!row[col.referenceKey]}
        //             placeholder=""
        //             clearable
        //           />
        //         </div>
        //       </div>
        //     )
        //   }
        // },
        {
          label: "单包厂价（单包）",
          prop: "unitFactoryPrice",
          visible: true,
          type: "string",
          fill: false,
          width: 135
        },
        {
          label: "正常供价（单包）",
          prop: "normalSupplyPrice",
          visible: true,
          type: "string",
          fill: false,
          width: 135
        },
        {
          label: "日常零售价（单包）",
          prop: "regularRetailPrice",
          visible: true,
          type: "string",
          fill: false,
          width: 150
        },
        {
          label: "计划促销售价（单包）",
          prop: "plannedPromotionPrice",
          visible: true,
          type: "string",
          fill: false,
          width: 165
        },
        // {
        //   label: "实际促销售价（单包）",
        //   prop: "actualPromotionPrice",
        //   visible: true,
        //   type: 'input',
        //   format: 'number',
        //   referenceKey: "plannedPromotionPrice",
        //   fill: true,
        //   width: 165,
        //   render: (_, row, col) => {
        //     return (
        //       <div>
        //         <span>{row[col.referenceKey] || '-'}</span>
        //         <div>
        //           <el-input modelValue={row[col.prop]}
        //             onUpdate:modelValue={(value) => {
        //               row[col.prop] = value;
        //               submitChange(row, col);
        //             }}
        //             disabled={!row[col.referenceKey]}
        //             placeholder=""
        //             clearable
        //           />
        //         </div>
        //       </div>
        //     )
        //   },
        //   requestKey: ["promotionPriceExecutionStatus"]
        // },
        {
          label: "促销价是否",
          subLabel: '按计划执行',
          prop: "promotionPriceExecutionStatus",
          visible: true,
          type: 'formula',
          func: (row) => {
            row.promotionPriceExecutionStatus = row.actualPromotionMechanism === '执行与计划一致' ? '执行' : '未执行';
            return row.promotionPriceExecutionStatus;
          },
          formulaStr: '公式：（计划促销机制 = 执行促销机制）',
          fill: true,
          width: 150
        },
        {
          label: "正常经销商毛利现状",
          prop: "normalDealerMarginStatus",
          visible: true,
          type: "string",
          fill: false,
          width: 150
        },
        {
          label: "系统前台毛利保证",
          prop: "systemFrontendMarginGuarantee",
          visible: true,
          type: "string",
          fill: false,
          width: 135
        },
        {
          label: "系统后台毛利保证",
          prop: "systemBackendMarginGuarantee",
          visible: true,
          type: "string",
          fill: false,
          width: 135
        },
        {
          label: "系统促销毛利保证",
          prop: "systemPromotionMarginGuarantee",
          visible: true,
          type: "string",
          fill: false,
          width: 135
        },
        {
          label: "经销商毛利保证",
          prop: "dealerMarginGuarantee",
          visible: true,
          type: "string",
          fill: false,
          width: 125
        },
        {
          label: "单袋补差金额（费用）",
          prop: "unitBagAdjustmentAmount",
          visible: true,
          type: "string",
          fill: false,
          width: 165
        },
        {
          label: "补差费比（%）",
          prop: "adjustmentCostRatio",
          visible: true,
          type: "string",
          fill: false,
          width: 125
        },
        {
          label: "整体补差（费用）",
          prop: "totalAdjustmentCost",
          visible: true,
          type: "string",
          fill: false,
          width: 135
        },
        // {
        //   label: "档期是否执行",
        //   prop: "promotionExecutionStatus",
        //   visible: true,
        //   type: 'formula',
        //   func: (row) => {
        //     // 过滤掉值为"-"的项，只对有实际值的项进行判断
        //     const executionStatuses = [
        //       row.promotionPriceExecutionStatus,
        //       row.promotionMechanismExecutionStatus,
        //       row.specExecutionStatus,
        //       row.promotionImplementationStatus
        //     ].filter(status => status !== '-');

        //     // 如果所有过滤后的状态都是'是'，则返回'是'，否则返回'否'
        //     row.promotionExecutionStatus = executionStatuses.every(status => status === '是') ? '执行' : '未执行';
        //     return row.promotionExecutionStatus;
        //   },
        //   formulaStr: '公式：促销价执行，并且促销口味执行，并且促销规格执行，并且档期开展（某项无计划时，忽略该项）',
        //   fill: true,
        //   width: 125
        // }
      ],
      visible: true
    },
    {
      label: "海报计划",
      prop: 'posterPlan',
      children: [
        {
          label: "海报形式",
          subLabel: '计划',
          prop: "plannedPosterFormat",
          visible: true,
          type: "string",
          fill: true,
          width: 150
        },
        {
          label: "计划-海报费用",
          prop: "plannedPosterCost",
          visible: true,
          type: "string",
          fill: false,
          width: 115
        },
        {
          label: "海报形式",
          subLabel: '实际',
          prop: "actualPosterFormat",
          visible: true,
          type: 'select',
          options: [
            {
              label: '插卡',
              value: '插卡'
            },
            {
              label: '厂商周',
              value: '厂商周'
            },
            {
              label: '电子',
              value: '电子'
            },
            {
              label: '海报',
              value: '海报'
            },
            {
              label: '跳卡',
              value: '跳卡'
            },
            {
              label: '纸质',
              value: '纸质'
            }
          ],
          referenceKey: "plannedPosterFormat",
          fill: true,
          width: 150,
          render: (_, row, col) => {
            return (
              <div>
                <div style="width: 100%">
                  <el-select modelValue={row[col.prop]}
                    onUpdate:modelValue={(value) => {
                      row[col.prop] = value;
                      submitChange(row, col);
                    }}
                    disabled={!row[col.referenceKey]}
                    class={{ 'no-disabled': row[col.referenceKey] }}
                    placeholder=""
                    clearable
                  >
                    {col.options.map(item => (
                      <el-option key={item.value} label={item.label} value={item.value} />
                    ))}
                  </el-select>
                </div>
              </div>
            )
          },
          requestKey: ["posterExecutionStatus"]
        },
        {
          label: "海报是否",
          subLabel: '按计划执行',
          prop: "posterExecutionStatus",
          visible: true,
          type: 'formula',
          func: (row) => {
            if (!row.plannedPosterFormat) return row.posterExecutionStatus = '-'
            if (!row.actualPosterFormat) return row.posterExecutionStatus = '未执行'
            row.posterExecutionStatus = row.plannedPosterFormat == row.actualPosterFormat ? '执行' : '未执行';
            return row.posterExecutionStatus;
          },
          formulaStr: '公式：（计划海报形式 = 实际海报形式）',
          fill: true,
          width: 150
        }
      ],
      visible: true
    },
    {
      label: "档期陈列",
      prop: 'displayPlan',
      children: [
        {
          label: "门店数",
          prop: "storeCountInt",
          visible: true,
          type: "string",
          fill: false,
          width: 75
        },
        {
          label: "店均费用",
          prop: "averageStoreCost",
          visible: true,
          type: "string",
          fill: false,
          width: 115
        },
        {
          label: "费用",
          prop: "cost",
          visible: true,
          type: "string",
          fill: false,
          width: 115
        },
        {
          label: '修改人',
          prop: 'updateBy',
          visible: true,
          type: 'string',
          fill: false,
          width: 120
        },
        {
          label: '修改时间',
          prop: 'updateTime',
          visible: true,
          type: 'string',
          fill: false,
          width: 180
        }
      ],
      visible: true
    }
  ]);

  // 表格列数据
  const tableColumns = ref([])
  // 右上角工具选择列
  const chooseColumns = ref([])

  // 计算列具体数据
  const updateColumns = (operation) => {
    // 保存用户选择的列配置
    if (operation === '展示模式') {
      chooseColumns.value = baseColumns.value
      tableColumns.value = baseColumns.value.flatMap(item => {
        if (item.children) {
          return item.children.filter(child => !child.onlyFill);
        }
        return [];
      });
    } else if (operation === '填报模式') {
      chooseColumns.value = baseColumns.value.flatMap(item => {
        if (item.children) {
          return item.children
            .filter(child => child.fill)
        }
        return [];
      });
      tableColumns.value = chooseColumns.value
    }
  }

  // 选择列默认选中哪些
  const visibleProps = computed(() => {
    // 分情况返回
    return tableColumns.value.flatMap(item => {
      if (item.children) {
        return item.children.map(child => child.prop);
      }
      return item.prop;
    });
  });

  // 提交变更
  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 = tableColumns.value.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 tableData = ref([])
  const isLoading = ref(true)
  let params = reactive({
    pageNum: 1,
    pageSize: 20,
  })
  const total = ref(0)

  // 获取表格数据
  const getTableList = async () => {
    isLoading.value = true
    const res = await getDisplayScheduleList({
      ...params
    })
    // 处理日期格式
    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(() => {
    updateColumns()
    getTableList()
  })

  const isContentOverflow = (key, content, col) => {
    if (!content) return false; // 没有内容则直接禁用

    // 创建 DOM 计算
    const tempSpan = document.createElement('span');
    tempSpan.textContent = content;
    tempSpan.className = 'ellipsis-tooltip';
    tempSpan.style.visibility = 'hidden';
    tempSpan.style.position = 'absolute';
    document.body.appendChild(tempSpan);

    // 获取元素宽度和内容宽度
    const width = tempSpan.getBoundingClientRect().width;

    // 移除临时元素
    document.body.removeChild(tempSpan);

    // 当内容宽度大于元素宽度时，表示内容溢出
    return width > col.width;
  };

  const showSearch = ref(true)
  const updateShowSearch = (newVal) => {
    showSearch.value = newVal
  }

  const searchChange = (newVal) => {
    // 计划月份
    if (newVal.salesMonth) {
      newVal.salesMonth = parseTime(newVal.salesMonth, '{y}-{m}-{d}')
    }
    params = { ...params, ...newVal }
    getTableList()
  }

  /*************** 弹窗 ***************/
  const showPromotionDialog = ref(false)
  const nowEnterRow = ref({}) // 当前弹窗弹出时，要填写哪行的数据对象
  const nowEnterRowProp = ref('') // 当前弹窗弹出时，要填写哪行的数据对象的属性
  const dialogForm = reactive({
    actualPromotionContent: '',
  })
  // 弹窗打开
  const handleDialogOpen = () => {
    // 检查实际促销机制内容是否与计划促销机制内容不一致
    showPromotionDialog.value = true
  }
  // 弹窗关闭时，清空表单数据
  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>

<style scoped
  lang="scss">

  /* 保留原有样式，但简化了结构 */
  .formula-column {
    display: flex;
    justify-content: center;
    align-items: center;

    .el-icon {
      margin-left: 2px;
    }
  }

  ::v-deep(.el-table) {
    .cell {
      padding: 0;
    }

    .cell-style {
      // margin: 0 -12px;

      >div {
        display: flex;
        flex-direction: column;
        align-items: flex-start;

        >span.ellipsis-tooltip {
          text-align: left;
          text-indent: 5px;
          display: inline-block;
          width: 100%;
          background-color: #e1e2e6;
          border-bottom: 1px solid #ebeef5;

          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          display: inline-block;
          max-width: 100%;
        }
      }

      /* 表格内下拉框 */
      // .el-select {
      //   width: 100% !important;
      //   padding: 10px;
      // }

      // .el-input {
      //   padding: 10px;
      // }

      // .date-picker {
      //   padding: 10px;


      //   .el-input {
      //     padding: 0;
      //   }
      // }
    }
  }

  ::v-deep(.el-date-editor) {
    width: 100%;
  }
</style>