<template>
  <div style="padding: 20px 2vw">
    <el-form ref="ruleForm" :model="aftermarketContract" :rules="formRules" :inline="true">
      <el-collapse v-model="activeNames">
        <div v-for="(item, index) in aftermarketContract.aftermarketContractProductList" :key="index" style="margin-bottom: 20px">
          <div style="border: 1px solid #edf0f5">
            <table cellspacing="0" cellpadding="0" border="0" class="productTable">
              <thead>
                <tr>
                  <th style="width: 230px">
                    <div>产品</div>
                  </th>
                  <th style="width: 150px">
                    <div>图稿（设计图）</div>
                  </th>
                  <th style="width: 330px">
                    <div>图稿（生产文件）</div>
                  </th>
                  <th>
                    <div>包材配件/单品</div>
                  </th>
                  <th style="width: 80px">
                    <div style="text-align: center">操作</div>
                  </th>
                </tr>
              </thead>
              <tr class="tr">
                <td>
                  <div style="display: flex; padding: 8px 20px 0px">
                    <div>
                      <div style="line-height: 28px">
                        <span>品号: {{ item.code }}</span>
                      </div>
                      <div style="line-height: 28px">
                        <span>品名: {{ item.colorName }}</span>
                      </div>
                      <div style="line-height: 40px">
                        <span>数量: </span>
                        <el-form-item :prop="'aftermarketContractProductList.' + index + '.quantity'" :rules="formRules.quantity">
                          <el-input-number
                            size="mini"
                            v-model="item.quantity"
                            :controls="false"
                            :min="1"
                            :max="10000000"
                            :precision="0"
                            @change="
                              (val) => {
                                return getPrice(item, index)
                              }
                            "
                          />
                        </el-form-item>
                      </div>
                      <div style="line-height: 28px">
                        <span>加工费: {{ item.processPrice }}</span>
                      </div>
                      <div style="line-height: 28px">
                        <span>代发费: {{ item.deliverGoodsPrice }}</span>
                      </div>
                      <div style="line-height: 28px">
                        <span>快递包材费: {{ item.expressPrice }}</span>
                      </div>
                      <div style="line-height: 28px">
                        <span>包装人工费: {{ item.expensePrice }}</span>
                      </div>
                      <div style="line-height: 28px">
                        <span>单价: ¥{{ moneyFormat(item.productPrice, 2) }}</span>
                      </div>
                      <div style="line-height: 28px">
                        <span>小计: ¥{{ statisticalAmount(item) }}</span>
                      </div>
                      <div style="line-height: 40px">
                        <el-form-item :prop="'aftermarketContractProductList.' + index + '.identification'" :rules="formRules.identification">
                          <span style="margin-right: 10px">打印: </span>
                          <el-radio-group v-model="item.identification">
                            <el-radio :label="1">单面</el-radio>
                            <el-radio :label="2">双面</el-radio>
                          </el-radio-group>
                        </el-form-item>
                      </div>
                    </div>
                  </div>
                </td>
                <td>
                  <div style="padding: 8px 20px 0px">
                    <el-upload
                      class="avatar-uploader"
                      :action="action"
                      :headers="{ 'Blade-Auth': token }"
                      :show-file-list="false"
                      :before-upload="beforeAvatarUpload"
                      :on-success="
                        (response, file, fileList) => {
                          return uploadSuccess(response, file, fileList, index)
                        }
                      "
                      :on-error="
                        (err, file, fileList) => {
                          return uploadError(err, file, fileList, index)
                        }
                      "
                      :on-progress="
                        (event, file, fileList) => {
                          return uploadProgress(event, file, fileList, index)
                        }
                      "
                      :disabled="item.loading"
                      accept=".jpg, .png, .jpeg"
                    >
                      <div v-loading="item.loading">
                        <div v-if="item.imgPath">
                          <img v-if="!item.imgPath.includes('https')" class="productImg" style="width: 80px; height: 80px" :src="pathPrefix + item.imgPath" />
                          <img v-else :src="item.imgPath" class="productImg" style="width: 80px; height: 80px" />
                        </div>
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      </div>
                    </el-upload>
                  </div>
                </td>
                <td>
                  <div style="padding: 8px 20px 0px">
                    <div>共享文件夹路径（点击下方链接并上传文件）：</div>
                    <span style="color: #027db4; cursor: pointer" @click="handleClickUpload(item.artworkDocument)">上传ez3/dxf</span>
                  </div>
                </td>
                <td>
                  <div style="padding: 8px 20px 0px">
                    <div style="display: flex; margin-bottom: 10px">
                      <el-button size="mini" type="primary" @click="handleOpenOftenDialog(index)">选择常用包材</el-button>
                      <el-button size="mini" type="primary" style="background: #20b2aa; border-color: #20b2aa" @click="openSaveOftenDialog(index)"
                        >保存常用包材</el-button
                      >
                      <el-button size="mini" type="primary" @click="handleOpenBOM(index)">选择包材配件</el-button>
                    </div>
                    <el-table
                      :data="item.partsContractProductList"
                      size="small"
                      :row-style="{ height: '35px' }"
                      :cell-style="{ padding: '0' }"
                      border
                      ref="table"
                    >
                      <el-table-column label="单价￥" prop="price" align="left" width="80">
                        <template slot-scope="scope">
                          {{ moneyFormat(scope.row.price, 2) }}
                        </template>
                      </el-table-column>
                      <el-table-column label="数量" prop="singleQuantity" align="left" width="90">
                        <template slot-scope="scope">
                          <el-form-item
                            label-width="0px"
                            :prop="'aftermarketContractProductList.' + index + '.partsContractProductList.' + scope.$index + '.singleQuantity'"
                            :rules="formRules.singleQuantity"
                            class="input"
                          >
                            <el-input-number
                              style="width: 52%"
                              size="mini"
                              v-model="scope.row.singleQuantity"
                              :controls="false"
                              :min="1"
                              :max="10000000"
                              :precision="0"
                              @change="
                                (val) => {
                                  return changeProductQuantity(val, index, scope.$index)
                                }
                              "
                            />
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column label="名称" prop="name" align="left" min-width="150" />
                      <el-table-column label="总量" prop="quantity" align="center" width="70">
                        <template slot-scope="scope">
                          {{ scope.row.quantity }}
                        </template>
                      </el-table-column>
                      <el-table-column label="小计￥" align="center" width="100">
                        <template slot-scope="scope">
                          {{ partsAmount(scope.row) }}
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" align="center" width="50" fixed="right">
                        <template slot-scope="scope">
                          <span
                            class="el-icon-remove-outline"
                            style="font-size: 16px; cursor: pointer; color: #d9001b"
                            @click="removeBOM(index, scope.$index)"
                          ></span>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </td>
                <td style="width: 80px; text-align: center; vertical-align: inherit">
                  <el-button type="text" @click="clickRemove(index)" v-if="aftermarketContract.dataResource !== 1" v-db-click>删除</el-button>
                </td>
              </tr>
            </table>
            <el-collapse-item title="包装" :name="index">
              <div style="display: flex; padding: 8px 10px 0px">
                <div style="flex: 1; padding: 0px 10px">
                  <div>包装要求:</div>
                  <Editor v-model="item.packageRemarks" :min-height="100" />
                </div>
              </div>
            </el-collapse-item>
          </div>
        </div>
      </el-collapse>
    </el-form>

    <!-- 选择包材配件-->
    <el-dialog title="选择包材配件" v-if="openBOM" top="50px" :visible.sync="openBOM" width="90%" append-to-body center>
      <SelectBOM @selectBOM="handleSelectBOM" showType="parts" ref="SelectBOM"></SelectBOM>
      <span slot="footer" class="dialog-footer">
        <el-button @click="openBOM = false">关 闭</el-button>
      </span>
    </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 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="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>
      <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">
              <div class="miniBtn">
                <el-button size="mini" type="text" @click="removeCompose(scope.row.id)"> 删 除</el-button>
                <el-button size="mini" type="text" @click="selectCompose(scope.row)">选择</el-button>
              </div>
            </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>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Editor from '@/components/Editor'
import SelectBOM from '@/components/shengde/SelectBOM/index'
import { createFile, deleteFile, judgeFile } from '@/api/shengde/subsidiary/AddOrModifiedOrder/index.js'
import { addFolder } from '@/api/product/customProductLibrary'
import * as API from '@/api/shengde/subsidiary/compose/index.js'
import { getPrice } from '@/api/product/customProductLibrary'

export default {
  name: 'OrderProduct',
  props: {
    aftermarketContract: Object,
  },
  components: { Editor, SelectBOM },
  data() {
    let checkQuantity = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入数量'))
      }
      callback()
    }
    let checkPrint = (rule, value, callback) => {
      if (value) {
        if (value == 0) {
          callback(new Error('请选择打印面数'))
        } else {
          callback()
        }
      } else {
        callback(new Error('请选择打印面数'))
      }
    }
    return {
      formRules: {
        singleQuantity: [{ validator: checkQuantity, trigger: 'blur' }],
        quantity: [{ validator: checkQuantity, trigger: 'blur' }],
        identification: [{ validator: checkPrint, trigger: 'change' }],
      },
      action: process.env.VUE_APP_ACTION_URL,
      pathPrefix: process.env.VUE_APP_IMG_URL,
      filePrefix: process.env.VUE_APP_FILE_PREFIX,
      openProduct: false,
      openBOM: false,
      selectIndex: null,
      activeNames: [],
      saveOftenDialog: false,
      saveform: {
        name: '',
        bomCombinationDetailsList: [],
      },
      rules: {
        name: [{ required: true, message: '请输入常用包材配组合名称', trigger: 'blur' }],
      },
      saveOftenList: [], //点击保存常用包材保存的数据
      openOftenDialog: false,
      oftenTableList: [],
      composeQuery: {
        name: '',
        pageSize: 999,
        pageNum: 1,
      },
      separateBillForm: {
        id: '',
        splitOrderQuantity: undefined,
      },
      separateBillItem: {},
      separateBillFormRules: {
        splitOrderQuantity: [{ required: true, message: '请输入拆解数量', trigger: 'blur' }],
      },
      loadingStatus: false,
    }
  },
  created() {},
  mounted() {},
  computed: mapGetters(['token']),
  methods: {
    handleCollapse() {
      let arr = []
      for (let index = 0; index < this.aftermarketContract.aftermarketContractProductList.length; index++) {
        arr.push(index)
      }
      this.activeNames = arr
    },
    validateForm() {
      let flag = null
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          for (let i = 0; i < this.aftermarketContract.aftermarketContractProductList.length; i++) {
            const element = this.aftermarketContract.aftermarketContractProductList[i]
            element.artworkDocument = element.artworkDocument.replace(/\\/g, '/')
            if (!element.imgPath) return this.msgInfo('请上传设计图！')
          }
          flag = true
        } else {
          flag = false
        }
      })
      return flag
    },
    fileUpload(file) {
      const isLt50M = file.size / 1024 / 1024 < 50
      if (!isLt50M) {
        this.$message.error('上传设计素材文件单个不能超过50MB!')
      }
      return isLt50M
    },
    clickRemove(index) {
      this.$confirm('确认删除该产品？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          const row = this.aftermarketContract.aftermarketContractProductList[index]
          let path = row.artworkDocument.slice(this.filePrefix.length).replace(/\\/g, '/')
          deleteFile(path).then(() => {
            this.aftermarketContract.aftermarketContractProductList.splice(index, 1)
            this.calculationMoney()
            this.msgSuccess('删除成功!')
          })
        })
        .catch()
    },
    handleSelect(data, index) {
      const row = data.colors[index]
      if (row.mountingsList && row.mountingsList.length > 0) {
        row.mountingsList = row.mountingsList.map((item) => {
          if (item.quantity) {
            item.singleQuantity = Number(item.quantity)
          }
          delete item.id
          delete item.quantity
          return {
            ...item,
            name: item.bomColorName,
            price: item.bomColorPrice,
          }
        })
      }
      let path = ''
      if (row.artworkDocument !== '') {
        judgeFile({ artworkDocument: row.artworkDocument }).then((res) => {
          if (res.data.data) {
            path = row.artworkDocument.replace(/\//g, '\\')
            const product = {
              productId: data.id,
              productPrice: data.price,
              quantity: undefined,
              expensePrice: data.expensePrice,
              deliverGoodsPrice: data.deliverGoodsPrice,
              expressPrice: data.expressPrice,
              nameChinese: data.nameChinese,
              nameEnglish: data.nameEnglish,
              customsCode: data.customsCode,
              declarationElements: data.declarationElements,
              declarationElementsChinese: data.declarationElementsChinese,
              price: data.subsidiaryPrice || data.price,
              expressCostPrice: '',
              deliverGoodsCostPrice: '',
              expenseCostPrice: '',
              designRemarks: '',
              packageRemarks: '',
              pic: data.pic,
              code: row.specCode,
              partsContractProductList: row.mountingsList,
              productColorId: row.id,
              colorName: row.nameChinese,
              artworkDocument: path,
              imgPath: row.designSketch,
              imgPathName: row.designSketchName,
              loading: false,
              identification: 1,
            }
            this.aftermarketContract.aftermarketContractProductList.push(product)
            this.msgSuccess('添加完成')
          } else {
            createFile().then((resFile) => {
              path = resFile.data.data.replace(/\//g, '\\')
              const product = {
                productId: data.id,
                productPrice: data.price,
                quantity: undefined,
                expensePrice: data.expensePrice,
                deliverGoodsPrice: data.deliverGoodsPrice,
                expressPrice: data.expressPrice,
                nameChinese: data.nameChinese,
                nameEnglish: data.nameEnglish,
                customsCode: data.customsCode,
                declarationElements: data.declarationElements,
                declarationElementsChinese: data.declarationElementsChinese,
                price: data.subsidiaryPrice || data.price,
                expressCostPrice: '',
                deliverGoodsCostPrice: '',
                expenseCostPrice: '',
                designRemarks: '',
                packageRemarks: '',
                pic: data.pic,
                code: row.specCode,
                partsContractProductList: row.mountingsList,
                productColorId: row.id,
                colorName: row.nameChinese,
                artworkDocument: path,
                imgPath: row.designSketch,
                imgPathName: row.designSketchName,
                loading: false,
                identification: 1,
              }
              this.aftermarketContract.aftermarketContractProductList.push(product)
              this.msgSuccess('添加完成')
            })
          }
        })
      } else {
        createFile().then((resFile) => {
          path = resFile.data.data.replace(/\//g, '\\')
          const product = {
            productId: data.id,
            productPrice: data.price,
            quantity: undefined,
            expensePrice: data.expensePrice,
            deliverGoodsPrice: data.deliverGoodsPrice,
            expressPrice: data.expressPrice,
            nameChinese: data.nameChinese,
            nameEnglish: data.nameEnglish,
            customsCode: data.customsCode,
            declarationElements: data.declarationElements,
            declarationElementsChinese: data.declarationElementsChinese,
            price: data.subsidiaryPrice || data.price,
            expressCostPrice: '',
            deliverGoodsCostPrice: '',
            expenseCostPrice: '',
            designRemarks: '',
            packageRemarks: '',
            pic: data.pic,
            code: row.specCode,
            partsContractProductList: row.mountingsList,
            productColorId: row.id,
            colorName: row.nameChinese,
            artworkDocument: path,
            imgPath: row.designSketch,
            imgPathName: row.designSketchName,
            loading: false,
            identification: 1,
          }
          this.aftermarketContract.aftermarketContractProductList.push(product)
          this.msgSuccess('添加完成')
        })
      }
    },
    handleOpenBOM(index) {
      if (
        this.aftermarketContract.aftermarketContractProductList[index].quantity &&
        this.aftermarketContract.aftermarketContractProductList[index].quantity > 0
      ) {
        this.selectIndex = index
        this.openBOM = true
      } else return this.msgInfo('请先输入产品数量')
    },
    handleSelectBOM(data, index) {
      const row = data.bomColors[index]
      const item = {
        name: row.nameChinese,
        bomId: data.id,
        bomColorId: row.id,
        price: row.price,
        quantity: '',
        singleQuantity: undefined,
        costPrice: row.costPrice,
      }
      this.aftermarketContract.aftermarketContractProductList[this.selectIndex].partsContractProductList.push(item)
      this.msgSuccess('添加完成')
    },
    removeBOM(index, j) {
      this.$confirm('确认删除该行包材配件？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.aftermarketContract.aftermarketContractProductList[index].partsContractProductList.splice(j, 1)
        this.changeProductQuantity(this.aftermarketContract.aftermarketContractProductList[index].quantity, index)
        this.msgSuccess('删除成功!')
      })
    },
    openImg(path) {
      window.open(path)
    },
    statisticalAmount(item) {
      if (item.quantity && item.quantity > 0) {
        let money = item.productPrice || 0
        if (item.expensePrice) {
          money = parseFloat(Number(money) + Number(item.expensePrice)).toFixed(2)
        }
        if (item.deliverGoodsPrice) {
          money = parseFloat(Number(money) + Number(item.deliverGoodsPrice)).toFixed(2)
        }
        if (item.expressPrice) {
          money = parseFloat(Number(money) + Number(item.expressPrice)).toFixed(2)
        }
        money = parseFloat(Number(money) * Number(item.quantity)).toFixed(2)
        return this.moneyFormat(money, 2)
      }
      return ''
    },
    partsAmount(item) {
      if (item.quantity && item.quantity > 0) {
        return this.moneyFormat(parseFloat(Number(item.price) * Number(item.quantity)).toFixed(2), 2)
      }
      return ''
    },
    changeProductQuantity(val, productIndex, partsIndex) {
      if (partsIndex || partsIndex === 0) {
        // 包材配件的合计
        if (
          this.aftermarketContract.aftermarketContractProductList[productIndex].partsContractProductList[partsIndex].singleQuantity > 0 &&
          this.aftermarketContract.aftermarketContractProductList[productIndex].quantity
        ) {
          this.aftermarketContract.aftermarketContractProductList[productIndex].partsContractProductList[partsIndex].quantity =
            Number(this.aftermarketContract.aftermarketContractProductList[productIndex].partsContractProductList[partsIndex].singleQuantity) *
            Number(this.aftermarketContract.aftermarketContractProductList[productIndex].quantity)
        } else {
          this.aftermarketContract.aftermarketContractProductList[productIndex].partsContractProductList[partsIndex].quantity = 0
        }
      } else {
        if (
          this.aftermarketContract.aftermarketContractProductList[productIndex].partsContractProductList &&
          this.aftermarketContract.aftermarketContractProductList[productIndex].partsContractProductList.length > 0
        ) {
          this.aftermarketContract.aftermarketContractProductList[productIndex].partsContractProductList =
            this.aftermarketContract.aftermarketContractProductList[productIndex].partsContractProductList.map((item) => {
              if (val && item) {
                item.quantity = Number(val) * Number(item.singleQuantity)
              } else {
                item.quantity = 0
              }
              return {
                ...item,
              }
            })
        }
      }
      this.$nextTick(() => {
        this.calculationMoney()
      })
    },
    calculationMoney() {
      if (this.aftermarketContract.aftermarketContractProductList && this.aftermarketContract.aftermarketContractProductList.length > 0) {
        let productPriceAmount = 0
        let deliverGoodsPriceAmount = 0
        let expressPriceAmount = 0
        let expensePriceAmount = 0
        let packingMaterialAmount = 0
        this.aftermarketContract.aftermarketContractProductList.map((item) => {
          if (item.quantity) {
            if (item.productPrice) {
              productPriceAmount = parseFloat(Number(productPriceAmount) + Number(item.productPrice) * Number(item.quantity)).toFixed(2)
            }
            if (item.deliverGoodsPrice) {
              deliverGoodsPriceAmount = parseFloat(Number(deliverGoodsPriceAmount) + Number(item.deliverGoodsPrice) * Number(item.quantity)).toFixed(2)
            }
            if (item.expressPrice) {
              expressPriceAmount = parseFloat(Number(expressPriceAmount) + Number(item.expressPrice) * Number(item.quantity)).toFixed(2)
            }
            if (item.expensePrice) {
              expensePriceAmount = parseFloat(Number(expensePriceAmount) + Number(item.expensePrice) * Number(item.quantity)).toFixed(2)
            }
            if (item.partsContractProductList && item.partsContractProductList.length > 0) {
              item.partsContractProductList.map((itemBOM) => {
                if (itemBOM.quantity && itemBOM.price) {
                  packingMaterialAmount = parseFloat(Number(packingMaterialAmount) + Number(itemBOM.price) * Number(itemBOM.quantity)).toFixed(2)
                }
              })
            }
          }
        })
        this.aftermarketContract.productPriceAmount = productPriceAmount
        this.aftermarketContract.deliverGoodsPriceAmount = deliverGoodsPriceAmount
        this.aftermarketContract.expressPriceAmount = expressPriceAmount
        this.aftermarketContract.expensePriceAmount = expensePriceAmount
        this.aftermarketContract.packingMaterialAmount = packingMaterialAmount
        this.aftermarketContract.contractAmount = parseFloat(
          Number(productPriceAmount) + Number(deliverGoodsPriceAmount) + Number(expressPriceAmount) + Number(expensePriceAmount) + Number(packingMaterialAmount)
        ).toFixed(2)
        this.aftermarketContract.amount = this.aftermarketContract.contractAmount
      }
    },
    beforeAvatarUpload(file) {
      let fileType = this.getFileType(file.name)
      if (['jpg', 'png', 'jpeg'].includes(fileType)) {
        const isLt5M = file.size / 1024 / 1024 < 5
        if (!isLt5M) {
          this.$message.error('上传图片大小不能超过 5MB!')
        }
        return isLt5M
      } else {
        this.msgInfo('请上传jpg，png，jpeg格式的文件')
        return false
      }
    },
    uploadSuccess(response, file, fileList, index) {
      this.aftermarketContract.aftermarketContractProductList[index].loading = false
      this.aftermarketContract.aftermarketContractProductList[index].imgPath = response.data.details.path
      this.aftermarketContract.aftermarketContractProductList[index].imgPathName = response.data.details.realName
    },
    uploadError(response, file, fileList, index) {
      this.aftermarketContract.aftermarketContractProductList[index].loading = false
    },
    uploadProgress(event, file, fileList, index) {
      this.aftermarketContract.aftermarketContractProductList[index].loading = true
    },
    saveCancel() {
      this.saveOftenDialog = false
      this.saveform = {
        name: '',
        bomCombinationDetailsList: [],
      }
    },
    openSaveOftenDialog(index) {
      if (!this.aftermarketContract.aftermarketContractProductList[index].partsContractProductList.length > 0) return this.msgInfo('请先选择包材配件！')
      this.saveOftenList = this.aftermarketContract.aftermarketContractProductList[index].partsContractProductList //记录此次要保存的组合包材数据
      this.saveOftenDialog = true
    },
    saveOften() {
      this.$refs['saveform'].validate((valid) => {
        if (valid) {
          let arr = this.saveOftenList.map((item) => ({ bomColorId: item.bomColorId, singleQuantity: item.singleQuantity, price: item.price }))
          this.saveform.bomCombinationDetailsList = arr
          API.save(this.saveform).then(
            () => {
              this.msgSuccess('保存成功！')
              this.saveCancel()
            },
            () => {}
          )
        } else {
          return false
        }
      })
    },
    handleOpenOftenDialog(index) {
      if (
        this.aftermarketContract.aftermarketContractProductList[index].quantity &&
        this.aftermarketContract.aftermarketContractProductList[index].quantity > 0
      ) {
        this.getComposeList()
        this.selectIndex = index
        this.openOftenDialog = true
      } else return this.msgInfo('请先输入产品数量')
    },
    getComposeList() {
      API.list({ name: '', pageSize: 9999, pageNum: 1 }).then(
        (res) => {
          this.oftenTableList = res.data.data
        },
        (err) => {
          console.log(err)
        }
      )
    },
    removeCompose(id) {
      this.$confirm('是否确认删除此条包材组合？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          API.del({ id }).then(
            () => {
              this.msgSuccess('删除成功！')
              this.getComposeList()
            },
            (err) => {
              console.log(err, 'ss')
            }
          )
        })
        .catch((err) => {
          console.log(err)
        })
    },
    handleQuery() {
      this.getComposeList()
    },
    resetQuery() {
      this.resetForm('composeForm')
      this.handleQuery()
    },
    selectCompose(row) {
      const list = row.bomCombinationDetailsList
      let sum = this.aftermarketContract.aftermarketContractProductList[this.selectIndex].quantity
      let arr = list.map((item) => {
        return {
          name: item.bomColorName,
          bomColorId: item.bomColorId,
          price: item.price,
          quantity: Number(item.singleQuantity) * sum,
          singleQuantity: Number(item.singleQuantity),
          bomId: item.bomId,
          costPrice: item.costPrice,
        }
      })
      this.aftermarketContract.aftermarketContractProductList[this.selectIndex].partsContractProductList = arr
      //选择完成后重新计算价格
      this.$nextTick(() => {
        this.changeProductQuantity(this.aftermarketContract.aftermarketContractProductList[this.selectIndex].quantity, this.selectIndex)
        this.msgSuccess('选择完成')
      })
    },
    handleClickUpload(item) {
      let path = JSON.parse(JSON.stringify(item)).replace(/\\/g, '/')
      addFolder(path).then(
        () => {
          let a = document.createElement('a')
          a.href = 'printer://' + (this.filePrefix + path).replace(/\//g, '/') + '/'
          a.style.display = 'none'
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        },
        (err) => {
          console.log('addFolder:' + err)
        }
      )
    },
    submitSeparateBill() {
      this.$refs.separateBill.validate((valid) => {
        if (valid) {
          if (this.separateBillForm.splitOrderQuantity >= Number(this.separateBillItem.quantity)) {
            return this.msgInfo('拆解数量不能大于等于产品数量!')
          }
          this.loadingStatus = true
          API.splitOrder(this.separateBillForm).then(
            () => {
              this.$emit('separateBillSubmit', true)
              this.msgSuccess('拆解完成')
              this.openSeparateBill = false
              this.loadingStatus = false
            },
            (err) => {
              console.log('splitOrder: ' + err)
              this.loadingStatus = false
            }
          )
        }
      })
    },
    clickCancelSeparateBill(item) {
      let data = {
        id: item.id,
        artworkDocument: JSON.parse(JSON.stringify(item.artworkDocument)).replace(/\\/g, '/'),
        parentId: item.parentId,
        quantity: item.quantity,
      }
      API.cancelSplitOrder(data).then(() => {
        this.$emit('separateBillSubmit', true)
        this.msgSuccess('拆解完成')
      })
    },
    getPrice(item, index) {
      if (item.quantity) {
        getPrice({ id: item.productColorId, quantity: item.quantity }).then((res) => {
          item.productPrice = res.data.data.bomPrice
          item.expensePrice = res.data.data.expensePrice
          item.deliverGoodsPrice = res.data.data.deliverGoodsPrice
          item.expressPrice = res.data.data.expressPrice
          item.expressCostPrice = res.data.data.expressCostPrice
          item.deliverGoodsCostPrice = res.data.data.deliverGoodsCostPrice
          item.expenseCostPrice = res.data.data.expenseCostPrice
          this.$nextTick(() => {
            this.changeProductQuantity(item.quantity, index)
          })
        })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.searchBtn {
  background: #20b2aa;
  color: #fff;
  border: 1px solid #20b2aa;
}
.img {
  width: 32px;
  height: 32px;
  cursor: pointer;
  object-fit: contain;
  vertical-align: middle;
}
::v-deep {
  .el-input__inner {
    border-radius: 1px;
  }
  .el-button--mini {
    border-radius: 1px;
  }
  .miniBtn .el-button {
    padding: 0px !important;
  }
  .tableHeader th {
    background-color: #edf0f5;
    height: 35px;
    padding: 0;
  }
  .el-form-item__content {
    min-width: 60px !important;
  }
  .el-collapse-item__header {
    justify-content: center;
  }
  .el-collapse-item__arrow {
    margin: 0;
  }
  .el-input-number {
    .el-input__inner {
      text-align: left !important;
    }
  }
  .el-input__inner {
    height: 28px;
    line-height: 28px;
  }
  .input .el-input__inner {
    width: 70px;
  }
  .smallInput .el-input-number--mini,
  .smallInput .el-input__inner {
    width: 100px;
  }
  .el-radio__label {
    font-size: 12px;
  }
}
.factoryLoad {
  background-color: #f59a234d;
  padding: 0 8px;
  border-radius: 50px;
  border: 1px solid #f59a234d;
}
.insufficientInventory {
  background-color: #931e2c4d;
  padding: 0 8px;
  border-radius: 50px;
  border: 1px solid #931e2c4d;
}
.productTable {
  width: 100%;
  table-layout: fixed;
  th {
    background-color: #edf0f5;
    height: 35px;
    padding: 0;
    div {
      text-align: left;
      padding: 0 20px;
    }
  }
  .tr {
    td {
      vertical-align: top;
    }
  }
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  border: 1px dashed #ccc;
  // background-color: #f9f9f9;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  &:hover {
    border-color: #409eff;
  }
}
.productImg {
  width: 60px;
  height: 60px;
  cursor: pointer;
  object-fit: contain;
  vertical-align: middle;
  border: none;
}
.table {
  width: 100%;
}
.compose-table {
  td {
    padding: 3px;
    vertical-align: middle;
  }
}
</style>
