<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="品牌:" prop="brandName">
        <el-select
          v-model="queryParams.brandCode"
          filterable
          placeholder="品牌"
          clearable
        >
          <el-option
            v-for="(dict, index) in brandNameList"
            :key="index"
            :label="dict.brandName"
            :value="dict.brandCode"
          />
        </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 icon="el-icon-plus" size="mini" @click="handleAdd"
          >新增</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-upload2"
          size="mini"
          @click="handleImport"
          >导入</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="160" align="center" prop="spuName" />
      <el-table-column label="属性" width="360" align="center" prop="specs">
        <template slot-scope="scope">
          <div v-for="(item, index) in scope.row.attrs">
            {{ item.attrName }}:{{ item.attrValue }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建人" width="160" align="center" prop="createBy" />
      <el-table-column label="创建时间" width="160" align="center" prop="createTime" />
      <el-table-column label="更新人" width="160" align="center" prop="updateBy" />
      <el-table-column label="更新时间" width="160" align="center" prop="updateTime" />
      <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"
      top="50px"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form ref="spuRef" :model="form" label-width="120px">
        <el-form-item
          label="品牌:"
          :rules="[{ required: true, message: '请选择品牌', trigger: 'change' }]"
        >
          <el-select v-model="form.brandCode" filterable placeholder="品牌" clearable>
            <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="型号:"
          :rules="[{ required: true, message: '请输入型号名称', trigger: 'change' }]"
        >
          <el-input
            style="width: 220px"
            v-model="form.spuName"
            placeholder="请输入型号名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="销售属性:">
          <el-table ref="addTable" border v-loading="loading" :data="attrLists">
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <el-table-column label="属性名" align="center" prop="attrName" />
            <el-table-column
              label="属性值"
              min-width="360"
              align="center"
              prop="attrValue"
            />
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="showChart2(scope.row, scope.$index)"
                  >编辑</el-button
                >

                <el-button
                  size="mini"
                  type="text"
                  @click="removeAttr2(scope.row, scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-button type="text" icon="el-icon-plus" @click="handleAdd2">新增</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDataScope">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="title2"
      top="50px"
      :visible.sync="attrOpen"
      width="500px"
      append-to-body
    >
      <el-form :model="form2" label-width="120px">
        <el-form-item
          label="属性名称:"
          :rules="[{ required: true, message: '请输入属性名称', trigger: 'change' }]"
        >
          <el-input v-model="form2.attrName" placeholder="请输入属性名称" clearable />
        </el-form-item>
        <el-form-item label="属性值:">
          <el-input
            v-for="(item, index) in form2.attrValue"
            v-model="item.name"
            placeholder="请输入属性值"
            clearable
            style="margin-bottom: 8px"
          >
            <el-button
              v-if="index > 0"
              @click="removeAttr(form2.attrValue, index)"
              slot="append"
              icon="el-icon-remove"
            ></el-button>
          </el-input>
          <el-button type="text" icon="el-icon-plus" @click="handleAdd3(form2.attrValue)"
            >添加属性值</el-button
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addAttritem">确 定</el-button>
        <el-button @click="attrOpen = 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 { getList, getBrandNameList, spuList, spuAdd, spuUpdate } from "@/api/goods/index";
import { getToken } from "@/utils/auth";
import LoadMoreSelect from "@/components/LoadMoreSelect/index";

export default {
  name: "SpuList",
  components: {
    LoadMoreSelect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      spuList: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API_NEW + "/spu/import",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        brandCode: "",
      },
      bindForm: {
        bindSkuNo: "",
      },
      platform: ["1", "2", "3"],
      // 表单参数
      form: { brandCode: "", spuName: "" },
      form2: { attrName: "", attrValue: [{ name: "" }] },
      // 表单校验
      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,
      attrOpen: false,
      title2: "",
      chartLading: true,
      loadDataStatus: true,
      tableHeight: "auto",
      attrLists: [],
      attrList: [],
      attrRow: {},
      attrListsIndex: 1,
      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.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) {
    //     getSpuList([value]).then((res) => {
    //       this.spuList = res.data;
    //     });
    //   } else {
    //     this.spuList = [];
    //   }
    // },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      spuList(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();
          // }
        });
      });
    },
    // 表单重置
    reset() {
      this.form = { brandCode: "", spuName: "" };
      this.attrLists = [];
      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.title = "编辑型号";
      this.form = row;
      this.attrLists = row.attrs || [];
    },
    showChart2(row, index) {
      this.attrOpen = true;
      this.title2 = "编辑属性";
      this.form2.attrName = row.attrName;
      this.form2.attrValue = [];
      row.attrValue.split(",").forEach((i) => {
        this.form2.attrValue.push({ name: i });
      });
      this.attrListsIndex = index;
    },
    handleAdd2() {
      this.form2 = {
        attrName: "",
        attrValue: [],
      };
      this.attrOpen = true;
      this.title2 = "新增属性";
    },
    handleAdd3(value) {
      value.push({ name: "" });
    },
    removeAttr(value, index) {
      value.splice(index, 1);
    },
    removeAttr2(value, index) {
      this.attrLists.splice(index, 1);
    },
    addAttritem() {
      let status = true;
      const attrValues = [];
      this.form2.attrValue.forEach((item) => {
        if (item.name == "") {
          this.$message.warning("请填写属性值");
          status = false;
          return false;
        }
        attrValues.push(item.name);
      });
      if (!status) {
        return false;
      }
      if (this.title2 == "编辑属性") {
        this.$set(this.attrLists, this.attrListsIndex, {
          attrName: this.form2.attrName,
          attrValue: attrValues.join(","),
        });
        this.attrLists[this.attrListsIndex] = {
          attrName: this.form2.attrName,
          attrValue: attrValues.join(","),
        };
      } else {
        this.attrLists.push({
          attrName: this.form2.attrName,
          attrValue: attrValues.join(","),
        });
      }

      this.attrOpen = false;
    },
    // 文件上传中处理
    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();
    },
    submitDataScope() {
      this.$refs["spuRef"].validate((valid) => {
        if (valid) {
          let attrs = [];
          this.attrLists.forEach((items) => {
            const arr1 = [];
            items.attrValue.split(",").forEach((item) => {
              arr1.push({ attrName: items.attrName, attrValue: item });
            });
            attrs = attrs.concat(arr1);
          });
          if (this.title == "新增型号") {
            spuAdd({
              spuName: this.form.spuName,
              brandCode: this.form.brandCode,
              attrs: attrs,
            }).then((res) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          } else {
            spuUpdate({
              id: this.form.id,
              spuName: this.form.spuName,
              brandCode: this.form.brandCode,
              attrs: attrs,
            }).then((res) => {
              this.$modal.msgSuccess("编辑成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    skuInfo() {},
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      const data = { ...this.queryParams };
      delete data.pageNum;
      delete data.pageSize;
      this.newDownload(
        "/spu/exportList?brandCode=" + this.queryParams.brandCode,
        data,
        `商品_${new Date().getTime()}.xlsx`
      );
    },
    /** 下载模板操作 */
    importTemplate() {
      this.newDownload(
        "spu/importTemplate",
        {},
        `spu_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>
