<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 { getThreeMetersTwoSecondsPlanList, submitThreeMetersTwoSecondsPlan } from '@/api'

  const { proxy } = getCurrentInstance()

  /*************** 搜索列表 ***************/
  const showSearch = ref(true)
  const searchChange = (val) => {
    params.value = val
    getTableList()
  }

  /*************** 表格 ***************/
  // 全部列
  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: 120
        },
        {
          label: '经销商-城市',
          prop: 'dealerCity',
          visible: true,
          type: 'string',
          fill: false,
          width: 120
        },
        {
          label: '经销商-代码',
          prop: 'dealerCode',
          visible: true,
          type: 'string',
          fill: false,
          width: 120
        },
        {
          label: '经销商名称',
          prop: 'dealerName',
          visible: true,
          showOverflowTooltip: true,
          type: 'string',
          fill: false,
          width: 200
        },
        {
          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: 'storeCode',
          visible: true,
          type: 'string',
          fill: false,
          width: 150
        },
        {
          label: '门店名称',
          prop: 'storeName',
          visible: true,
          showOverflowTooltip: true,
          type: 'string',
          fill: true,
          fixed: true,
          width: 180
        },
        {
          label: '门店-省份',
          prop: 'storeProvince',
          visible: true,
          type: 'string',
          fill: false,
          width: 120
        },
        {
          label: '门店-城市',
          prop: 'storeCity',
          visible: true,
          type: 'string',
          fill: false,
          width: 120
        },
        {
          label: '系统名称',
          prop: 'lineName',
          visible: true,
          type: 'string',
          fill: false,
          width: 100
        },
        {
          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: 'storeType',
          visible: true,
          type: 'string',
          fill: false,
          width: 100
        },
        {
          label: '系统业态',
          prop: 'lineLf',
          visible: true,
          type: 'string',
          fill: false,
          width: 100
        }
      ],
      prop: 'baseInfoColumns',
      visible: true
    },
    // 60g挂条陈列分组
    {
      label: "60g挂条陈列",
      children: [
        {
          label: '计划-60g挂条陈列数量',
          prop: 'plannedDisplayQty60',
          visible: true,
          type: 'string',
          fill: false,
          width: 160
        },
        {
          label: '60g挂条陈列费',
          prop: 'totalCost60',
          visible: true,
          type: 'string',
          fill: false,
          width: 140
        },
        {
          label: '实际-60g挂条陈列数量',
          prop: 'actualDisplayQty60',
          referenceKey: 'plannedDisplayQty60',
          visible: true,
          type: 'input',
          fill: true,
          width: 160,
          render: (_, row, col) => {
            return (
              <div>
                <span>{row[col.referenceKey] || '-'}</span>
                <div>
                  <el-input
                    modelValue={row[col.prop]}
                    onUpdate:modelValue={(value) => {
                      {/* 小于 0 */}
                      if (value < 0) {
                        row[col.prop] = 0;
                        return;
                      }
                      row[col.prop] = value;
                      submitChange(row, col);
                    }}
                    min="0"
                    type="number"
                    disabled={!row[col.referenceKey]}
                    placeholder=""
                    clearable
                  />
                </div>
              </div>
            );
          },
          requestKey: ["displayQtyExecuted60"]
        },
        // 60g挂条陈列-是否执行
        {
          label: '60g挂条陈列-是否执行',
          prop: 'displayQtyExecuted60',
          visible: true,
          type: 'formula',
          func: (row) => {
            // 如果参考值是空则返回 '-'
            if (!row.plannedDisplayQty60) {
              row.displayQtyExecuted60 = '-';
              return '-';
            }
            // 判断区间，未执行，部分执行，执行
            if (!row.actualDisplayQty60 || row.actualDisplayQty60 == 0) {
              row.displayQtyExecuted60 = '未执行'
              return '未执行'
            } else if (row.actualDisplayQty60 * 1 < row.plannedDisplayQty60 * 1) {
              row.displayQtyExecuted60 = '部分执行'
              return '部分执行'
            } else {
              row.displayQtyExecuted60 = '执行'
              return '执行'
            }
          },
          formulaStr: '公式：（实际-60g挂条陈列数量 >= 计划-60g挂条陈列数量）',
          fill: true,
          width: 200
        },
      ],
      prop: 'sixtyGramHangBarColumns',
      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()
    })
  }
  // 树形结构选择列默认有哪些
  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
    })
  })

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

  const tableData = ref([])
  const isLoading = ref(false)
  const total = ref(0)

  const params = ref({
    pageNum: 1,
    pageSize: 20,
  })
  const showFill = ref(true)
  const getTableList = () => {
    isLoading.value = true
    getThreeMetersTwoSecondsPlanList(params.value).then(res => {
      isLoading.value = false
      tableData.value = res.data.rows.map(item => {
        // 计划月份
        item.salesMonth = proxy.parseTime(item.salesMonth, '{y}-{m}')
        return item
      }) || []
      total.value = res.data.total || 0
    })
  }
  getTableList()

  const updateShowSearch = (val) => {
    showSearch.value = val
  }


  // 提交变更
  const submitChange = async (row, col) => {


    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 submitThreeMetersTwoSecondsPlan({
      id: row.sadsId,
      [col.prop]: row[col.prop], // 当前修改列的值
      ...requestObj
    })

  }

</script>

<style scoped></style>