<template>
  <div style="height: calc(100vh - 58px - 20px - 114px); overflow-y: auto; overflow-x: hidden">
    <el-form :model="queryParams" ref="queryForm" :inline="true" @submit.native.prevent>
      <el-form-item label="群组品号" prop="specCode">
        <el-input v-model="queryParams.specCode" placeholder="请输入群组品号" size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="BOM品号" prop="bomColorCode">
        <el-input v-model="queryParams.bomColorCode" placeholder="请输入BOM品号" size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="尺寸 (cm):">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="" prop="length">
              <el-input-number size="small" v-model="queryParams.length" placeholder="请输入长" :precision="2" :controls="false" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="" prop="width">
              <el-input-number size="small" v-model="queryParams.width" placeholder="请输入宽" :precision="2" :controls="false" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="" prop="height">
              <el-input-number size="small" v-model="queryParams.height" placeholder="请输入高" :precision="2" :controls="false" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </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">
      <el-col :span="24" style="display: flex">
        <div style="height: 40px; line-height: 40px; margin-right: 10px" v-if="!userInfo.subsidiaryId">
          <el-button type="primary" size="mini" @click="handleBOM()" v-db-click>选择bom</el-button>
        </div>
        <div style="height: 40px; line-height: 40px; margin-right: 10px" v-if="userInfo.subsidiaryId">
          <el-button type="primary" size="mini" @click="handleOpenOftenDialog()">选择常用包材</el-button>
        </div>
        <div style="height: 40px; line-height: 40px; margin-right: 10px" v-if="userInfo.subsidiaryId">
          <el-button type="primary" size="mini" style="background: #20b2aa; border-color: #20b2aa" @click="openSaveOftenDialog()">保存常用包材</el-button>
        </div>
        <div style="height: 40px; line-height: 40px; margin-right: 10px" v-if="userInfo.subsidiaryId">
          <el-button type="primary" size="mini" @click="handleOpenTwoBOM()">选择包材配件</el-button>
        </div>
        <div style="height: 40px; line-height: 40px; margin-right: 10px">
          <el-button type="text" @click="clickReset">重置</el-button>
        </div>
        <div style="height: 40px; line-height: 40px; margin-right: 10px">
          <el-button type="text" @click="clickReplace">一键替换</el-button>
        </div>
        <div style="margin-left: 32px">
          <el-form :model="specCode" :inline="true" @submit.native.prevent>
            <el-form-item label="BOM品号" prop="specCode">
              <el-input v-model="specCode" placeholder="请输入BOM品号" size="small" />
            </el-form-item>
          </el-form>
        </div>
        <div style="height: 40px; line-height: 40px; margin-right: 10px">
          <el-button type="text" @click="clickRemove">一键移除</el-button>
        </div>
      </el-col>
    </el-row>

    <el-form ref="ruleForm" :model="form" :rules="rules" label-width="100px">
      <el-table
        :data="form.selectData"
        :cell-style="{ padding: '0' }"
        :row-style="{ height: '35px' }"
        header-row-class-name="tableHeader"
        style="margin-bottom: 10px"
      >
        <el-table-column label="品号" prop="specCode" width="220" />
        <el-table-column label="品名" prop="bomColorName" min-width="220" />
        <el-table-column label="数量" align="center" width="200">
          <template slot-scope="scope">
            <el-form-item label-width="0px" :prop="'selectData.' + scope.$index + '.quantity'" :rules="rules.quantity" class="input">
              <el-input-number style="width: 100%" size="mini" v-model="scope.row.quantity" :controls="false" :min="1" :max="10000000" :precision="0" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button type="text" @click="handleDelete(scope.$index)">删 除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <br />

    <el-table
      :data="tableList"
      :cell-style="{ padding: '0' }"
      :row-style="{ height: '35px' }"
      v-loading="loading"
      header-row-class-name="tableHeader"
      ref="table"
      v-if="userInfo.subsidiaryId"
    >
      <el-table-column label="群组品号" prop="productCode" width="120" fixed />
      <el-table-column label="SKU品号" prop="specCode" width="140" fixed />
      <el-table-column label="品名" prop="nameChinese" min-width="220" fixed />
      <el-table-column label="裸垫品号" prop="bomColorCode" width="140" />
      <template v-if="packingFittings && packingFittings.length > 0">
        <el-table-column v-for="item in packingFittings" :key="item.id" :label="item.text + '品号'" width="140">
          <template slot-scope="scope">
            <span>{{ getLabel(scope.row, item) }}</span>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <el-table
      :data="tableList"
      :cell-style="{ padding: '0' }"
      :row-style="{ height: '35px' }"
      v-loading="loading"
      header-row-class-name="tableHeader"
      ref="table"
      v-else
    >
      <el-table-column label="群组品号" prop="productCode" width="120" />
      <el-table-column label="SKU品号" prop="specCode" width="140" />
      <el-table-column label="品名" prop="nameChinese" min-width="220" />
      <el-table-column label="裸垫品号" prop="bomColorCode" width="140" />
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <el-dialog v-if="openOftenDialog" :visible.sync="openOftenDialog" title="选择常用包材" width="60%" append-to-body>
      <el-form :model="composeQuery" ref="composeForm" :inline="true">
        <el-form-item label="组合名称" prop="name">
          <el-input placeholder="请输入" v-model="composeQuery.name" clearable size="small" @keyup.enter.native="handleGetList" />
        </el-form-item>
        <el-form-item>
          <el-button size="mini" @click="handleGetList" class="searchBtn">搜索</el-button>
          <el-button size="mini" @click="resetGetList">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="compose-table">
        <el-table :data="oftenTableList" size="small" :row-style="{ height: '35px' }" :cell-style="{ padding: '0' }" header-row-class-name="tableHeader">
          <el-table-column type="expand" align="left" width="50">
            <template slot-scope="scope">
              <div>
                <el-table :data="scope.row.bomCombinationDetailsList" size="small" :row-style="{ height: '35px' }" :cell-style="{ padding: '0' }">
                  <el-table-column label="主图" width="80" align="center">
                    <template slot-scope="scope">
                      <div v-if="scope.row.magPath">
                        <img class="img" :src="pathPrefix + scope.row.magPath" @click="openFile(pathPrefix + scope.row.magPath)" />
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="品号" prop="bomColorspecCode" />
                  <el-table-column label="品名" prop="bomColorName" />
                  <el-table-column label="数量" prop="singleQuantity" width="80" />
                  <el-table-column label="单价￥" prop="price" width="80" align="right" />
                </el-table>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="组合名称" prop="name" align="left" />
          <el-table-column label="操作" align="center" width="120" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="removeCompose(scope.row.id)">删 除</el-button>
              <el-button type="text" @click="selectCompose(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-row style="text-align: center; margin-top: 30px">
        <el-button size="small" @click="openOftenDialog = false">取 消</el-button>
      </el-row>
    </el-dialog>

    <el-dialog v-if="saveOftenDialog" :visible.sync="saveOftenDialog" title="保存常用包材" width="40%" append-to-body>
      <el-form label-width="120px" :model="saveForm" ref="saveForm" :rules="rules">
        <el-form-item label="常用包材名称：" prop="name">
          <el-input v-model="saveForm.name" placeholder="请输入"> </el-input>
        </el-form-item>
      </el-form>
      <el-row style="text-align: center; margin-top: 30px">
        <el-button size="small" @click="saveCancel">取 消</el-button>
        <el-button size="small" type="primary" @click="saveOften">保 存</el-button>
      </el-row>
    </el-dialog>

    <!-- 选择包材配件-->
    <el-dialog title="选择包材配件" v-if="openTwoBOM" top="50px" :visible.sync="openTwoBOM" width="90%" append-to-body center>
      <SelectBOM @selectBOM="handleSelectTwoBOM" showType="parts"></SelectBOM>
      <span slot="footer" class="dialog-footer">
        <el-button @click="openTwoBOM = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 选择主材-->
    <el-dialog title="选择主材" v-if="openBOM" top="50px" :visible.sync="openBOM" width="80%" append-to-body center>
      <SelectBOM @selectBOM="handleSelectBOM" showType="principalMaterial"></SelectBOM>
      <span slot="footer" class="dialog-footer">
        <el-button @click="openBOM = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as API from '@/api/shengde/product/batchModification'
import { list, del, save } from '@/api/shengde/subsidiary/compose/index.js'
import { categoryList } from '@/api/shengde/group/BOM/category'
import SelectBOM from '@/components/shengde/SelectBOM/index'
import { mapGetters } from 'vuex'

export default {
  name: 'batchModification',
  components: { SelectBOM },
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        specCode: '',
        bomColorCode: '',
        length: undefined,
        width: undefined,
        height: undefined,
      },
      loading: false,
      tableList: [],
      total: 0,
      openOftenDialog: false,
      saveOftenDialog: false,
      openTwoBOM: false,
      oftenTableList: [],
      composeQuery: {
        pageNum: 1,
        pageSize: 9999,
        name: '',
      },
      pathPrefix: process.env.VUE_APP_IMG_URL,
      saveForm: {
        name: '',
        bomCombinationDetailsList: [],
      },
      rules: {
        name: [{ required: true, message: '请输入常用包材配组合名称', trigger: 'blur' }],
        quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
      },
      packingFittings: [],
      form: {
        selectData: [],
      },
      openBOM: false,
      specCode: '',
    }
  },
  created() {
    categoryList({ categoryType: '3' }).then((res) => {
      this.packingFittings = this.packingFittings.concat(res.data.data)
      categoryList({ categoryType: '2' }).then((res) => {
        this.packingFittings = this.packingFittings.concat(res.data.data)
      })
    })
  },
  mounted() {
    this.getList()
  },
  computed: mapGetters(['userInfo']),
  methods: {
    getList() {
      this.loading = true
      API.batchReplaceList(this.queryParams).then(
        (res) => {
          this.tableList = res.data.data.records
          this.total = res.data.data.total
          this.loading = false
          this.$nextTick(() => {
            this.$refs.table.doLayout()
          })
        },
        (err) => {
          console.log('batchReplaceList: ' + err)
          this.loading = false
        }
      )
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleBOM() {
      this.openBOM = true
    },
    handleOpenOftenDialog() {
      this.handleGetList()
      this.openOftenDialog = true
    },
    openSaveOftenDialog() {
      if (this.form.selectData && this.form.selectData.length > 0) {
        let packing = this.form.selectData.filter((item) => item.categoryId)
        if (!(packing && packing.length > 0)) {
          return this.msgInfo('请选择包材配件')
        }
      } else {
        return this.msgInfo('请选择包材配件')
      }
      this.saveOftenDialog = true
    },
    handleOpenTwoBOM() {
      this.openTwoBOM = true
    },
    handleGetList() {
      list(this.composeQuery).then((res) => {
        this.oftenTableList = res.data.data
      })
    },
    resetGetList() {
      this.resetForm('composeForm')
      this.handleGetList()
    },
    openFile(path) {
      window.open(path)
    },
    removeCompose(id) {
      this.$confirm('是否确认删除此条包材组合？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        del({ id }).then(() => {
          this.msgSuccess('删除成功！')
          this.handleGetList()
        })
      })
    },
    selectCompose(row) {
      const list = row.bomCombinationDetailsList
      let arr = list.map((item) => {
        return {
          bomColorName: item.bomColorName,
          specCode: item.bomColorspecCode,
          bomId: item.bomId,
          quantity: Number(item.singleQuantity),
          id: item.bomColorId,
          price: item.price,
          categoryId: item.categoryId,
        }
      })
      this.form.selectData = arr
      this.msgSuccess('选择完成')
    },
    saveCancel() {
      this.saveOftenDialog = false
      this.saveForm = {
        name: '',
        bomCombinationDetailsList: [],
      }
    },
    saveOften() {
      this.$refs['saveForm'].validate((valid) => {
        if (valid) {
          let arr = this.form.selectData.map((item) => ({ bomColorId: item.bomId, singleQuantity: item.quantity, price: item.price }))
          this.saveForm.bomCombinationDetailsList = arr
          save(this.saveForm).then(() => {
            this.msgSuccess('保存成功！')
            this.saveCancel()
          })
        }
      })
    },
    getLabel(row, item) {
      let text = ''
      if (row.mountingsList && row.mountingsList.length > 0) {
        let data = row.mountingsList.filter((mountings) => mountings.categoryId === item.id)
        if (data && data.length > 0) {
          text = data[0].bomColorCode
        }
      }
      return text
    },
    handleSelectTwoBOM(data, index) {
      if (this.form.selectData && this.form.selectData.length > 0) {
        let packing = this.form.selectData.filter((item) => item.categoryId)
        if (!(packing && packing.length > 0)) {
          this.form.selectData = []
        }
      }
      let row = data.bomColors[index]
      let item = {
        bomColorName: row.nameChinese,
        specCode: row.specCode,
        id: data.id,
        bomId: row.id,
        quantity: undefined,
        price: row.price,
      }
      this.form.selectData.push(item)
      this.msgSuccess('添加完成')
    },
    handleDelete(index) {
      this.form.selectData.splice(index, 1)
    },
    clickReset() {
      this.form.selectData = []
    },
    clickReplace() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (this.form.selectData && this.form.selectData.length > 0) {
            this.$confirm('是否确认替换所有包材配件?', '警告', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                let type = 10
                if (this.userInfo.subsidiaryId) {
                  type = 20
                }
                API.batchReplace({ type: type, bomColorList: this.form.selectData, productColor: this.queryParams }).then(() => {
                  this.msgSuccess('替换成功!')
                  this.handleQuery()
                })
              })
              .catch(() => {})
          } else {
            this.msgInfo('请选择BOM或包材配件')
          }
        }
      })
    },
    handleSelectBOM(data, index) {
      let row = data.bomColors[index]
      this.form.selectData = [
        {
          bomColorName: row.nameChinese,
          specCode: row.specCode,
          id: row.id,
          bomId: data.id,
          quantity: undefined,
          price: row.price,
        },
      ]
      this.msgSuccess('选择完成')
      this.openBOM = false
    },
    clickRemove() {
      if (this.specCode) {
        this.$confirm('是否确认移除?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            API.touchRemove({ bomColorCode: this.specCode, productColor: this.queryParams }).then(() => {
              this.msgSuccess('移除成功!')
              this.specCode = ''
              this.handleQuery()
            })
          })
          .catch(() => {})
      } else {
        this.msgInfo('请输入要移除的BOM品号')
      }
    },
  },
}
</script>

<style lang="scss" scoped>
* {
  font-size: 12px;
}
.searchBtn {
  background: #20b2aa;
  color: #fff;
  border: 1px solid #20b2aa;
}
::v-deep {
  .el-input__inner {
    border-radius: 1px;
  }
  .el-button--small {
    border-radius: 1px;
  }
  .tableHeader th {
    background-color: #edf0f5;
    height: 35px;
    padding: 0;
  }
}
</style>
