<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- 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="商品:" prop="skuNo">
        <el-input
          v-model="queryParams.skuNo"
          placeholder="请输入商品名称或编码"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="是否匹配ERP编码:" label-width="140px" prop="isBandSku">
        <el-select v-model="queryParams.isBandSku" placeholder="请选择" clearable>
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌:" prop="brandName">
        <el-select
          multiple
          v-model="queryParams.brandName"
          filterable
          placeholder="品牌"
          clearable
        >
          <el-option
            v-for="(dict, index) in brandNameList"
            :key="index"
            :label="dict.brandName"
            :value="dict.brandName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="电商平台:" label-width="90px" prop="platform">
        <el-select
          multiple
          v-model="platform"
          placeholder="电商平台"
          style="width: 220px"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_commerce_platform"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </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="primary" plain size="mini" @click="handlePrice"
          >爬取最新数据</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <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"
      :height="tableHeight"
      border
      v-loading="loading"
      :data="postList"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="品牌" width="160" align="center" prop="brandName">
        <template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">{{ scope.row.brandName }}</div>
            <div class="table-overflow">{{ scope.row.brandName }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <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="180" align="center" prop="attr">
        <template template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">{{ scope.row.attr }}</div>
            <div class="table-overflow">{{ scope.row.attr }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="规格" width="160" align="center" prop="specs">
        <template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">{{ scope.row.specs }}</div>
            <div class="table-overflow">{{ scope.row.specs }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="商品图片" width="100" align="center" prop="img">
        <template slot-scope="scope">
          <el-popover placement="top-start" title="" trigger="hover" v-if="scope.row.img">
            <img :src="scope.row.img" alt="" style="width: 150px; height: auto" />
            <img
              slot="reference"
              :src="scope.row.img"
              style="width: 40px; height: 40px"
            />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="ERP商品编码" align="center" prop="skuNo" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.skuNo }}</span>
          <i class="el-icon-edit iconEdit" @click="showBindSku(scope.row.id)"></i>
        </template>
      </el-table-column>
      <el-table-column label="ERP商品采购价" width="140" align="center" prop="postSort">
        <template slot-scope="scope">
          <div>{{ scope.row.erpPrice }}</div>
          <div
            class="erpPrice"
            v-for="(item, index) in scope.row.procureDetails"
            :key="index"
          >
            <span>采</span>{{ item.price }} <span>返</span>{{ item.rebatePrice }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        v-for="item in platform"
        :label="platformList[item]"
        align="center"
        prop="plat"
      >
        <template slot-scope="scope">
          {{ scope.row[platformList2[item]] }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="140"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="showChart(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="title" :visible.sync="open" width="1000px" append-to-body>
      <el-row>
        <el-col :span="20" style="height: 36px; line-height: 36px">
          <el-descriptions>
            <el-descriptions-item label="商品名称">{{
              chartRow.goodName
            }}</el-descriptions-item>
            <el-descriptions-item label="统计日期"
              ><el-date-picker
                v-model="dateRange"
                style="width: 240px"
                value-format="yyyyMMdd"
                :picker-options="pickerOptions"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker
            ></el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="4" style="height: 36px; line-height: 36px">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleChart"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetChart"
            >重置</el-button
          >
        </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="cancel('open')">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 关联商品 -->
    <el-dialog
      title="关联商品"
      :visible.sync="bindModal.open"
      width="450px"
      append-to-body
    >
      <el-form
        :model="bindForm"
        ref="bindForm"
        size="small"
        :inline="true"
        :rules="rules"
      >
        <el-form-item label="选择关联商品:" label-width="120px" prop="bindSkuNo">
          <!-- <el-select
            v-model="bindForm.bindSkuNo"
            remote
            :remote-method="skuNoFilter"
            filterable
            clearable
            placeholder="请输入商品名称或编码"
          >
            <el-option
              v-for="item in skuOptions"
              :key="item.skuNo"
              :label="item.skuName + '/' + item.skuNo"
              :value="item.skuNo"
            >
            </el-option>
          </el-select> -->
          <LoadMoreSelect :skuNo="bindForm.bindSkuNo" @queryParams="(val) => (bindForm.bindSkuNo = val)" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBindForm">确 定</el-button>
        <el-button @click="cancel('bindModal')">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPost, getPost, delPost, addPost, updatePost } from "@/api/system/post";
import {
  getList,
  getBrandNameList,
  getGoodsDetail,
  bindSku,
  getPrice,
} from "@/api/procure/index";
import LoadMoreSelect from "@/components/LoadMoreSelect/index";
import LineChart from "../../charts/LineChart";

export default {
  name: "Procure",
  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,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        skuNo: undefined,
        isBandSku: undefined,
        brandName: [],
      },
      bindForm: {
        bindSkuNo: "",
      },
      platform: ["ho", "jrc", "hy"],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        bindSkuNo: [{ 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",
      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() {
    if(this.$route.query.sku){
      this.queryParams.skuNo = this.$route.query.sku;
    }
    this.getList();
    this.getBrandNameList();
  },
  mounted() {},
  methods: {
    handleCheckedCitiesChange(value) {
      // let checkedCount = value.length;
      // this.checkAll = checkedCount === this.cities.length;
      // this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
      this.cities = value;
    },
    getBrandNameList() {
      getBrandNameList().then((res) => {
        this.brandNameList = res.data;
      });
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      getList(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.bindForm.bindSkuNo = '';
      this.bindModal = {
        open: true,
        id,
      };
    },
    // 取消按钮
    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);
    },
    handleChart() {
      this.getChart(this.chartRow);
    },
    resetChart() {
      this.dateRange = [];
    },
    getChart(row) {
      this.chartLading = true;
      const data = { id: row.id };
      if (this.dateRange && this.dateRange.length != 0) {
        data.startDate = this.dateRange[0];
        data.endDate = this.dateRange[1];
      } else {
        data.startDate = "";
        data.endDate = "";
      }
      (this.lineChartData = {
        xData: [],
        sData: [
          {
            name: "鸿欧",
            data: [],
          },
          {
            name: "吉瑞城",
            data: [],
          },
          {
            name: "惠友",
            data: [],
          },
        ],
      }),
        getGoodsDetail(data).then((res) => {
          if (res.data && res.data.length != 0) {
            res.data.forEach((item) => {
              this.lineChartData.xData.unshift(item.oprDate);
              this.lineChartData.sData[0].data.unshift(item.hoPrice || 0);
              this.lineChartData.sData[1].data.unshift(item.jrcPrice || 0);
              this.lineChartData.sData[2].data.unshift(item.hyPrice || 0);
            });
          }
          this.chartLading = false;
        });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.postId != undefined) {
            updatePost(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPost(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handlePrice() {
      getPrice().then((res) => {
        if (res.code == 200 && res.data) {
          this.$modal.msgSuccess("爬取数据成功");
        }
      });
    },
    submitBindForm() {
      this.$refs["bindForm"].validate((valid) => {
        if (valid) {
          bindSku({ id: this.bindModal.id, skuNo: this.bindForm.bindSkuNo }).then(
            (res) => {
              this.$modal.msgSuccess("绑定成功");
              this.bindModal.open = false;
              this.getList();
            }
          );
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const data = { ...this.queryParams };
      delete data.pageNum;
      delete data.pageSize;
      this.newDownload("procure/export", data, `选品池采购_${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>
