<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" />
</template>

<script setup
  lang="jsx">
  import CustomTable from '@/views/promotion/components/Table'
  import SearchList from '@/views/promotion/components/SearchList'
  import { getSixLittleDiamondsPlanList, submitSixLittleDiamondsPlan } 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
    },
    // 六小金刚批发挂网分组
    {
      label: "六小金刚批发挂网",
      children: [
        {
          label: '计划执行-六小金刚批发挂网',
          prop: 'plannedGw6',
          visible: true,
          type: 'string',
          fill: false,
          width: 180
        },
        {
          label: '实际执行-六小金刚批发挂网',
          prop: 'actualGw6',
          referenceKey: 'plannedGw6',
          visible: true,
          type: 'select',
          // options: [
          //   // { label: '是', value: '是' },
          //   // { label: '否', value: '否' }
          //   // { label: 0, value: 0 },
          //   // { label: 1, value: 1 },
          //   // { label: '其他', value: '其他' }
          // ],
          render: (_, row, col) => {
            return (
              <div>
                <span>{row[col.referenceKey] || '-'}</span>
                <el-input modelValue={row[col.prop]}
                  onUpdate:modelValue={(value) => {
                    const numValue = value === '' ? 0 : Number(value);
                    row[col.prop] = numValue;
                    submitChange(row, col);
                  }}
                  disabled={!row[col.referenceKey]}
                  class={{'no-disabled': row[col.referenceKey]}}
                  min="0"
                  type="number"
                  placeholder=""
                  clearable>
                </el-input>
              </div>
            )
          },
          fill: true,
          width: 190
        },
        {
          label: '六小金刚批发挂网陈列费',
          prop: 'totalCostGw6',
          visible: true,
          type: 'string',
          fill: false,
          width: 160
        },
        {
          label: '六小金刚批发挂网-是否执行',
          prop: 'gwExecuted6',
          visible: true,
          type: 'formula',
          func: (row) => {
            // 如果参考值是空则返回 '-'
            if (!row.plannedGw6) {
              row.gwExecuted6 = '-'
              return '-';
            }
            // 判断区间，未执行，部分执行，执行
            if (!row.actualGw6 || row.actualGw6 == 0) {
              row.gwExecuted6 = '未执行'
              return '未执行'
            } else if (row.actualGw6 < row.plannedGw6) {
              row.gwExecuted6 = '部分执行'
              return '部分执行'
            } else {
              row.gwExecuted6 = '执行'
              return '执行'
            }
          },
          formulaStr: '公式：（计划执行-六小金刚批发挂网 = 实际执行-六小金刚批发挂网）',
          fill: true,
          width: 210
        }
      ],
      prop: 'wholesaleNetColumns',
      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: 10,
  })
  const showFill = ref(true)
  const getTableList = () => {
    isLoading.value = true
    getSixLittleDiamondsPlanList(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 submitSixLittleDiamondsPlan({
      id: row.sadjId,
      [col.prop]: row[col.prop], // 当前修改列的值
      ...requestObj
    })

  }

</script>

<style scoped></style>