<template>
  <!-- 零食陈列 -->
  <SearchList :showSearch="showSearch"
    @change="searchChange" />
  <CustomTable :tableData="tableData"
    :isLoading="isLoading"
    :total="total"
    :tableColumns="tableColumns"
    :chooseColumns="chooseColumns"
    :visibleProps="visibleProps"
    :params="params"
    :showFill="showFill"
    @updateColumns="updateColumns"
    @getTableList="getTableList"
    @updateShowSearch="updateShowSearch" />
</template>

<script setup
  lang="jsx">
  import CustomTable from '@/views/promotion/components/Table'
  import SearchList from '@/views/promotion/components/SearchList'
  import { getSnackPlanList, submitSnackPlan } from '@/api'
  import { parseTime } from '@/utils'
  import { onMounted } from 'vue';
  import userStore from '@/store/modules/user'

  // 是否启用填报模式
  const showFill = userStore().hasQcMarketEmpInfo
  /*************** 操作类型 ***************/
  // 全部列
  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: true, // 是否为填报列
          fixed: 'left', // 是否固定在左侧
          width: 90
        },
        {
          "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": 110
        },
        {
          "label": "经销商 - 城市",
          "prop": "dealerCity",
          "visible": true,
          "type": "string",
          "fill": false,
          "width": 110
        },
        {
          "label": "经销商 - 代码",
          "prop": "dealerCode",
          "visible": true,
          "type": "string",
          "fill": false,
          "width": 110
        },
        {
          "label": "经销商名称",
          "prop": "dealerName",
          "visible": true,
          showOverflowTooltip: true,
          "type": "string",
          "fill": true,
          "width": 200,
          fixed: 'left'
        },
        {
          "label": "经销商类型",
          "prop": "dealerType",
          "visible": true,
          showOverflowTooltip: true,
          "type": "string",
          "fill": false,
          "width": 150
        },
        {
          "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,
          "width": 100,
          fixed: 'left'
        },
        {
          "label": "系统类型",
          "prop": "lineType",
          "visible": true,
          "type": "string",
          "fill": false,
          "width": 100
        },
        {
          "label": "渠道大类",
          "prop": "channelDl",
          "visible": true,
          "type": "string",
          "fill": false,
          "width": 100
        },
        {
          "label": "渠道小类",
          "prop": "channelXl",
          "visible": true,
          "type": "string",
          "fill": false,
          "width": 100
        },
        {
          "label": "系统业态",
          "prop": "lineLf",
          "visible": true,
          "type": "string",
          "fill": false,
          "width": 100
        },
        {
          "label": "是否直营",
          "prop": "isDirect",
          "visible": true,
          "type": "string",
          "fill": false,
          "width": 100
        }
      ],
      prop: 'baseColumns',
      visible: true
    },
    {
      label: "零食折扣门店陈列计划",
      children: [
        {
          "label": "门店编码",
          "prop": "storeCode",
          "visible": true,
          "type": "string",
          "fill": false,
          "width": 150
        },
        {
          "label": "门店名称",
          "prop": "storeName",
          "visible": true,
          "type": "string",
          showOverflowTooltip: true,
          "fill": false,
          "width": 180
        },
        // {
        //   "label": "门店计数",
        //   "prop": "storeCount",
        //   "visible": true,
        //   "type": "string",
        //   "fill": false,
        //   "width": 100
        // },
        {
          "label": "门店地址",
          "prop": "storeAddress",
          "visible": true,
          showOverflowTooltip: true,
          "type": "string",
          "fill": false,
          "width": 280
        },
        {
          "label": "计划 - 陈列形式",
          "prop": "plannedDisplay",
          "visible": true,
          "type": "string",
          "fill": false,
          "width": 140
        },
        {
          "label": "实际 - 陈列形式",
          "prop": "actualDisplay",
          "visible": true,
          "type": "input",
          options: [
            {
              label: '执行与计划一致',
              value: '执行与计划一致'
            },
            {
              label: '执行与计划不一致',
              value: '执行与计划不一致'
            }
          ],
          referenceKey: "plannedDisplay",
          render: (_, row, col) => {
            return (
              <div>
                <span>{row[col.referenceKey] || '-'}</span>
                <div style="width: 100%">
                  <el-select modelValue={row[col.prop]}
                    onUpdate:modelValue={(value) => {
                      row[col.prop] = value;
                      submitChange(row, col);
                    }}
                    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>
            )
          },
          "fill": true,
          "width": 160,
          // "options": [
          //   {
          //     "label": "端架",
          //     "value": "端架"
          //   },
          //   {
          //     "label": "收银台",
          //     "value": "收银台"
          //   },
          //   {
          //     "label": "端架和收银台",
          //     "value": "端架和收银台"
          //   }
          // ],
          // render: (_, row, col) => {
          //   return (
          //     <div>
          //       <el-tooltip placement="top" content={row[col.referenceKey] || '-'} disabled={!isContentOverflow(col.referenceKey, row[col.referenceKey], col)}>
          //         <span style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: inline-block; max-width: 100%;">
          //           {row[col.referenceKey] || '-'}
          //         </span>
          //       </el-tooltip>
          //       <el-select modelValue={row[col.prop]}
          //         onUpdate:modelValue={(value) => {
          //           row[col.prop] = value;
          //           submitChange(row, col);
          //         }}
          //         disabled={!row[col.referenceKey]}
          //         placeholder="">
          //         {col.options.map(item => (
          //           <el-option
          //             key={item.value}
          //             label={item.label}
          //             value={item.value}
          //           />
          //         ))}
          //       </el-select>
          //     </div>
          //   )
          // },
          // requestKey: ["displayExecuted", "snackDisplayExecuted"]
          requestKey: ["displayExecuted"]
        },
        // {
        //   "label": "陈列形式是否执行",
        //   "prop": "displayExecuted",
        //   "visible": true,
        //   "type": "formula",
        //   "fill": false,
        //   "width": 150,
        //   func: (row) => {
        //     if (!row.plannedDisplay) {
        //       row.displayExecuted = '-'
        //       return '-';
        //     }
        //     // 截取计划陈列形式数据
        //     row.displayExecuted = row.actualDisplay === '执行与计划一致' ? '执行' : '未执行'
        //     return row.displayExecuted
        //   },
        //   formulaStr: "实际陈列形式 === 计划陈列形式"
        // },
        {
          "label": "计划 - 端架数量（组）",
          "prop": "plannedEndCapQty",
          "visible": true,
          "type": "string",
          "fill": false,
          "width": 160
        },
        {
          "label": "实际 - 端架数量（组）",
          "prop": "actualEndCapQty",
          "visible": true,
          "type": "input",
          referenceKey: "plannedEndCapQty",
          "fill": true,
          // "options": [
          //   {
          //     "label": "0",
          //     "value": 0
          //   },
          //   {
          //     "label": "0.5",
          //     "value": 0.5
          //   },
          //   {
          //     "label": "1",
          //     "value": 1
          //   },
          //   {
          //     "label": "2",
          //     "value": 2
          //   }
          // ],
          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]}
                    min="0"
                    type="number"
                    placeholder=""
                    clearable
                  />
                </div>
              </div>
            )
          },
          "width": 160,
          // requestKey: ["endCapQtyExecuted", "snackDisplayExecuted"]
          requestKey: ["endCapQtyExecuted"]
        },
        {
          "label": "端架数量是否执行",
          "prop": "endCapQtyExecuted",
          "visible": true,
          "type": "formula",
          "fill": false,
          "width": 150,
          func: (row) => {
            if (!row.plannedEndCapQty) {
              row.endCapQtyExecuted = '-'
              return '-'
            }
            // 截取计划端架数量数据
            row.endCapQtyExecuted = row.actualEndCapQty >= row.plannedEndCapQty ? '执行' : '未执行'
            return row.endCapQtyExecuted
          },
          formulaStr: "执行端架数量 == 计划端架数量"
        },
        {
          "label": "零食陈列是否执行",
          "prop": "snackDisplayExecuted",
          "visible": true,
          "type": "formula",
          "fill": true,
          "width": 150,
          func: (row) => {
            // 如果关键的 2 个计划属性无值，则直接返回 '-'
            if (!row.plannedDisplay && !row.plannedEndCapQty) {
              row.snackDisplayExecuted = '-'
              return '-'
            }
            if ((row.plannedDisplay && row.actualDisplay === '执行与计划一致')) {
              // 判断实际端架数量为 0 或者空时就是未执行，如果小于计划是部分执行，如果大于等于就是执行
              if (!row.actualEndCapQty || row.actualEndCapQty == 0) {
                row.snackDisplayExecuted = '未执行'
                return '未执行'
              } else if (row.actualEndCapQty < row.plannedEndCapQty) {
                row.snackDisplayExecuted = '部分执行'
                return '部分执行'
              } else {
                row.snackDisplayExecuted = '执行'
                return '执行'
              }
            } else {
              row.snackDisplayExecuted = '未执行'
              return '未执行'
            }
          },
          formulaStr: "公式：陈列形式执行，并且端架数量执行（某项无计划时，忽略该项）"
        },
        {
          "label": "计划 - 陈列费用",
          "prop": "totalCost",
          "visible": true,
          "type": "string",
          "fill": false,
          "width": 120
        },
        {
          "label": "付费陈列 - 是否",
          "prop": "paidDisplay",
          "visible": true,
          "type": "string",
          "fill": false,
          "width": 120
        },
        {
          "label": "当月拜访目标 - 是否",
          "prop": "monthlyVisitTarget",
          "visible": true,
          "type": "string",
          "fill": false,
          "width": 150
        },
        {
          label: '修改人',
          prop: 'updateBy',
          visible: true,
          type: 'string',
          fill: false,
          width: 120
        },
        {
          label: '修改时间',
          prop: 'updateTime',
          visible: true,
          type: 'string',
          fill: false,
          width: 180
        }
      ],
      prop: 'snackColumns',
      visible: true
    }
  ]);
  // 表格列
  const tableColumns = ref([])
  // 右上角工具选择列
  const chooseColumns = ref([])
  // 计算列具体数据
  const updateColumns = (operation) => {
    return new Promise((resolve, reject) => {
      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 === true)
          }
          return [];
        });

        tableColumns.value = chooseColumns.value
      }
      resolve()
    })
  }

  onMounted(() => {
    updateColumns()
  })

  // 树形结构选择列默认有哪些
  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) => {
    // 需要特殊处理的
    // 1. 实际主货架-形式，为空时，置空实际主货架-数量
    // if (col.prop === 'actualMainShelfType' && !row.actualMainShelfType) {
    //   row.actualMainShelfQty = 0
    // }

    // 关联的公式计算列，需要特殊处理
    for (const str of col.requestKey) {
      const obj = tableColumns.value.find(item => item.prop === str)
      if (obj && obj.type === 'formula') {
        obj.func(row)
      }
    }

    await submitSnackPlan({
      id: row.sasdId,
      [col.prop]: row[col.prop], // 当前修改列的值
      ...col.requestKey.reduce((acc, key) => ({ ...acc, [key]: row[key] }), {}), // 额外携带影响的列字段值
    })
    // // 这些提交变化的，同时会影响公式计算的，需要把公式计算的字段列结果，一起发给后台
    // // 注意：实际主货架形式改变并为空时，要置空实际主货架数量
    // if (col.prop === 'actualMainShelfType' && !row.actualMainShelfType) {
    //   row.actualMainShelfQty = ''
    //   // 并提交保存一次
    //   await submitDisplayPlan({
    //     id: row.sadId,
    //     actualMainShelfQty: row.actualMainShelfQty,
    //   })
    // }

    // // 主货架
    // 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)
  let params = reactive({
    pageNum: 1,
    pageSize: 20,
  })
  const total = ref(0)

  // 筛选工具
  const getTableList = async () => {
    isLoading.value = true
    const res = await getSnackPlanList({
      ...params
    })
    res.data.rows.forEach(item => {
      // 计划月份
      item.salesMonth = parseTime(item.salesMonth, '{y}-{m}')
      // 开户日期
      item.openingDate = parseTime(item.openingDate, '{y}-{m}-{d}')
      // 闭户日期
      item.closingDate = parseTime(item.closingDate, '{y}-{m}-{d}')
      // 修改时间
      item.updateTime = parseTime(item.updateTime, '{y}-{m}-{d} {h}:{i}:{s}')
    })
    tableData.value = res.data.rows
    total.value = res.data.total
    isLoading.value = false
  }
  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()
  }
</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;
          }

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

    }
  }
</style>