<template>
  <el-row>
    <el-form-item>
      <el-radio-group v-model="operation"
        @change="checkTableColumns">
        <el-radio-button label="平铺模式"
          value="平铺模式" />
        <el-radio-button label="填报模式"
          value="填报模式" />
      </el-radio-group>
    </el-form-item>
    <right-toolbar v-model:showSearch="showSearch"
      @queryTable="getTableList()"
      :columns="chooseColumns"
      :showColumnsType="operation === '平铺模式' ? 'tree' : 'checkbox'"
      :defaultCheckedKeys="visibleProps">
    </right-toolbar>
  </el-row>
  <!-- 筛选列组的按钮 -->
  <el-table :data="tableData"
    border
    ref="tableRef"
    class="auto-fit-header-table"
    v-loading="isLoading">
    <template v-for="col in tableColumns">
      <el-table-column v-if="col.visible"
        :label="col.label"
        :key="col.prop"
        align="center"
        :show-overflow-tooltip="col.type === 'string'"
        class-name="column-style"
        :width="getColumnMinWidth(col)"
        :fixed="operation === '填报模式' && col.fixed">
        <template #header="{ column }">
          <!-- 只为特定列添加问号图标 -->
          <span class="formula-column">
            {{ column.label }}
            <el-tooltip v-if="col.type === 'formula'"
              :content="col.formulaStr"
              placement="top">
              <el-icon><question-filled /></el-icon>
            </el-tooltip>
          </span>
        </template>
        <template #default="{ row }">
          <div v-if="col.type === 'select'"
            class="cell-style">
            <!-- 实际主货架-数量（要根据实际主货架-形式不为空时才可以选择否则为 0） -->
            <div v-if="col.prop === 'actualMainShelfQty'">
              <span>{{ row[col.referenceKey] || '-' }}</span>
              <el-select :disabled="!row.actualMainShelfType"
                v-model="row[col.prop]"
                placeholder=""
                clearable
                @change="submitChange(row, col)">
                <el-option v-for="item in col.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value" />
              </el-select>
            </div>
            <div v-else>
              <span>{{ row[col.referenceKey] || '-' }}</span>
              <el-select v-model="row[col.prop]"
                placeholder=""
                clearable
                @change="submitChange(row, col)">
                <el-option v-for="item in col.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value" />
              </el-select>
            </div>
          </div>
          <!-- 公式计算 -->
          <div v-else-if="col.type === 'formula'">
            {{ col.func(row) }}
          </div>
          <!-- 输入框 -->
          <div v-else-if="col.type === 'input'">
            <el-input v-model="row[col.prop]"
              placeholder=""
              @input="submitChange(row, col)" />
          </div>
          <!-- 为其他类型或未定义类型提供默认显示 -->
          <div v-else>
            <div class="ellipsis-text"
              style="max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
              {{ formatterTableData(row, col) }}
            </div>
          </div>
        </template>
      </el-table-column>
    </template>
  </el-table>
  <!-- 分页 -->
  <pagination :total="total"
    v-model:page="params.pageNum"
    v-model:limit="params.pageSize"
    @pagination="getTableList" />
</template>

<script setup>
import { getDisplayList, submitDisplayPlan } from '@/api'
import { parseTime } from '@/utils'
import { onMounted } from 'vue';

/*************** 操作类型 ***************/
const operation = ref('平铺模式');
const tableRef = ref(null)
// 平铺模式
const baseColumns = ref([
  {
    label: "基础信息",
    children: [
      { label: "销售大区", prop: "regionName", visible: true, type: 'string', fill: false },
      { label: "销售战区", prop: "districtName", visible: true, type: 'string', fill: false },
      { label: "经销商-省份", prop: "dealerProvince", visible: true, type: 'string', fill: false },
      { label: "经销商-城市", prop: "dealerCity", visible: true, type: 'string', fill: false },
      { label: "经销商-代码", prop: "dealerCode", visible: true, type: 'string', fill: false },

      { label: "经销商-类型", prop: "dealerType", visible: true, type: 'string', fill: false },
      { label: "开户日期", prop: "openingDate", visible: true, type: 'string', fill: false },
      { label: "闭户日期", prop: "closingDate", visible: true, type: 'string', fill: false },
      { label: "大区总监", prop: "regionManager", visible: true, type: 'string', fill: false },
      { label: "战区经理", prop: "districtManager", visible: true, type: 'string', fill: false },
      { label: "城市经理", prop: "cityManager", visible: true, type: 'string', fill: false },
      { label: "门店名称", prop: "storeName", visible: true, type: 'string', fill: true, fixed: 'left' },
      { label: "门店编码", prop: "storeCode", visible: true, type: 'string', fill: true, fixed: 'left' },
      { label: "经销商名称", prop: "dealerName", visible: true, type: 'string', fill: true, fixed: 'left' },
      { label: "系统类型", prop: "lineType", visible: true, type: 'string', fill: true, fixed: 'left' },
      { label: "门店-省份", prop: "storeProvince", visible: true, type: 'string', fill: false },
      { label: "门店-城市", prop: "storeCity", visible: true, type: 'string', fill: false },
      { label: "系统名称", prop: "lineName", visible: true, type: 'string', fill: true },
      { label: "渠道大类", prop: "channelDl", visible: true, type: 'string', fill: false },
      { label: "渠道小类", prop: "channelXl", visible: true, type: 'string', fill: false },
      { label: "门店类型", prop: "storeType", visible: true, type: 'string', fill: false },
      { label: "系统业态", prop: "systemFormat", visible: true, type: 'string', fill: false },
      { label: "门店面积", prop: "storeArea", visible: true, type: 'string', fill: false },
      { label: "门店分级（销量坎级）", prop: "storeLevel", visible: true, type: 'string', fill: false },
      { label: "门店地址", prop: "storeAddress", visible: true, type: 'string', fill: false },
      { label: "品项数", prop: "productCount", visible: true, type: 'string', fill: false }
    ],
    prop: 'baseColumns',
    visible: true
  },
  {
    label: "大业态测试",
    children: [
      { label: "大业态测试-动销模型", prop: "lfSalesModel", visible: true, type: 'string', fill: false },
      { label: "大业态测试-月均POS", prop: "lfMonthlyPos", visible: true, type: 'string', fill: false },
    ],
    prop: 'lfColumns',
    visible: true
  },
  {
    label: "费用计划",
    prop: 'fpColumns',
    children: [
      // { label: "计划主货架-形式", prop: "plannedMainShelfType", visible: true, type: 'string' },
      // { label: "计划主货架-数量", prop: "plannedMainShelfQty", visible: true, type: 'string' },
      { label: "计划主货架-单个费用", prop: "plannedMainShelfUnitCost", visible: true, type: 'string', fill: false },
      { label: "计划主货架-总费用", prop: "plannedMainShelfTotalCost", visible: true, type: 'string', fill: false },
      {
        label: "实际主货架-形式",
        prop: "actualMainShelfType",
        visible: true,
        type: 'select',
        options: [
          { label: '4纵', value: '4纵' },
          { label: '5纵', value: '5纵' },
          { label: '6纵', value: '6纵' },
          { label: '7纵', value: '7纵' },
          { label: '8纵及以上', value: '8纵及以上' }
        ],
        referenceKey: "plannedMainShelfType",
        fill: true
      },
      {
        label: "实际主货架-数量",
        prop: "actualMainShelfQty",
        visible: true,
        type: 'select',
        options: [
          { label: '1', value: 1 },
          { label: '2', value: 2 }
        ],
        referenceKey: "plannedMainShelfQty",
        fill: true
      },
      {
        label: "实际主货架-是否执行",
        prop: "actualMainShelfExecuted",
        visible: true,
        type: 'formula', // 公式
        func: (row) => {
          row.actualMainShelfExecuted = ((parseInt(row.actualMainShelfType) >= parseInt(row.plannedMainShelfType)) && (parseInt(row.actualMainShelfQty) >= parseInt(row.plannedMainShelfQty))) ? '是' : '否';
          return row.actualMainShelfExecuted;
        },
        formulaStr: '公式：（实际主货架形式 >= 计划主货架形式）并且（实际主货架数量 >= 计划主货架数量）',
        fill: true
      },
      // {
      //   label: "计划端架-数量", prop: "plannedEndCapQty", visible: true, type: 'string',
      //   fill: true
      // },
      {
        label: "计划端架-总费用", prop: "plannedEndCapTotalCost", visible: true, type: 'string',
        fill: false
      },
      {
        label: "计划端架-单个费用", prop: "plannedEndCapUnitCost", visible: true, type: 'string',
        fill: false
      },
      {
        label: "实际端架-数量",
        prop: "actualEndCapQty",
        visible: true,
        type: 'select',
        options: [
          { label: '0', value: 0 },
          { label: '0.5', value: 0.5 },
          { label: '1', value: 1 },
          { label: '2', value: 2 }
        ],
        referenceKey: "plannedEndCapQty",
        fill: true
      },
      {
        label: "实际端架-是否执行",
        prop: "actualEndCapExecuted",
        visible: true,
        type: 'formula', // 公式
        func: (row) => {
          row.actualEndCapExecuted = ((parseFloat(row.actualEndCapQty) >= parseFloat(row.plannedEndCapQty))) ? '是' : '否';
          return row.actualEndCapExecuted;
        },
        formulaStr: '公式：（实际端架数量 >= 计划端架数量）',
        fill: true
      },
      {
        label: "计划地堆-平米数（㎡）",
        prop: "plannedFloorStackArea",
        visible: true,
        type: 'string',
        fill: true
      },
      {
        label: "计划地堆-数量", prop: "plannedFloorStackQty", visible: true, type: 'string',
        fill: true
      },
      {
        label: "计划主题地堆-是否", prop: "plannedThemedFloorStack", visible: true, type: 'string',
        fill: true
      },
      {
        label: "计划地堆-总费用", prop: "plannedFloorStackTotalCost", visible: true, type: 'string',
        fill: false
      },
      {
        label: "计划折算1㎡-单个费用", prop: "plannedFloorStackUnitCostPerSqm", visible: true, type: 'string',
        fill: false
      },
      {
        label: "实际地堆-平米数（㎡）",
        prop: "actualFloorStackArea",
        visible: true,
        type: 'select',
        options: [
          { label: '0', value: 0 },
          { label: '0.5', value: 0.5 },
          { label: '0.8', value: 0.8 },
          { label: '1', value: 1 },
          { label: '2', value: 2 },
          { label: '3', value: 3 },
          { label: '4', value: 4 },
        ],
        referenceKey: "plannedFloorStackArea",
        fill: true
      },
      {
        label: "实际地堆-数量",
        prop: "actualFloorStackQty",
        visible: true,
        type: 'select',
        options: [
          { label: '0', value: 0 },
          { label: '1', value: 1 },
          { label: '2', value: 2 },
          { label: '3', value: 3 }
        ],
        referenceKey: "plannedFloorStackQty",
        fill: true
      },
      {
        label: "实际主题地堆-是否",
        prop: "actualThemedFloorStack",
        visible: true,
        type: 'select',
        options: [
          { label: '是', value: '是' },
          { label: '否', value: '否' },
        ],
        referenceKey: "plannedThemedFloorStack",
        fill: true
      },
      {
        label: "实际地堆是否执行",
        prop: "actualFloorStackExecuted",
        visible: true,
        type: 'formula', // 公式
        func: (row) => {
          row.actualFloorStackExecuted = ((parseFloat(row.actualFloorStackArea) >= parseFloat(row.plannedFloorStackArea)) && (parseInt(row.actualFloorStackQty) >= parseInt(row.plannedFloorStackQty))) ? '是' : '否';
          return row.actualFloorStackExecuted;
        },
        formulaStr: '公式：（实际地堆平米数 >= 计划地堆平米数）并且（实际地堆数量 >= 计划地堆数量）',
        fill: true
      },
      {
        label: "计划多点陈列-数量+形式", prop: "plannedMultiDisplay", visible: true, type: 'string',
        fill: true
      },
      {
        label: "计划多点陈列-总费用", prop: "plannedMultiDisplayTotalCost", visible: true, type: 'string',
        fill: false
      },
      {
        label: "实际多点陈列-数量+形式",
        prop: "actualMultiDisplay",
        visible: true,
        type: 'input',
        func: (row) => {
          // 没有输入内容时，则是否执行设置为否
          row.actualMultiDisplayExecuted = !row.actualMultiDisplay ? '否' : '是'
        },
        referenceKey: "plannedMultiDisplay",
        fill: true
      },
      {
        label: "实际多点陈列-是否执行",
        prop: "actualMultiDisplayExecuted",
        visible: true,
        type: 'select',
        options: [
          { label: '是', value: '是' },
          { label: '否', value: '否' },
        ],
        fill: true
      },
      {
        label: "合计费用-费用", prop: "totalCost", visible: true, type: 'string',
        fill: false
      },
      {
        label: "合计费用-费率", prop: "totalCostRate", visible: true, type: 'string',
        fill: false
      },
      {
        label: "常规陈列是否执行",
        prop: "regularDisplayExecuted",
        visible: true,
        type: 'formula', // 公式
        func: (row) => {
          // 实际主货架-是否执行 && 实际端架-是否执行 && 实际地堆-是否执行 && 实际多点陈列-是否执行
          row.regularDisplayExecuted = (row.actualMainShelfExecuted === '是' && row.actualEndCapExecuted === '是' && row.actualFloorStackExecuted === '是' && row.actualMultiDisplayExecuted === '是') ? '是' : '否';
          return row.regularDisplayExecuted;
        },
        fill: true
      },
      {
        label: "综合标签-拜访辅助列", prop: "visitAssistTag", visible: true, type: 'string',
        fill: false
      },
      {
        label: "付费陈列- 是否", prop: "paidDisplay", visible: true, type: 'string',
        fill: false
      },
      {
        label: "当月拜访目标", prop: "monthlyVisitTarget", visible: true, type: 'string',
        fill: false
      },
      {
        label: "当月是否拜访", prop: "monthlyVisited", visible: true, type: 'string',
        fill: false
      }
    ],
    visible: true
  }
]);
// 表格列
const tableColumns = ref([])
// 右上角工具选择列
const chooseColumns = ref([])
// 计算列具体数据
const checkTableColumns = () => {
  if (operation.value === '平铺模式') {
    chooseColumns.value = baseColumns.value
    tableColumns.value = baseColumns.value.flatMap(item => {
      if (item.children) {
        return item.children.filter(child => child);
      }
      return [];
    });
  } else if (operation.value === '填报模式') {
    chooseColumns.value = baseColumns.value.flatMap(item => {
      if (item.children) {
        return item.children
          .filter(child => child.fill)
      }
      return [];
    });
    tableColumns.value = chooseColumns.value
  }

  // 强制表格立即应用所有宽度设置，避免先自适应再调整
  nextTick(() => {
    if (tableRef.value) {
      tableRef.value.doLayout()
    }
  })
}

onMounted(() => {
  checkTableColumns()
})

// 树形结构选择列默认有哪些
const visibleProps = computed(() => {
  return baseColumns.value.flatMap(item => {
    if (item.children) {
      return item.children.filter(child => child.visible).map(child => child.prop);
    }
    return item.prop;
  });
});

// 提交变更
const submitChange = async (row, col) => {
  // 有个类型输入框的需要调用 func
  if (col.type === 'input') {
    col.func(row)
  }
  await submitDisplayPlan({
    id: row.sadId,
    [col.prop]: row[col.prop]
  })
  // 这些提交变化的，同时会影响公式计算的，需要把公式计算的字段列结果，一起发给后台
  // 主货架
  if (['actualMainShelfType', 'actualMainShelfQty'].includes(col.prop)) {
    await submitDisplayPlan({
      id: row.sadId,
      actualMainShelfExecuted: row.actualMainShelfExecuted,
    })
  }
  // 端架
  if (['actualEndCapQty'].includes(col.prop)) {
    await submitDisplayPlan({
      id: row.sadId,
      actualEndCapExecuted: row.actualEndCapExecuted,
    })
  }
  // 地堆
  if (['actualFloorStackArea', 'actualFloorStackQty'].includes(col.prop)) {
    await submitDisplayPlan({
      id: row.sadId,
      actualFloorStackExecuted: row.actualFloorStackExecuted,
    })
  }
  // 常规陈列是否执行
  await submitDisplayPlan({
    id: row.sadId,
    regularDisplayExecuted: row.regularDisplayExecuted,
  })
}

// 表格数据
const tableData = ref([])
const isLoading = ref(true)
const params = reactive({
  pageNum: 1,
  pageSize: 10,
})
const total = ref(0)

// 筛选工具
const showSearch = ref(true);
const getTableList = async () => {
  isLoading.value = true
  const res = await getDisplayList({
    ...params
  })
  tableData.value = res.data.rows
  total.value = res.data.total
  isLoading.value = false
}
getTableList()

// 列宽度
const getColumnMinWidth = (column) => {
  // 根据列名或属性判断合适的最小宽度
  const widthMap = {
    'regionName': 85,
    'districtName': 85,
    'dealerProvince': 100,
    'dealerCity': 100,
    'dealerCode': 100,
    'dealerName': 210,
    'dealerType': 140,
    'openingDate': 100,
    'closingDate': 100,
    'regionManager': 85,
    'districtManager': 85,
    'cityManager': 85,
    'storeCode': 100,
    'storeName': 170,
    'storeProvince': 85,
    'storeCity': 85,
    'lineName': 85,
    'lineType': 85,
    'channelDl': 85,
    'channelXl': 135,
    'storeType': 85,
    'systemFormat': 85,
    'storeArea': 85,
    'storeLevel': 160,
    'storeAddress': 250,
    'productCount': 75,
    'lfSalesModel': 150,
    'lfMonthlyPos': 150,
    'plannedMainShelfType': 125,
    'plannedMainShelfQty': 125,
    'plannedMainShelfUnitCost': 150,
    'plannedMainShelfTotalCost': 140,
    'actualMainShelfType': 135,
    'actualMainShelfQty': 125,
    'actualMainShelfExecuted': 165,
    'plannedEndCapQty': 110,
    'plannedEndCapTotalCost': 125,
    'plannedEndCapUnitCost': 135,
    'actualEndCapQty': 110,
    'actualEndCapExecuted': 150,
    'plannedFloorStackArea': 165,
    'plannedFloorStackQty': 110,
    'plannedThemedFloorStack': 135,
    'plannedFloorStackTotalCost': 125,
    'plannedFloorStackUnitCostPerSqm': 155,
    'actualFloorStackArea': 165,
    'actualFloorStackQty': 110,
    'actualThemedFloorStack': 135,
    'actualFloorStackExecuted': 145,
    'plannedMultiDisplay': 170,
    'plannedMultiDisplayTotalCost': 150,
    'actualMultiDisplay': 170,
    'actualMultiDisplayExecuted': 165,
    'totalCost': 110,
    'totalCostRate': 110,
    'regularDisplayExecuted': 145,
    'visitAssistTag': 155,
    'paidDisplay': 115,
    'monthlyVisitTarget': 105,
    'monthlyVisited': 105
  };

  return widthMap[column.prop] || 100; // 默认宽度
};

// 格式化函数
const formatterTableData = (row, col) => {
  if (col.prop === 'openingDate' || col.prop === 'closingDate') {
    return parseTime(row[col.prop], '{y}-{m}-{d}')
  }
  return row[col.prop] || '-'
}

</script>

<style scoped
  lang="scss">
  .container {

    .el-tabs {
      height: 100%;
      display: flex;
      flex-direction: column-reverse;

      .el-tabs__content {
        display: flex;
        flex-direction: column;
        height: 100%;

        .el-tab-pane {
          height: 100%;
          display: flex;
          flex-direction: column;

          .pagination-container {
            margin: 10px;
          }
        }

        .formula-column {
          display: flex;
          justify-content: center;
          align-items: center;

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

    .el-form-item {
      align-items: center;
    }

    /* 表格区域 */
    .auto-fit-header-table {

      /* 优化超长文本的显示效果 */
      .cell {
        /* padding: 0 .2133rem; */
      }

      ::v-deep(.el-table__row) {
        .el-table__cell {
          padding: 0;
        }
      }


      ::v-deep(.column-style) {

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


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

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

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

    }
  }
</style>