<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="120px"
    >
      <!-- v-selectLazyLoad:pageNum="skuNoFilter(skuPageNum)"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" -->

      <!-- <el-select
          v-model="queryParams.skuNo"
          remote
          :remote-method="skuNoFilter"
          filterable
          clearable
          placeholder="请输入商品名称或编码"
        >
          <el-option
            v-for="(item, index) in skuOptions"
            :key="index"
            :label="item.skuName + '/' + item.skuNo"
            :value="item.skuNo"
          >
          </el-option>
        </el-select> -->

      <el-form-item label="网站:" label-width="90px" prop="platform">
        <el-select
          v-model="queryParams.channelCode"
          placeholder="电商平台"
          style="width: 220px"
          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="xsGoodCode">
        <el-input
          v-model="queryParams.xsGoodCode"
          placeholder="请输入湘商商品编码"
          clearable
        />
      </el-form-item>
      <el-form-item label="商品名称:" prop="goodName">
        <el-input v-model="queryParams.goodName" placeholder="请输入商品名称" clearable />
      </el-form-item>
      <el-form-item label="状态:" prop="goodStatus">
        <el-select v-model="queryParams.goodStatus" placeholder="请选择">
          <el-option label="启用" :value="1" />
          <el-option label="停用" :value="2" />
        </el-select>
      </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="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          >导入</el-button
        >
        <el-button type="success" plain size="mini" @click="handlePause2(1)"
          >批量启用</el-button
        >
        <el-button type="info" plain size="mini" @click="handlePause2(2)"
          >批量作废</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"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="网站" width="110" align="center" prop="channelName" />
      <el-table-column label="商品名称" width="180" align="center" prop="goodName">
        <template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">{{ scope.row.goodName }}</div>
            <div class="table-overflow">{{ scope.row.goodName }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="湘商商品编码" width="140" align="center" prop="xsGoodCode">
        <template template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">{{ scope.row.xsGoodCode }}</div>
            <div class="table-overflow">{{ scope.row.xsGoodCode }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="页面类型" width="100" align="center" prop="pageType" />
      <el-table-column label="网站商品页面链接" width="180" align="center" prop="goodUrl">
        <template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">{{ scope.row.goodUrl }}</div>
            <div class="table-overflow">{{ scope.row.goodUrl }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="90" align="center" prop="goodStatus">
        <template slot-scope="scope">
          {{ scope.row.goodStatus == 1 ? "启用" : "作废" }}
        </template>
      </el-table-column>
      <el-table-column label="爬出销售价格" width="110" align="center" prop="goodPrice">
        <template slot-scope="scope">
          <div>{{ scope.row.goodPrice }}</div>
          <el-button
            size="mini"
            type="text"
            @click="showPrice(scope.row)"
            >价格趋势图</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        label="湘商标准销售价格"
        width="140"
        align="center"
        prop="xsSalePrice"
      />
      <el-table-column label="最新爬出时间" width="140" align="center" prop="crawlTime" />
      <el-table-column
        label="商品添加时间"
        width="160"
        align="center"
        prop="createTime"
      />
      <el-table-column label="商品添加人" width="140" align="center" prop="createBy" />
      <el-table-column label="作废时间" width="140" align="center" prop="cancelTime" />
      <el-table-column label="作废人" width="110" align="center" prop="cancelBy" />
      <el-table-column
        label="操作"
        width="140"
        align="center"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-show="scope.row.goodStatus == 2"
            @click="handlePause(scope.row, 1)"
            >启用</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-show="scope.row.goodStatus == 1"
            @click="handlePause(scope.row, 2)"
            >停用</el-button
          >
          <el-button size="mini" type="text" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>

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

    <el-dialog
      :title="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>

    <el-dialog
      title="编辑商品"
      top="50px"
      :visible.sync="goodsOpen"
      width="600px"
      append-to-body
    >
      <el-form ref="bindForm" :model="bindForm" :rules="rules" label-width="140px">
        <el-form-item label="网站:" prop="channelCode">
          <el-select
            v-model="bindForm.channelCode"
            placeholder="电商平台"
            style="width: 220px"
            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="pageType">
          <el-input v-model="bindForm.pageType" />
        </el-form-item>
        <el-form-item label="商品名称:" prop="goodName">
          <el-input v-model="bindForm.goodName" />
        </el-form-item>
        <el-form-item label="ERP商品编码:" prop="xsGoodCode">
          <el-input v-model="bindForm.xsGoodCode" />
        </el-form-item>
        <el-form-item label="网站商品页面链接:" prop="goodUrl">
          <el-input v-model="bindForm.goodUrl" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBindForm">确 定</el-button>
        <el-button @click="goodsOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="价格趋势" bottom="100px" :visible.sync="open2" width="1000px" append-to-body>
      <el-row style="margin-bottom: 18px;">
          <el-col :span="24">
            <el-descriptions>
              <el-descriptions-item label="商品名称">{{ detailRow.goodName }}</el-descriptions-item>
              <el-descriptions-item label="日期">
                <el-date-picker
                  v-model="detailQuery.dates"
                  style="width: 240px"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="getChart"
                  :clearable="false"
                ></el-date-picker>
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>

        <div class="charts-box" v-loading="chartLading">
          <line-chart :chart-data="lineChartData" :className="'procure-chart'" />
        </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="open2 = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  goodsList,
  getGoodsDetail,
  getPrice,
  channelList,
  goodsUpdata,
  saleList
} from "@/api/goods/index";
import LoadMoreSelect from "@/components/LoadMoreSelect/index";
import LineChart from "../charts/LineChart";
import { getToken } from "@/utils/auth";

export default {
  name: "PriceCrawler",
  dicts: ["sys_yes_no", "sys_commerce_platform"],
  components: {
    LineChart,
    LoadMoreSelect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API_NEW + "/whole_goods/import",
      },
      goodsOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodName: "",
        xsGoodCode: "",
        channelCode: "",
        goodStatus: 1
      },
      bindForm: {
        bindSkuNo: "",
      },
      platform: ["ho", "jrc", "hy"],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        channelCode: [{ required: true, message: "网站不能为空", trigger: "blur" }],
        pageType: [{ required: true, message: "页面类型不能为空", trigger: "blur" }],
        goodName: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
        xsGoodCode: [{ required: true, message: "商品编码不能为空", trigger: "blur" }],
        goodUrl: [{ required: true, message: "商品链接不能为空", trigger: "blur" }],
      },
      skuOptions: [],
      skuPageNum: 1,
      platformList: {
        ho: "鸿欧",
        jrc: "吉瑞城",
        hy: "惠友",
      },
      platformList2: {
        ho: "hoPrice",
        jrc: "jrcPrice",
        hy: "hyPrice",
      },
      checkedGroup: ["鸿欧", "吉瑞城", "惠友"],
      dateRange: [],
      brandNameList: [],
      bindModal: {
        open: false,
        id: "",
      },
      chartRow: { goodName: "" },
      timer: null,
      lineChartData: {
        xData: [],
        sData: [
          {
            name: "",
            data: [],
          },
          {
            name: "",
            data: [],
          },
          {
            name: "",
            data: [],
          },
        ],
      },
      chartLading: true,
      loadDataStatus: true,
      tableHeight: "auto",
      channelList: [],
      open2: false,
      detailRow:{},
      detailQuery: {dates:[]},
      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]);
            },
          },
        ],
      },
    };
  },
  created() {
    this.getChannelList();
  },
  mounted() {},
  methods: {
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },
    getChannelList() {
      channelList().then((res) => {
        this.channelList = res.data;
        this.queryParams.channelCode = res.data[0].channelCode;
        this.getList();
      });
    },
    showPrice(row){
      const date = new Date();

      const year = date.getFullYear();
      const month =
        date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
      const day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      const endDate = year + "-" + month + "-" + day;
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 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.detailQuery.dates = [startDate,endDate];

      this.detailRow = row;
      this.open2 = true;
      this.$nextTick(()=>{
        this.getChart();
      })
      
    },
    getChart(){
      this.chartLading = true;
      saleList({
        "channelCode": this.detailRow.channelCode,
        "endDate": this.detailQuery.dates[1],
        "startDate": this.detailQuery.dates[0],
        "xsGoodCode": this.detailRow.xsGoodCode,
      }).then(res=>{
        this.lineChartData = {
          xData: [],
          sData: [
            {
              name: "湘商",
              data: [],
            },
            {
              name: "",
              data: [],
            },
          ],
        };
        this.lineChartData.sData[1].name = this.detailRow.channelName;
        res.data.forEach((item) => {
          this.lineChartData.xData.unshift(item.operDate);
          this.lineChartData.sData[0].data.unshift(item.xsSalePrice || 0);
          this.lineChartData.sData[1].data.unshift(item.goodPrice || 0);
        });
        this.chartLading = false;
      }).catch(err=>{
        this.chartLading = false;
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      goodsList(this.queryParams).then((response) => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;

        this.$nextTick(() => {
          const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 210;
          this.tableHeight = height+'px';
          // if (height < this.$refs.proTable.$el.offsetHeight) {
          //   this.$refs.proTable.height = height + "px";
          //   this.$refs.proTable.doLayout();
          // } else if (height == this.$refs.proTable.$el.offsetHeight) {
          //   this.$refs.proTable.height = height + "px";
          //   this.$refs.proTable.doLayout();
          // }
        });
      });
    },
    showBindSku(id) {
      this.bindModal = {
        open: true,
        id,
      };
    },
    // 文件上传中处理
    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();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    handlePause(row, type) {
      this.$confirm("确认要" + (type == 1 ? "启用" : "停用") + "吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          goodsUpdata([{ id: row.id, goodStatus: type + "" }])
            .then((res) => {
              if (res.code == 200) {
                this.$modal.msgSuccess("修改成功");
                this.getList();
              }
            })
            .catch(() => {
              this.loading = false;
            });
        })
        .catch(() => {});
    },
    submitBindForm() {
      this.$refs["bindForm"].validate((valid) => {
        if (valid) {
          this.loading = true;
          goodsUpdata([this.bindForm])
            .then((res) => {
              if (res.code == 200 && res.data) {
                this.$modal.msgSuccess("编辑成功");
                this.getList();
              }
              this.goodsOpen = false;
            })
            .catch(() => {
              this.loading = false;
              this.goodsOpen = false;
            });
        }
      });
    },
    handlePause2(type) {
      if (this.ids.length == 0) {
        this.$modal.msgWarning("请选择数据");
        return false;
      }
      this.$confirm("确认要" + (type == 1 ? "启用" : "停用") + "吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.loading = true;

        const datas = [];
        this.ids.forEach((item) => {
          datas.push({ id: item, goodStatus: type });
        });
        goodsUpdata(datas).then((res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess("修改成功");
            this.getList();
          }
        });
      });
    },
    handleEdit(row, type) {
      this.bindForm = JSON.parse(JSON.stringify(row));
      this.goodsOpen = true;
    },
    // 取消按钮
    cancel(type) {
      if (type == "open") {
        this.open = false;
        this.reset();
      } else {
        this.bindModal.open = false;
      }
    },
    // 表单重置
    reset() {
      this.form = {
        postId: undefined,
        postCode: undefined,
        postName: undefined,
        postSort: 0,
        status: "0",
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.platform = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.postId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "价格趋势";
    },
    /** 修改按钮操作 */
    showChart(row) {
      this.open = true;
      this.chartRow = row;
      this.getChart(row);
    },
    handlePrice() {
      getPrice().then((res) => {
        if (res.code == 200 && res.data) {
          this.$modal.msgSuccess("爬取数据成功");
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const data = { ...this.queryParams };
      delete data.pageNum;
      delete data.pageSize;
      this.newDownload(
        "whole_goods/exportList",
        data,
        `热销商品价格_${new Date().getTime()}.xlsx`
      );
    },
    /** 下载模板操作 */
    importTemplate() {
      this.newDownload(
        "whole_goods/importTemplate",
        {},
        `goods_template_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped>
.charts-box {
  height: 350px;
  margin-top: 30px;
}
.erpPrice > span {
  color: #409eff;
}
.iconEdit {
  cursor: pointer;
}
.app-container {
  padding-bottom: 50px;
}
</style>
