<template>
  <div>
    <el-card style="height: calc(100vh - 110px)" class="scroll">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="群组品号" prop="code">
          <el-input v-model="queryParams.code" placeholder="请输入群组品号" clearable size="small" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="群组品名" prop="nameChinese">
          <el-input v-model="queryParams.nameChinese" placeholder="请输入群组品名" clearable size="small" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <!-- <el-form-item label="品牌" prop="brandName">
          <el-select v-model="queryParams.brandName" placeholder="请选择品牌" size="small" @change="handleQuery">
            <el-option v-for="item in brandName" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="品号" prop="specCode">
          <el-input v-model="queryParams.specCode" placeholder="请输入品号" clearable size="small" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="品名" prop="colorNameChinese">
          <el-input v-model="queryParams.colorNameChinese" placeholder="请输入品名" clearable size="small" @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item>
          <el-button size="small" @click="handleQuery" class="searchBtn">搜索</el-button>
          <el-button size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" style="margin-bottom: 10px" v-if="!userInfo.subsidiaryId">
        <el-col :span="24">
          <el-button type="primary" size="mini" @click="handleAdd">添加产品</el-button>
          <!-- <el-button type="primary" size="mini" @click="importExcel" v-db-click>导入Excel</el-button>
          <el-button type="primary" size="mini" @click="historyManagement" v-db-click>导入历史管理</el-button> -->
        </el-col>
      </el-row>

      <el-table
        v-loading="loadingTable"
        :data="productList"
        size="small"
        :row-style="{ height: '35px' }"
        :cell-style="{ padding: '0' }"
        header-row-class-name="tableHeader"
      >
        <el-table-column label="" type="expand" width="50">
          <template slot-scope="scope">
            <div style="padding: 0px 20px; box-sizing: border-box">
              <div
                v-for="(color, index) in scope.row.colors"
                :key="index"
                style="display: flex; padding: 3px 10px; align-items: center; box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1); margin-bottom: 8px"
              >
                <div style="width: 80px">
                  <div v-if="color.colorAccessory">
                    <img
                      v-if="!color.colorAccessory.includes('https')"
                      style="width: 40px; height: 40px; object-fit: contain; vertical-align: middle; border: none; cursor: pointer"
                      :src="pathPrefix + color.colorAccessory"
                      @click="openFile(pathPrefix + color.colorAccessory)"
                    />
                    <img
                      v-else
                      style="width: 40px; height: 40px; object-fit: contain; vertical-align: middle; border: none; cursor: pointer"
                      :src="color.colorAccessory"
                      @click="openFile(color.colorAccessory)"
                    />
                  </div>
                  <div
                    v-else
                    class="el-icon-picture-outline"
                    style="width: 40px; height: 40px; font-size: 36px; line-height: 40px; text-align: center; color: rgb(229 228 228)"
                  ></div>
                </div>
                <div style="width: 140px">
                  {{ color.specCode }}
                </div>
                <div style="flex: 1">
                  {{ color.nameChinese }}
                </div>
                <div style="width: 160px">
                  {{ `${color.length}  *  ${color.width}  *  ${color.height}（cm³）` }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="群组品号" prop="code" width="120" />
        <el-table-column label="群组品名" min-width="220">
          <template slot-scope="scope">
            <div>
              <a style="color: #409eff; cursor: pointer" @click="clickProductName(scope.row)">{{ scope.row.nameChinese }}</a>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="品牌" prop="brandName" width="100" />
        <el-table-column label="型号" prop="productModelChinese" min-width="150" />
        <el-table-column label="材质" prop="materialChinese" min-width="150" />
        <el-table-column label="操作" align="center" width="100" fixed="right" v-if="!userInfo.subsidiaryId">
          <template slot-scope="scope">
            <el-button type="text" @click="handleUpdate(scope.row)" v-db-click>编辑</el-button>
            <el-button type="text" @click="handleDelete(scope.row)" v-db-click>删除</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" />
    </el-card>

    <!-- 添加或修改产品信息对话框 -->
    <el-dialog v-if="openProduct" :visible.sync="openProduct" width="98%" append-to-body>
      <Product :rowData="rowData" @clickCancel="clickCancel"></Product>
    </el-dialog>

    <!-- 产品详情 -->
    <el-dialog v-if="openDetails" :visible.sync="openDetails" width="98%" append-to-body>
      <ProductDetails :rowData="rowData" @clickCancel="clickCancelDetails"></ProductDetails>
    </el-dialog>

    <!-- 导入SKU  -->
    <el-dialog title="导入SKU" v-if="openImportExcel" :visible.sync="openImportExcel" style="margin-top: 15vh" width="30%" append-to-body>
      <div
        v-loading="loadingStatus"
        element-loading-text="导入中,请稍后"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.2)"
      >
        <el-row :gutter="10" style="margin-bottom: 15px">
          <el-col :span="1.5">
            <el-upload
              class="upload-demo"
              :action="actionProduct"
              :headers="{ 'Blade-Auth': 'bearer ' + token }"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-progress="excelProgress"
              :on-success="excelSuccess"
              :on-error="excelError"
              accept=".xlsx"
            >
              <el-button type="primary" size="mini">导入文件</el-button>
            </el-upload>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-tooltip placement="bottom" effect="light">
              <div slot="content">
                <div v-html="getStyle(errMsg)" style="max-height: 500px; overflow: auto; line-height: normal"></div>
              </div>
              <div style="cursor: pointer; color: #940819; overflow: hidden; white-space: nowrap; text-overflow: ellipsis">{{ errMsg }}</div>
            </el-tooltip>
          </el-col>
        </el-row>
        <div style="width: 100%; text-align: center; padding-top: 16px">
          <el-button @click="openImportExcel = false">取 消</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- SKU导入历史  -->
    <el-dialog title="SKU导入历史" v-if="openHistory" :visible.sync="openHistory" width="40%" style="margin-top: 15vh" append-to-body>
      <div
        v-loading="loadingVersion"
        element-loading-text="还原版本中,请稍后"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.2)"
      >
        <el-table
          :data="historyList"
          :cell-style="{ padding: '0' }"
          :row-style="{ height: '35px' }"
          header-row-class-name="tableHeader"
          v-loading="loadingHistory"
          border
        >
          <el-table-column label="版本时间" align="center" prop="createTime" />
          <el-table-column label="导入人" align="center" prop="userName" />
          <el-table-column label="操作" align="center" width="100" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="restoreVersion(scope.row)" v-db-click>还原版本</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="historyTotal > 0"
          :total="historyTotal"
          :page.sync="queryParamsTwo.pageNum"
          :limit.sync="queryParamsTwo.pageSize"
          @pagination="getHistoryList"
        />
        <div style="width: 100%; text-align: center; padding-top: 16px">
          <el-button type="primary" @click="openHistory = false">确 定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API from '@/api/shengde/product/groupSKU'
import { del } from '@/api/product/customProductLibrary'
import { mapGetters } from 'vuex'
import Product from './product'
import ProductDetails from './details'
import { versionList, versionListCount, backupVersion } from '@/api/shengde/group/order/orderManagement.js'

export default {
  name: 'groupSKU',
  components: { Product, ProductDetails },
  data() {
    return {
      pathPrefix: process.env.VUE_APP_IMG_URL,
      inputCategory: '',
      categoryTreeData: [],
      defaultProps: {
        children: 'children',
        label: 'text',
      },
      // 总条数
      total: 0,
      // 产品信息表格数据
      productList: [],
      loadingTable: false,
      // 是否显示弹出层
      openProduct: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: '',
        code: '',
        brandName: '',
        nameChinese: '',
        specCode: '',
        colorNameChinese: '',
        type: '',
        subsidiaryId: '',
        purchaseContractId: '',
      },
      fileData: [],
      rowData: {},
      openDetails: false,
      openImportExcel: false,
      actionProduct: process.env.VUE_APP_ACTION_PRODUCT_URL,
      loadingStatus: false,
      openHistory: false,
      loadingHistory: false,
      queryParamsTwo: {
        pageNum: 1,
        pageSize: 10,
        model: '1',
      },
      historyList: [],
      historyTotal: 0,
      loadingVersion: false,
    }
  },
  created() {},
  mounted() {
    this.getList()
  },
  computed: mapGetters(['dictData', 'userInfo', 'token']),
  methods: {
    handleNodeClick(data) {
      this.queryParams.pageNum = 1
      if (data.dictKey) {
        this.queryParams.categoryType = data.dictKey
        this.queryParams.categoryId = ''
      } else {
        this.queryParams.categoryType = ''
        this.queryParams.categoryId = data.id
      }
      this.getList()
    },
    /** 查询产品信息列表 */
    getList() {
      this.loadingTable = true
      API.getGroupList(this.queryParams).then(
        (response) => {
          this.total = response.data.data.total
          response.data.data.records = response.data.data.records.map((item) => {
            if (!item.subsidiaryPrice) {
              item.subsidiaryPrice = undefined
            }
            if (item.colors && item.colors.length > 0) {
              item.colors = item.colors.map((itemColors) => {
                itemColors.nameChinese = itemColors.nameChinese.replace(item.nameChinese + '  ： ', '')
                itemColors.nameChinese = itemColors.nameChinese.replace(item.nameChinese + '：', '')
                return {
                  ...itemColors,
                }
              })
            }
            return {
              ...item,
            }
          })
          this.productList = response.data.data.records
          this.loadingTable = false
        },
        (err) => {
          console.log('getGroupList: ' + err)
          this.loadingTable = false
        }
      )
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.rowData = {
        dataResource: 0,
      }
      this.openProduct = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.rowData = row
      this.openProduct = true
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除群组品名为"' + row.nameChinese + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          del({ id: row.id }).then(() => {
            this.msgSuccess('删除成功')
            this.getList()
          })
        })
        .catch(() => {})
    },
    clickProductName(row) {
      this.rowData = row
      this.openDetails = true
    },
    clickCancel(status) {
      this.openProduct = false
      if (status) {
        this.getList()
      }
    },
    clickCancelDetails() {
      this.openDetails = false
    },
    openFile(path) {
      window.open(path)
    },
    importExcel() {
      this.errMsg = ''
      this.openImportExcel = true
    },
    getStyle(text) {
      if (text) {
        return text.replace(/\n|\r\n/g, '<br>')
      } else {
        return ''
      }
    },
    beforeUpload(file) {
      this.errMsg = ''
      const isLt50M = file.size / 1024 / 1024 < 50
      if (!isLt50M) {
        this.$message.error('上传文件大小不能超过50MB!')
      }
      return isLt50M
    },
    excelProgress() {
      this.loadingStatus = true
    },
    excelSuccess(msg) {
      if (msg && msg.data) {
        this.msgSuccess('文件导入成功: ' + msg.data)
      } else {
        this.msgSuccess('文件导入成功')
      }
      this.loadingStatus = false
      this.openImportExcel = false
      this.getList()
    },
    excelError(err) {
      var res = JSON.parse(err.message)
      this.errMsg = '导入失败: ' + res.msg
      this.loadingStatus = false
    },
    historyManagement() {
      this.historyTotal = 0
      this.historyList = []
      this.queryParamsTwo = {
        pageNum: 1,
        pageSize: 10,
        model: '1',
      }
      this.loadingVersion = false
      this.openHistory = true
      this.getHistoryList()
    },
    getHistoryList() {
      this.loadingHistory = true
      versionList(this.queryParamsTwo).then(
        (res) => {
          this.historyList = res.data.data.list
          this.loadingHistory = false
        },
        (err) => {
          console.log('versionList:' + err)
          this.loadingHistory = false
        }
      )
      versionListCount(this.queryParamsTwo).then((res) => {
        this.historyTotal = res.data.data.count
      })
    },
    restoreVersion(row) {
      this.loadingVersion = true
      backupVersion({ id: row.id }).then(
        (res) => {
          this.msgSuccess('版本还原成功')
          this.loadingVersion = false
          this.openHistory = false
          this.getList()
        },
        (err) => {
          console.log('backupVersion: ' + err)
          this.loadingVersion = false
        }
      )
    },
  },
}
</script>

<style lang="scss" scoped>
/deep/ .el-tree-node__label {
  font-size: 12px !important;
}
* {
  font-size: 12px;
}
.el-tree {
  display: inline-block;
  min-width: 100%;
}
::v-deep {
  .el-input__inner {
    border-radius: 1px;
  }
  .el-button--mini {
    border-radius: 1px;
  }
  .tableHeader th {
    background-color: #edf0f5;
    height: 35px;
    padding: 0;
  }
  .el-dialog__footer {
    text-align: center;
    padding-bottom: 50px;
    .el-button {
      border-radius: 1px;
    }
  }
  .el-card__body {
    padding: 15px;
  }
  .el-table__cell {
    vertical-align: middle !important;
  }
  .el-input-number {
    .el-input__inner {
      text-align: left !important;
    }
  }
}
.box-card {
  height: calc(100vh - 50px - 50px - 10px);
  // overflow-y: auto;
}
.searchBtn {
  background: #20b2aa;
  color: #fff;
  border: 1px solid #20b2aa;
}
// 详情页需要加这个
/deep/ .el-dialog {
  margin: 0 auto;
  margin-top: 10px !important;
}
.scroll {
  overflow: hidden overlay !important;
  &::-webkit-scrollbar {
    width: 0px;
  }
  &:hover {
    &::-webkit-scrollbar {
      width: 7px;
    }
  }
}
</style>
