<template>
  <div v-loading="loadingStatus" element-loading-text="获取数据中,请稍后" element-loading-background="rgba(0, 0, 0, 0.2)">
    <el-row style="padding-top: 0">
      <el-col :span="4">
        <el-card style="height: calc(100vh - 110px); margin-right: 10px">
          <el-input v-model="inputCategory" placeholder="请输入产品分类" size="small" clearable></el-input>
          <div style="margin-top: 15px; height: calc(100vh - 170px)" class="scroll">
            <el-tree
              ref="treeCategory"
              :data="categoryTreeData"
              :props="defaultProps"
              node-key="id"
              default-expand-all
              :expand-on-click-node="false"
              :filter-node-method="treeCategory"
              @node-click="handleNodeClick"
            ></el-tree>
          </div>
        </el-card>
      </el-col>
      <el-col :span="20">
        <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="nameChinese">
              <el-input v-model="queryParams.nameChinese" placeholder="请输入群组品名" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="BOM品号" prop="bomColorSpecCode">
              <el-input v-model="queryParams.bomColorSpecCode" placeholder="请输入BOM品号" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="BOM品名" prop="bomColorName">
              <el-input v-model="queryParams.bomColorName" placeholder="请输入BOM品名" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="种类" prop="generalCategory">
              <el-select v-model="queryParams.generalCategory" placeholder="请选择种类" size="small" @change="handleQuery">
                <el-option v-for="item in generalCategory" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
              </el-select>
            </el-form-item>
            <el-form-item label="色层" prop="chromatogram">
              <el-select v-model="queryParams.chromatogram" placeholder="请选择色层" size="small" @change="handleQuery">
                <el-option v-for="item in chromatogram" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
              </el-select>
            </el-form-item>
            <el-form-item label="压纹工艺" prop="formula">
              <el-select v-model="queryParams.formula" placeholder="请选择压纹工艺" size="small" @change="handleQuery">
                <el-option v-for="item in formula" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
              </el-select>
            </el-form-item>
            <el-form-item label="正面纹路" prop="frontalGrain">
              <el-select v-model="queryParams.frontalGrain" placeholder="请选择正面纹路" size="small" @change="handleQuery">
                <el-option v-for="item in frontalGrain" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
              </el-select>
            </el-form-item>
            <el-form-item label="背面纹路" prop="reverseGrain">
              <el-select v-model="queryParams.reverseGrain" placeholder="请选择背面纹路" size="small" @change="handleQuery">
                <el-option v-for="item in reverseGrain" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
              </el-select>
            </el-form-item>
            <el-form-item label="颜色" prop="color">
              <el-input v-model="queryParams.color" 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-if="!selectStatus">
            <el-button type="primary" size="mini" @click="handleAdd">添加BOM</el-button>
          </el-row>

          <div style="width: 100%; position: relative">
            <div style="position: absolute; right: 0; top: -34px; width: 120px; text-align: center">
              <el-button type="primary" size="mini" @click="openOperationLog = true" v-db-click>操作日志</el-button>
            </div>
            <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>
                    <el-table
                      :data="scope.row.bomColors"
                      size="small"
                      :row-style="{ height: '35px' }"
                      :cell-style="{ padding: '0' }"
                      header-row-class-name="tableHeader"
                      :show-header="false"
                    >
                      <el-table-column width="150" align="center" />
                      <el-table-column label="设计图" width="100">
                        <template slot-scope="scope">
                          <div v-if="scope.row.magPath">
                            <img
                              style="width: 32px; height: 32px; object-fit: contain; vertical-align: middle; border: none; cursor: pointer; margin-bottom: 8px"
                              :src="pathPrefix + scope.row.magPath"
                              @click="openFile(pathPrefix + scope.row.magPath)"
                            />
                          </div>
                        </template>
                      </el-table-column>
                      <el-table-column label="品号" prop="specCode" width="200" />
                      <el-table-column label="品名" prop="nameChinese" />
                      <el-table-column label="单品尺寸(L*W*H)" prop="specCode" width="240">
                        <template slot-scope="scope">
                          <span>{{ `${scope.row.productLong} * ${scope.row.productWide} * ${scope.row.productHigh}` }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" prop="weight" width="80" v-if="selectStatus">
                        <template slot-scope="sonScope">
                          <div>
                            <el-button type="text" @click="selectBOM(scope.row, sonScope.$index)" v-db-click>选择</el-button>
                          </div>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </template>
              </el-table-column>
              <!-- <el-table-column label="图片" width="100">
                <template width="90" slot-scope="scope">
                  <img
                    v-if="scope.row.pic"
                    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)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="群组品号" prop="code" width="160" /> -->
              <el-table-column label="群组品名" min-width="200">
                <template slot-scope="scope">
                  <span style="color: #409eff; cursor: pointer" @click="clickProductName(scope.row)">{{ scope.row.nameChinese }}</span>
                </template>
              </el-table-column>
              <el-table-column label="项目小类" width="120" :formatter="projectTypeFormat" />
              <el-table-column label="种类" width="120" :formatter="generalCategoryFormat" />
              <el-table-column label="色层" width="120" :formatter="chromatogramFormat" />
              <el-table-column label="压纹工艺" width="120" :formatter="formulaFormat" />
              <el-table-column label="正面纹路" width="120" :formatter="frontalGrainFormat" />
              <el-table-column label="背面纹路" width="120" :formatter="reverseGrainFormat" />
              <!-- <el-table-column label="报价规则名称" prop="newSalesQuotationName" width="140" /> -->
              <el-table-column label="操作" align="center" width="120" fixed="right">
                <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" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog v-if="openBOM" :visible.sync="openBOM" width="90%" append-to-body :close-on-click-modal="false">
      <BOM :rowData="rowData" @clickCancel="clickCancel"></BOM>
    </el-dialog>

    <el-dialog v-if="openBOMDetails" :visible.sync="openBOMDetails" width="90%" append-to-body :close-on-click-modal="false">
      <BOMDetails :rowData="rowData" @clickCancel="clickCancelDetails"></BOMDetails>
    </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>
  </div>
</template>

<script>
import * as API from '@/api/shengde/group/BOM/bom'
import { categoryList } from '@/api/shengde/group/BOM/category'
import { mapGetters } from 'vuex'
import BOM from '@/views/AddOrModifiedProduct/BOM'
import BOMDetails from '@/views/shengde/group/BOM/library/details'
import OperationLog from '@/components/shengde/operationLog/index'

export default {
  name: 'BOMLibrary',
  components: { BOM, BOMDetails, OperationLog },
  props: {
    selectStatus: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      value: '',
      pathPrefix: process.env.VUE_APP_IMG_URL,
      inputCategory: '',
      categoryTreeData: [],
      defaultProps: {
        children: 'children',
        label: 'text',
      },
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品信息表格数据
      productList: [],
      loadingTable: false,
      // 是否显示弹出层
      openBOM: false,
      openBOMDetails: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: '',
        nameChinese: '',
        categoryType: '',
        bomColorName: '',
        bomColorSpecCode: '',
        generalCategory: '',
        chromatogram: '',
        formula: '',
        reverseGrain: '',
        frontalGrain: '',
        color: '',
      },
      // 表单参数
      form: {
        attachments: [],
        materials: [],
      },
      fileData: [],
      loadingStatus: false,
      rowData: {},
      productCategoryType: [],
      generalCategory: [],
      chromatogram: [],
      formula: [],
      reverseGrain: [],
      frontalGrain: [],
      projectType: [],
      openOperationLog: false,
      operationLogKey: 30,
    }
  },
  created() {
    this.productCategoryType = this.dictData
      .filter((item) => item.code === 'bom_category_type')[0]
      .children.map((item, index) => {
        return {
          ...item,
          children: [],
          text: item.dictValue,
          attrs: {
            sort: index,
          },
          id: item.dictKey,
        }
      })
    this.generalCategory = this.dictData.filter((item) => item.code === 'generalCategory')[0].children
    this.chromatogram = this.dictData.filter((item) => item.code === 'bom_chromatogram')[0].children
    this.formula = this.dictData.filter((item) => item.code === 'formula')[0].children
    this.reverseGrain = this.dictData.filter((item) => item.code === 'reverse_grain')[0].children
    this.frontalGrain = this.dictData.filter((item) => item.code === 'frontal_grain')[0].children
    this.projectType = this.dictData.filter((item) => item.code === 'project_type')[0].children
    this.getCategory()
  },
  mounted() {
    this.getList()
  },
  watch: {
    inputCategory(val) {
      this.$refs.treeCategory.filter(val)
    },
  },
  computed: mapGetters(['menuAll', 'token', 'dictData', 'userInfo']),
  methods: {
    changeValue(val) {
      this.form.categoryId = val.toString()
    },
    treeCategory(value, data) {
      if (!value) return true
      return data.text.indexOf(value) !== -1
    },
    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()
    },
    getCategory() {
      categoryList({}).then((res) => {
        this.categoryTreeData = JSON.parse(JSON.stringify(this.productCategoryType))
        let data = this.handleTree(res.data.data, 'id', 'pId')
        if (data && data.length > 0) {
          for (let i = 0; i < this.categoryTreeData.length; i++) {
            for (let j = 0; j < data.length; j++) {
              if (this.categoryTreeData[i].dictKey === data[j].attrs.categoryType) {
                this.categoryTreeData[i].children.push(data[j])
              }
            }
          }
        }
      })
    },
    /** 查询产品信息列表 */
    getList() {
      this.loadingTable = true
      API.list(this.queryParams).then(
        (res) => {
          if (res.data.data.records && res.data.data.records.length > 0) {
            res.data.data.records = res.data.data.records.map((item) => {
              if (item.bomColors && item.bomColors.length > 0) {
                item.bomColors = item.bomColors.map((itemBomColors) => {
                  itemBomColors.nameChinese = itemBomColors.nameChinese.replace(item.nameChinese + '  ： ', '')
                  itemBomColors.nameChinese = itemBomColors.nameChinese.replace(item.nameChinese + '：', '')
                  return {
                    ...itemBomColors,
                  }
                })
              }
              return {
                ...item,
              }
            })
          }
          this.total = res.data.data.total
          this.productList = res.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.queryParams.categoryType = ''
      this.$refs.treeCategory.setCurrentKey(null)
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.rowData = {}
      this.openBOM = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.rowData = row
      this.openBOM = true
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除群组名称为"' + row.nameChinese + '"的数据项?', '警告', {
        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.openBOMDetails = true
    },
    clickCancel(status) {
      this.openBOM = false
      if (status) {
        this.getList()
      }
    },
    clickCancelDetails() {
      this.openBOMDetails = false
    },
    openFile(path) {
      window.open(path)
    },
    handleProLibrary() {
      this.openProLibrary = true
    },
    selectBOM(row, index) {
      this.$emit('selectBOM', row, index)
    },
    beforeUpload(file) {
      this.errMsg = ''
      const isLt50M = file.size / 1024 / 1024 < 50
      if (!isLt50M) {
        this.$message.error('上传文件大小不能超过50MB!')
      }
      return isLt50M
    },
    excelProgress() {
      this.openProLibrary = true
    },
    excelSuccess() {
      this.msgSuccess('文件导入成功')
      this.openProLibrary = false
      this.getList()
    },
    excelError(err) {
      var res = JSON.parse(err.message)
      this.errMsg = '导入失败: ' + res.msg
      this.openProLibrary = false
    },
    generalCategoryFormat(row) {
      return this.selectConstantsLabel(this.generalCategory, row.generalCategory)
    },
    chromatogramFormat(row) {
      return this.selectConstantsLabel(this.chromatogram, row.chromatogram)
    },
    formulaFormat(row) {
      return this.selectConstantsLabel(this.formula, row.formula)
    },
    frontalGrainFormat(row) {
      return this.selectConstantsLabel(this.frontalGrain, row.frontalGrain)
    },
    reverseGrainFormat(row) {
      return this.selectConstantsLabel(this.reverseGrain, row.reverseGrain)
    },
    projectTypeFormat(row) {
      return this.selectConstantsLabel(this.projectType, row.projectType)
    },
  },
}
</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>
