<template>
  <div class="active pagePadding">
    <ex-table
      v-loading="loading"
      v-if="powers.some((i) => i == '001')"
      :table="table"
      :data="tableData"
      :columns="columns"
      :page="pageInfo"
      :size="size"
      @page-curr-change="handlePageChange"
      @page-size-change="handleSizeChange"
      @screen-reset="
        pageInfo.curr = 1;
        parmValue.page = 1;
        searchList();
      "
      @screen-submit="
        pageInfo.curr = 1;
        parmValue.page = 1;
        searchList();
      "
    >
      <template #table-header="{ selection }">
        <div style="width: 100%">
          <el-row style="padding: 0 0 10px 80px">
            <!-- <el-col :span="4" style="width: 205px">
              <el-select
                v-model="parmValue.status"
                filterable
                clearable
                :size="searchSize"
                placeholder="活动状态"
                style="width: 100%"
                @change="
                  pageInfo.curr = 1;
                  parmValue.page = 1;
                  searchList();
                "
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="'status' + item.id"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-col> -->
            <!-- <el-col :span="4" style="width: 205px; padding: 0 0 0 10px">
              <el-select
                v-model="parmValue.exam_status"
                filterable
                clearable
                :size="searchSize"
                placeholder="商品上线状态"
                style="width: 100%"
                @change="
                  pageInfo.curr = 1;
                  parmValue.page = 1;
                  searchList();
                "
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="'status' + item.id"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-col> -->
            <el-col :span="6" style="width: 310px; padding: 0 0 0 10px">
              <good-class
                :value="parmValue.cat_id"
                @handleChange="goods_class_change"
                :disabled="false"
                :size="searchSize"
                :isDetail="false"
                :placeholder="'分类'"
              />
            </el-col>
            <!-- <el-col :span="6" style="width: 303px; padding: 0 0 0 10px">
              <period-date-picker
                :type="1"
                :width="'135px'"
                :size="searchSize"
                :start="parmValue.start"
                :end="parmValue.end"
                @timeReturned="handleTime"
              />
            </el-col> -->

            <el-col :span="3" class="fr" style="width: 66px; padding: 0 0 0 10px">
              <el-button type="primary" :size="searchSize" @click="searchList">
                刷新
              </el-button>
            </el-col>
            <el-col :span="3" class="fr" style="width: 66px; padding: 0 0 0 10px">
              <el-button type="warning" :size="searchSize" @click="restSearch">
                重置
              </el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" style="width: 500px">
              <el-input
                :size="searchSize"
                v-model="sinput"
                :maxlength="40"
                clearable
                @blur="
                  pageInfo.curr = 1;
                  parmValue.page = 1;
                  searchList();
                "
                placeholder="关键字"
              >
                <el-select
                  v-model="select"
                  slot="prepend"
                  style="width: 130px"
                  @change="
                    pageInfo.curr = 1;
                    parmValue.page = 1;
                    searchList();
                  "
                  placeholder="关键字类型"
                >
                  <el-option label="活动名称" value="1" />
                  <el-option label="活动编码" value="2" />
                  <el-option label="活动公司" value="3" />
                  <el-option label="活动负责人" value="4" />
                  <el-option label="商品名称" value="5" />
                  <el-option label="商品成本编号" value="6" />
                  <el-option label="商品上线编号" value="7" /> </el-select
              ></el-input>
            </el-col>
            <!-- <el-col
              :span="3"
              class="fr"
              style="width: 66px; padding: 0 0 0 10px"
              v-if="powers.some((i) => i == '087')"
            >
              <el-button
                :size="searchSize"
                type="success"
                style="float: right"
                @click="batchExport(selection)"
              >
                导出
              </el-button>
            </el-col> -->
            <!-- <el-col
              :span="3"
              class="fr"
              style="width: 66px; padding: 0 0 0 10px"
              v-if="powers.some((i) => i == '086')"
            >
              <el-button
                :size="searchSize"
                type="success"
                style="float: right"
                @click="showModel = true"
              >
                导入
              </el-button>
            </el-col> -->
          </el-row>
        </div></template
      >
      <!-- <template #status="{ scope }">
        <el-tag
          :size="tablebtnSize"
          :type="scope.row.status + '' == '0' ? 'warning' : ''"
          v-text="
            (statusOptions.find((item) => item.id == scope.row.status + '') || {})
              .label || '--'
          "
        ></el-tag>
      </template> -->
      <template #atime="{ scope }"> {{ scope.row.start }}~{{ scope.row.end }} </template>
      <template #operation="{ scope }">
        <!-- <el-tooltip effect="dark" content="详情" placement="top">
          <i class="el-icon-view tb-icon"></i>
        </el-tooltip> -->
        <el-tooltip effect="dark" content="兑换链接列表" placement="top">
          <i class="el-icon-s-grid tb-icon" @click="showUrlList(scope.row)"></i>
        </el-tooltip>
      </template>
    </ex-table>
    <no-auth v-else></no-auth>
    <!-- 弹窗 新增/修改 -->
    <weburlImport
      :show-model="showModel"
      @refresh="(showModel = false), searchList()"
      @cancel="showModel = false"
    />
    <webUrlList
      :show-model="webShowModel"
      :sitem="websitem"
      @refresh="(webShowModel = false), searchList()"
      @cancel="webShowModel = false"
    />
  </div>
</template>
<script>
import asyncRequest from "@/apis/service/youzan/luckDrawGood";
import mixinPage from "@/mixins/elPaginationHandle";
import { mapGetters } from "vuex";
import resToken from "@/mixins/resToken";
import { columns, tHeader, filterVal } from "./columns";
import { formatJson } from "@/utils/publicMethods";
import weburlImport from "./weburlImport";
import webUrlList from "./webUrlList";
export default {
  name: "luckyDrawGood",
  mixins: [mixinPage, resToken],
  components: { weburlImport, webUrlList },
  computed: {
    //组件SIZE设置
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      const tran =
        this.$store.getters.btnList.find((item) => item.menu_route == "luckyDrawGood") ||
        {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      select: "1",
      sinput: "",
      websitem: null,
      webShowModel: false,
      showModel: false,
      loading: false,
      parmValue: {
        act_name: "",
        actCode: "",
        status: "",
        start: "",
        end: "",
        page: 1, // 页码
        size: 15, // 每页显示条数
        company_id: "",
        contactor: "",
        company_name: "", //活动公司
      },
      // 状态
      statusOptions: [
        { id: "0", label: "待上传" },
        { id: "1", label: "已完成" },
      ],
      // 表格 - 数据
      tableData: [],
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        _defaultHeader_: ["setcol"],
      },
      // 表格 - 分页
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0,
      },
      // 表格 - 列参数
      columns,
      tHeader,
      filterVal,
    };
  },
  mounted() {
    const { back } = this.$route.query;
    if (back) {
      this.parmValue = JSON.parse(back);
      console.log(this.parmValue);
      const { page, size } = this.parmValue;
      // this.parmValue.start = start || last_start;
      // this.parmValue.end = end || last_end;
      // if(this.parmValue.brandid.length>0){
      //   this.brandid = [this.parmValue.brandid] ;
      // }

      this.pageInfo = {
        size: size,
        curr: page,
        total: 0,
      };
      //多选条件
      this.select = this.parmValue.select;
      // this.sselect = this.parmValue.sselect;
      this.sinput = this.parmValue.sinput;
    } else {
      this.select = "1";
      //  this.sselect = "创建时间"
    }
    this.searchList();
  },
  methods: {
    showUrlList(sitem) {
      this.websitem = sitem;
      this.webShowModel = true;
    },
    async expandChange({ row, expandedRows }) {
      if (expandedRows.length === 0) return;
      const { id } = row;
      this.getChildren(id);
    },
    async getChildren(id) {
      let index = this.tableData.findIndex((a) => a.id === id);
      if (this.tableData[index].loading) return;
      this.tableData[index].loading = true;
      const { code, data, message } = await asyncRequest.goodUrlList({ act_good_id: id });
      this.tableData[index].loading = false;
      if (code === 0) {
        const { list } = data || {};
        this.tableData[index].children = list || [];
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.tableData[index].children = [];
      }
    },
    getRouter(toRouter, queryId) {
      if (toRouter && queryId) {
        let model = {
          id: queryId,
          type: "view",
        };

        //有多选框的条件
        this.parmValue.select = this.select;
        // this.parmValue.sselect = this.sselect ;
        this.parmValue.sinput = this.sinput;
        //
        console.log(this.parmValue);
        let routerModel = {
          options: JSON.parse(JSON.stringify(this.parmValue)),
          router: this.$route.path,
        };
        model.preModel = JSON.stringify(routerModel);

        this.routeGoto(toRouter, model);
      } else {
        this.$message.warning("暂未找到相关流程！");
      }
    },
    restSearch() {
      // 表格 - 分页
      this.select = "1";
      this.sinput = "";
      this.pageInfo = {
        size: 15,
        curr: 1,
        total: 0,
      };
      this.parmValue = {
        act_name: "",
        actCode: "",
        status: "",
        start: "",
        end: "",
        page: 1, // 页码
        size: 15, // 每页显示条数
        company_id: "",
        contactor: "",
        company_name: "", //活动公司
      };
      this.searchList();
    },
    async platform_codesearchChange(e) {
      const { id, code, label } = e;
      this.parmValue.platform_code = id || "";
      this.pageInfo.curr = 1;
      this.parmValue.page = 1;
      await this.searchList();
    },

    async company_idsearchChange(e) {
      const { id, code, label } = e;
      this.parmValue.company_id = code || "";
      this.pageInfo.curr = 1;
      this.parmValue.page = 1;
      await this.searchList();
    },
    // 刷新表格
    async searchList() {
      if (
        (this.parmValue.start !== "" && this.parmValue.end === "") ||
        (this.parmValue.start === "" && this.parmValue.end !== "")
      ) {
        this.$message.warning("时间区间不完整！");
        return;
      }
      this.loading = true;
      let model = JSON.parse(JSON.stringify(this.parmValue));
      model.act_name = this.select === "1" ? this.sinput : "";
      model.actCode = this.select === "2" ? this.sinput : "";
      model.contactor = this.select === "3" ? this.sinput : "";
      model.company_name = this.select === "4" ? this.sinput : ""; // 部门
      const { code, data, message } = await asyncRequest.list(model);
      if (code === 0) {
        const { list, count } = data;
        this.tableData = list;
        this.tableData.forEach((a) => {
          a.children = [];
          a.loading = false;
        });
        this.pageInfo.total = Number(count);
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.tableData = [];
        this.pageInfo.total = 0;
      }
      this.loading = false;
    },
    //商品分类选择
    async goods_class_change(e) {
      this.cat_id = e;
      this.parmValue.cat_id =
        this.cat_id.length === 0 ? "" : this.cat_id[this.cat_id.length - 1];
      this.pageInfo.curr = 1;
      this.parmValue.page = 1;
      await this.searchList();
    },
    async deleteItem(row, id) {
      await this.$confirm("确定要删除？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const model = {
            web_url_ids: [id],
          };
          const { code, data, message } = await asyncRequest.delete(model);
          if (code === 0) {
            this.$notify.success({
              title: "删除成功",
              message: "",
            });
            await this.getChildren(row.id);
          } else if (code >= 100 && code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(message);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },
    /**
     *  批量导出
     * @param {Array} selection 当前选择项
     */
    batchExport(selection) {
      if (!this.loading) {
        if (selection.length == 0) {
          this.$message.warning("请至少选择一条数据！");
          return;
        }

        console.log(selection);

        this.loading = true;
        let data = [].concat(...selection);
        let list = [];
        data.forEach((item) => {
          const num = parseInt(item.stock_num);
          for (let i = 0; i < num; i++) {
            let model = Object.assign({}, item);
            model.status_name = model.status === "0" ? "待上传" : "已完成";
            model.sindex = i + 1;
            model.act_good_id = model.id;
            list.push(model);
          }
        });
        console.log(list);
        const xlsName = `抽奖活动商品批量导出`;
        import("@/vendor/Export2Excel").then((excel) => {
          const data = formatJson(filterVal, list);
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: `${xlsName}`,
          });
          this.$message.success(`${xlsName}成功！`);
          setTimeout(() => {
            this.loading = false;
          }, 500);
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
