<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="电商渠道:" label-width="90px" prop="channelCode">
        <el-select
          v-model="queryParams.channelCode"
          placeholder="请选择电商渠道"
          filterable
          clearable
        >
          <el-option
            v-for="dict in channelList"
            :key="dict.channelCode"
            :label="dict.channelName"
            :value="dict.channelCode"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="商品编码:" prop="skuNos">
        <el-input
          v-model="queryParams.skuNos"
          placeholder="多个商品编码使用逗号隔开"
          clearable
          @input="value=>copySkus(value,'skuNos')"
        />
      </el-form-item>
      <el-form-item label="商品名称:" prop="skuNo">
        <LoadMoreSelect
          :skuNo="queryParams.skuNo"
          @queryParams="(val) => (queryParams.skuNo = val)"
        />
      </el-form-item>
      <el-form-item label="活动类型:" prop="activityType">
        <el-select
          v-model="queryParams.activityType"
          placeholder="请选择活动类型"
          clearable
        >
          <el-option label="百亿补贴" :value="0" />
          <el-option label="秒杀活动" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态:" prop="activityState">
        <el-select
          v-model="queryParams.activityState"
          clearable
          placeholder="请选择"
        >
          <el-option label="启用" :value="0" />
          <el-option label="停用" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="统计日期:" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
        ></el-date-picker>
      </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="success"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          >导入</el-button
        >
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
        <el-button
          type="info"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleStop"
          >批量停用</el-button
        >
        <el-button
          type="danger"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleStart"
          >批量启用</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      ref="proTable"
      :height="tableHeight"
      border
      v-loading="loading"
      :data="postList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="电商渠道"
        min-width="160"
        align="center"
        prop="goodName"
      >
        <template slot-scope="scope">
          {{ formatChannel(scope.row.channelCode) }}
        </template>
      </el-table-column>
      <el-table-column
        label="商品编码"
        min-width="120"
        align="center"
        prop="skuNo"
      >
        <template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">
              {{ scope.row.skuNo }}
            </div>
            <div class="table-overflow">{{ scope.row.skuNo }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        label="商品名称"
        min-width="180"
        align="center"
        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="120"
        align="center"
        prop="quote"
      />
      <el-table-column
        label="活动类型"
        min-width="120"
        align="center"
        prop="spuName"
      >
        <template slot-scope="scope">
          {{ scope.row.activityType == 0 ? "百亿补贴" : "秒杀活动" }}
        </template>
      </el-table-column>
      <el-table-column
        label="活动开始时间"
        width="160"
        align="center"
        prop="startTime"
      />
      <el-table-column
        label="活动结束时间"
        width="160"
        align="center"
        prop="endTime"
      />
      <el-table-column
        label="状态"
        width="100"
        align="center"
        prop="activityState"
      >
        <template slot-scope="scope">
          {{ scope.row.activityState == 0 ? "启用" : "停用" }}
        </template>
      </el-table-column>
      <el-table-column
        label="创建人"
        width="120"
        align="center"
        prop="createName"
      />
      <el-table-column
        label="创建时间"
        width="160"
        align="center"
        prop="createTime"
      />
      <el-table-column
        label="修改人"
        width="120"
        align="center"
        prop="updateBy"
      />
      <el-table-column
        label="修改时间"
        width="160"
        align="center"
        prop="updateTime"
      />
      <el-table-column
        label="操作"
        width="180"
        fixed="right"
        align="center"
        prop="status"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            v-show="scope.row.activityState == 1"
            type="text"
            :disabled="userId != scope.row.createBy"
            @click="handleSwitch(scope.row, 1)"
            >启用</el-button
          >
          <el-button
            size="mini"
            v-show="scope.row.activityState == 0"
            type="text"
            :disabled="userId != scope.row.createBy"
            @click="handleSwitch(scope.row, 2)"
            >停用</el-button
          >
          <el-button
            size="mini"
            v-show="scope.row.activityState == 0"
            type="text"
            :disabled="userId != scope.row.createBy"
            @click="showDetail(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="showLog(scope.row)"
            >日志</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      class="fixed-pagination"
    />
    <el-dialog
      title="日志"
      top="50px"
      :visible.sync="log.open"
      width="820px"
      append-to-body
    >
      <el-table
        ref="proTable"
        :height="tableHeight"
        border
        v-loading="loading"
        :data="log.detail"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          label="操作步骤"
          min-width="120"
          align="center"
          prop="operateName"
        />
        <el-table-column
          label="操作描述"
          min-width="251"
          align="center"
          prop="operateMsg"
        />
        <el-table-column
          label="操作人"
          min-width="120"
          align="center"
          prop="createdBy"
        />
        <el-table-column
          label="操作时间"
          min-width="120"
          align="center"
          prop="createdTime"
        />
      </el-table>

    </el-dialog>

    <el-dialog
      :title="title"
      top="50px"
      :visible.sync="open"
      width="500px"
      append-to-body
    >
      <el-form ref="addForm" :model="addForm" label-width="120px">
        <el-form-item
          label="电商渠道:"
          :rules="[
            { required: true, message: '请选择电商渠道', trigger: 'change' },
          ]"
          prop="channelCode"
        >
          <el-select
            v-model="addForm.channelCode"
            placeholder="请选择电商渠道"
            style="width: 280px"
            filterable
            clearable
          >
            <el-option
              v-for="dict in channelList"
              :key="dict.channelCode"
              :label="dict.channelName"
              :value="dict.channelCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="活动类型:"
          :rules="[
            { required: true, message: '请选择活动类型', trigger: 'change' },
          ]"
          prop="activityType"
        >
          <el-select
            v-model="addForm.activityType"
            placeholder="请选择活动类型"
            @change="activityTypeChange"
            style="width: 280px"
            clearable
          >
            <el-option label="百亿补贴" :value="0" />
            <el-option label="秒杀活动" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="商品编码:"
          :rules="[
            { required: true, message: '请选择商品编码', trigger: 'change' },
          ]"
          prop="skuNo"
        >
          <LoadMoreSelect
            :skuNo="addForm.skuNo"
            @queryParams="(val) => (addForm.skuNo = val)"
            style="width: 280px"
            @skuOptions="skuOptions"
          />
        </el-form-item>
        <el-form-item
          label="报名价格:"
          :rules="[
            { required: true, message: '请选择报名价格', trigger: 'change' },
          ]"
          prop="quote"
        >
          <el-input
            v-model="addForm.quote"
            placeholder="请输入报名价格"
            clearable
            :min="0.0001"
            :max="100"
            style="width: 280px"
            type="number"
          />
        </el-form-item>
        <el-form-item
          label="活动开始时间:"
          :rules="[
            {
              required: true,
              message: '请选择活动开始时间',
              trigger: 'change',
            },
          ]"
          prop="startTime"
        >
          <el-date-picker
            v-model="addForm.startTime"
            value-format="yyyy-MM-dd hh:mm:ss"
            type="datetime"
            style="width: 280px"
            :picker-options="pickerOptions2"
            placeholder="请选择活动开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="活动结束时间:"
          :rules="[
            {
              required: true,
              message: '请选择活动结束时间',
              trigger: 'change',
            },
          ]"
          prop="endTime"
        >
          <el-date-picker
            v-model="addForm.endTime"
            :disabled="addForm.activityType == 0"
            value-format="yyyy-MM-dd hh:mm:ss"
            type="datetime"
            style="width: 280px"
            placeholder="请选择活动结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动备注:" prop="remark">
          <el-input
            v-model="addForm.remark"
            placeholder="请输入活动备注"
            clearable
            type="textarea"
            :rows="5"
            style="width: 280px"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button :loading="saveLoading" type="primary" @click="submitForm"
          >保存</el-button
        >
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="upload.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 LoadMoreSelect from "@/components/LoadMoreSelect/index";
import {
  pddActivityList,
  pddActivityAdd,
  logList,
  pddActivityUpdate,
  pddActivityToggleSwitch,
} from "@/api/activitie/index";
import { getToken } from "@/utils/auth";
import { getChannelList } from "@/api/bizMonitor/index";

export default {
  name: "PddActivity",
  // dicts: ["sys_yes_no"],
  components: {
    LoadMoreSelect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      rows: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      saveLoading: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API_NEW + "/pddActivity/import",
      },
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      activitedList: [],
      rowDetail: {},
      log: {
        detail: [],
        open: false,
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      activitedLoading: false,
      // 查询参数
      queryParams: {
        activityState: 0,
        activityType: "",
        channelCode: "",
        endTime: "",
        page: 1,
        pageSize: 10,
        skuArr: [],
        skuNo: "",
        skuNos: "",
        startTime: "",
        dateRange: [],
      },
      addForm: {
        activityType: "",
        channelCode: "",
        endTime: "",
        quote: "",
        remark: "",
        skuName: "",
        skuNo: "",
        startTime: "",
      },
      timer: null,
      tableHeight: "auto",
      channelList: [],
      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]);
            },
          },
        ],
      },
      pickerOptions2: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.67e7;
        },
      },
    };
  },
  computed: {
    userId() {
      return this.$store.getters.userid;
    },
  },
  created() {
    if (localStorage.getItem("pddActivity-query")) {
      this.queryParams = JSON.parse(localStorage.getItem("pddActivity-query"));
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
    }
    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 * 30);

    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.queryParams.dateRange = [startDate, endDate];

    this.getList();
    this.getChannelLists();
  },
  mounted() {},
  methods: {
    copySkus(value,row,type){
      // row = value.replace(/\s+/g, ',');
      // row = value.trim().split(/\s+/).join(',');
      if(type==2){
        this.goodsText = value.trim().split(/\s+/).join(',')
      }else{
        this.$set(this.queryParams,row,value.trim().split(/\s+/).join(','))
      }
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    /** 批量启用 */
    handleStart() {
      if (this.ids.length == 0) {
        this.$message.warning("请选择活动");
        return;
      }
      var hasStop = false;
      this.rows.forEach((item) => {
        if (item.activityState != 1) {
          hasStop = true;
        }
      });
      if (hasStop) {
        this.$message.warning("只可选择停用的活动");
        return;
      }
      this.$confirm("确定要对选中的活动进行启用吗？", "提示", {
        type: "warning",
      }).then(() => {
        pddActivityToggleSwitch({
          ids: this.ids,
          activityState: 0,
        }).then((res) => {
          if (res.status == 200) {
            this.$modal.msgSuccess("启用成功");
            this.getList();
          }
        });
      });
    },
    /** 批量停用 */
    handleStop() {
      if (this.ids.length == 0) {
        this.$message.warning("请选择活动");
        return;
      }
      var hasStart = false;
      this.rows.forEach((item) => {
        console.log(item.activityState);
        if (item.activityState != 0) {
          hasStart = true;
        }
      });
      if (hasStart) {
        this.$message.warning("只可选择启用的活动");
        return;
      }

      this.$confirm("确定要对选中的活动进行停用吗？", "提示", {
        type: "warning",
      }).then(() => {
        pddActivityToggleSwitch({
          ids: this.ids,
          activityState: 1,
        }).then((res) => {
          if (res.status == 200) {
            this.$modal.msgSuccess("停用成功");
            this.getList();
          }
        });
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = [];
      this.rows = [];
      selection.forEach((item) => {
        // item.orderListDetailDTOList.forEach(i=>{
        //   this.ids.push(i.orderId);
        // })
        this.ids.push(item.id);
        this.rows.push(item);
      });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    formatChannel(value) {
      const data = this.channelList.find((item) => {
        return item.channelCode == value;
      });
      return data ? data.channelName : "";
    },
    getChannelLists() {
      getChannelList().then((res) => {
        this.channelList = res.data;
      });
    },
    /** 查询岗位列表 */
    getList() {
      this.queryParams.startTime = this.queryParams.dateRange[0];
      this.queryParams.endTime = this.queryParams.dateRange[1];

      localStorage.setItem(
        "pddActivity-query",
        JSON.stringify(this.queryParams)
      );

      this.loading = true;
      pddActivityList(this.queryParams).then((response) => {
        this.postList = response.data.list;
        this.total = response.data.total;
        this.loading = false;

        this.$nextTick(() => {
          const height =
            window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 210;
          this.tableHeight = height + "px";
        });
      });
    },
    activityTypeChange(value) {
      if (value == 0) {
        this.addForm.endTime = "9999-12-31 23:59:59";
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    skuOptions(val) {
      const data = val.find((item) => {
        return item.skuNo == this.addForm.skuNo;
      });
      console.log(data);
      this.addForm.skuName = data.skuName || "";
    },
    showDetail(row) {
      this.rowDetail = row;
      const copyRow = JSON.parse(JSON.stringify(row));
      this.addForm = Object.assign(this.addForm, copyRow);
      this.open = true;
      this.title = "编辑活动";
    },
    showLog(row) {
      var param={
        id:row.id
      }
      logList(param).then((response) => {
        this.log.detail = response.data;
        this.loading = false;

        // this.$nextTick(() => {
        //   const height =
        //     window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 210;
        //   this.tableHeight = height + "px";
        // });
      });
      this.log.open = true;
    },
    handleSwitch(row, type) {
      this.$confirm(
        "确定要" + (row.activityState == 0 ? "停用" : "启用") + "吗？",
        "提示",
        { type: "warning" }
      ).then(() => {
        pddActivityToggleSwitch({
          ids: [row.id],
          activityState: row.activityState == 0 ? 1 : 0,
        }).then((res) => {
          if (res.status == 200) {
            row.activityState == 0
              ? this.$modal.msgSuccess("停用成功")
              : this.$modal.msgSuccess("启用成功");

            this.getList();
          }
        });
      });
    },
    handleAdd() {
      this.open = true;
      this.title = "新增活动";
      this.resetForm("addForm");
      this.addForm = {
        activityType: "",
        channelCode: "",
        endTime: "",
        quote: "",
        remark: "",
        skuName: "",
        skuNo: "",
        startTime: "",
      };
    },
    submitForm() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.saveLoading = true;
          if (this.title == "新增活动") {
            pddActivityAdd(this.addForm)
              .then((res) => {
                if (res.status == 200) {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
                this.saveLoading = false;
              })
              .catch((err) => {
                this.saveLoading = false;
              });
          } else {
            pddActivityUpdate(this.addForm)
              .then((res) => {
                if (res.status == 200) {
                  this.$modal.msgSuccess("编辑成功");
                  this.open = false;
                  this.getList();
                }
                this.saveLoading = false;
              })
              .catch((err) => {
                this.saveLoading = false;
              });
          }
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const data = { ...this.queryParams };
      delete data.page;
      delete data.pageSize;
      this.newDownload(
        "pddActivity/export",
        data,
        `活动报名管理_${new Date().getTime()}.xlsx`
      );
    },
    /** 下载模板操作 */
    importTemplate() {
      // this.newDownload(
      //   "spu/importTemplate",
      //   {},
      //   `spu_template_${new Date().getTime()}.xlsx`
      // );
      window.location.href =
        "https://newfirst.oss-cn-shanghai.aliyuncs.com/pddActivity/%E6%8B%BC%E5%A4%9A%E5%A4%9A%E6%B4%BB%E5%8A%A8.xlsx";
    },
  },
};
</script>
<style scoped>
.charts-box {
  height: 350px;
  margin-top: 30px;
}
.erpPrice > span {
  color: #409eff;
}
.iconEdit {
  cursor: pointer;
}
.app-container {
  padding-bottom: 50px;
}

.detail-btn {
  margin-left: 8px;
}
</style>
