<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="销售公司" prop="companyId">
        <el-select filterable v-model="queryParams.companyId" clearable placeholder="请选择公司名称" size="small">
          <el-option
            v-for="item in companyList"
            :key="item.companyId"
            :label="item.companyName"
            :value="item.companyId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="员工账号" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入员工账号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="员工名称" prop="companyUser">
        <el-input
          v-model="queryParams.companyUser"
          placeholder="请输入员工名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="商品标签" prop="cateIds">
        <el-cascader
          v-model="cateIds"
          placeholder="请选择商品标签"
          :options="categoryOptions"
          :props="{ checkStrictly: true }"
          :normalizer="normalizer"
          clearable
          filterable
        ></el-cascader>
      </el-form-item>

      <el-form-item label="商品" prop="productId">
        <el-select v-model="queryParams.productId" clearable filterable placeholder="请选择商品">
          <el-option
            v-for="item in productList"
            :key="item.productId"
            :label="item.productName"
            :value="item.productId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单日期">
        <el-date-picker
          v-model="queryDate"
          type="monthrange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!--    <el-tabs v-model="activeName" @tab-click="handleClick">-->
    <!--      <el-tab-pane label="员工统计" name="1"></el-tab-pane>-->
    <!--      <el-tab-pane label="标签统计" name="2"></el-tab-pane>-->
    <!--      <el-tab-pane label="商品统计" name="3"></el-tab-pane>-->
    <!--    </el-tabs>-->

    <!--    <el-table border v-loading="loading" :data="pageList" @selection-change="handleSelectionChange" v-show="queryParams.groupType !== '1'">-->
    <!--      <el-table-column label="员工编码" align="center" prop="userId" "/>-->
    <!--      <el-table-column label="标签编码" align="center" prop="cateId" v-else-if="queryParams.groupType === '2'"/>-->
    <!--      <el-table-column label="商品编码" align="center" prop="productId" v-else/>-->
    <!--      <el-table-column label="企业名称" align="center" prop="companyName" "/>-->
    <!--      <el-table-column label="员工账号" align="center" prop="userName" "/>-->
    <!--      <el-table-column label="员工名称" align="center" prop="nickName" "/>-->
    <!--      <el-table-column label="标签名称" align="center" prop="cateName" v-if="queryParams.groupType === '2'"/>-->
    <!--      <el-table-column label="商品名称" align="center" prop="productName" v-if="queryParams.groupType === '3'"/>-->
    <!--      <el-table-column label="销售订单数量" align="center" prop="orderNum"/>-->
    <!--      &lt;!&ndash;      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">&ndash;&gt;-->
    <!--      &lt;!&ndash;        <template v-slot="scope">&ndash;&gt;-->
    <!--      &lt;!&ndash;          <el-button&ndash;&gt;-->
    <!--      &lt;!&ndash;            size="mini"&ndash;&gt;-->
    <!--      &lt;!&ndash;            type="text"&ndash;&gt;-->
    <!--      &lt;!&ndash;            icon="el-icon-edit"&ndash;&gt;-->
    <!--      &lt;!&ndash;          >修改&ndash;&gt;-->
    <!--      &lt;!&ndash;          </el-button>&ndash;&gt;-->
    <!--      &lt;!&ndash;          <el-button&ndash;&gt;-->
    <!--      &lt;!&ndash;            size="mini"&ndash;&gt;-->
    <!--      &lt;!&ndash;            type="text"&ndash;&gt;-->
    <!--      &lt;!&ndash;            icon="el-icon-delete"&ndash;&gt;-->
    <!--      &lt;!&ndash;          >删除&ndash;&gt;-->
    <!--      &lt;!&ndash;          </el-button>&ndash;&gt;-->
    <!--      &lt;!&ndash;        </template>&ndash;&gt;-->
    <!--      &lt;!&ndash;      </el-table-column>&ndash;&gt;-->
    <!--    </el-table>-->

    <el-table border v-loading="loading" :data="pageList" @selection-change="handleSelectionChange"
              :span-method="objectSpanMethod" v-show="queryParams.groupType === '1'"
              style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="companyName" align="center" label="企业名称" width="180"></el-table-column>
      <el-table-column label="员工编码" align="center" prop="userId"/>
      <el-table-column label="员工账号" align="center" prop="userName"/>
      <el-table-column label="员工名称" align="center" prop="nickName"/>
      <el-table-column label="总单数" align="center" prop="totalNum"/>
      <el-table-column label="总金额" align="center" prop="totalPrice"/>
      <el-table-column label="成交单数" align="center" prop="dealNum"/>
      <el-table-column label="成交金额" align="center" prop="dealPrice"/>
      <el-table-column label="取消单数" align="center" prop="cancelNum"/>
      <el-table-column label="取消金额" align="center" prop="cancelPrice"/>
      <el-table-column label="待发货单数" align="center" prop="pendingNum"/>
      <el-table-column label="待发货金额" align="center" prop="pendingPrice"/>
      <el-table-column label="发货单数" align="center" prop="invoiceNum"/>
      <el-table-column label="发货金额" align="center" prop="invoicePrice"/>
      <el-table-column label="签收单数" align="center" prop="signForNum"/>
      <el-table-column label="签收金额" align="center" prop="signFPrice"/>
      <el-table-column label="退单数" align="center" prop="chargebackNum"/>
      <el-table-column label="退单金额" align="center" prop="chargebackPrice"/>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { orderDimensionStatisticsList, orderDimensionStatisticsExport } from '@/api/hisStore/storeOrder'
import { getCompanyList } from '@/api/company/company'
import { getAllStoreProductCategory } from '@/api/hisStore/storeProductCategory'
import { listStoreProduct } from '@/api/hisStore/storeProduct'

export default {
  name: 'HisCompanyBindUser',
  data() {
    return {
      activeName: '1',
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分页List
      pageList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      //选中的公司
      companyList: [],
      spanArr: [],
      queryDate: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        userName: null,
        companyUser: null,
        productName: null,
        productId: null,
        cateName: null,
        startDate: null,
        endDate: null,
        cateId: null,
        groupType: '1'
      },
      //商品查询参数
      productQueryParams: {},
      productList: [],
      cateIds: [],
      categoryOptions: [],
      // 表单参数
      form: {},
      pickerOptions: {
        shortcuts: [{
          text: '本月',
          onClick(picker) {
            picker.$emit('pick', [new Date(), new Date()])
          }
        }, {
          text: '今年至今',
          onClick(picker) {
            const end = new Date()
            const start = new Date(new Date().getFullYear(), 0)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 2)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  created() {
    /**
     * 赋值默认日期
     * **/
    this.queryDate = this.getDefaultDateRange()

    /**
     * 查询
     * **/
    this.getList()

    /**
     * 销售企业下拉列表
     * **/
    getCompanyList().then(response => {
      this.companyList = response.data
    })

    /**
     * 商品标签
     * **/
    this.getTreeselect()

    /**
     * 获取商品
     * **/
    this.getProductList();
  },
  watch: {
    pageList: {
      handler() {
        if (this.queryParams.groupType === '1') {
          this.getSpanArr()
        }
      },
      deep: true
    },
    'queryParams.groupType'(newVal) {
      if (newVal === '1') {
        this.getSpanArr()
      }
    }
  },
  methods: {
    /** 查询企业域名分配中间表列表 */
    getList() {
      this.loading = true

      this.queryParams.startDate = this.queryDate ? this.queryDate[0] : null
      this.queryParams.endDate = this.queryDate ? this.queryDate[1] : null
      this.queryParams.cateId = this.cateIds ? this.cateIds[this.cateIds.length - 1] : null

      orderDimensionStatisticsList(this.queryParams).then(response => {
        this.pageList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        companyUserId: null,
        bindId: null,
        createTime: null,
        createBy: null,
        updateBy: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      /**
       * 赋值默认日期
       * **/
      this.queryDate = this.getDefaultDateRange()
      this.cateIds = []
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有企业域名分配中间表数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true
        return orderDimensionStatisticsExport(queryParams)
      }).then(response => {
        this.download(response.msg)
        this.exportLoading = false
      }).catch(() => {
      })
    },
    handleClick(tab, event) {
      this.queryParams.groupType = tab.name
      this.getList()
    },

    /**
     * 赋值时间组件默认日期
     * **/
    getDefaultDateRange() {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 2)

      const formatDate = (date) => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        return `${year}-${month}-01`
      }

      return [formatDate(start), formatDate(end)]
    },

    getSpanArr() {
      this.spanArr = []
      if (this.pageList.length === 0) return

      let pos = 0
      this.spanArr.push(1)

      for (let i = 1; i < this.pageList.length; i++) {
        const currentRow = this.pageList[i]
        const prevRow = this.pageList[i - 1]

        if (currentRow.companyId === prevRow.companyId) {
          this.spanArr[pos] += 1
          this.spanArr.push(0)
        } else {
          this.spanArr.push(1)
          pos = i
        }
      }
    },

    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const rowspan = this.spanArr[rowIndex]
        return {
          rowspan: rowspan,
          colspan: 1
        }
      }
    },

    normalizer(node) {
      const normalized = {
        value: node.cateId,
        label: node.cateName
      }
      if (node.children && node.children.length > 0) {
        normalized.children = node.children.map(child => this.normalizer(child))
      }
      return normalized
    },
    handleTree(data, idKey, parentKey, rootId = 0) {
      return data
        .filter(item => item[parentKey] === rootId)
        .map(item => {
          const children = this.handleTree(data, idKey, parentKey, item[idKey])
          return {
            ...item,
            ...(children.length > 0 ? { children } : {})
          }
        })
    },

    getTreeselect() {
      getAllStoreProductCategory()
        .then(response => {
          if (!response.data || !Array.isArray(response.data)) {
            console.error('分类数据格式不正确:', response.data)
            return
          }
          const data = this.handleTree(response.data, 'cateId', 'pid')
          this.categoryOptions = data.map(node => this.normalizer(node))
          console.log('分类选项加载成功:', this.categoryOptions)
        })
        .catch(error => {
          console.error('获取分类数据失败:', error)
        })
    },
    /**
     * 查询商品
     * **/
    getProductList() {
      listStoreProduct(this.productQueryParams).then(response => {
        this.productList = response.rows;
      })
    }
  }
}
</script>
