<template>
  <div class="app-container">
    <div class="container"
      v-loading="loading">
      <!-- 搜索表单 -->
      <el-form :model="queryParams"
        label-position="right"
        label-width="88px"
        inline
        v-show="showSearch">
        <el-form-item label="直播间分类">
          <xl-select v-model="queryParams.zbjQdType"
            :options="brandList"
            selectAllValue="ALL"
            multiple
            clearable
            filterable
            collapse-tags
            collapse-tags-tooltip
            @change="getList">
          </xl-select>
        </el-form-item>
        <el-form-item label="口味">
          <xl-select v-model="queryParams.flavorErp"
            multiple
            :options="tasteList"
            clearable
            filterable
            collapse-tags
            collapse-tags-tooltip
            @change="getList">
            <!-- <el-option v-for="item in tasteList"
              :label="item.label"
              :value="item.value">
            </el-option> -->
          </xl-select>
        </el-form-item>
        <el-form-item label="规格">
          <xl-select v-model="queryParams.specNameErp"
            :options="specList"
            multiple
            clearable
            filterable
            collapse-tags
            collapse-tags-tooltip
            @change="getList">
            <!-- <el-option v-for="item in specList"
              :label="item.label"
              :value="item.value">
            </el-option> -->
          </xl-select>
        </el-form-item>
        <el-form-item label="系列商品"
          class="series">
          <el-cascader v-model="queryParams.seriesPrdMap"
            v-if="seriesList.length"
            :options="seriesList"
            :props="props"
            :show-all-levels="false"
            collapse-tags
            collapse-tags-tooltip
            clearable
            filterable
            @change="getList"></el-cascader>
          <!-- <el-select v-model="queryParams.series"
            multiple
            clearable
            collapse-tags
            collapse-tags-tooltip
            @change="getList">
            <el-option v-for="str in seriesList"
              :label="str"
              :value="str">
            </el-option>
          </el-select> -->
        </el-form-item>
        <!-- <el-form-item label="商品">
          <el-select v-model="queryParams.goods"
            multiple
            clearable
            collapse-tags
            collapse-tags-tooltip
            @change="getList">
            <el-option v-for="str in goodsList"
              :label="str"
              :value="str">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="日期选择"
          class="date_picker">
          <el-date-picker v-model="queryParams.date"
            type="daterange"
            :clearable="false"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="pickerOptions"
            @change="getList()">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <!-- 操作工具 -->
      <el-row class="mb8">
        <el-button icon="Refresh"
          @click="reset"
          v-show="showSearch">
          重置
        </el-button>
        <el-button icon="Download"
          @click="downLoadExcel"
          type="success"
          v-show="showSearch">
          下载表格
        </el-button>
        <right-toolbar v-model:showSearch="showSearch"
          @queryTable="getList"
          :columns="columns">
        </right-toolbar>
      </el-row>
      <!-- 数据 -->
      <el-table :data="tableList"
        border
        @expand-change="expandChangeFn"
        @mousedown="handleMouseDown"
        ref="expandTableRef"
        show-overflow-tooltip>
        <el-table-column type="expand">
          <template #default="props">
            <div class="expand-div">
              <el-table :data="expandTableList"
                show-overflow-tooltip
                class="expand-table"
                v-loading="expandLoading">
                <el-table-column v-for="item in columns"
                  :key="item.prop"
                  :label="item.label"
                  :prop="item.prop"
                  :min-width="item.width"
                  :formatter="formatter"
                  :sortable="item.sortable">
                </el-table-column>
                <el-table-column label="操作"
                  width="120">
                  <template v-slot="scope">
                    <el-button type="primary"
                      link
                      @click="rowClick(scope.row)">订单详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination :total="expandTotal"
                v-model:page="expandQuery.pageNum"
                v-model:limit="expandQuery.pageSize"
                @pagination="getSubList"></pagination>
            </div>

          </template>
        </el-table-column>

        <template v-for="item in columns">
          <el-table-column v-if="item.visible"
            :key="item.prop"
            :label="item.label"
            :prop="item.prop"
            :align="item.align"
            :min-width="item.width"
            :formatter="formatter"
            :sortable="item.sortable">
          </el-table-column>
        </template>

        <el-table-column label="操作"
          width="250">
          <template v-slot="scope">
            <el-button type="primary"
              link
              @click="rowClick(scope.row)">订单详情</el-button>
            <el-button type="primary"
              v-if="scope.row.zbjQdType === '达人'"
              link
              @click="downAllExpert(scope.row)">下载全部达人</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"></pagination>
      <!-- 订单详情 -->
      <el-dialog v-model="detailVisible"
        title="订单详情"
        width="80%"
        footer-class="dialog-footer">
        <el-table :data="detailList"
          ref="detailTableRef"
          border
          :key="showOverFlowToolTip"
          height="100%"
          scrollbar-always-on
          :show-overflow-tooltip="showOverFlowToolTip"
          scrollbar-tabindex="0">
          <el-table-column v-for="item in detailColumns"
            :prop="item.prop"
            :label="item.label"
            :width="item.width"
            :formatter="detailFormatter" />
        </el-table>
        <template #footer>
          <el-row>
            <el-button icon="Download"
              @click="downLoadDetailExcel"
              type="success">
              下载订单详情表格
            </el-button>
            <el-button class="semi-btn"
              type="primary"
              icon="SemiSelect"
              @click="changeShowOver">
              {{ showOverFlowToolTip ? '自然展示' : '强制一行' }}
            </el-button>
            <pagination :total="detailTotal"
              v-model:page="detailQueryParams.pageNum"
              v-model:limit="detailQueryParams.pageSize"
              @pagination="getDetailList"></pagination>
          </el-row>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { getBrandListAPI, getTasteListAPI, getSpecListAPI, getSeriesListAPI, getProductListAPI, getFinanceListAPI, getFinanceDetailAPI, getFinanceSubListAPI, downloadFinanceListAPI, addPlanAPI } from '@/api'
import { useDatePickerOptions } from '@/hooks'
import { formatNumberWithUnit, parseTime } from '@/utils'

const { lastPickerOptions: pickerOptions, lastDate } = useDatePickerOptions()
const showSearch = ref(true) // 搜索
const detailVisible = ref(false) // 详情
const loading = ref(false)

const data = reactive({
  queryParams: {
    zbjQdType: [], // 直播间
    flavorErp: [], // 口味
    specNameErp: [], // 规格
    date: lastDate, // 日期
    seriesPrdMap: [], // 系列商品
    pageNum: 1,
    pageSize: 10
  },
  detailQueryParams: { // 详情查询
    pageNum: 1,
    pageSize: 10
  },
  expandQuery: { // 展开查询
    pageNum: 1,
    pageSize: 10
  }
})

const { queryParams, detailQueryParams, expandQuery } = toRefs(data)

const reset = () => {
  queryParams.value = {
    zbjQdType: [], // 直播间
    flavorErp: [], // 口味
    specNameErp: [], // 规格
    date: lastDate, // 日期
    seriesPrdMap: [], // 系列商品
    pageNum: 1,
    pageSize: 10
  }
  getList()
}

// 直播间列表
const brandList = ref([])
const getBrandList = async () => {
  const response = await getBrandListAPI();
  brandList.value = response.data.map(obj => {
    return {
      value: obj.zbjQdType,
      label: obj.zbjQdType
    };
  });
  // 默认查询所有直播间列表
  queryParams.value.zbjQdType = brandList.value.map(obj => obj.value);
};
getBrandList();

// 口味列表
const tasteList = ref([])
const getTasteList = async () => {
  const response = await getTasteListAPI();
  tasteList.value = response.data.map(obj => {
    return {
      value: obj.flavor,
      label: obj.flavor
    };
  });
};
getTasteList();

// 规格列表
const specList = ref([])
const getSpecList = async () => {
  const response = await getSpecListAPI();
  specList.value = response.data.map(obj => {
    return {
      value: obj.spec,
      label: obj.spec
    };
  });
};
getSpecList();

// 系列+商品列表
const seriesList = ref([])
const getSeriesList = async () => {
  const response = await getSeriesListAPI();
  seriesList.value = response.data.map(obj => {
    return {
      value: obj.seriesId,
      // value: obj.seriesName,
      label: obj.seriesName
    };
  });
};
getSeriesList();
const props = reactive({ // 级联选择器配置
  multiple: true,
  lazy: true,
  async lazyLoad(node, resolve) {
    const { value: seriesId } = node;
    try {
      const { data: { total } } = await getProductListAPI({ seriesId });
      const { data: { rows } } = await getProductListAPI({ seriesId, pageNum: 1, pageSize: total });
      const nodes = rows.map(item => ({
        // value: item.prdCode,
        value: item.prdName,
        label: item.prdName,
        leaf: true // 指定叶子节点
      }));
      resolve(nodes);
    } catch (error) {
      resolve([]);
    }
  }
})


// 表格数据
const columns = ref([
  {
    label: '直播间分类',
    prop: 'zbjQdType',
    visible: true,
    width: 140,
    check: true, // 根据查询条件有无，判断当前列实/隐
    sortable: false,
    align: 'left' // 对齐
  },
  {
    label: '口味',
    prop: 'flavorErp',
    visible: true,
    width: 120,
    check: true,
    sortable: false,
    align: 'left'
  },
  {
    label: '规格',
    prop: 'specNameErp',
    visible: true,
    width: 140,
    check: true,
    sortable: false,
    align: 'left'
  },
  {
    label: '系列',
    prop: 'series',
    visible: true,
    width: 140,
    check: true,
    sortable: false,
    align: 'left'
  },
  {
    label: '商品',
    prop: 'goodsName',
    visible: true,
    width: 140,
    check: true,
    sortable: false,
    align: 'left'
  },
  {
    label: '分销商 id',
    prop: 'fenxiaoId',
    visible: true,
    width: 100,
    check: true,
    sortable: false,
    align: 'left'
  },
  {
    label: '分销商名称',
    prop: 'fenxiaoName',
    visible: true,
    width: 200,
    check: true,
    sortable: false,
    align: 'left'
  },
  {
    label: '分摊后总价',
    prop: 'shareAmountSum',
    visible: true,
    width: 120,
    check: false,
    sortable: true,
    align: 'right'
  },
  {
    label: '实际成本',
    prop: 'actualCostSum',
    visible: true,
    width: 120,
    check: false,
    sortable: true,
    align: 'right'
  },
  {
    label: '实际成本毛利',
    prop: 'actualCostGrossProfitSum',
    visible: true,
    width: 160,
    check: false,
    sortable: true,
    align: 'right'
  },
  {
    label: '标准成本',
    prop: 'standardCostSum',
    visible: true,
    width: 120,
    check: false,
    sortable: true,
    align: 'right'
  },
  {
    label: '标准成本毛利',
    prop: 'standardCostGrossProfitSum',
    visible: true,
    width: 160,
    check: false,
    sortable: true,
    align: 'right'
  }
])
const tableList = ref([
])
const total = ref(0)
const getList = async () => {
  loading.value = true
  // 直播间分类全选时，单独增加字段给后台
  queryParams.value.zbjQdTypeAll = (queryParams.value.zbjQdType.length === brandList.value.length)
  // 口味
  queryParams.value.flavorErpAll = (queryParams.value.flavorErp.length === tasteList.value.length)
  // 规格
  queryParams.value.specNameErpAll = (queryParams.value.specNameErp.length === specList.value.length)

  // 获取财务数据
  const res = await getFinanceListAPI(queryParams.value)
  total.value = res.data.total
  tableList.value = res.data.list
  loading.value = false
}
getList()

const formatter = (row, column, value) => {
  if (['shareAmountSum', 'actualCostSum', 'actualCostGrossProfitSum', 'standardCostSum', 'standardCostGrossProfitSum'].includes(column.property)) {
    return formatNumberWithUnit({ value, carry: false, fixed: 4, round: false, post: false, comma: true, des: '' })
  } else {
    return value
  }
}

// 展开行
const expandTableList = ref([])
const expandTotal = ref(0)
let lastExpandRow = ref(null) // 上一次展开的行
const expandTableRef = ref(null)
const expandLoading = ref(false)
const expandChangeFn = async (row, nowRow) => {
  // 展开
  if (nowRow.length > 0) {
    // 折叠掉之前展开的行
    lastExpandRow && expandTableRef.value.toggleRowExpansion(lastExpandRow, false)
    lastExpandRow = row
    nextTick(() => {
      getSubList()
    })
  } else {
    // 折叠
    lastExpandRow = null
  }
  expandTableList.value = []
}
const getSubList = async () => {
  expandLoading.value = true
  // 参数顺序不能更改
  const res = await getFinanceSubListAPI({
    ...queryParams.value,
    ...lastExpandRow,
    ...expandQuery.value
  })
  expandTableList.value = res.data.list
  expandTotal.value = res.data.total
  expandLoading.value = false
}
// 下载达人数据
const downAllExpert = async (row) => {
  const res = await downloadFinanceListAPI({
    ...queryParams.value,
    zbjQdType: [row.zbjQdType],
    zbjQdTypeAll: false,
    type: 1 // 代表达人数据
  }, '财务分析-达人数据.xlsx')
}
// 下载全部表格数据
const downLoadExcel = async () => {
  const res = await downloadFinanceListAPI({
    ...queryParams.value,
    zbjQdTypeAll: true,
    type: 2 // 代表全部数据
  }, '财务分析.xlsx')
}
// 下载订单详情表格
const downLoadDetailExcel = async (row) => {
  const res = await downloadFinanceListAPI({
    ...queryParams.value,
    ...lastExpandRow,
    ...expandQuery.value,
    ...row,
    type: 3 // 代表订单详情数据
  }, '财务分析-订单详情.xlsx')
}

const handleMouseDown = (event) => {
  if (event.button === 1) { // 1 表示鼠标中键
    event.preventDefault(); // 阻止默认的滚动行为
  }
}

// 观察查询表单选择字段，则显示
// watch(queryParams, (val) => {
//   // 日期无需决定列显示与否
//   const showQuery = { ...val }
//   delete showQuery.date
//   // 如果每个筛选条件都无值，则显示直播间分类这一列
//   if (Object.values(showQuery).every(item => item.length === 0)) {
//     columns.value.forEach(item => {
//       if (item.check) {
//         item.visible = item.prop === 'zbjQdType'
//       }
//     })
//     return
//   }
//   // 哪个筛选条件有值，则显示哪一列
//   Object.entries(showQuery).forEach(([key, value]) => {
//     // 处理查询参数名和列 prop 字段名不同的情况
//     // 系列和商品搜索字段叫 seriesPrdMap，但是列字段叫 series 和 goodsName
//     if (key === 'seriesPrdMap') {
//       const columnSeries = columns.value.find(item => item.prop === 'series')
//       const columnGoods = columns.value.find(item => item.prop === 'goodsName')
//       if (columnSeries && columnGoods) {
//         columnSeries.visible = value.length > 0
//         columnGoods.visible = value.length > 0
//       }
//     } else {
//       // 查询参数名和 prop 能对上的
//       const columnObj = columns.value.find(item => item.prop === key)
//       if (columnObj && columnObj.check) {
//         // 显示该列
//         columnObj.visible = value.length > 0
//       }
//     }
//   })
// }, {
//   deep: true,
//   immediate: true
// })

// 详情数据
const detailList = ref([])
const detailColumns = ref([
  {
    label: '订单编号',
    prop: 'tradeNo',
    width: 160
  }, {
    label: '店铺名称',
    prop: 'shopName',
    width: 220
  }, {
    label: '原始单号',
    prop: 'srcTid',
    width: 180
  }, {
    label: '原始子单号',
    prop: 'srcOid',
    width: 180
  }, {
    label: '订单状态',
    prop: 'tradeStatus',
    width: 80
  }, {
    label: '交易时间',
    prop: 'tradeTime',
    width: 170
  }, {
    label: '付款时间',
    prop: 'payTime',
    width: 170
  }, {
    label: '发货时间',
    prop: 'consignTime',
    width: 170
  }, {
    label: '省市县',
    prop: 'receiverArea',
    width: 170
  }, {
    label: '备注',
    prop: 'remark',
    width: 250
  }, {
    label: '应收金额',
    prop: 'receivable',
    width: 80
  }, {
    label: '货品编号',
    prop: 'goodsNo',
    width: 120
  }, {
    label: '货品名称',
    prop: 'goodsName',
    width: 250
  }, {
    label: '规格名称',
    prop: 'specName'
  }, {
    label: '分类',
    prop: 'goodsType',
    width: 100
  }, {
    label: '数量',
    prop: 'num'
  }, {
    label: '优惠',
    prop: 'discount'
  }, {
    label: '分摊后总价',
    prop: 'shareAmount',
    width: 120
  }, {
    label: '拆自组合装',
    prop: 'suiteNo',
    width: 200
  }, {
    label: '组合装编码',
    prop: 'suiteName',
    width: 200
  }, {
    label: '组合装数量',
    prop: 'suiteNum',
    width: 140
  }, {
    label: '赠品方式',
    prop: 'giftType',
    width: 160
  }, {
    label: '分销商名称',
    prop: 'fenxiaoName',
    width: 240
  }, {
    label: '分销商编号',
    prop: 'fenxiaoId',
    width: 160
  }, {
    label: '平台货品名称',
    prop: 'apiGoodsName',
    width: 540
  }
])
const detailTotal = ref(0)
const showOverFlowToolTip = ref(true) // 强制表格一行显示
const detailTableRef = ref(null)
// 订单状态
const orderStatus = {
  4: "线下退款",
  5: "已取消",
  6: "待转预订单(待审核)",
  7: "待转已完成",
  10: "未付款",
  12: "待尾款",
  15: "等未付",
  16: "延时审核",
  19: "预订单前处理",
  20: "审核前处理",
  21: "自流转待发货",
  23: "异常订单",
  24: "换货预订单",
  25: "待处理预订单",
  27: "待分配预订单",
  30: "待客审",
  35: "待财审",
  40: "审核中",
  55: "已审核",
  95: "已发货",
  96: "成本确认（待录入计划成本，订单结算时有货品无计划成本）",
  101: "已过账",
  110: "已完成"
};
// 分类（货品类型）
const goodsType = {
  1: "销售商品",
  2: "原材料",
  3: "包装",
  4: "周转材料",
  5: "虚拟商品",
  6: "固定资产",
  0: "其它"
};
// 赠品方式
const giftType = {
  0: "非赠品",
  1: "自动赠送",
  2: "手工赠送",
  4: "周期购赠送",
  8: "平台赠送",
  32: "阶梯满赠",
  64: "CRM追加赠送",
  128: "主品"
};

const rowClick = (row) => {
  detailQueryParams.value = {
    zbjQdType: row.zbjQdType && [row.zbjQdType], // 直播间
    flavorErp: row.flavorErp && [row.flavorErp], // 口味
    specNameErp: row.specNameErp && [row.specNameErp], // 规格
    // seriesPrdMap: row.seriesId && [{ value: row.seriesId, label: row.seriesName }], // TODO：行里没有系列字段等会看下,现在格式应该是 [[系列id],[商品id]]
    seriesPrdMap: [],
    date: queryParams.value.date, // 日期
    pageNum: 1,
    pageSize: 10
  }
  detailVisible.value = true
  getDetailList()
}
const getDetailList = async () => {
  const { data: { list, total } } = await getFinanceDetailAPI(detailQueryParams.value)
  detailList.value = list
  detailTotal.value = total
}
const detailFormatter = (row, column, value) => {
  if (['tradeTime', 'payTime', 'consignTime'].includes(column.property)) {
    return parseTime(value, '{y}-{m}-{d} {h}:{i}:{s}')
  } else if (['tradeStatus'].includes(column.property)) {
    return orderStatus[value]
  } else if (['goodsType'].includes(column.property)) {
    return goodsType[value]
  } else if (['giftType'].includes(column.property)) {
    return giftType[value]
  }
  return value
}
const changeShowOver = () => {
  showOverFlowToolTip.value = !showOverFlowToolTip.value
}
</script>

<style scoped
  lang="scss">
  ::v-deep(.el-form-item) {
    width: 300px;

    &.date_picker {
      width: 350px;
    }

  }

  .series {
    width: 460px !important;

    ::v-deep(.el-cascader) {
      width: 460px !important;
    }
  }

  .dialog-footer {
    .el-row {
      display: flex;
      justify-content: flex-end;
      align-items: center;

      .semi-btn {
        margin-right: 20px;
      }

      .pagination-container {
        margin: 0 !important;
        height: auto !important;
      }
    }
  }

  /* 展开行表格 */
  .expand-div {
    background-color: rgb(240, 240, 240);
    padding: 20px !important;
  }

  .el-scrollbar__bar {
    height: 0;
  }

</style>