<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="110px"
    >
      <el-form-item label="分货日期:" prop="splitDate">
        <el-date-picker
          v-model="queryParams.splitDate"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="类目:" prop="categoryCode">
        <el-select
          v-model="queryParams.categoryCode"
          filterable
          placeholder="请选择类目"
          clearable
        >
          <el-option
            v-for="(dict, index) in categoryList"
            :key="index"
            :label="dict.categoryName"
            :value="dict.categoryCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌:" prop="brandNames">
        <el-select
          v-model="queryParams.brandNames"
          filterable
          placeholder="品牌"
          clearable
          multiple
          @change="brandChange"
        >
          <el-option
            v-for="(dict, index) in brandNameList"
            :key="index"
            :label="dict.brandName"
            :value="dict.brandName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="型号:" prop="spuNames">
        <el-select
          v-model="queryParams.spuNames"
          multiple
          filterable
          placeholder="型号"
          clearable
        >
          <el-option
            v-for="(dict, index) in spuList"
            :key="index"
            :label="dict.spuName"
            :value="dict.spuName"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="商品:" prop="skuNos">
        <!-- <el-input
          v-model="queryParams.skuNos"
          placeholder="请输入完整商品编码,多个用逗号隔开"
          clearable
        /> -->
        <LoadMoreSelect
          :skuNo="queryParamsSkuNos"
          @queryParams="(val) => (queryParams.skuNos = val)"
        />
      </el-form-item>
      <!-- <el-form-item label="商品名称:" prop="skuNames">
        <el-input
          v-model="queryParams.skuNames"
          placeholder="请输入商品名称关键字"
          clearable
        />
      </el-form-item> -->
      <el-row :gutter="10" class="mb8" type="flex" justify="end">
        <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-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain size="mini" @click="expandChange">{{
          expandText
        }}</el-button>
        <!-- <el-button type="info" plain size="mini" @click="handleImport"
          >参与分货渠道</el-button
        >
        <el-button type="success" plain size="mini" @click="handlePause2(1)"
          >品牌采购负责人设置</el-button
        > -->
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        :columns="columns"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      ref="proTable"
      border
      v-loading="loading"
      :data="postList"
      row-key="id"
      :tree-props="{ children: 'channelSkuStockListDTOS' }"
      :key="treeKey"
      :default-expand-all="isExpand"
      :height="tableHeight"
    >
      <!-- <el-table-column type="selection" width="55" align="left" /> -->
      <el-table-column label="型号" min-width="140" align="left" prop="spuName" />
      <el-table-column label="商品名称" min-width="140" align="left" prop="skuName">
        <!-- <template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">{{ scope.row.skuName }}</div>
            <div class="table-overflow">{{ scope.row.skuName }}</div>
          </el-tooltip>
        </template> -->
      </el-table-column>
      <el-table-column label="商品编码" min-width="100" align="left" prop="skuCode">
        <template template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">{{ scope.row.skuCode }}</div>
            <div class="table-overflow">{{ scope.row.skuCode }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        label="品牌"
        min-width="90"
        v-if="columns[0].visible"
        align="left"
        prop="brandName"
      />
      <el-table-column
        label="采购经理"
        min-width="85"
        v-if="columns[1].visible"
        align="left"
        prop="purManageName"
      />
      <el-table-column
        label="近期日平均销量"
        min-width="110"
        align="left"
        v-if="columns[2].visible"
        prop="day3AverageSale"
      >
        <template template slot-scope="scope">
          <div><span class="colorG">近三日</span> {{ scope.row.day3AverageSale }}</div>
          <el-button
            size="mini"
            v-if="scope.row.skuName"
            type="text"
            @click="splitDetail(scope.row)"
            >详情</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        label="今日总销量"
        v-if="columns[3].visible"
        min-width="70"
        align="left"
        prop="todaySale"
      />
      <el-table-column
        label="当前可销库存"
        v-if="columns[4].visible"
        min-width="70"
        align="left"
        prop="curSale"
      />
      <el-table-column
        label="日初库存"
        v-if="columns[5].visible"
        min-width="70"
        align="left"
        prop="initStock"
      />
      <el-table-column
        label="销售一部"
        v-if="columns[6].visible"
        min-width="105"
        align="left"
        prop="xsGoodCode"
      >
        <template template slot-scope="scope">
          <div class="table-dp">
            分:
            <span :class="{ colorRed: scope.row.dept1Red }">{{
              scope.row.dept1SplitStock
            }}</span>
          </div>
          <div class="table-dp">
            昨销: <span>{{ scope.row.dept1YesterdaySale }}</span>
          </div>
          <div class="table-dp">
            近3销: <span>{{ scope.row.dept1Day3Sale }}</span>
          </div>
          <div class="table-dp">
            今销: <span>{{ scope.row.dept1TodaySale }}</span>
            <img
              v-show="scope.row.dept1Up"
              src="../../assets/images/up.png"
              class="up-png"
            />
          </div>
          <el-button
            type="text"
            size="mini"
            v-if="today == queryParams.splitDate"
            @click="channelDia(scope.row, '销售一部')"
            >分货到渠道</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        label="销售二部"
        v-if="columns[7].visible"
        min-width="105"
        align="left"
        prop="xsGoodCode"
      >
        <template template slot-scope="scope">
          <div class="table-dp">
            分:
            <span :class="{ colorRed: scope.row.dept2Red }">{{
              scope.row.dept2SplitStock
            }}</span>
          </div>
          <div class="table-dp">
            昨销: <span>{{ scope.row.dept2YesterdaySale }}</span>
          </div>
          <div class="table-dp">
            近3销: <span>{{ scope.row.dept2Day3Sale }}</span>
          </div>
          <div class="table-dp">
            今销: <span>{{ scope.row.dept2TodaySale }}</span>
            <img
              v-show="scope.row.dept2Up"
              src="../../assets/images/up.png"
              class="up-png"
            />
          </div>
          <el-button
            type="text"
            size="mini"
            v-if="today == queryParams.splitDate"
            @click="channelDia(scope.row, '销售二部')"
            >分货到渠道</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        label="销售三部"
        v-if="columns[8].visible"
        min-width="105"
        align="left"
        prop="xsGoodCode"
      >
        <template template slot-scope="scope">
          <div class="table-dp">
            分:
            <span :class="{ colorRed: scope.row.dept3Red }">{{
              scope.row.dept3SplitStock
            }}</span>
          </div>
          <div class="table-dp">
            昨销: <span>{{ scope.row.dept3YesterdaySale }}</span>
          </div>
          <div class="table-dp">
            近3销: <span>{{ scope.row.dept3Day3Sale }}</span>
          </div>
          <div class="table-dp">
            今销: <span>{{ scope.row.dept3TodaySale }}</span>
            <img
              v-show="scope.row.dept3Up"
              src="../../assets/images/up.png"
              class="up-png"
            />
          </div>
          <el-button
            type="text"
            size="mini"
            v-if="today == queryParams.splitDate"
            @click="channelDia(scope.row, '销售三部')"
            >分货到渠道</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        label="新媒体部门"
        v-if="columns[9].visible"
        min-width="105"
        align="left"
        prop="xsGoodCode"
      >
        <template template slot-scope="scope">
          <div class="table-dp">
            分:
            <span :class="{ colorRed: scope.row.dept4Red }">{{
              scope.row.dept4SplitStock
            }}</span>
          </div>
          <div class="table-dp">
            昨销: <span>{{ scope.row.dept4YesterdaySale }}</span>
          </div>
          <div class="table-dp">
            近3销: <span>{{ scope.row.dept4Day3Sale }}</span>
          </div>
          <div class="table-dp">
            今销: <span>{{ scope.row.dept4TodaySale }}</span>
            <img
              v-show="scope.row.dept4Up"
              src="../../assets/images/up.png"
              class="up-png"
            />
          </div>
          <el-button
            type="text"
            size="mini"
            v-if="today == queryParams.splitDate"
            @click="channelDia(scope.row, '新媒体部')"
            >分货到渠道</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" width="130" align="left" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="deptDia(scope.row)"
            v-if="
              today == queryParams.splitDate &&
              (roles.includes('admin') || roles.includes('purManage'))
            "
            >分货到部门</el-button
          >
          <br />
          <el-button
            size="mini"
            v-if="scope.row.skuName"
            type="text"
            @click="historySplit(scope.row)"
            >查看历史分货</el-button
          >
          <el-button
            size="mini"
            v-if="scope.row.skuName"
            type="text"
            @click="historyLog(scope.row)"
            >日志</el-button
          >
        </template>
      </el-table-column>
    </el-table>

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

    <el-dialog
      title="分货到渠道"
      :visible.sync="open"
      width="1200px"
      append-to-body
      destroy-on-close
    >
      <el-row>
        <el-col :span="20" style="height: 36px; line-height: 36px">
          <el-descriptions>
            <el-descriptions-item label="日期">{{
              listRow.operDate
            }}</el-descriptions-item>
            <el-descriptions-item label="部门">{{ deptName }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
      <el-table
        ref="channelTable"
        :span-method="objectSpanMethod"
        border
        v-loading="channelTableLoading"
        :data="channelTableList"
      >
        <el-table-column label="商品" min-width="170" align="left" prop="skuName">
          <template slot-scope="scope">
            <!-- <el-tooltip class="item" content="Top center" placement="top">
              <div slot="content" style="width: auto">{{ scope.row.skuName }}</div>
              <div class="table-overflow">{{ scope.row.skuName }}</div>
            </el-tooltip> -->
            <div v-if="scope.row.skuName != '总计' && scope.row.skuName != '合计'">
              {{ scope.row.skuName }} / {{ scope.row.skuNo }}
            </div>
            <div v-else>{{ scope.row.skuName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="部门分配库存" width="110" align="left" prop="deptStock" />
        <el-table-column label="渠道" width="160" align="left" prop="channelName" />
        <el-table-column label="渠道分配库存" width="110" align="left" prop="splitStock">
          <template slot-scope="scope">
            {{ scope.row.splitStock }}
            <span
              class="rate-span"
              v-if="
                scope.row.deptStock &&
                scope.row.splitStock != 0 &&
                scope.row.skuName != '总计' &&
                scope.row.skuName != '合计'
              "
              >{{
                ((scope.row.splitStock / scope.row.deptStock) * 100).toFixed(0) || 0
              }}%</span
            >
          </template>
        </el-table-column>
        <el-table-column label="调整后库存" width="160" align="left" prop="stockNum">
          <template slot-scope="scope">
            <el-input
              type="number"
              v-if="scope.row.skuName != '总计' && scope.row.skuName != '合计'"
              style="width: 90px"
              v-model="scope.row.stockNum"
              :class="{ 'change-input': scope.row.stockNum != scope.row.splitStock }"
              :min="0"
              :max="scope.row.deptStock"
              :disabled="
                scope.row.totalUpdateStock != undefined &&
                scope.row.totalUpdateStock != '' &&
                scope.row.totalUpdateStock != null
              "
              @input="stockNumChange(scope.row)"
            />
            <span
              class="rate-span"
              v-if="
                scope.row.stockNum &&
                scope.row.skuName != '总计' &&
                scope.row.skuName != '合计' &&
                scope.stockNum != 0 &&
                scope.row.deptStock != 0
              "
              >{{ ((scope.row.stockNum / scope.row.deptStock) * 100).toFixed(0) }}%</span
            >
            <span
              :class="{ 'change-input': scope.row.stockNum != scope.row.deptStock }"
              v-if="scope.row.skuName == '总计' || scope.row.skuName == '合计'"
              >{{ scope.row.stockNum }}</span
            >
          </template>
        </el-table-column>
        <el-table-column label="近3日平均销量" width="120" align="left" prop="day3Sale" />
        <el-table-column label="昨日销量" width="90" align="left" prop="yesterdaySale" />
        <el-table-column label="今日销量" width="90" align="left" prop="todaySale" />
        <el-table-column label="日志" width="120" align="left" prop="operLogs">
          <template slot-scope="scope">
            <el-tooltip class="item" content="Top center" placement="top">
              <div slot="content" style="width: auto">{{ scope.row.operLogs }}</div>
              <div class="table-overflow">{{ scope.row.operLogs }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="saveLoading" type="primary" @click="saveChannel"
          >保存</el-button
        >
        <el-button @click="cancel('open')">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="分货到部门"
      :visible.sync="open2"
      width="1200px"
      append-to-body
      destroy-on-close
    >
      <el-row>
        <el-col :span="20" style="height: 36px; line-height: 36px">
          <el-descriptions>
            <el-descriptions-item label="日期">{{
              listRow.operDate
            }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
      <el-table
        ref="deptTable"
        :span-method="objectSpanMethod2"
        border
        v-loading="channelTableLoading"
        :data="deptTableList"
        :row-style="rowStyle"
      >
        <el-table-column label="商品" min-width="180" align="left" prop="skuName">
          <template slot-scope="scope">
            <!-- <el-tooltip class="item" content="Top center" placement="top">
              <div slot="content" style="width: auto">{{ scope.row.skuName }}</div>
              <div class="table-overflow">{{ scope.row.skuName }}</div>
            </el-tooltip> -->
            <div v-if="scope.row.skuName != '总计' && scope.row.skuName != '合计'">
              {{ scope.row.skuName }} / {{ scope.row.skuNo }}
            </div>
            <div v-else>{{ scope.row.skuName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="日初总库存" width="100" align="left" prop="initStock" />
        <el-table-column label="部门" width="100" align="left" prop="name" />
        <el-table-column
          label="部门分配库存"
          width="130"
          align="left"
          prop="dept1InitStock"
        >
          <template slot-scope="scope">
            {{ scope.row.dept1InitStock }}
            <span
              class="rate-span"
              v-if="
                scope.row.dept1InitStock &&
                scope.row.dept1InitStock != 0 &&
                scope.row.skuName != '总计' &&
                scope.row.skuName != '合计'
              "
              >{{
                ((scope.row.dept1InitStock / scope.row.initStock) * 100).toFixed(0)
              }}%</span
            >
          </template>
        </el-table-column>
        <el-table-column label="调整后库存" width="160" align="left" prop="stockNum">
          <template slot-scope="scope">
            <el-input
              type="number"
              v-if="scope.row.skuName != '总计' && scope.row.skuName != '合计'"
              style="width: 90px"
              v-model="scope.row.stockNum"
              :min="0"
              :max="scope.row.initStock"
              :disabled="
                scope.row.totalUpdateStock != undefined &&
                scope.row.totalUpdateStock != '' &&
                scope.row.totalUpdateStock != null
              "
              :class="{ 'change-input': scope.row.stockNum != scope.row.dept1InitStock }"
              @input="stockNumChange2(scope.row)"
            />
            <span
              class="rate-span"
              v-if="
                scope.row.stockNum &&
                scope.row.skuName != '总计' &&
                scope.row.skuName != '合计' &&
                scope.row.stockNum != 0 &&
                scope.row.initStock != 0
              "
              >{{ ((scope.row.stockNum / scope.row.initStock) * 100).toFixed(0) }}%</span
            >
            <span
              :class="{ 'change-input': scope.row.stockNum != scope.row.dept1InitStock }"
              v-if="scope.row.skuName == '总计' || scope.row.skuName == '合计'"
              >{{ scope.row.stockNum }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="近3日平均销量"
          width="120"
          align="left"
          prop="dept1Day3Sale"
        />
        <el-table-column
          label="昨日销量"
          width="100"
          align="left"
          prop="dept1YesterdaySale"
        />
        <el-table-column
          label="今日销量"
          width="100"
          align="left"
          prop="dept1TodaySale"
        />

        <el-table-column label="日志" min-width="120" align="left" prop="operLogs">
          <template template slot-scope="scope">
            <el-tooltip class="item" content="Top center" placement="top">
              <div slot="content" style="width: auto">{{ scope.row.operLogs }}</div>
              <div class="table-overflow">{{ scope.row.operLogs }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="saveLoading" type="primary" @click="saveDept"
          >保存</el-button
        >
        <el-button @click="cancel('open2')">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="历史分货查询"
      bottom="100px"
      :visible.sync="open3"
      width="1100px"
      append-to-body
    >
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="按部门分配" name="1">
          <el-row style="margin-bottom: 18px">
            <el-col :span="24">
              <el-descriptions direction="vertical">
                <el-descriptions-item label="商品名称">{{
                  splitRow.skuName
                }}</el-descriptions-item>
                <el-descriptions-item label="商品编码">{{
                  splitRow.skuCode
                }}</el-descriptions-item>
                <el-descriptions-item label="日期">
                  <el-date-picker
                    v-model="historyQuery.dates"
                    style="width: 240px"
                    value-format="yyyy-MM-dd"
                    :picker-options="pickerOptions"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change="getHistoryList(1)"
                    :clearable="false"
                  ></el-date-picker>
                </el-descriptions-item>
              </el-descriptions>
            </el-col>

            <el-col :span="24" style="height: 36px; line-height: 36px">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport2"
                >导出</el-button
              >
            </el-col>
          </el-row>

          <el-table
            ref="historyTable"
            border
            v-loading="loading"
            :data="historyTableList"
          >
            <el-table-column label="日期" min-width="120" align="left" prop="operDate" />
            <el-table-column
              label="今日总销量"
              width="110"
              align="left"
              prop="todaySale"
            />
            <el-table-column label="日初库存" width="110" align="left" prop="initStock" />
            <el-table-column
              label="销售一部"
              width="120"
              align="left"
              prop="dept1YesterdaySale"
            >
              <template template slot-scope="scope">
                <div>初分: {{ scope.row.dept1InitStock }}</div>
                <div>末分: {{ scope.row.dept1SplitStock }}</div>
                <div>日销: {{ scope.row.dept1TodaySale }}</div>
              </template>
            </el-table-column>
            <el-table-column
              label="销售二部"
              width="120"
              align="left"
              prop="dept1YesterdaySale"
            >
              <template template slot-scope="scope">
                <div>初分: {{ scope.row.dept2InitStock }}</div>
                <div>末分: {{ scope.row.dept2SplitStock }}</div>
                <div>日销: {{ scope.row.dept2TodaySale }}</div>
              </template>
            </el-table-column>
            <el-table-column
              label="销售三部"
              width="120"
              align="left"
              prop="dept1YesterdaySale"
            >
              <template template slot-scope="scope">
                <div>初分: {{ scope.row.dept3InitStock }}</div>
                <div>末分: {{ scope.row.dept3SplitStock }}</div>
                <div>日销: {{ scope.row.dept3TodaySale }}</div>
              </template>
            </el-table-column>
            <el-table-column
              label="新媒体部"
              width="120"
              align="left"
              prop="dept1YesterdaySale"
            >
              <template template slot-scope="scope">
                <div>初分: {{ scope.row.dept4InitStock }}</div>
                <div>末分: {{ scope.row.dept4SplitStock }}</div>
                <div>日销: {{ scope.row.dept4TodaySale }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="90" align="left" prop="operLogs">
              <template template slot-scope="scope">
                <el-button size="mini" type="text" @click="historyLog(scope.row)"
                  >日志</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="historyQuery.total > 0"
            :total="historyQuery.total"
            :page.sync="historyQuery.pageNum"
            :limit.sync="historyQuery.pageSize"
            @pagination="getHistoryList(1)"
          />
        </el-tab-pane>
        <el-tab-pane label="按渠道分配" name="2">
          <el-row style="margin-bottom: 18px">
            <el-col :span="24">
              <el-descriptions direction="vertical">
                <el-descriptions-item label="商品名称">{{
                  splitRow.skuName
                }}</el-descriptions-item>
                <el-descriptions-item label="商品编码">{{
                  splitRow.skuCode
                }}</el-descriptions-item>
                <el-descriptions-item label="日期">
                  <el-date-picker
                    v-model="historyQuery2.dates"
                    style="width: 240px"
                    value-format="yyyy-MM-dd"
                    :picker-options="pickerOptions"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change="getHistoryList(2)"
                    :clearable="false"
                  ></el-date-picker>
                </el-descriptions-item>
              </el-descriptions>
            </el-col>

            <el-col :span="24" style="height: 36px; line-height: 36px">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport3"
                >导出</el-button
              >
            </el-col>
          </el-row>

          <el-table
            ref="historyTable2"
            border
            v-loading="loading"
            :data="historyTableList2"
          >
            <el-table-column label="日期" min-width="140" align="left" prop="operDate" />
            <el-table-column
              label="今日总销量"
              min-width="120"
              align="left"
              prop="todaySale"
            />
            <el-table-column
              label="日初库存"
              min-width="120"
              align="left"
              prop="initStock"
            />
            <el-table-column
              label="渠道"
              min-width="210"
              align="left"
              prop="dept1YesterdaySale"
            >
              <template template slot-scope="scope">
                <div
                  class="channel-box"
                  v-for="(item, index) in scope.row.channelDetailDTOList"
                  :key="index"
                >
                  <div>{{ item.channelName }}:</div>
                  <span>初分: {{ item.initStock }}</span>
                  <span>末分: {{ item.splitStock }}</span>
                  <span>日销: {{ item.todaySale }}</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="操作" min-width="120" align="left" prop="operLogs">
              <template template slot-scope="scope">
                <el-button size="mini" type="text" @click="historyLog(scope.row)"
                  >日志</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="historyQuery2.total > 0"
            :total="historyQuery2.total"
            :page.sync="historyQuery2.pageNum"
            :limit.sync="historyQuery2.pageSize"
            @pagination="getHistoryList(2)"
          />
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('open3')">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="历史销量查询"
      bottom="100px"
      :visible.sync="open5"
      width="800px"
      append-to-body
    >
      <el-row style="margin-bottom: 18px">
        <el-col :span="24">
          <el-descriptions direction="vertical">
            <el-descriptions-item label="商品名称">{{
              splitDetailRow.skuName
            }}</el-descriptions-item>
            <el-descriptions-item label="商品编码">{{
              splitDetailRow.skuCode
            }}</el-descriptions-item>
            <el-descriptions-item label="日期">
              <el-date-picker
                v-model="detailQuery.dates"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="getDetailList"
                :clearable="false"
              ></el-date-picker>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>

        <el-col :span="24" style="height: 36px; line-height: 36px">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport4"
            >导出</el-button
          >
        </el-col>
      </el-row>

      <el-table ref="detailTable" border v-loading="loading" :data="detailTableList">
        <el-table-column label="日期" align="left" prop="operDate" />
        <el-table-column label="销售数量" align="left" prop="saleNum" />
        <el-table-column label="最近三天销量" align="left" prop="day3SaleNum" />
        <el-table-column label="平均销售单价" align="left" prop="saleAverageAmount" />
        <el-table-column label="销售金额" align="left" prop="saleAmount" />
      </el-table>

      <pagination
        v-show="detailQuery.total > 0"
        :total="detailQuery.total"
        :page.sync="detailQuery.pageNum"
        :limit.sync="detailQuery.pageSize"
        @pagination="getDetailList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('open5')">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="分货日志"
      bottom="100px"
      :visible.sync="open4"
      width="1000px"
      append-to-body
    >
      <el-table
        ref="historyLogTable"
        border
        v-loading="loading"
        :data="historyLogTableList"
      >
        <el-table-column label="商品名称" min-width="140" align="left" prop="skuName" />
        <el-table-column label="商品编码" min-width="120" align="left" prop="skuNo" />
        <el-table-column
          label="部门/渠道"
          min-width="110"
          align="left"
          prop="deptChannel"
        />
        <el-table-column
          label="业务动作"
          min-width="110"
          align="left"
          prop="serviceName"
        />
        <el-table-column label="操作人" min-width="120" align="left" prop="operName" />
        <el-table-column label="操作时间" min-width="120" align="left" prop="operDate" />
        <el-table-column label="日志" min-width="180" align="left" prop="content" />
      </el-table>

      <pagination
        v-show="historyLogQuery.total > 0"
        :total="historyLogQuery.total"
        :page.sync="historyLogQuery.pageNum"
        :limit.sync="historyLogQuery.pageSize"
        @pagination="getSplitLog()"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('open4')">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getBrandNameList, getSpuList } from "@/api/goods/index";
import {
  getSplitList,
  splitChannelList,
  splitDeptList,
  saveSplitChannel,
  saveSplitDept,
  oldListChannel,
  oldListDept,
  splitLog,
  saleDetailList,
  getCategory,
} from "@/api/split/index";
import LoadMoreSelect from "@/components/LoadMoreSelect/index";
// import { getToken } from "@/utils/auth";

export default {
  name: "Index",
  dicts: ["sys_yes_no", "sys_commerce_platform"],
  components: {
    LoadMoreSelect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      spuList: [],
      historyTableList: [],
      historyTableList2: [],
      historyLogTableList: [],
      spiltRow: {},
      queryParamsSkuNos: "",
      historyQuery: {
        total: 0,
        pageSize: 10,
        pageNum: 1,
        dates: [],
      },
      historyQuery2: {
        total: 0,
        pageSize: 10,
        pageNum: 1,
        dates: [],
      },
      historyLogQuery: {
        total: 0,
        pageSize: 10,
        pageNum: 1,
        dates: [],
      },
      detailQuery: {
        total: 0,
        pageSize: 10,
        pageNum: 1,
        dates: [],
      },
      detailTableList: [],
      // 非单个禁用
      single: true,
      listRow: {},
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      goodsOpen: false,
      channelTableLoading: false,
      activeName: "1",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        brandNames: [],
        skuNameList: [],
        skuNames: "",
        skuNoList: [],
        skuNos: "",
        splitDate: "",
        categoryCode: "",
        spuNames: [],
      },
      bindForm: {
        bindSkuNo: "",
      },
      platform: ["ho", "jrc", "hy"],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        channelCode: [{ required: true, message: "网站不能为空", trigger: "blur" }],
        pageType: [{ required: true, message: "页面类型不能为空", trigger: "blur" }],
        goodName: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
        xsGoodCode: [{ required: true, message: "商品编码不能为空", trigger: "blur" }],
        goodUrl: [{ required: true, message: "商品链接不能为空", trigger: "blur" }],
      },
      expandRowKeys: [],
      treeKey: "",
      isExpand: false,
      skuOptions: [],
      spanArr2: [],
      skuPageNum: 1,
      dateRange: [],
      brandNameList: [],
      saveLoading: false,
      bindModal: {
        open: false,
        id: "",
      },
      chartRow: { goodName: "" },
      timer: null,
      lineChartData: {
        xData: [],
        sData: [
          {
            name: "鸿欧",
            data: [],
          },
          {
            name: "吉瑞城",
            data: [],
          },
          {
            name: "惠友",
            data: [],
          },
        ],
      },
      chartLading: true,
      loadDataStatus: true,
      tableHeight: "auto",
      channelList: [],
      channelTableList: [],
      deptTableList: [],
      spanArr: [],
      deptName: "",
      splitRow: {},
      pickerOptions: {
        shortcuts: [
          {
            text: "最近三天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近半个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      // 列信息
      columns: [
        { key: 1, label: `品牌`, visible: true },
        { key: 2, label: `采购经理`, visible: true },
        { key: 3, label: `近期日平均销量`, visible: true },
        { key: 4, label: `今日总销量`, visible: true },
        { key: 5, label: `当前可销库存`, visible: true },
        { key: 6, label: `日初库存`, visible: true },
        { key: 7, label: `销售一部`, visible: true },
        { key: 8, label: `销售二部`, visible: true },
        { key: 9, label: `销售三部`, visible: true },
        { key: 10, label: `新媒体部门`, visible: true },
      ],
      today: "",
      expandText: "全部展开",
      tableHeight: "",
      open3: false,
      open4: false,
      open5: false,
      splitDetailRow: {},
      categoryList: [],
    };
  },
  watch: {
    showSearch(n, _) {
      this.$nextTick(() => {
        const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 210;
        this.tableHeight = height + "px";
      });
    },
  },
  computed: {
    roles() {
      return this.$store.getters.roles;
    },
  },
  created() {
    if (localStorage.getItem("automaticDistribution-query")) {
      this.queryParams = JSON.parse(localStorage.getItem("automaticDistribution-query"));
      this.queryParamsSkuNos = this.queryParams.skuNos;
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
    }
    this.treeKey = new Date();
    this.channelTableKey = new Date();
    this.deptTableKey = new Date();
    const date = new Date();
    const year = date.getFullYear();
    const month =
      date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    const day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    this.today = year + "-" + month + "-" + day;
    this.queryParams.splitDate = year + "-" + month + "-" + day;
    // this.getChannelList();

    this.getList();
    this.getBrandNameList();
  },
  mounted() {},
  methods: {
    handleClick() {},
    expandChange() {
      this.treeKey = new Date();
      this.isExpand = !this.isExpand;
      this.expandText == "全部展开"
        ? (this.expandText = "全部收起")
        : (this.expandText = "全部展开");

      // this.$nextTick(() => {
      //     const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 210;
      //     if (height < this.$refs.proTable.$el.offsetHeight) {
      //       this.$refs.proTable.height = height + "px";
      //       this.$refs.proTable.doLayout();
      //     } else if (height == this.$refs.proTable.$el.offsetHeight) {
      //       this.$refs.proTable.height = height + "px";
      //       this.$refs.proTable.doLayout();
      //     }
      //   });
    },
    getBrandNameList() {
      getBrandNameList().then((res) => {
        this.brandNameList = res.data;
        if (localStorage.getItem("automaticDistribution-query")) {
          this.brandChange(this.queryParams.brandNames);
        }
      });
      getCategory().then((res) => {
        this.categoryList = res.data;
      });
    },
    rowStyle({ row, rowIndex }) {
      if (row.skuName == "合计" || row.skuName == "总计") {
        return { background: "#f5f7fa" };
      }
    },
    brandChange(value) {
      if (value.length != 0) {
        const data = [];
        this.brandNameList.forEach((item) => {
          value.forEach((i) => {
            if (item.brandName == i) {
              data.push(item.brandCode);
            }
          });
        });

        getSpuList(data).then((res) => {
          this.spuList = res.data;
        });
      } else {
        this.spuList = [];
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    /** 查询岗位列表 */
    getList() {
      localStorage.setItem(
        "automaticDistribution-query",
        JSON.stringify(this.queryParams)
      );
      this.loading = true;
      getSplitList(this.queryParams).then((response) => {
        this.postList = response.data.channelSpuListResDTOS;
        this.total = response.data.total;
        this.loading = false;

        this.$nextTick(() => {
          const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 210;
          this.tableHeight = height + "px";
          // if (height < this.$refs.proTable.$el.offsetHeight) {
          //   this.$refs.proTable.height = height + "px";
          //   this.$refs.proTable.doLayout();
          // } else if (height == this.$refs.proTable.$el.offsetHeight) {
          //   this.$refs.proTable.height = height + "px";
          //   this.$refs.proTable.doLayout();
          // }
        });
      });
    },
    handleEdit(row, type) {
      this.bindForm = JSON.parse(JSON.stringify(row));
      this.goodsOpen = true;
    },
    // 取消按钮
    cancel(type) {
      this[type] = false;
    },

    historySplit(row) {
      this.open3 = true;
      this.splitRow = row;
      this.getHistoryList(1);
      this.getHistoryList(2);
    },
    getHistoryList(type) {
      let startDate = "",
        endDate = "";

      if (type == 1) {
        if (this.historyQuery.dates && this.historyQuery.dates.length != 0) {
          startDate = this.historyQuery.dates[0];
          endDate = this.historyQuery.dates[1];
        } else {
          const date = new Date();
          const year = date.getFullYear();
          const month =
            date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
          const day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
          endDate = year + "-" + month + "-" + day;

          date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
          const year2 = date.getFullYear();
          const month2 =
            date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
          const day2 = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
          startDate = year2 + "-" + month2 + "-" + day2;

          this.historyQuery.dates = [startDate, endDate];
        }
      } else {
        if (this.historyQuery2.dates && this.historyQuery2.dates.length != 0) {
          startDate = this.historyQuery2.dates[0];
          endDate = this.historyQuery2.dates[1];
        } else {
          const date = new Date();
          const year = date.getFullYear();
          const month =
            date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
          const day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
          endDate = year + "-" + month + "-" + day;

          date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
          const year2 = date.getFullYear();
          const month2 =
            date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
          const day2 = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
          startDate = year2 + "-" + month2 + "-" + day2;

          this.historyQuery2.dates = [startDate, endDate];
        }
      }

      if (type == 1) {
        oldListDept({
          endDate: endDate,
          pageNum: this.historyQuery.pageNum,
          pageSize: this.historyQuery.pageSize,
          skuName: this.splitRow.skuName,
          startDate: startDate,
        }).then((res) => {
          this.historyTableList = res.data.splitOldDeptResDTOList;
          this.historyQuery.total = res.data.total;
        });
      } else {
        oldListChannel({
          endDate: endDate,
          pageNum: this.historyQuery2.pageNum,
          pageSize: this.historyQuery2.pageSize,
          skuName: this.splitRow.skuName,
          startDate: startDate,
        }).then((res) => {
          this.historyTableList2 = res.data.splitOldChannelResDTOS;
          this.historyQuery2.total = res.data.total;
        });
      }
    },
    historyLog(row, splitRow) {
      this.open4 = true;
      this.historyLogRow = row;
      this.getSplitLog();
    },
    getSplitLog() {
      splitLog({
        operDate: this.historyLogRow.operDate ? this.historyLogRow.operDate : "",
        pageNum: this.historyLogQuery.pageNum,
        pageSize: this.historyLogQuery.pageSize,
        skuName: this.historyLogRow.skuName
          ? this.historyLogRow.skuName
          : this.splitRow
          ? this.splitRow.skuName
          : "",
      }).then((res) => {
        this.historyLogTableList = res.data.splitLogResDTOS;
        this.historyLogQuery.total = res.data.total;
      });
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 1) {
        if (this.spanArr[rowIndex]) {
          return {
            rowspan: this.spanArr[rowIndex],
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }
    },
    objectSpanMethod2({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 1) {
        if (this.spanArr2[rowIndex]) {
          return {
            rowspan: this.spanArr2[rowIndex],
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }
    },
    filterTableData() {
      this.spanArr = [];
      let contactDot = 0;
      this.channelTableList.forEach((item, index) => {
        if (index == 0) {
          this.spanArr.push(1);
        } else {
          if (item.skuName === this.channelTableList[index - 1].skuName) {
            this.spanArr[contactDot] += 1;
            this.spanArr.push(0);
          } else {
            contactDot = index;
            this.spanArr.push(1);
          }
        }
      });
    },
    filterTableData2() {
      this.spanArr2 = [];
      let contactDot = 0;
      this.deptTableList.forEach((item, index) => {
        if (index == 0) {
          this.spanArr2.push(1);
        } else {
          if (item.skuName === this.deptTableList[index - 1].skuName) {
            this.spanArr2[contactDot] += 1;
            this.spanArr2.push(0);
          } else {
            contactDot = index;
            this.spanArr2.push(1);
          }
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.platform = [];
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        brandNames: [],
        skuNameList: [],
        skuNames: "",
        skuNoList: [],
        skuNos: "",
        splitDate: "",
        categoryCode: "",
        spuNames: [],
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.postId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    splitDetail(row) {
      const date = new Date();
      const year = date.getFullYear();
      const month =
        date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
      const day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      const endDate = year + "-" + month + "-" + day;
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 3);
      const year2 = date.getFullYear();
      const month2 =
        date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
      const day2 = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      const startDate = year2 + "-" + month2 + "-" + day2;
      this.detailQuery.dates = [startDate, endDate];

      this.open5 = true;
      this.splitDetailRow = row;
      this.getDetailList();
    },
    getDetailList() {
      const data = {
        endDate: this.detailQuery.dates[1],
        pageNum: this.detailQuery.pageNum,
        pageSize: this.detailQuery.pageSize,
        skuName: this.splitDetailRow.skuName,
        skuNo: this.splitDetailRow.skuCode,
        startDate: this.detailQuery.dates[0],
      };
      saleDetailList(data).then((res) => {
        this.detailTableList = res.data.saleDetailResDTOS;
        this.detailQuery.total = res.data.total;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const data = { ...this.queryParams };
      delete data.pageNum;
      delete data.pageSize;
      this.newDownload(
        "auto/split/export",
        data,
        `自动分货_${new Date().getTime()}.xlsx`
      );
    },
    handleExport2() {
      const data = {
        endDate: this.historyQuery.dates[1],
        pageNum: this.historyQuery.pageNum,
        pageSize: this.historyQuery.pageSize,
        skuName: this.splitRow.skuName,
        startDate: this.historyQuery.dates[0],
      };

      this.newDownload(
        "auto/split/old/dept/export",
        data,
        `历史分货部门_${new Date().getTime()}.xlsx`
      );
    },
    handleExport3() {
      const data = {
        endDate: this.historyQuery2.dates[1],
        pageNum: this.historyQuery2.pageNum,
        pageSize: this.historyQuery2.pageSize,
        skuName: this.splitRow.skuName,
        startDate: this.historyQuery2.dates[0],
      };

      this.newDownload(
        "auto/split/old/channel/export",
        data,
        `历史分货渠道_${new Date().getTime()}.xlsx`
      );
    },
    handleExport4() {
      const data = {
        endDate: this.detailQuery.dates[1],
        pageNum: this.detailQuery.pageNum,
        pageSize: this.detailQuery.pageSize,
        skuName: this.splitDetailRow.skuName,
        skuNo: this.splitDetailRow.skuCode,
        startDate: this.detailQuery.dates[0],
      };

      this.newDownload(
        "auto/split/sale/detail/export",
        data,
        `历史销量查询_${new Date().getTime()}.xlsx`
      );
    },
    stockNumChange(row) {
      row.stockNum = row.stockNum.replace(/[^\d]/g, "");
      let stockNum = 0;
      this.channelTableList.forEach((item) => {
        if (item.skuName != "总计" && item.skuName != "合计") {
          stockNum += parseInt(item.stockNum) || 0;
        }
      });
      this.channelTableList[this.channelTableList.length - 1].stockNum = stockNum;
    },
    stockNumChange2(row) {
      row.stockNum = row.stockNum.replace(/[^\d]/g, "");
      let stockNum = 0,
        stockNum2 = 0;
      this.deptTableList.forEach((item) => {
        if (item.skuName != "总计" && item.skuName != "合计") {
          stockNum += parseInt(item.stockNum) || 0;
        }

        if (item.skuNo == row.skuNo && item.skuName != "合计") {
          stockNum2 += parseInt(item.stockNum) || 0;
        }
        if (item.skuNo == row.skuNo && item.skuName == "合计") {
          item.stockNum = stockNum2;
        }
      });
      this.deptTableList[this.deptTableList.length - 1].stockNum = stockNum;
    },
    saveChannel() {
      const data = [];
      let status = true;
      this.channelTableList.forEach((item) => {
        if (
          item.skuName != "总计" &&
          item.skuName != "合计" &&
          item.stockNum != item.splitStock
        ) {
          data.push({
            channelName: item.channelName,
            channelCode: item.channelCode,
            deptName: item.deptName,
            oldStockNum: item.splitStock,
            skuName: item.skuName,
            skuNo: item.skuNo,
            stockNum: item.stockNum,
          });
          if (item.stockNum === "" || item.stockNum < 0) {
            status = false;
          }
        }
      });
      if (!status) {
        this.$message.warning("请填写调整后库存");
        return false;
      }
      if (
        this.channelTableList[this.channelTableList.length - 1].stockNum !=
        this.channelTableList[this.channelTableList.length - 1].deptStock
      ) {
        this.$message.warning("调整后库存总计不等于部门分配库存");
        return false;
      }

      const sortData = this.sortClass(this.channelTableList);

      let sortSta = false;
      for (let i = 0; i < sortData.length; i++) {
        let stockNum = 0;
        for (let x = 0; x < sortData[i].length; x++) {
          if (sortData[i][x].skuName != "合计") {
            stockNum += parseInt(sortData[i][x].stockNum);
          }
        }
        if (stockNum != sortData[i][0].deptStock) {
          this.$message.warning(
            "商品" + sortData[i][0].skuName + "调整后库存总计不等于部门库存"
          );
          sortSta = true;
          break;
        }
      }
      if (sortSta) {
        return false;
      }

      if (data.length == 0) {
        this.$message.warning("库存无变化,请确认");
        return false;
      }
      this.saveLoading = true;
      saveSplitChannel(data).then((res) => {
        this.saveLoading = false;
        if (res.status == "200") {
          this.$message.success("分配成功");
          this.open = false;
          this.getList();
        }
      });
    },
    sortClass(sortData) {
      const groupBy = (array, f) => {
        let groups = {};
        array.forEach((o) => {
          let group = JSON.stringify(f(o));
          groups[group] = groups[group] || [];
          groups[group].push(o);
        });
        return Object.keys(groups).map((group) => {
          return groups[group];
        });
      };
      const sorted = groupBy(sortData, (item) => {
        return item.skuName; // 返回需要分组的对象
      });
      return sorted;
    },
    saveDept() {
      const data = [];
      let status = true;

      this.deptTableList.forEach((item) => {
        if (
          item.skuName != "总计" &&
          item.skuName != "合计" &&
          item.stockNum != item.dept1SplitStock
        ) {
          data.push({
            deptName: item.name,
            oldStockNum: item.dept1SplitStock,
            skuName: item.skuName,
            skuNo: item.skuNo,
            stockNum: item.stockNum,
          });
          if (item.stockNum === "" || item.stockNum < 0) {
            status = false;
          }
        }
      });
      if (!status) {
        this.$message.warning("请填写调整后库存");
        return false;
      }
      if (
        this.deptTableList[this.deptTableList.length - 1].stockNum >
        this.deptTableList[this.deptTableList.length - 1].initStock
      ) {
        this.$message.warning("调整后库存总计不能大于部门分配库存");
        return false;
      }

      const sortData = this.sortClass(this.deptTableList);
      let sortSta = false;
      for (let i = 0; i < sortData.length; i++) {
        let stockNum = 0;
        for (let x = 0; x < sortData[i].length; x++) {
          if (sortData[i][x].skuName != "合计") {
            stockNum += parseInt(sortData[i][x].stockNum);
          }
        }
        if (stockNum > sortData[i][0].initStock) {
          this.$message.warning(
            "商品" + sortData[i][0].skuName + "调整后库存总计大于部门库存"
          );
          sortSta = true;
          break;
        }
      }
      if (sortSta) {
        return false;
      }

      if (data.length == 0) {
        this.$message.warning("库存无变化,请确认");
        return false;
      }
      this.saveLoading = true;
      saveSplitDept(data).then((res) => {
        this.saveLoading = false;
        if (res.status == "200") {
          this.$message.success("提交审核成功");
          this.open2 = false;
          this.getList();
        }
      });
    },
    channelDia(row, type) {
      const data = {};
      data.deptName = type;
      this.deptName = type;
      this.listRow = row;
      if (row.skuName) {
        data.skuName = row.skuName;
      } else {
        data.spuName = row.spuName;
      }
      this.open = true;
      this.channelTableLoading = true;
      splitChannelList(data).then((res) => {
        this.channelTableLoading = false;
        const channelTableList = [];
        this.channelTableList = [];
        let deptStock = 0,
          splitStock = 0,
          stockNum = 0,
          day3Sale = 0,
          todaySale = 0,
          yesterdaySale = 0;
        res.data.channelSplitListResDTOS.forEach((element) => {
          element.channels.forEach((item) => {
            item.skuName = element.skuName;
            item.skuNo = element.skuNo;
            item.deptName = element.deptName;
            item.deptStock = element.deptStock;
            item.stockNum = item.updateStock ? item.updateStock : item.splitStock;
            item.totalUpdateStock = element.totalUpdateStock;
            channelTableList.push(item);

            splitStock += item.splitStock;
            day3Sale += item.day3Sale;
            todaySale += item.todaySale;
            yesterdaySale += item.yesterdaySale;
            stockNum += item.stockNum;
          });
          deptStock += element.deptStock;
        });

        if (channelTableList.length != 0) {
          channelTableList.push({
            skuName: "总计",
            deptStock,
            splitStock,
            day3Sale,
            todaySale,
            yesterdaySale,
            stockNum,
          });
        }

        this.channelTableList = channelTableList;
        this.filterTableData();
      });
    },
    deptDia(row) {
      const data = {};
      data.deptName = "";
      this.deptName = "";
      if (row.skuName) {
        data.skuName = row.skuName;
      } else {
        data.spuName = row.spuName;
      }

      this.listRow = row;
      this.open2 = true;
      this.channelTableLoading = true;
      splitDeptList(data).then((res) => {
        this.channelTableLoading = false;
        const data = [];
        let initStock = 0,
          stockNum = 0,
          dept1Day3Sale = 0,
          dept1YesterdaySale = 0,
          dept1TodaySale = 0,
          dept1InitStock = 0;
        res.data.deptSplitListResDTOS.forEach((element) => {
          let stockNum2 = 0;
          let obj = {};
          obj.name = "销售一部";
          obj.skuName = element.skuName;
          obj.skuNo = element.skuNo;
          obj.initStock = element.initStock;
          obj.dept1Day3Sale = element.dept1Day3Sale;
          dept1Day3Sale += element.dept1Day3Sale;
          obj.dept1YesterdaySale = element.dept1YesterdaySale;
          dept1YesterdaySale += element.dept1YesterdaySale;
          obj.dept1TodaySale = element.dept1TodaySale;
          dept1TodaySale += element.dept1TodaySale;
          obj.dept1InitStock = element.dept1InitStock;
          obj.dept1SplitStock = element.dept1SplitStock;
          dept1InitStock += element.dept1InitStock;
          obj.operLogs = element.dept1OperLogs;
          obj.stockNum =
            element.totalUpdateStock != null
              ? element.dept1UpdateStock
              : element.dept1SplitStock;
          stockNum2 += obj.stockNum;
          obj.totalUpdateStock = element.totalUpdateStock;

          stockNum += obj.stockNum;
          data.push(obj);

          obj = {};
          obj.name = "销售二部";
          obj.skuName = element.skuName;
          obj.skuNo = element.skuNo;
          obj.initStock = element.initStock;
          obj.dept1Day3Sale = element.dept2Day3Sale;
          dept1Day3Sale += element.dept2Day3Sale;
          obj.dept1YesterdaySale = element.dept2YesterdaySale;
          dept1YesterdaySale += element.dept2YesterdaySale;
          obj.dept1TodaySale = element.dept2TodaySale;
          dept1TodaySale += element.dept2TodaySale;
          obj.dept1InitStock = element.dept2InitStock;
          obj.dept1SplitStock = element.dept2SplitStock;
          dept1InitStock += element.dept2InitStock;
          obj.operLogs = element.dept2OperLogs;
          obj.stockNum =
            element.totalUpdateStock != null
              ? element.dept2UpdateStock
              : element.dept2SplitStock;
          obj.totalUpdateStock = element.totalUpdateStock;
          stockNum += obj.stockNum;
          stockNum2 += obj.stockNum;
          data.push(obj);

          obj = {};
          obj.name = "销售三部";
          obj.skuName = element.skuName;
          obj.skuNo = element.skuNo;
          obj.initStock = element.initStock;
          obj.dept1Day3Sale = element.dept3Day3Sale;
          dept1Day3Sale += element.dept3Day3Sale;
          obj.dept1YesterdaySale = element.dept3YesterdaySale;
          dept1YesterdaySale += element.dept3YesterdaySale;
          obj.dept1TodaySale = element.dept3TodaySale;
          dept1TodaySale += element.dept3TodaySale;
          obj.dept1InitStock = element.dept3InitStock;
          obj.dept1SplitStock = element.dept3SplitStock;
          dept1InitStock += element.dept3InitStock;
          obj.operLogs = element.dept3OperLogs;
          obj.stockNum =
            element.totalUpdateStock != null
              ? element.dept3UpdateStock
              : element.dept3SplitStock;
          obj.totalUpdateStock = element.totalUpdateStock;
          stockNum += obj.stockNum;
          stockNum2 += obj.stockNum;
          data.push(obj);

          obj = {};
          obj.name = "新媒体部";
          obj.skuName = element.skuName;
          obj.skuNo = element.skuNo;
          obj.initStock = element.initStock;
          obj.dept1Day3Sale = element.dept4Day3Sale;
          dept1Day3Sale += element.dept4Day3Sale;
          obj.dept1YesterdaySale = element.dept4YesterdaySale;
          dept1YesterdaySale += element.dept4YesterdaySale;
          obj.dept1TodaySale = element.dept4TodaySale;
          dept1TodaySale += element.dept4TodaySale;
          obj.dept1InitStock = element.dept4InitStock;
          dept1InitStock += element.dept4InitStock;
          obj.dept1SplitStock = element.dept4SplitStock;
          obj.operLogs = element.dept4OperLogs;
          obj.stockNum =
            element.totalUpdateStock != null
              ? element.dept4UpdateStock
              : element.dept4SplitStock;
          stockNum2 += obj.stockNum;
          obj.totalUpdateStock = element.totalUpdateStock;
          stockNum += obj.stockNum;
          data.push(obj);

          if (
            res.data.deptSplitListResDTOS &&
            res.data.deptSplitListResDTOS.length != 1
          ) {
            obj = {};
            obj.name = "";
            obj.skuName = "合计";
            obj.skuNo = element.skuNo;
            obj.initStock = element.initStock;
            obj.dept1Day3Sale =
              element.dept4Day3Sale +
              element.dept3Day3Sale +
              element.dept2Day3Sale +
              element.dept1Day3Sale;
            obj.dept1YesterdaySale =
              element.dept4YesterdaySale +
              element.dept3YesterdaySale +
              element.dept2YesterdaySale +
              element.dept1YesterdaySale;
            obj.dept1TodaySale =
              element.dept4TodaySale +
              element.dept3TodaySale +
              element.dept2TodaySale +
              element.dept1TodaySale;
            obj.dept1InitStock =
              element.dept4InitStock +
              element.dept3InitStock +
              element.dept2InitStock +
              element.dept1InitStock;
            // obj.operLogs = element.operLogs;
            obj.stockNum = stockNum2;
            data.push(obj);
          }

          initStock += element.initStock;
        });

        if (data.length != 0) {
          data.push({
            skuName: "总计",
            initStock,
            stockNum,
            dept1Day3Sale,
            dept1YesterdaySale,
            dept1TodaySale,
            dept1InitStock,
          });
        }

        this.deptTableList = data;
        this.filterTableData2();
      });
    },
  },
};
</script>
<style scoped lang="scss">
.charts-box {
  height: 350px;
  margin-top: 30px;
}
.erpPrice > span {
  color: #409eff;
}
.iconEdit {
  cursor: pointer;
}
.app-container {
  padding-bottom: 60px;
}

.table-dp {
  display: flex;
  align-items: center;
  color: #999;
  span {
    color: #333;
  }
  .colorRed {
    color: red;
  }
}
.rate-span {
  margin-left: 5px;
  color: #999;
}
.dept-box {
  height: 40px;
  line-height: 40px;
  border-bottom: solid 1px #dfe6ec;
}

.el-tab-pane {
  .pagination-container {
    margin-bottom: 20px;
  }
}
.channel-box {
  margin: 5px 0;
  span {
    margin-right: 5px;
  }
}
.change-input {
  color: red;
  ::v-deep .el-input__inner {
    color: red;
  }
}
.up-png {
  width: 12px;
}
.colorG {
  color: #999;
}
</style>
