<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="生效日期:" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          :picker-options="pickerOptions"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          style="width: 225px"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="品牌:" prop="brandCodes">
        <el-select
          v-model="queryParams.brandCodes"
          filterable
          placeholder="请选择品牌"
          clearable
          multiple
        >
          <el-option
            v-for="(dict, index) in brandNameList"
            :key="index"
            :label="dict.brandName"
            :value="dict.brandCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="品类:" prop="cateCodes">
        <el-select
          v-model="queryParams.cateCodes"
          filterable
          placeholder="请选择品类"
          clearable
          multiple
        >
          <el-option
            v-for="(dict, index) in cateLists"
            :key="index"
            :label="dict.cateName"
            :value="dict.cateCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="类型:" prop="configType">
        <el-select
          v-model="queryParams.configType"
          filterable
          placeholder="请选择类型"
          clearable
        >
          <el-option label="资源品毛利分摊" :value="0" />
          <el-option label="滞销品亏损指定SKU分摊" :value="1" />
          <el-option label="滞销品亏损全局分摊" :value="2" />
        </el-select>
      </el-form-item>

      <el-form-item label="状态:" prop="status">
        <el-select
          v-model="queryParams.status"
          filterable
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="(item, index) in statusList"
            :key="index"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="商品编码:" prop="skuNos">
        <el-input
          v-model="queryParams.skuNos"
          placeholder="多个商品编码使用逗号隔开"
          clearable
        />
      </el-form-item>
      <el-form-item label="商品名称:" prop="skuNo">
        <LoadMoreSelect
          :skuNo="queryParams.skuNo"
          @queryParams="(val) => (queryParams.skuNo = val)"
        />
      </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="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          >新增</el-button
        >
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      ref="proTable"
      border
      v-loading="loading"
      :data="postList"
      :height="tableHeight"
      :key="randomKey"
    >
    <!-- @cell-click="cellClick"
      :cell-style="cellStyle" -->
      <!-- <el-table-column type="selection" width="55" align="left" /> -->
      <el-table-column label="品牌" min-width="120" align="left" prop="brandName" />
      <el-table-column label="品类" min-width="70" align="left" prop="cateName" />
      <el-table-column label="类型" min-width="140" align="left" prop="configType" />
      <el-table-column label="生效日期" min-width="180" align="left" prop="startTime">
        <template slot-scope="scope">
          {{scope.row.startTime}} ~ {{ scope.row.endTime }}
        </template>
      </el-table-column>
      <el-table-column label="状态" min-width="80" align="left" prop="status" />
      <el-table-column label="说明" min-width="120" align="left" prop="remark" />
      <el-table-column label="指定商品范围" min-width="160" align="left" prop="skus" />
      <el-table-column
        label="分摊规则配置"
        min-width="220"
        align="left"
        prop="configDetail"
      >
        <template slot-scope="scope">
          <div v-html="scope.row.configDetail"></div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" min-width="160" align="left" prop="createdTime">
      </el-table-column>
      <el-table-column label="创建人" min-width="120" align="left" prop="createdBy">
      </el-table-column>
      <el-table-column label="操作" width="180" align="left" fixed="right">
        <template slot-scope="scope">
          <div v-if="!scope.row.skuName">
            <el-button
              size="mini"
              type="text"
              v-if="scope.row.status == '待审批' || scope.row.status == '变更待审批'"
              @click="recallItem(scope.row)"
              :disabled="userName!=scope.row.createdBy"
              >撤回</el-button
            >
            <el-button
              size="mini"
              v-if="
                scope.row.status == '待提交' ||
                scope.row.status == '审批打回' ||
                scope.row.status == '变更审批打回'
              "
              type="text"
              @click="handleEdit(scope.row, 1)"
              :disabled="userName!=scope.row.createdBy"
              >编辑</el-button
            >
            <el-button
              size="mini"
              v-if="scope.row.status == '启用'"
              type="text"
              @click="handleEdit(scope.row, 3)"
              :disabled="userName!=scope.row.createdBy"
              >变更</el-button
            >
            <!-- :disabled="userName!=scope.row.createdBy" -->
            <el-button size="mini" type="text" @click="handleEdit(scope.row, 2)"
              >查看详情</el-button
            >
          </div>
        </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="title"
      :visible.sync="open2"
      top="50px"
      width="900px"
      append-to-body
    >
      <el-tabs type="card" v-model="activeName">
        <el-tab-pane label="销售分摊" name="1">
          <el-row>
            <h3 style="margin-top: 0"><span></span>销售分摊配置</h3>
            <el-form
              :model="addForm"
              ref="addForm"
              size="small"
              :inline="true"
              :disabled="disabledForm"
              label-width="170px"
            >
              <el-row>
                <el-col :span="24">
                  <el-form-item
                    label="分摊类型:"
                    :rules="[
                      {
                        required: true,
                        message: '请选择分摊类型',
                        trigger: 'change',
                      },
                    ]"
                    prop="configType"
                  >
                    <el-radio-group v-model="addForm.configType" @change="cfChange">
                      <el-radio :label="0">资源品毛利分摊</el-radio>
                      <el-radio :label="1">滞销品亏损指定SKU分摊</el-radio>
                      <el-radio :label="2">滞销品亏损全局分摊</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="品牌:"
                    :rules="[
                      {
                        required: true,
                        message: '请选择品牌',
                        trigger: 'change',
                      },
                    ]"
                    prop="brandCode"
                  >
                    <el-select
                      v-model="addForm.brandCode"
                      filterable
                      placeholder="请选择品牌"
                      clearable
                    >
                      <el-option
                        v-for="(dict, index) in brandNameList"
                        :key="index"
                        :label="dict.brandName"
                        :value="dict.brandCode"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="品类:"
                    :rules="[
                      {
                        required: true,
                        message: '请选择品类',
                        trigger: 'change',
                      },
                    ]"
                    prop="cateDTOS"
                  >
                    <el-select
                      v-model="addForm.cateDTOS"
                      filterable
                      placeholder="请选择品类"
                      clearable
                      multiple
                    >
                      <el-option
                        v-for="(dict, index) in cateLists"
                        :key="index"
                        :label="dict.cateName"
                        :value="dict.cateCode"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="生效日期:"
                    :rules="[
                      {
                        required: true,
                        message: '请选择生效日期',
                        trigger: 'change',
                      },
                    ]"
                    prop="dateRange"
                  >
                    <el-date-picker
                      v-model="addForm.dateRange"
                      :picker-options="pickerOptions"
                      type="daterange"
                      range-separator="-"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="yyyy-MM-dd"
                      style="width: 225px"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item
                    label="说明:"
                    prop="remark"
                  >
                  <el-input
                    v-model="addForm.remark"
                    placeholder="请输入活动备注"
                    clearable
                    type="textarea"
                    :rows="3"
                    style="width: 380px"
                  />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-form-item label="分摊配置:" prop="rebateTypeCode">
                  <div v-show="addForm.configType == 1">输入商品编码：</div>
                  <el-input
                    v-model="addForm.skus"
                    type="textarea"
                    :rows="3"
                    placeholder="多个商品编码使用逗号隔开"
                    clearable
                    v-show="addForm.configType == 1"
                    style="width: 500px; margin-bottom: 16px"
                  />
                  <el-table
                    ref="goodsTable"
                    border
                    :data="goodsTableList"
                    style="width: 500px"
                    v-show="addForm.configType != 1"
                  >
                    <el-table-column
                      label="部门"
                      align="left"
                      prop="dept"
                      min-width="140"
                    >
                    </el-table-column>
                    <el-table-column
                      label="毛利分摊比例"
                      min-width="180"
                      align="left"
                      prop="rate"
                      v-if="addForm.configType == 0"
                    >
                      <template slot-scope="scope">
                        <div v-if="scope.row.dept != ''">
                          <el-input-number
                            v-model="scope.row.rate"
                            type="number"
                            :min="0"
                            :max="100"
                            placeholder="毛利分摊比例"
                            clearable
                            style="width: 170px"
                            @input="(value) => rateChange2(value, scope.row)"
                          />%
                        </div>
                        <div v-else>
                          合计：
                          <span :class="{ 'color-s': scope.row.rate != 100 }">{{
                            scope.row.rate
                          }}</span>
                          %
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="亏损分摊比例"
                      min-width="180"
                      align="left"
                      prop="rate"
                      v-if="addForm.configType == 2"
                    >
                      <template slot-scope="scope">
                        <div v-if="scope.row.dept != ''">
                          <el-input-number
                            v-model="scope.row.rate"
                            type="number"
                            :min="0"
                            :max="100"
                            placeholder="亏损分摊比例"
                            clearable
                            style="width: 170px"
                            @input="(value) => rateChange2(value, scope.row)"
                          />%
                        </div>
                        <div v-else>
                          合计：
                          <span :class="{ 'color-s': scope.row.rate != 100 }">{{
                            scope.row.rate
                          }}</span>
                          %
                        </div>
                      </template>
                    </el-table-column>
                  </el-table>

                  <el-table
                    border
                    :data="wareHouseTableList"
                    :span-method="objectSpanMethod"
                    style="width: 600px"
                    v-show="addForm.configType == 1"
                  >
                    <el-table-column
                      label="仓库"
                      align="left"
                      prop="warehouse"
                      min-width="140"
                    />
                    <el-table-column
                      label="归属部门"
                      min-width="180"
                      align="left"
                      prop="dept"
                    />
                    <el-table-column
                      label="亏损分摊比例"
                      min-width="180"
                      align="left"
                      prop="rate"
                    >
                      <template slot-scope="scope">
                        <div v-if="scope.row.dept != ''">
                          <el-input-number
                            v-model="scope.row.rate"
                            type="number"
                            :min="0"
                            :max="100"
                            placeholder="亏损分摊比例"
                            clearable
                            style="width: 170px"
                            @input="(value) => rateChange(value, scope.row)"
                          />%
                        </div>
                        <div v-else>
                          合计：
                          <span :class="{ 'color-s': scope.row.rate != 100 }">{{
                            scope.row.rate
                          }}</span>
                          %
                        </div>
                      </template>
                    </el-table-column>
                  </el-table>


                </el-form-item>
              </el-row>
            </el-form>

            <h3><span></span>上传附件</h3>
            <div class="color-r">上传分摊配置依据文件（上限最多5个文件，最大20M）</div>
            <el-upload
              class="upload-demo"
              :action="fileAction"
              :on-preview="handlePreview"
              :before-remove="beforeRemove"
              :on-remove="handleRemove"
              :on-success="handleFileSuccess2"
              :headers="upload.headers"
              :before-upload="beforeAvatarUpload"
              :disabled="disabledForm"
              multiple
              :limit="5"
              :on-exceed="handleExceed"
              :file-list="fileList"
            >
              <el-button size="small" type="primary" :disabled="disabledForm"
                >点击上传</el-button
              >
            </el-upload>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="日志" name="2">
          <el-table ref="logTable" border :data="historyLogTableList">
            <el-table-column
              label="操作步骤"
              min-width="140"
              align="left"
              prop="logType"
            />
            <el-table-column label="操作描述" min-width="140" align="left" prop="logMsg">
              <template slot-scope="scope">
                <span v-html="scope.row.logMsg"></span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作人"
              min-width="100"
              align="left"
              prop="createBy"
            />
            <el-table-column
              label="操作时间"
              min-width="90"
              align="left"
              prop="createTime"
            />
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="saveLoading"
          type="primary"
          @click="saveDept"
          v-show="!disabledForm"
          >提交</el-button
        >
        <el-button @click="open2 = false">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="商品导入" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getChannelList } from "@/api/bizMonitor/index";
import { getBrandNameList, getList } from "@/api/goods/index";
import {
  saleConfigList,
  saleConfigAdd,
  saleConfigUpdate,
  cateList,
  saleConfigDetail,
  saleConfigLogs,
  saleConfigAuditCancel,
  saleConfigAuditSubmit,
  gyDeptList,
} from "@/api/saleConfig";
import LoadMoreSelect from "@/components/LoadMoreSelect/index";
import { getToken } from "@/utils/auth";

export default {
  name: "ActivitieIndex",
  dicts: ["warehouse_list",],
  components: {
    LoadMoreSelect,
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      spuList: [],
      historyTableList: [],
      historyLogTableList: [],
      fileAction: process.env.VUE_APP_BASE_API_NEW + "/activitie/upload/file",
      goodsTableList: [],
      goodsVisible: false,
      headerValue: "",
      headerValue2: "",
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API_NEW + "/sale/config/upload/file",
      },
      stageInfos: [
        {
          price: 0,
          ratePrice: 0,
          stage: 1,
        },
        {
          price: 0,
          ratePrice: 0,
          stage: 1,
        },
      ],
      detailQuery: {
        total: 0,
        pageSize: 10,
        pageNum: 1,
        dates: [],
      },
      detailTableList: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      goodsOpen: false,
      channelTableLoading: false,
      activeName: "1",
      statusList: [
        { code: 0, name: "待提交" },
        { code: 1, name: "待审批" },
        { code: 2, name: "审批打回" },
        { code: 3, name: "启用" },
        { code: 4, name: "变更待提交" },
        { code: 5, name: "变更待审批" },
        { code: 6, name: "变更审批打回" },
      ],
      wareHouseList: [
        { code: "XS-SH-01", name: "湘商-钦雨仓" },
        { code: "XS-SH-02", name: "湘商-唯品仓" },
        // { code: 'XS-SH-03', name: "湘商-湘商仓" },
        { code: "XS-SH-04", name: "湘商-美丽班仓" },
        { code: "XS-SH-05", name: "湘商-湘百仓" },
        { code: "XS-SH-06", name: "湘商-湘商仓" },
      ],
      wareHouseTableList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        brandCodes: [],
        configType: "",
        endTime: "",
        skuNo: "",
        skuNoList: [],
        skuNos: "",
        startTime: "",
        status: "",
      },
      addForm: {
        annexDTOS: [],
        brandCode: "",
        cateDTOS: [],
        configType: 0,
        createdBy: "",
        createdTime: "",
        deptDTOS: [],
        endTime: "",
        remark: "",
        skus: "",
        startTime: "",
        status: 0,
      },
      dateRange: [],
      fileList: [],
      goodsText: "",
      columnIndex: 0,
      rowId: 0,
      randomKey: Math.random(),
      bindForm: {
        bindSkuNo: "",
      },
      // 表单参数
      form: {},
      expandRowKeys: [],
      treeKey: "",
      isExpand: false,
      brandNameList: [],
      saveLoading: false,
      bindModal: {
        open: false,
        id: "",
      },
      timer: null,
      chartLading: true,
      loadDataStatus: true,
      tableHeight: "auto",
      channelList: [],
      pickerOptions2: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.67e7 ;
        },
        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]);
            },
          },
        ],
      },
      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]);
            },
          },
        ],
      },
      today: "",
      cateLists: [],
      gyDeptLists: [],
      spanArr: [],
      disabledForm: false,
    };
  },
  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;
    },
    userName() {
      return this.$store.getters.name;
    },
  },
  created() {
    this.treeKey = new Date();

    if (localStorage.getItem("saleConfig-query")) {
      this.queryParams = JSON.parse(localStorage.getItem("saleConfig-query"));
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
    }

    // 获取当前月的第一天
    const currentMonthFirstDay = new Date();
    currentMonthFirstDay.setDate(1);

    // 获取当前月的最后一天
    const currentMonthLastDay = new Date();
    currentMonthLastDay.setMonth(currentMonthLastDay.getMonth() + 1);
    currentMonthLastDay.setDate(0);

    const year = currentMonthFirstDay.getFullYear();
    const month =
      currentMonthFirstDay.getMonth() + 1 < 10
        ? "0" + (currentMonthFirstDay.getMonth() + 1)
        : currentMonthFirstDay.getMonth() + 1;
    const day =
      currentMonthFirstDay.getDate() < 10
        ? "0" + currentMonthFirstDay.getDate()
        : currentMonthFirstDay.getDate();
    this.queryParams.dateRange = [];
    this.queryParams.dateRange[0] = year + "-" + month + "-" + day;
    const year2 = currentMonthLastDay.getFullYear();
    const month2 =
      currentMonthLastDay.getMonth() + 1 < 10
        ? "0" + (currentMonthLastDay.getMonth() + 1)
        : currentMonthLastDay.getMonth() + 1;
    const day2 =
      currentMonthLastDay.getDate() < 10
        ? "0" + currentMonthLastDay.getDate()
        : currentMonthLastDay.getDate();
    this.queryParams.dateRange[1] = year2 + "-" + month2 + "-" + day2;

    this.getList();
    this.getBrandNameList();
  },
  mounted() {},
  methods: {
    rateChange(value, row) {
      let total = 0;
      this.wareHouseTableList.forEach((item) => {
        if (item.warehouse == row.warehouse) {
          if (item.dept == "") {
            item.rate = total;
          } else {
            // total += parseFloat(item.rate) || 0;
            total = this.commonAdd(total, item.rate)
          }
        }
      });
    },
    rateChange2(value, row) {
      let total = 0;
      this.goodsTableList.forEach((item) => {
        if (item.dept == "") {
          item.rate = total;
        } else {
          // total += parseFloat(item.rate) || 0;
          total = this.commonAdd(total, item.rate)
        }
      });
    },
    commonAdd (number1, number2) {
      let result = 0;
      if (Number.isInteger(number1) || Number.isInteger(number2)) {
          result = number1 + number2;
      } else {
          //两个都是纯小数
          const number1Array = (number1).toString().split('.');
          const number2Array = (number2).toString().split('.');
          //最大的除数位数
          let maxBit = 1;
          if (number1Array[1].length >= number2Array[1].length) {
            maxBit = number1Array[1].length + 1;
          } else {
            maxBit = number2Array[1].length + 1;
          }
          const divisor = parseInt('1'.padEnd(maxBit, 0));
          result = (number1 * divisor + number2 * divisor) / divisor;
      }
      return result;
    },
    cellClick(row, column, cell, event){
      console.log(row, column, cell, event);
      this.columnIndex = column.label;
      this.rowId = row.id;
      this.randomKey = Math.random();
    },
    cellStyle({ row, column, rowIndex, columnIndex }){
      let bg = {};
      console.log(this.columnIndex,this.rowId)
      if(column.label==this.columnIndex&&row.id==this.rowId){
        bg.background = 'rgb(255,238,211)';
      }
      return bg;
    },
    filterStatusList(status) {
      const data = this.statusList.find((item) => {
        return item.code == status;
      });
      console.log(data);
      return (data && data.name) || "";
    },
    cfChange() {
      if (this.addForm.configType == 1 || this.addForm.configType == 2) {
        this.addForm.brandCode = "001";
      } else {
        this.addForm.brandCode = "";
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.annexs = [];
      fileList.forEach((item) => {
        this.annexs.push({
          annexName: item.name,
          annexPath: item.path ? item.path : item.response.data,
        });
      });
      console.log(this.annexs);
    },
    brandChange(val) {
      const brandCodes = this.brandNameList.filter((sp) => {
        return sp.brandName == val;
      });
      const brandCode = brandCodes[0].brandCode;

      this.getConfigKey("activitie." + brandCode)
        .then((res) => {
          this.addForm.suppliers = [];
          if (res.code == 200 && res.msg) {
            this.addForm.suppliers = res.msg.split(",");
          }
        })
        .catch((err) => {
          this.addForm.suppliers = [];
        });
    },
    handlePreview(file) {
      console.log(file);
      if (file.response && file.response.data) {
        window.open(
          "https://newfirst.oss-cn-shanghai.aliyuncs.com/" + file.response.data
        );
      } else {
        window.open("https://newfirst.oss-cn-shanghai.aliyuncs.com/" + file.path);
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      // return this.$confirm(`确定移除 ${ file.name }？`).then(res=>{
      // console.log(3)
      // });
      return true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      response.data.forEach((item) => {
        let status = true;
        this.goodsTableList.forEach((it) => {
          if (it.skuNo == item.skuNo) {
            status = false;
          }
        });
        if (status) {
          this.goodsTableList.push(item);
        }
      });
      this.$refs.upload.clearFiles();
    },
    handleFileSuccess2(response, file, fileList) {
      console.log(fileList);
      this.annexs = [];
      fileList.forEach((item) => {
        this.annexs.push({
          annexName: item.name,
          annexPath: item.path ? item.path : item.response.data,
        });
      });
    },
    beforeAvatarUpload(file) {
      return new Promise((resolve, reject) => {
        console.log(file.size / 1024 / 1024);
        const isLt1M = file.size / 1024 / 1024 > 20;
        if (isLt1M) {
          this.$message.error("上传文件大小不能超过 20MB!");
          reject();
        }

        resolve();
      });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    filterTableData() {
      this.spanArr = [];
      let contactDot = 0;
      this.wareHouseTableList.forEach((item, index) => {
        if (index == 0) {
          this.spanArr.push(1);
        } else {
          if (item.warehouse === this.wareHouseTableList[index - 1].warehouse) {
            this.spanArr[contactDot] += 1;
            this.spanArr.push(0);
          } else {
            contactDot = index;
            this.spanArr.push(1);
          }
        }
      });
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (this.spanArr[rowIndex]) {
          return {
            rowspan: this.spanArr[rowIndex],
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }
    },
    getBrandNameList() {
      getBrandNameList().then((res) => {
        this.brandNameList = res.data;
      });
      getChannelList().then((res) => {
        this.channelList = res.data || [];
      });
      cateList().then((res) => {
        this.cateLists = res.data;
      });
      gyDeptList({}).then((res) => {
        // const res = {
        //   data: [
        //     { deptName: "销售一部", code: "dept1" },
        //     { deptName: "销售二部", code: "dept2" },
        //     { deptName: "销售三部", code: "dept3" },
        //   ],
        // };
        res.data.forEach((item) => {
          this.goodsTableList.push({
            dept: item.deptName,
            deptCode: item.deptCode,
            rate: 0,
          });
        });
        this.goodsTableList.push({
          dept: "",
          deptCode: "",
          rate: 0,
        });

        this.dict.type.warehouse_list.forEach((items) => {
          res.data.forEach((item) => {
            this.wareHouseTableList.push({
              warehouse: items.label,
              warehouseCode: items.value,
              dept: item.deptName,
              deptCode: item.deptCode,
              rate: 0,
            });
          });
          this.wareHouseTableList.push({
            warehouse: items.label,
            warehouseCode: items.value,
            dept: "",
            deptCode: "",
            rate: 0,
          });
        });
        this.filterTableData();
      });
    },
    rowStyle({ row, rowIndex }) {
      if (row.dept == "") {
        return { background: "#f5f7fa" };
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.activitieCode);
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    submitItem(row) {
      this.$confirm("确定要提交审核吗？", "提示", { type: "warning" }).then(() => {
        this.loading = true;
        saleConfigAuditSubmit({ activitieCode: row.activitieCode })
          .then((res) => {
            if (res.status == 200) {
              this.$message.success("提交审核成功");
              this.getList();
            }
            this.loading = false;
          })
          .catch((_) => {
            this.loading = false;
          });
      });
    },
    recallItem(row) {
      this.$confirm("撤回后审批人将无法审批当前分摊配置，确定要撤回吗？", "提示", {
        type: "warning",
      }).then(() => {
        this.loading = true;
        saleConfigAuditCancel(row.id)
          .then((res) => {
            if (res.status == 200) {
              this.$message.success("撤回成功");
              this.getList();
            }
            this.loading = false;
          })
          .catch((_) => {
            this.loading = false;
          });
      });
    },
    /** 查询岗位列表 */
    getList() {
      const data = { ...this.queryParams };
      if (data.dateRange && data.dateRange.length != 0) {
        data.startTime = data.dateRange[0];
        data.endTime = data.dateRange[1];
      } else {
        data.startTime = "";
        data.endTime = "";
      }

      localStorage.setItem("saleConfig-query", JSON.stringify(data));

      this.loading = true;
      saleConfigList(data).then((response) => {
        this.postList = response.data.saleConfigListResDTOS;
        this.total = response.data.total;
        this.loading = false;

        this.$nextTick(() => {
          const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 210;
          this.tableHeight = height + "px";
        });
      });
    },
    handleEdit(row, type) {
      if (type == 2 || type == 3 || type == 1) {
        saleConfigDetail(row.id).then((res) => {
          this.addForm = Object.assign(
            this.addForm,
            JSON.parse(JSON.stringify(res.data))
          );
          this.addForm.dateRange = [this.addForm.startTime, this.addForm.endTime];
          this.$nextTick(() => {
            if (this.$refs["addForm"]) {
              this.$refs["addForm"].clearValidate();
            }
          });             
          this.annexs = res.data.annexDTOS;
          this.addForm.cateDTOS = [];
          res.data.cateDTOS.forEach(item=>{
            this.addForm.cateDTOS.push(item.cateCode)
          })
          // console.log(this.addForm)
          if (res.data.configType == "0" || res.data.configType == "2") {
          
          this.goodsTableList.forEach(item=>{
            res.data.deptDTOS.forEach(dtos=>{
              if(dtos.deptCode==item.deptCode){
                item.rate=dtos.rate;
              }
            })
          })
          console.log(this.goodsTableList)
            // this.goodsTableList = res.data.deptDTOS;
            // this.goodsTableList.push({
            //   dept: "", 
            //   deptCode: "",
            //   rate: 100,
            // });
          } else {
      
            const sortData = this.sortClass(this.wareHouseTableList);
            let deptDTOS = [];
            console.log(sortData)
            sortData.forEach(items=>{
              items.forEach(item=>{
                res.data.deptDTOS.forEach(dtos=>{
                  if(dtos.deptCode==item.deptCode&&dtos.warehouseCode==item.warehouseCode){
                    item.rate=dtos.rate;
                  }
                })
              });
             
              // items.push({
              //   warehouse: items[0].warehouse,
              //   warehouseCode: items[0].warehouseCode,
              //   dept: "",
              //   deptCode: "",
              //   rate: 100,
              // })
              deptDTOS = deptDTOS.concat(items);
            })
            this.wareHouseTableList = deptDTOS;

          }

          this.fileList = [];
          res.data.annexDTOS.forEach((item) => {
            this.fileList.push({ name: item.annexName, path: item.annexPath });
          });
          this.activeName = "1";
          if (type == 1) {
            this.disabledForm = false;
            this.title = "编辑销售分摊";
          } else if (type == 3) {
            this.disabledForm = false;
            this.title = "变更销售分摊";
          } else {
            this.disabledForm = true;
            this.title = "销售分摊详情";
          }
          this.open2 = true;
        });
      }

      saleConfigLogs(row.id).then((res) => {
        this.historyLogTableList = res.data;
      });
    },
    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.warehouseCode; // 返回需要分组的对象
      });
      return sorted;
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.addForm = {
        annexDTOS: [],
        brandCode: "",
        cateDTOS: [],
        configType: 0,
        createdBy: "",
        createdTime: "",
        deptDTOS: [],
        endTime: "",
        remark: "",
        skus: "",
        startTime: "",
        dateRange: []
      };

      this.historyLogTableList = [];
      this.annexs = [];
      this.fileList = [];
      // this.goodsTableList = [];
      this.activeName = "1";
      this.open2 = true;
      this.disabledForm = false;
      this.title = "新建销售分摊";
      this.goodsTableList.forEach(item=>{
        item.rate = 0;
      });
      this.wareHouseTableList.forEach(item=>{
        item.rate = 0;
      });

      this.$nextTick(() => {
        if (this.$refs["addForm"]) {
          this.$refs["addForm"].clearValidate();
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      const data = { ...this.queryParams };
      if (data.dateRange && data.dateRange.length != 0) {
        data.startTime = data.dateRange[0];
        data.endTime = data.dateRange[1];
      } else {
        data.startTime = "";
        data.endTime = "";
      }
      delete data.pageNum;
      delete data.pageSize;
      this.newDownload(
        "sale/config/export",
        data,
        `分摊配置_${new Date().getTime()}.xlsx`
      );
    },
    saveDept() {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          const datas = JSON.parse(JSON.stringify(this.addForm));
          const goodsTableList = JSON.parse(JSON.stringify(this.goodsTableList));
          const wareHouseTableList = JSON.parse(JSON.stringify(this.wareHouseTableList));

          let goodsTableListStatus = true,
            goodsTableListStatus2 = true;
          if (datas.configType == "0" || datas.configType == "2") {
            goodsTableList.forEach((item, i) => {
              // if (item.rate < 0 || item.rate == "") {
              //   goodsTableListStatus = false;
              // }
              if (item.dept == "" && item.rate != 100 && item.rate!=0) {
                if (datas.configType == "0") {
                  this.$message.warning("资源品毛利分摊合计不等于100%或者0%");
                } else {
                  this.$message.warning("所有部门的亏损分摊合计不等于100%或者0%");
                }

                goodsTableListStatus2 = false;
              }
              if (item.dept == "") {
                goodsTableList.splice(i, 1);
              }
            });
          } else {
            for (let i = 0; i < wareHouseTableList.length; i++) {
              let item = wareHouseTableList[i];
              // if (item.rate < 0) {
              //   goodsTableListStatus = false;
              // }
              if (item.dept == "" && item.rate != 100&&item.rate!=0) {
                this.$message.warning(
                  item.warehouse + "仓库所有部门的亏损分摊合计不等于100%或者0%"
                );
                goodsTableListStatus2 = false;
                break;
              }
              if (item.dept == "") {
                wareHouseTableList.splice(i, 1);
              }
            }
          }
          if (!goodsTableListStatus2) {
            return false;
          }
          if (!goodsTableListStatus) {
            this.$message.warning("请填写完整分摊比例");
            return false;
          }

          let cateCodes = [];
          this.cateLists.forEach((item) => {
            datas.cateDTOS.forEach((i) => {
              if (i == item.cateCode) {
                cateCodes.push(item);
              }
            });
          });
          datas.cateDTOS = cateCodes;

          if (datas.configType == "0" || datas.configType == "2") {
            datas.deptDTOS = goodsTableList;
          } else {
            datas.deptDTOS = wareHouseTableList;
          }

          datas.startTime = this.addForm.dateRange[0];
          datas.endTime = this.addForm.dateRange[1];
          datas.annexDTOS = this.annexs;

          delete datas.createdTime;

          if (this.annexs.length == 0) {
            this.$message.warning("请上传附件！");
            return false;
          }

          this.saveLoading = true;
          if (this.title == "编辑销售分摊") {
            saleConfigUpdate(datas)
              .then((res) => {
                this.saveLoading = false;
                if (res.status == "200") {
                  this.$message.success("编辑成功");
                  this.open2 = false;
                  this.getList();
                }
              })
              .catch((err) => {
                this.saveLoading = false;
              });
          } else if (this.title == "新建销售分摊") {
            saleConfigAdd(datas)
              .then((res) => {
                this.saveLoading = false;
                if (res.status == "200") {
                  this.$message.success("新建成功");
                  this.open2 = false;
                  this.getList();
                }
              })
              .catch((err) => {
                this.saveLoading = false;
              });
          } else if (this.title == "变更销售分摊") {
            saleConfigUpdate(datas)
              .then((res) => {
                this.saveLoading = false;
                if (res.status == "200") {
                  this.$message.success("变更成功");
                  this.open2 = false;
                  this.getList();
                }
              })
              .catch((err) => {
                this.saveLoading = false;
              });
          }
        }
      });
    },
    /** 下载模板操作 */
    importTemplate() {
      window.open(
        "https://newfirst.oss-cn-shanghai.aliyuncs.com/activitie/temp/%E8%BF%94%E5%88%A9%E5%95%86%E5%93%81%E6%A8%A1%E7%89%88.xlsx"
      );
      // this.newDownload(
      //   "whole_goods/importTemplate",
      //   {},
      //   `goods_template_${new Date().getTime()}.xlsx`
      // );
    },
  },
};
</script>
<style scoped lang="scss">
.color-r {
  color: #e6a23c;
}
.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;
}
.table-box2 {
  margin: 5px;
}

h3 {
  font-weight: bold;
  display: flex;
  align-items: center;
  margin-top: 36px;
  span {
    display: block;
    width: 2px;
    height: 14px;
    background: #f56c6c;
    margin-right: 6px;
  }
}
.color-s {
  color: #e63c3c;
}
</style>
