<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <!-- 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="sku">
        <el-input
          v-model="queryParams.sku"
          placeholder="请输入完整商品编码,多个用逗号隔开"
          clearable
        />
      </el-form-item>
      <el-form-item label="商品名称:" prop="skuName">
        <el-input
          v-model="queryParams.skuName"
          placeholder="请输入商品名称关键字"
          clearable
        />
      </el-form-item>
      <el-form-item label="状态:" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择">
          <el-option label="启用" :value="0" />
          <el-option label="停用" :value="1" />
        </el-select>
      </el-form-item>

      <el-form-item label="品牌:" prop="brandNo">
        <el-select
          v-model="queryParams.brandNo"
          filterable
          placeholder="品牌"
          clearable
          multiple
          @change="brandChange"
        >
          <el-option
            v-for="(dict, index) in brandNameList"
            :key="index"
            :label="dict.brandName"
            :value="dict.brandCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="型号:" prop="platform">
        <el-select
          v-model="queryParams.spu"
          multiple
          filterable
          placeholder="型号"
          clearable
        >
          <el-option
            v-for="(dict, index) in spuList"
            :key="index"
            :label="dict.spuName"
            :value="dict.spuNo"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标签:" prop="tags">
        <!-- multiple -->
        <el-select v-model="queryParams.tags" multiple placeholder="标签" clearable>
          <el-option
            v-for="dict in dict.type.goods_tag"
            :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="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="商品编码" align="center" prop="sku" min-width="140">
        <template slot-scope="scope">
          <span>{{ scope.row.sku }}</span>
        </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="140" align="center" prop="brand">
        <template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">{{ scope.row.brand }}</div>
            <div class="table-overflow">{{ scope.row.brand }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="型号" min-width="140" align="center" prop="spuName">
        <template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">{{ scope.row.spuName }}</div>
            <div class="table-overflow">{{ scope.row.spuName }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="120" align="center" prop="status">
        <template slot-scope="scope">
          {{ scope.row.status == 0 ? "启用" : "停用" }}
        </template>
      </el-table-column>
      <el-table-column
        label="上市时间"
        min-width="160"
        align="center"
        prop="marketDate"
      />
      <el-table-column
        label="建档时间"
        min-width="160"
        align="center"
        prop="filingTime"
      />
      <el-table-column label="标签" width="120" align="center" prop="tag">
        <template slot-scope="scope">
          <span v-if="scope.row.tag != null">{{
            scope.row.tag == 0 ? "常规品" : scope.row.tag == 1 ? "资源品" : "滞销品"
          }}</span>
        </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="编辑商品"
      top="50px"
      :visible.sync="open"
      width="600px"
      append-to-body
    >
      <el-form ref="bindForm" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="商品编码:">
          <el-input v-model="form.sku" :disabled="true" />
        </el-form-item>
        <el-form-item label="商品名称:">
          <el-input v-model="form.skuName" :disabled="true" />
        </el-form-item>
        <el-form-item label="品牌:">
          <el-input v-model="form.brand" :disabled="true" />
        </el-form-item>

        <el-form-item label="建档时间:">
          <el-date-picker
            v-model="form.filingTime"
            :disabled="true"
            type="datetime"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="型号:"  prop="spuId">
          <el-select
            v-model="form.spuId"
            @change="changeSpu"
            filterable
            placeholder="型号"
            clearable
            prop="spuId"
          >
            <el-option
              v-for="(dict, index) in spuList2"
              :key="index"
              :label="dict.spuName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <div v-for="(item, index) in attrList">
            {{ item.name }}:
            <el-radio v-for="it in item.attrValue" v-model="item.checked" :label="it">{{
              it
            }}</el-radio>
          </div>
        </el-form-item>
        <el-form-item label="商品标签:" prop="tag">
          <el-select v-model="form.tag" clearable filterable placeholder="商品标签">
            <el-option
              v-for="dict in dict.type.goods_tag"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="资源品生效时间:" v-if="form.tag == 1 || form.tag == 2">
          <el-date-picker
            v-model="form.dateRange"
            :picker-options="pickerOptions"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="滞销品生效时间:" v-if="form.tag == 1 || form.tag == 2">
          <el-date-picker
            v-model="form.dateRange1"
            :picker-options="pickerOptions"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="上市时间:" prop="marketDate">
          <el-date-picker
            v-model="form.marketDate"
            type="datetime"
            placeholder="选择日期"
            :clearable="true"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBindForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getBrandNameList, getList, getPrice, getSpuList, skuInfo, spuAttr,} from "@/api/goods/index";
import LoadMoreSelect from "@/components/LoadMoreSelect/index";

export default {
  name: "Index",
  dicts: ["sys_yes_no", "goods_tag"],
  components: {
    LoadMoreSelect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      attrList: {},
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        spuId: "",
        sku: "",
        skuName: "",
        brandNo: [],
        spu: [],
        status: 0,
        tags: [],
      },
      platform: ["0", "1", "2"],
      // 表单参数
      form: {
        id: 0,
        skuName: "",
        sku: "",
        spuId: "",
        tag: 0,
        resourceStartTime: "",
        resourceEndTime: "",
        unsalableStartTime: "",
        unsalableEndTime: "",
        colour: "",
        capacity: "",
        marketDate: "",
        dateRange: [],
        dateRange1: [],
      },
      // 表单校验
      rules: {
        spuId: [{ required: true, message: "型号不能为空", trigger: "change" }],
        tag: [{ required: true, message: "标签不能为空", trigger: "change" }],
        // marketDate: [{ required: true, message: "请选择上市时间", trigger: "blur" }],
      },
      skuOptions: [],
      skuPageNum: 1,
      platformList: {
        ho: "鸿欧",
        jrc: "吉瑞城",
        hy: "惠友",
      },
      platformList2: {
        ho: "hoPrice",
        jrc: "jrcPrice",
        hy: "hyPrice",
      },
      checkedGroup: ["鸿欧", "吉瑞城", "惠友"],
      dateRange: [],
      brandNameList: [],
      spuList: [],
      spuList2: [],
      bindModal: {
        open: false,
        id: "",
      },
      chartRow: { goodName: "" },
      timer: null,
      chartLading: true,
      loadDataStatus: true,
      tableHeight: "auto",
      pickerOptions: {
        shortcuts: [
          {
            text: "最近三天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit("pick", [end, start]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [end, start]);
            },
          },
          {
            text: "最近半个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
              picker.$emit("pick", [end, start]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [end, start]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [end, start]);
            },
          },
        ],
      },
    };
  },
  created() {
    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;
      });
    },
    brandChange(value) {
      if (value.length != 0) {
        getSpuList(value).then((res) => {
          this.spuList = res.data;
        });
      } else {
        this.spuList = [];
      }
    },
    changeSpu(value) {
      const arr = this.spuList2.filter((item) => {
        return item.id == value;
      });
      if(arr.length === 0) return false;
      spuAttr({ spuNo: arr[0].spuNo }).then((res) => {
        this.attrList = [];
        const datas = [];
        for (var i = 0; i < res.data.length; i++) {
          var n = datas.indexOf(res.data[i].attrName);
          if (n == -1) {
            datas.push(res.data[i].attrName);
            this.attrList.push({
              name: res.data[i].attrName,
              attrValue: [res.data[i].attrValue],
              checked:
                res.data[i].attrName == "颜色" ? this.form.colour : this.form.capacity,
            });
          } else {
            this.attrList[n].attrValue.push(res.data[i].attrValue);
          }
        }
        console.log(this.attrList);
      });
    },
    /** 查询岗位列表 */
    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();
          // }
        });
      });
    },
    // 取消按钮
    cancel(type) {
      if (type == "open") {
        this.open = false;
        this.reset();
      } else {
        this.bindModal.open = false;
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: 0,
        skuName: "",
        sku: "",
        spuId: "",
        tag: 0,
        resourceStartTime: "",
        resourceEndTime: "",
        unsalableStartTime: "",
        unsalableEndTime: "",
        colour: "",
        capacity: "",
        marketDate: "",
        dateRange: [],
        dateRange1: [],
      };
      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.form = Object.assign(this.form, JSON.parse(JSON.stringify(row)));
      if (row.resourceStartTime) {
        this.form.dateRange = [row.resourceStartTime, row.resourceEndTime];
      } else {
        this.form.dateRange = [];
      }
      if (row.unsalableStartTime) {
        this.form.dateRange1 = [row.unsalableStartTime, row.unsalableEndTime];
      } else {
        this.form.dateRange1 = [];
      }
      if (row.marketDate) {
        this.form.marketDate = row.marketDate;
      } else {
        this.form.marketDate = "";
      }
      this.form.tag = this.form.tag != null ? this.form.tag + "" : "0";

      getSpuList([row.brandNo]).then((res) => {
        this.spuList2 = res.data;
        res.data.forEach((item) => {
          if (item.spuName == this.form.spuName) {
            this.form.spuId = item.id;
          }
        });
        this.changeSpu(this.form.spuId);
      });
    },
    resetChart() {
      this.dateRange = [];
    },
    handlePrice() {
      getPrice().then((res) => {
        if (res.code == 200 && res.data) {
          this.$modal.msgSuccess("爬取数据成功");
        }
      });
    },
    submitBindForm() {
      this.$refs["bindForm"].validate((valid) => {
        if (valid) {
          if (this.form.dateRange) {
            this.form.resourceStartTime = this.form.dateRange[0];
            this.form.resourceEndTime = this.form.dateRange[1];
          } else {
            this.form.resourceStartTime = "";
            this.form.resourceEndTime = "";
          }
          if (this.form.dateRange1) {
            this.form.unsalableStartTime = this.form.dateRange1[0];
            this.form.unsalableEndTime = this.form.dateRange1[1];
          } else {
            this.form.unsalableStartTime = "";
            this.form.unsalableEndTime = "";
          }

          //校验时间重叠
          if (this.form.resourceStartTime != "" && this.form.unsalableStartTime != "") {
            const ranges = [
              [this.form.resourceStartTime, this.form.resourceEndTime],
              [this.form.unsalableStartTime, this.form.unsalableEndTime],
            ];

            const isOverlap = this.checkTimeRangesOverlap(ranges);
            if (isOverlap) {
              this.$message.warning("资源品与滞销品时间有重叠,请重新选择");
              return false;
            }
          }
          const attrs = [];
          this.attrList.forEach((item) => {
            attrs.push({
              attrName: item.name,
              attrValue: item.checked,
            });
          });
          this.form.attrs = attrs;

          const spuDatas = this.spuList2.find((item) => {
            return item.id == this.form.spuId;
          });
          this.form.spuNo = spuDatas.spuNo;
          this.form.spuName = spuDatas.spuName;
          skuInfo(this.form).then((res) => {
            this.$message.success("编辑成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const data = { ...this.queryParams };
      delete data.pageNum;
      delete data.pageSize;
      this.newDownload("sku/exportManageList", data, `商品_${new Date().getTime()}.xlsx`);
    },
    // 数组的情况
    checkTimeRangesOverlap(ranges) {
      // 将时间段按照开始时间排序
      const sortedRanges = ranges.slice().sort((a, b) => a[0] - b[0]);

      // 检查时间段是否重叠
      for (let i = 1; i < sortedRanges.length; i++) {
        if (sortedRanges[i][0] < sortedRanges[i - 1][1]) {
          return true;
        }
      }
      // 所有时间段都没有重叠
      return false;
    },
  },
};
</script>
<style scoped>
.charts-box {
  height: 350px;
  margin-top: 30px;
}
.erpPrice > span {
  color: #409eff;
}
.iconEdit {
  cursor: pointer;
}
.app-container {
  padding-bottom: 50px;
}
</style>
