<template>
  <div class="page">
    <topBar
      v-if="topList.length > 0"
      :topList="topList"
      :moren="moren"
    ></topBar>
    <div class="thetopbox">
      <el-form ref="queryParams" :model="queryParams" label-width="100px">
        <el-row>
          <el-col :span="4">
            <el-form-item
              :label="'活动名称'"
              prop="actName"
              class="el-inputs"
            >
              <el-input clearable v-model="queryParams.actName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item
              :label="'活动状态'"
              prop="activityStatus"
              class="el-inputs"
            >
              <el-select clearable v-model="queryParams.activityStatus">
                <el-option
                  v-for="item in stateList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="'开始日期'" prop="enableState">
              <el-date-picker
                @change="changeTime"
                type="datetimerange"
                range-separator="——"
                :start-placeholder="'开始日期'"
                :end-placeholder="'结束日期'"
                value-format="yyyy-MM-dd HH:mm:ss"
                :unlink-panels="true"
                v-model="queryParams.thetime1"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="'结束日期'" prop="enableState">
              <el-date-picker
                @change="changeTime2"
                type="datetimerange"
                range-separator="——"
                :start-placeholder="'开始日期'"
                :end-placeholder="'结束日期'"
                value-format="yyyy-MM-dd HH:mm:ss"
                :unlink-panels="true"
                v-model="queryParams.thetime2"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="'创建日期'" prop="enableState">
              <el-date-picker
                @change="changeTime3"
                type="datetimerange"
                range-separator="——"
                :start-placeholder="'开始日期'"
                :end-placeholder="'结束日期'"
                value-format="yyyy-MM-dd HH:mm:ss"
                :unlink-panels="true"
                v-model="queryParams.thetime3"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4" style="margin-left: 30px">
            <div class="searchbox">
              <el-button class="my_search" @click="reSearch">
                {{ '搜索' }}</el-button
              >
              <el-button class="my_reset" @click="reChongzhi">
                {{ '重置' }}</el-button
              >
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="main">
      <div class="maintop">
        <div class="mainbtn">
          <el-button
            size="mini"
            class="thebtn1"
            @click="adddate()"
            v-hasButtons="['lotteryAdd']"
            >{{ '添加' }}</el-button
          >
          <el-button
            size="mini"
            @click="handleExport"
            v-hasButtons="['lotteryExport']"
            class="exportBtn"
          >
            {{ '导出' }}</el-button
          >
        </div>
      </div>
      <div class="maintable">
        <el-table
          :data="tableData"
          v-loading="loading"
          style="width: 100%"
          height="680px"
          :header-cell-style="{ background: '#EEEEEE' }"
          :row-class-name="tableRowClassName"
          @selection-change="handleSelectionChange"
          :span-method="objectSpanMethod"
        >
          <el-table-column prop="colsele" type="selection" width="55">
          </el-table-column>

          <el-table-column
            align="center"
            prop="actName"
            :label="'活动名称'"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="giftCover"
            :label="'奖品图片'"
          >
            <template slot-scope="scope">
              <img
                style="width: 48px; height: 48px"
                :src="scope.row.giftCover"
                alt=""
              />
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="giftName"
            :label="'奖品名称'"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="giftNumber"
            :label="'奖品数量'"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="minNumber"
            :label="'最小中奖数量'"
          >
          </el-table-column>
          <!-- <el-table-column align="center" prop="" label="奖品类型">
          </el-table-column> -->
          <el-table-column
            align="center"
            prop="grantWayStr"
            :label="'发放方式'"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="status"
            :label="'活动状态'"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="actStartDate"
            :label="'开始日期'"
          >
          </el-table-column>

          <el-table-column
            align="center"
            prop="actEndDate"
            :label="'结束日期'"
          >
          </el-table-column>

          <el-table-column
            align="center"
            prop="creationTime"
            :label="'创建日期'"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="caozuo"
            :label="'操作'"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                style="color: #e70dec; padding: 0"
                @click.native.prevent="toFixed(scope.row, 4)"
                type="text"
                v-hasButtons="['lotterySee']"
                size="small"
              >
                {{ '查看' }}
              </el-button>
              <el-button
                style="color: #48b2fd; padding: 0"
                @click.native.prevent="toFixed(scope.row, 2)"
                type="text"
                v-hasButtons="['lotteryUpdata']"
                size="small"
              >
                {{ '修改' }}
              </el-button>

              <el-button
                @click.native.prevent="toFixed(scope.row, 3)"
                type="text"
                v-hasButtons="['lotteryDel']"
                size="small"
                style="color: #c73030; padding: 0"
              >
                {{ '删除' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <pagination
      v-if="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="reSearch"
    />
  </div>
</template>

<script>
import topBar from "@/components/topBar";
import * as api from "@/api/newgift";
export default {
  name: "LotteryList",
  components: {
    topBar,
  },
  data() {
    return {
      moren: "lotteryList",
      topList: [
        {
          name: '抽奖配置',
          path: "lotteryList",
        },
      ],
      total: 0,
      tableData: [],
      loading:false,
      queryParams: {
        pageNum: 1,
        pageSize: 50,
      },
      multipleSelection: [],
      stateList: [],
      // 需要合并项的列
      needMergeArr: [
        {
          colName: "colsele",
          mergeCheckNames: ["pkBaseId"],
        },
        {
          colName: "actName",
          mergeCheckNames: ["pkBaseId"],
        },
        {
          colName: "activityStatusVal",
          mergeCheckNames: ["pkBaseId"],
        },
        {
          colName: "caozuo",
          mergeCheckNames: ["pkBaseId"],
        },
        {
          colName: "creationTime",
          mergeCheckNames: ["pkBaseId"],
        },
        {
          colName: "actStartDate",
          mergeCheckNames: ["pkBaseId"],
        },
        {
          colName: "actEndDate",
          mergeCheckNames: ["pkBaseId"],
        },
      ],
      rowMergeArrs: {}, // 包含需要一个或多个合并项信息的对象
    };
  },
  created() {
    this.reSearch();
    this.getOther();
  },
  methods: {
    deleteRow(row) {
      this.$confirm('是否删除').then((_) => {
        // del.deleteDeliverItems({ id: row.pkBaseId || null }).then((res) => {
        //   if (res.code == 200) {
        //     this.$message({
        //       message: res.msg,
        //       type: "success",
        //     });
        //     this.getList();
        //   }
        // });
      });
    },
    reChongzhi() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 50,
      };
      this.reSearch();
    },
    getOther() {
      api.getActiveStatus().then((res) => {
        this.stateList = res.data;
      });
    },
    reSearch() {
      this.loading = true
      api.getDrawGiftConfigList(this.queryParams).then((res) => {
        this.tableData = res.rows;
        this.total = res.total;
        this.rowMergeArrs = this.rowMergeHandle(
          this.needMergeArr,
          this.tableData
        );
        this.loading = false
      });
    },
    adddate() {
      this.$router.push({
        path: "lotteryInfo",
        query: {
          controlType: 1,
        },
      });
    },
    // 点击修改
    toFixed(row, index) {
      if (index == 3) {
        let obj = Object.assign(
          {},
          {
            controlType: index,
            activityParam: row,
          }
        );
        this.$router.push({
          path: "lotteryGiftZxqc",
          query: {
            data: JSON.stringify(obj),
            approvalBusiness: 717,
          },
        });
      } else {
        this.$router.push({
          path: "lotteryInfo",
          query: {
            pkId: row.pkBaseId,
            controlType: index,
          },
        });
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 == 1) {
        return "warning-row";
      } else if (rowIndex % 2 == 0) {
        return "success-row";
      }
      return "";
    },
    changeTime(val) {
      if (val) {
        this.queryParams.startActStartDate = val[0];
        this.queryParams.endActStartDate = val[1];
      } else {
        this.queryParams.startActStartDate = "";
        this.queryParams.endActStartDate = "";
      }
    },
    changeTime2(val) {
      if (val) {
        this.queryParams.startActEndDate = val[0];
        this.queryParams.endActEndDate = val[1];
      } else {
        this.queryParams.startActEndDate = "";
        this.queryParams.endActEndDate = "";
      }
    },
    changeTime3(val) {
      if (val) {
        this.queryParams.startCreationTime = val[0];
        this.queryParams.endCreationTime = val[1];
      } else {
        this.queryParams.startCreationTime = "";
        this.queryParams.endCreationTime = "";
      }
    },
    //解决多列行列合并，根据某一列 合并其他列
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      let needMerge = this.needMergeArr.some((item) => {
        return item.colName === column.property;
      });
      if (needMerge === true) {
        return this.mergeAction(column.property, rowIndex, column);
      }
    },
    mergeAction(val, rowIndex, colData) {
      let _row = this.rowMergeArrs[val].rowArr[rowIndex];
      let _col = _row > 0 ? 1 : 0;
      return [_row, _col];
    },
    rowMergeHandle(arr, data) {
      if (!Array.isArray(arr) && !arr.length) return false;
      if (!Array.isArray(data) && !data.length) return false;
      let needMerge = {};

      arr.forEach((mergeItem) => {
        // 创建合并管理对象
        needMerge[mergeItem.colName] = {
          rowArr: [],
          rowMergeNum: 0,
        };
        let currentMergeItemData = needMerge[mergeItem.colName];

        // 进行合并管理对象数据的遍历整理
        data.forEach((item, index) => {
          if (index === 0) {
            currentMergeItemData.rowArr.push(1);
            currentMergeItemData.rowMergeNum = 0;
          } else {
            let currentRowData = data[index];
            let preRowData = data[index - 1];

            if (
              this.colMergeCheck(
                currentRowData,
                preRowData,
                mergeItem.mergeCheckNames
              )
            ) {
              currentMergeItemData.rowArr[
                currentMergeItemData.rowMergeNum
              ] += 1;
              currentMergeItemData.rowArr.push(0);
            } else {
              currentMergeItemData.rowArr.push(1);
              currentMergeItemData.rowMergeNum = index;
            }
          }
        });
      });
      return needMerge;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出所有数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning",
      }).then((_) => {
        this.download(
          "activity/manage/draw-gift-config/export",
          Object.assign({}, { actType: 12 }, this.queryParams, this.select),
          `${'抽奖配置'}${new Date().getTime()}.xlsx`
        );
      });
    },
    colMergeCheck(currentRowData, preRowData, mergeCheckNames) {
      if (!Array.isArray(mergeCheckNames) && !mergeCheckNames.length)
        return false;
      let result = true;
      for (let index = 0; index < mergeCheckNames.length; index++) {
        const mergeCheckName = mergeCheckNames[index];
        if (currentRowData[mergeCheckName] !== preRowData[mergeCheckName]) {
          result = false;
          break;
        }
      }
      return result;
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-range-editor.el-input__inner {
  width: 100%;
}
::v-deep .el-table .warning-row {
  background: #f9f9f9;
}

::v-deep .el-table .success-row {
  background: #ffffff;
}
::v-deep .el-table thead {
  color: #000000;
}
.page {
  padding: 10px 20px;
  background: #f9f9f9;
  font-size: 14px;
  .thetopbox {
    padding: 20px 20px 20px;
    background: #ffffff;
    border-radius: 8px;
    .searchbox {
      display: flex;
      align-items: center;
      .searchtitle {
        margin-right: 10px;
      }
      .searchbtn {
        background: #c8161d;
        color: #ffffff;
      }
    }
  }
  .main {
    background: #f9f9f9;
    .maintop {
      display: flex;
      // padding: 10px 0;
      justify-content: space-between;
      align-items: center;
      .mainbtn {
        .thebtn1 {
          background: #4391fd;
          color: #ffffff;
        }
        .thebtn2 {
          background: #ffad41;
          color: #ffffff;
        }
      }
    }
  }
}
</style>
