<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="130px"
    >
      <el-form-item label="湘商商品编码:" prop="skuNo">
        <el-input
          v-model="queryParams.skuNo"
          placeholder="请输入完整商品编码,多个用逗号隔开"
          clearable
        />
      </el-form-item>
      <el-form-item label="外部平台商品编码:" prop="platformSkuNo">
        <el-input
          v-model="queryParams.platformSkuNo"
          placeholder="请输入完整商品编码,多个用逗号隔开"
          clearable
        />
      </el-form-item>
      <el-form-item label="外部平台:" prop="platformName">
        <el-select v-model="queryParams.platformName" placeholder="请选择">
          <el-option v-for="item in platformList" :key="item.platformCode" :label="item.platformName" :value="item.platformName" />
        </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="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >批量删除</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 @selection-change="handleSelectionChange" ref="proTable" :height="tableHeight" border v-loading="loading" :data="postList">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="外部平台" min-width="120" align="center" prop="platformName" />
      <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="180" align="center" prop="skuNo">
        <template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">{{ scope.row.skuNo }}</div>
            <div class="table-overflow">{{ scope.row.skuNo }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="外部平台商品编码" min-width="180" align="center" prop="platformSkuNo">
        <template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">{{ scope.row.platformSkuNo }}</div>
            <div class="table-overflow">{{ scope.row.platformSkuNo }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="最后修改人" min-width="180" align="center" prop="updatedBy" />
      <el-table-column label="最后修改时间" min-width="180" align="center" prop="updatedTime" />
      <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="showDia(scope.row)"
            >编辑</el-button
          >
          <el-button size="mini" type="text" @click="handleDelete(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="500px"
      append-to-body
      destroy-on-close
    >
        <el-form ref="spuRef" :model="form" label-width="140px">
          <el-form-item label="湘商商品编码:"  :rules="[{ required: true, message: '请填写湘商商品编码', trigger: 'change' }]" prop="skuNo">
            <LoadMoreSelect :skuNo="formSkuNo" @queryParams="(val) => (form.skuNo = val)" @skuOptions="skuOptions" />
        </el-form-item>
        <el-form-item label="外部平台商品编码:" :rules="[{ required: true, message: '请填写外部平台商品编码', trigger: 'change' }]" prop="platformSkuNo">
          <el-input
            v-model="form.platformSkuNo"
            placeholder="最多20个字符"
            style="width: 220px;"
            clearable
          />
        </el-form-item>
        <el-form-item label="外部平台:"  :rules="[{ required: true, message: '请选择外部平台', trigger: 'change' }]" prop="platformName">
          <el-select v-model="form.platformName" placeholder="请选择">
            <el-option v-for="item in platformList" :key="item.platformCode" :label="item.platformName" :value="item.platformName" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="saveLoading" @click="submitDataScope">确 定</el-button>
        <el-button @click="open = fasle">取 消</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 {
  relationList,
  relationPlatformList,
  relationDelete,
  relationBatchDelete,
  relationAdd,
  relationUpdate
} from "@/api/goods/index";
import { getToken } from "@/utils/auth";
import LoadMoreSelect from "@/components/LoadMoreSelect/index";

export default {
  name: "GoodsWarehouse",
  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 + "/sku/relation/import",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        platformName: "",
        platformSkuNo: "",
        skuNo: "",
      },
      bindForm: {
        bindSkuNo: "",
      },
      formSkuNo: '',
      platformList: [],
      // 表单参数
      form: { 
        platformName: "",
        platformSkuNo: "",
        skuNo: ""
      },
      tableHeight: 'auto',
      saveLoading: false,
      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]);
            },
          },
        ],
      },
    };
  },
  watch:{
    showSearch(n,_){
      this.$nextTick(() => {
        const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 210;
        this.tableHeight = height+'px';
      });
    }
  },
  created() {
    this.relationPlatformList();
    this.getList();
  },
  mounted() {},
  methods: {
    relationPlatformList(){
      relationPlatformList({}).then(res=>{
        this.platformList = res.data;
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    handleDelete(row) {
      this.$modal.confirm('确认要删除选中数据吗？').then(() => {
        if(row&&row.id){
          relationDelete({id:row.id}).then(res=>{
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
        }else{
          relationBatchDelete({ids: this.ids}).then(res=>{
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
        }
        
      }).catch(() => {});
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      relationList(this.queryParams).then((response) => {
        this.postList = response.data.skuRelationListResDTOS;
        this.total = response.data.total;
        this.loading = false;

        this.$nextTick(() => {
          const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 210;
          this.tableHeight = height+'px';
        });
      }).catch(err=>{
        this.postList = [];
        this.total = 0;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = { 
        "platformName": "",
        "platformSkuNo": "",
        "skuNo": ""
      };
      this.resetForm("queryForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.formSkuNo = '';
      this.form = { 
        platformName: "",
        platformSkuNo: "",
        skuNo: ""
      };
      this.resetForm("spuRef");
      this.title = "新增外部商品映射";
      this.open = true;
    },
    /** 修改按钮操作 */
    showDia(row) {
      this.title = "编辑外部商品映射";
      this.formSkuNo = row.skuNo;
      this.form = JSON.parse(JSON.stringify(row));
      this.open = true;
    },
    // 文件上传中处理
    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();
    },
    skuOptions(val){
      const data = val.find(item=>{
        return item.skuNo == this.form.skuNo;
      });
      console.log(data)
      this.form.skuName = data.skuName;
    },
    submitDataScope() {

      this.$refs["spuRef"].validate((valid) => {
        if (valid) {
          this.saveLoading = true;
          if (this.title == "新增外部商品映射") {
            relationAdd(this.form).then((res) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.saveLoading = false;
            });
          } else {
            relationUpdate(this.form).then((res) => {
              this.$modal.msgSuccess("编辑成功");
              this.open = false;
              this.getList();
              this.saveLoading = false;
            });
          }
        }
      });
    },
    skuInfo() {},
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      const data = { ...this.queryParams };
      delete data.pageNum;
      delete data.pageSize;
      this.newDownload(
        "/sku/relation/export",
        data,
        `外部商品库_${new Date().getTime()}.xlsx`
      );
    },
    /** 下载模板操作 */
    importTemplate() {
      // this.newDownload(
      //   "spu/importTemplate",
      //   {},
      //   `spu_template_${new Date().getTime()}.xlsx`
      // );
      window.location.href = 'https://newfirst.oss-cn-shanghai.aliyuncs.com/sku_relation/%E5%B9%B3%E5%8F%B0%E5%95%86%E5%93%81%E5%85%B3%E8%81%94%E5%85%B3%E7%B3%BB%E6%A8%A1%E6%9D%BF.xlsx';
    },
  },
};
</script>
<style scoped>
.charts-box {
  height: 350px;
  margin-top: 30px;
}
.erpPrice > span {
  color: #409eff;
}
.iconEdit {
  cursor: pointer;
}
.app-container {
  padding-bottom: 50px;
}
</style>
