<template>
  <div>
    <el-row style="padding-top: 0">
      <el-col :span="24">
        <el-card style="height: calc(100vh - 110px)" class="scroll">
          <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
            <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" style="width: 100%" @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="mini" @click="handleQuery" class="searchBtn">搜索</el-button>
              <el-button size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" style="margin-bottom: 10px" v-show="showSearch">
            <el-col :span="24">
              <el-button type="primary" size="mini" @click="handleAdd" v-if="!userInfo.subsidiaryId">添加产品</el-button>
              <el-button type="primary" size="mini" @click="handleSynchronization" v-db-click>SKU同步</el-button>
              <el-button type="primary" size="mini" @click="batchModification" v-if="userInfo.subsidiaryId">批量修改</el-button>
              <el-button type="primary" size="mini" @click="openOperationLog = true" v-db-click>操作日志</el-button>
            </el-col>
          </el-row>
          <div style="margin-bottom: 15px" v-if="selectStatus"></div>

          <div style="width: 100%; position: relative">
            <el-table
              v-loading="loadingTable"
              :data="productList"
              size="small"
              :row-style="{ height: '35px' }"
              :cell-style="{ padding: '0' }"
              header-row-class-name="tableHeader"
              :default-expand-all="selectStatus"
            >
              <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="color.id"
                      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: 80px" v-if="userInfo.subsidiaryId">
                        <div v-if="color.designSketch">
                          <img
                            v-if="!color.designSketch.includes('https')"
                            style="width: 40px; height: 40px; object-fit: contain; vertical-align: middle; border: none; cursor: pointer"
                            :src="pathPrefix + color.designSketch"
                            @click="openFile(pathPrefix + color.designSketch)"
                          />
                          <img
                            v-else
                            style="width: 40px; height: 40px; object-fit: contain; vertical-align: middle; border: none; cursor: pointer"
                            :src="color.designSketch"
                            @click="openFile(color.designSketch)"
                          />
                        </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 style="width: 60px; text-align: center" v-if="selectStatus">
                        <el-button type="text" @click="handleSelect(scope.row, index)" v-db-click>选择</el-button>
                      </div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <!-- <el-table-column label="图片" width="80">
          <template slot-scope="scope">
            <div v-if="scope.row.pic">
              <img
                v-if="!scope.row.pic.includes('https')"
                style="width: 50px; height: 50px; object-fit: contain; vertical-align: middle; border: none; padding: 8px 0; cursor: pointer"
                :src="pathPrefix + scope.row.pic"
                @click="openFile(pathPrefix + scope.row.pic)"
              />
              <img
                v-else
                style="width: 50px; height: 50px; object-fit: contain; vertical-align: middle; border: none; padding: 8px 0; cursor: pointer"
                :src="scope.row.pic"
                @click="openFile(scope.row.pic)"
              />
            </div>
          </template>
        </el-table-column> -->
              <el-table-column label="归属单位" prop="subsidiaryName" width="120" v-if="userInfo.subsidiaryId">
                <template slot-scope="scope">
                  <span v-if="scope.row.subsidiaryName">{{ scope.row.subsidiaryName }}</span>
                  <span v-else>胜德集团</span>
                </template>
              </el-table-column>
              <el-table-column label="群组品号" prop="code" width="120"> </el-table-column>
              <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="产品来源" width="100" v-if="!selectStatus">
                <template slot-scope="scope">
                  <span v-if="scope.row.dataResource == 0">MES</span>
                  <span v-else>万里牛</span>
                </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="120" fixed="right" v-if="!selectStatus">
                <template slot-scope="scope">
                  <div>
                    <el-button
                      type="text"
                      v-if="!userInfo.subsidiaryId || (userInfo.subsidiaryId && userInfo.subsidiaryId === scope.row.subsidiaryId)"
                      @click="handleUpdate(scope.row)"
                      v-db-click
                      >编辑</el-button
                    >
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改产品信息对话框 -->
    <el-dialog v-if="openProduct" :visible.sync="openProduct" width="98%" append-to-body :close-on-click-modal="false">
      <ProductOne v-if="rowData.dataResource === 1 || userInfo.subsidiaryId" :rowData="rowData" @clickCancel="clickCancel"></ProductOne>
      <Product v-else :rowData="rowData" @clickCancel="clickCancel"></Product>
    </el-dialog>

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

    <!-- SKU同步 -->
    <el-dialog
      title="SKU同步"
      v-if="openSynchronization"
      :visible.sync="openSynchronization"
      width="30%"
      append-to-body
      v-loading="loadingSynchronizationStatus"
      element-loading-text="数据同步中,请稍后"
      element-loading-background="rgba(0, 0, 0, 0.2)"
    >
      <el-form ref="ruleForm" :model="synchronization" :rules="synchronizationRules" label-width="80px">
        <el-form-item label="SKU品号:" prop="spec_code">
          <el-input v-model="synchronization.spec_code" size="small" placeholder="请输入SKU品号" />
        </el-form-item>
        <div style="width: 100%; text-align: center; padding: 16px 0">
          <el-button type="primary" @click="clickSynchronizationSubmit()" size="small" v-db-click>提 交</el-button>
          <el-button @click="openSynchronization = false" size="small" v-db-click>取 消</el-button>
        </div>
      </el-form>
    </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=".xls"
            >
              <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>

    <el-dialog title="操作日志" v-if="openOperationLog" :visible.sync="openOperationLog" width="50%" append-to-body>
      <OperationLog :operationLogKey="operationLogKey"></OperationLog>
      <div style="text-align: center; margin-top: 20px">
        <el-button @click="openOperationLog = false" v-db-click>关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="SKU批量修改" v-if="openModification" :visible.sync="openModification" width="90%" append-to-body>
      <BatchModification></BatchModification>
      <div style="text-align: center; margin-top: 20px">
        <el-button @click="openModification = false" v-db-click>关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API from '@/api/product/customProductLibrary'
// import { productCategoryList } from '@/api/product/productCategories'
import { mapGetters } from 'vuex'
import Product from '@/views/AddOrModifiedProduct/Product'
import ProductOne from '@/views/AddOrModifiedProduct/ProductOne'
import ProductDetails from '@/views/shengde/product/management/details'
import { getDetail } from '@/api/shengde/group/subcompany/subcompanyManagement/index.js'
import OperationLog from '@/components/shengde/operationLog/index'
import BatchModification from './batchModification'

export default {
  name: 'ProductManagement',
  components: { Product, ProductOne, ProductDetails, OperationLog, BatchModification },
  props: {
    selectStatus: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: '',
    },
    subsidiaryId: String,
    purchaseContractId: String,
  },
  data() {
    return {
      value: '',
      btnDisabled: false,
      pathPrefix: process.env.VUE_APP_IMG_URL,
      inputCategory: '',
      categoryTreeData: [],
      defaultProps: {
        children: 'children',
        label: 'text',
      },
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品信息表格数据
      productList: [],
      loadingTable: false,
      // 是否显示弹出层
      openProduct: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: '',
        code: '',
        brandName: '',
        nameChinese: '',
        specCode: '',
        colorNameChinese: '',
        type: '',
        subsidiaryId: '',
        purchaseContractId: '',
      },
      // 表单参数
      form: {
        attachments: [],
        materials: [],
      },
      fileData: [],
      loadingStatus: false,
      rowData: {},
      openDetails: false,
      subsidiaryData: [{ id: '0', name: '集团' }],
      brandName: [],
      openSynchronization: false,
      synchronization: {
        page: 0,
        limit: 1,
        modify_time: 965381503,
        spec_code: '',
      },
      synchronizationRules: {
        spec_code: [{ required: true, message: '请输入SKU品号', trigger: 'blur' }],
      },
      loadingSynchronizationStatus: false,
      errMsg: '',
      openImportExcel: false,
      actionProduct: process.env.VUE_APP_ACTION_PRODUCT_URL,
      openOperationLog: false,
      operationLogKey: 20,
      openModification: false,
    }
  },
  created() {
    if (this.userInfo.subsidiaryId) {
      getDetail({ id: this.userInfo.subsidiaryId }).then((res) => {
        let brandNameArr = []
        if (res.data.data.brandName) {
          brandNameArr = res.data.data.brandName.split(',')
        }
        let data = this.dictData.filter((item) => item.code === 'brand_name')
        if (data && data.length > 0) {
          if (this.type) {
            let skuList = [
              {
                dictKey: '胜德科技',
                dictValue: '胜德科技',
              },
            ]
            this.brandName = skuList.concat(
              data[0].children.filter((item) => {
                return brandNameArr.some((i) => item.dictKey == i)
              })
            )
          } else {
            this.brandName = data[0].children.filter((item) => {
              return brandNameArr.some((i) => item.dictKey == i)
            })
          }
        }
      })
    } else {
      let data = this.dictData.filter((item) => item.code === 'brand_name')
      if (data && data.length > 0) {
        this.brandName = data[0].children
      }
    }
  },
  mounted() {
    if (this.type) {
      this.queryParams.type = this.type
    }
    this.getList()
  },
  computed: mapGetters(['menuAll', 'token', 'dictData', 'userInfo']),
  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() {
      if (this.subsidiaryId) {
        this.queryParams.subsidiaryId = this.subsidiaryId
        if (this.purchaseContractId) {
          this.queryParams.purchaseContractId = this.purchaseContractId
        }
        this.loadingTable = true
        API.getListStock(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('getListStock: ' + err)
            this.loadingTable = false
          }
        )
      } else {
        this.loadingTable = true
        API.list(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('list: ' + err)
            this.loadingTable = false
          }
        )
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      // this.queryParams.categoryId = ''
      // this.$refs.treeCategory.setCurrentKey(null)
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.rowData = {
        dataResource: 0,
      }
      this.openProduct = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.rowData = row
      this.openProduct = true
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除群组品名为"' + row.nameChinese + ' (' + row.nameEnglish + ')' + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return API.del({ id: row.id })
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '删除成功',
          })
          this.queryParams.pageNum = 1
          this.getList()
        })
    },
    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)
    },
    handleSelect(row, index) {
      this.$emit('handleSelect', row, index)
    },
    handleSynchronization() {
      this.loadingSynchronizationStatus = false
      this.synchronization.spec_code = ''
      this.openSynchronization = true
    },
    clickSynchronizationSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loadingSynchronizationStatus = true
          API.importSpec(this.synchronization).then(
            () => {
              this.openSynchronization = false
              this.loadingSynchronizationStatus = false
              this.getList()
            },
            (err) => {
              console.log('importSpec: ' + err)
              this.loadingSynchronizationStatus = false
            }
          )
        }
      })
    },
    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
    },
    batchModification() {
      this.openModification = true
    },
  },
}
</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>
