<template>
  <div class="container" id="index-app">
    <div class="center-container">
      <!-- 下拉弹出框，并设置两个按钮，第一个按钮作为弹出按钮 -->
      <el-collapse>
        <el-collapse-item>
          <template slot="title">
            <div>
              <el-button style="margin-left: 20px" size="small" type="primary" >财务费用明细</el-button>
              <el-button style="margin-left: 50px" @click.native.stop.prevent="restoreDefaults" size="small" type="primary" >恢复默认</el-button>
            </div>
          </template>
          <div class="form-box gray-background" style="margin-top: 5px; padding-top: 5px">
            <el-form label-width="150px" :model="formLabelAlign" :rules="formRules">
              <el-row>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.officeExpense.fieldStatus }">
                  <el-form-item label="办公费" title="办公费" prop="officeExpense.value">
                    <el-input v-model="formLabelAlign.officeExpense.value" placeholder="办公费"
                              @blur="validateAndSetDefault(formLabelAlign, 'officeExpense')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.travelExpense.fieldStatus }">
                  <el-form-item label="差旅费" title="差旅费" prop="travelExpense.value">
                    <el-input v-model="formLabelAlign.travelExpense.value" placeholder="差旅费"
                              @blur="validateAndSetDefault(formLabelAlign, 'travelExpense')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.salaryInsur.fieldStatus }">
                  <el-form-item label="工资及福利保险" title="工资及福利保险" prop="salaryInsur.value">
                    <el-input v-model="formLabelAlign.salaryInsur.value" placeholder="工资及福利保险"
                              @blur="validateAndSetDefault(formLabelAlign, 'salaryInsur')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.otherMgmtExpense.fieldStatus }">
                  <el-form-item label="其他管理费" title="其他管理费" prop="otherMgmtExpense.value">
                    <el-input v-model="formLabelAlign.otherMgmtExpense.value" placeholder="其他管理费"
                              @blur="validateAndSetDefault(formLabelAlign, 'otherMgmtExpense')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.carExpense.fieldStatus }">
                  <el-form-item label="汽车费用" title="汽车费用" prop="carExpense.value">
                    <el-input v-model="formLabelAlign.carExpense.value" placeholder="汽车费用"
                              @blur="validateAndSetDefault(formLabelAlign, 'carExpense')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col >
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.mgmtBizEntFee.fieldStatus }">
                  <el-form-item label="管理-业务招待费" title="管理-业务招待费" prop="mgmtBizEntFee.value">
                    <el-input v-model="formLabelAlign.mgmtBizEntFee.value" placeholder="管理-业务招待费"
                              @blur="validateAndSetDefault(formLabelAlign, 'mgmtBizEntFee')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.mgmtDeprecExpense.fieldStatus }">
                  <el-form-item label="管理-折旧费" title="管理-折旧费" prop="mgmtDeprecExpense.value"
                                @blur="validateAndSetDefault(formLabelAlign, 'mgmtDeprecExpense')">
                    <el-input v-model="formLabelAlign.mgmtDeprecExpense.value" placeholder="管理-折旧费">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.consultAuditFee.fieldStatus }">
                  <el-form-item label="咨询与审计费" title="咨询与审计费" prop="consultAuditFee.value"
                                @blur="validateAndSetDefault(formLabelAlign, 'consultAuditFee')">
                    <el-input v-model="formLabelAlign.consultAuditFee.value" placeholder="咨询与审计费">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6"  :class="{ 'changed-field': formLabelAlign.tenderCost.fieldStatus }">
                  <el-form-item label="标书费用" title="标书费用" prop="tenderCost.value">
                    <el-input v-model="formLabelAlign.tenderCost.value" placeholder="标书费用"
                              @blur="validateAndSetDefault(formLabelAlign, 'tenderCost')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.rentExpense.fieldStatus }">
                  <el-form-item  label="房租费" title="房租费" prop="rentExpense.value">
                    <el-input v-model="formLabelAlign.rentExpense.value" placeholder="房租费"
                              @blur="validateAndSetDefault(formLabelAlign, 'rentExpense')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.salary.fieldStatus }">
                  <el-form-item label="工资" title="工资" prop="salary.value">
                    <el-input v-model="formLabelAlign.salary.value" placeholder="工资"
                              @blur="validateAndSetDefault(formLabelAlign, 'salary')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.inspectFee.fieldStatus }">
                  <el-form-item label="检验检查费" prop="inspectFee.value">
                    <el-input v-model="formLabelAlign.inspectFee.value" placeholder="检验检查费"
                              @blur="validateAndSetDefault(formLabelAlign, 'inspectFee')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.transTravelExpense.fieldStatus }">
                  <el-form-item label="销售-交通与差旅费" title="交通与差旅费" prop="transTravelExpense.value">
                    <el-input v-model="formLabelAlign.transTravelExpense.value" placeholder="交通与差旅费"
                              @blur="validateAndSetDefault(formLabelAlign, 'transTravelExpense')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.otherSalesExpense.fieldStatus }">
                  <el-form-item label="其他销售费" title="其他销售费" prop="otherSalesExpense.value">
                    <el-input v-model="formLabelAlign.otherSalesExpense.value" placeholder="其他销售费"
                              @blur="validateAndSetDefault(formLabelAlign, 'otherSalesExpense')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.biddingCost.fieldStatus }">
                  <el-form-item label="投标费用" title="投标费用" prop="biddingCost.value">
                    <el-input v-model="formLabelAlign.biddingCost.value" placeholder="投标费用"
                              @blur="validateAndSetDefault(formLabelAlign, 'biddingCost')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.bizFee.fieldStatus }">
                  <el-form-item label="销售-业务费" title="销售-业务费" prop="bizFee.value">
                    <el-input v-model="formLabelAlign.bizFee.value" placeholder="销售-业务费"
                              @blur="validateAndSetDefault(formLabelAlign, 'bizFee')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.salesBizEntFee.fieldStatus }">
                  <el-form-item label="销售-业务招待费" title="销售-业务招待费" prop="salesBizEntFee.value">
                    <el-input v-model="formLabelAlign.salesBizEntFee.value" placeholder="销售-业务招待费"
                              @blur="validateAndSetDefault(formLabelAlign, 'salesBizEntFee')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.transpHandlingFee.fieldStatus }">
                  <el-form-item label="运输装卸费" title="运输装卸费" prop="transpHandlingFee.value">
                    <el-input v-model="formLabelAlign.transpHandlingFee.value" placeholder="运输装卸费"
                              @blur="validateAndSetDefault(formLabelAlign, 'transpHandlingFee')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.manufDeprecExpense.fieldStatus }">
                  <el-form-item label="制造-折旧费" title="制造-折旧费" prop="manufDeprecExpense.value">
                    <el-input v-model="formLabelAlign.manufDeprecExpense.value" placeholder="制造-折旧费"
                              @blur="validateAndSetDefault(formLabelAlign, 'manufDeprecExpense')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.interestExpense.fieldStatus }">
                  <el-form-item label="利息支出" title="利息支出" prop="interestExpense.value">
                    <el-input v-model="formLabelAlign.interestExpense.value" placeholder="利息支出"
                              @blur="validateAndSetDefault(formLabelAlign, 'interestExpense')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.handlingFee.fieldStatus }">
                  <el-form-item label="手续费" title="手续费" prop="handlingFee.value">
                    <el-input v-model="formLabelAlign.handlingFee.value" placeholder="手续费"
                              @blur="validateAndSetDefault(formLabelAlign, 'handlingFee')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.discInterest.fieldStatus }">
                  <el-form-item label="贴现利息" title="贴现利息" prop="discInterest.value">
                    <el-input v-model="formLabelAlign.discInterest.value" placeholder="贴现利息"
                              @blur="validateAndSetDefault(formLabelAlign, 'discInterest')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.otherFinExpenses.fieldStatus }">
                  <el-form-item label="财务-其他费用" title="财务-其他费用" prop="otherFinExpenses.value">
                    <el-input v-model="formLabelAlign.otherFinExpenses.value" placeholder="财务-其他费用"
                              @blur="validateAndSetDefault(formLabelAlign, 'otherFinExpenses')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :class="{ 'changed-field': formLabelAlign.invOpCost.fieldStatus }">
                  <el-form-item label="存货机会成本" title="存货机会成本" prop="invOpCost.value">
                    <el-input v-model="formLabelAlign.invOpCost.value" placeholder="存货机会成本"
                              @blur="validateAndSetDefault(formLabelAlign, 'invOpCost')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6"  :class="{ 'changed-field': formLabelAlign.tax.fieldStatus }">
                  <el-form-item label="税金" title="税金" prop="tax.value">
                    <el-input v-model="formLabelAlign.tax.value" placeholder="税金"
                              @blur="validateAndSetDefault(formLabelAlign, 'tax')">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
      </el-collapse>
      <!-- 总计的form -->
      <div class="total-box gray-background" style="margin-top: 5px; padding-top: 5px;">
        <el-form label-width="130px" class="" :model="totalForm" >
          <el-row>
            <el-col :span="6">
              <el-form-item label="财务点数合计" title="财务费用合计">
                <el-input :disabled="true" v-model="totalForm.totalFinExpenses" placeholder="财务费用合计">
                  <template slot="append">%</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" >
              <el-form-item label="厂价金额合计" title="厂价金额合计">
                <el-input :disabled="true" v-model="totalForm.totalFactoryAmount" placeholder="厂价金额合计">
                  <template slot="append">￥</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" >
              <el-form-item label="成本金额合计" title="成本金额合计">
                <el-input :disabled="true" v-model="totalForm.totalActualAmount" placeholder="成本金额合计">
                  <template slot="append">￥</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" >
              <el-form-item title="">
                            <span slot="label">
                                 合计差异
									<el-tooltip :content="'总差异 = (厂价金额合计 - 成本金额合计) / 厂价金额合计'" placement="top">
										<i class="el-icon-question"></i>
									</el-tooltip>
								</span>
                <el-input :disabled="true" v-model="totalForm.totalDifferenceValue" placeholder="总差异">
                  <template slot="append">%</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 添加物料和计算数据的按钮div -->
      <div class="button-box">
        <el-button type="text" @click="addMaterial">添加物料</el-button>
<!--        <el-button type="text" @click="calculateRedBookPrice">计算红本价格</el-button>-->
        <el-button type="text" @click="calculatedData">计算数据</el-button>
      </div>
      <!-- 物料表格控件 -->
      <div class="table-box">
        <el-table
          :data="materialData"
          border
          :cell-style="cellStyle"
          :header-cell-style="{ background: '#eef1f6', color: '#606266', 'text-align': 'center' }">
          <el-table-column
            fixed
            label="编号"
            type="index"
            width="50">
          </el-table-column>
          <el-table-column
            width="180"
            prop="prodCategory"
            label="产品大类">
          </el-table-column>
          <el-table-column
            width="120"
            prop="model"
            label="型号">
          </el-table-column>
          <el-table-column
            width="180"
            prop="specification"
            label="规格">
          </el-table-column>
          <el-table-column
            width="180"
            prop="voltLevel"
            label="电压等级">
          </el-table-column>
          <el-table-column
            width="180"
            prop="measureUnit"
            label="单位">
          </el-table-column>
          <el-table-column
            width="180"
            prop="matCostPrice"
            label="材料成本价格(￥)">
            <template slot-scope="scope">
              {{ parseFloat(scope.row.matCostPrice).toFixed(2)}}
            </template>
          </el-table-column>
          <el-table-column
            width="180"
            prop="redBookPrice"
            label="红本价格(￥)">
            <template slot-scope="scope">
              {{ parseFloat(scope.row.redBookPrice).toFixed(2)}}
            </template>
          </el-table-column>
          <el-table-column
            width="180"
            prop="redBookCost"
            label="红本成本(￥)">
            <template slot-scope="scope">
              {{ parseFloat(scope.row.redBookCost).toFixed(2)}}
            </template>
          </el-table-column>
          <el-table-column
            width="180"
            prop="rbFacPrice"
            label="红本厂价(￥)">
            <template slot-scope="scope">
              {{ parseFloat(scope.row.rbFacPrice).toFixed(2)}}
            </template>
          </el-table-column>
          <el-table-column
            width="180"
            prop="number"
            label="数量">
            <template v-slot="scope">
              <el-input v-model="scope.row.number">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            width="180"
            prop="varRatio"
            label="差异比率">
            <!-- 自定义表头 -->
            <template slot="header" slot-scope="scope">
              <div>
                差异比率
                <el-tooltip effect="dark" content="差异比率 = (红本厂价 - 材料成本价格) / 红本厂价">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </div>
            </template>

            <!-- 列内容 -->
            <template slot-scope="scope">
              <!-- 这里是列的具体内容 -->
              {{ scope.row.varRatio }}
            </template>
          </el-table-column>
          <el-table-column
            width="180"
            prop="wdFSurcharge"
            label="盘具运费">
            <template slot-scope="scope">
              {{ (parseFloat(scope.row.wdFSurcharge) * 100).toFixed(3) + '%' }}
            </template>
          </el-table-column>
          <el-table-column
            width="180"
            prop="manuCost"
            label="制造成本">
            <template slot-scope="scope">
              {{ (parseFloat(scope.row.manuCost) * 100).toFixed(3) + '%' }}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            width="120"
            prop="totalCost"
            label="总成本(￥)">
          </el-table-column>
          <el-table-column
            fixed="right"
            width="120"
            prop="totalFacPrice"
            label="总厂价(￥)">
          </el-table-column>
          <el-table-column
            fixed="right"
            width="200"
            prop="totalVariance"
            label="(总厂价 - 总成本)/总厂价">
          </el-table-column>
          <el-table-column
            fixed="right"
            width="150"
            label="操作">
            <template slot-scope="scope">
              <el-button @click="handleviewDetails(scope.row)" style="color: dodgerblue; margin-right: 20px" type="text">查看详情</el-button>
              <el-button @click="handleDeleteClick(scope.$index)" style="color: red;" type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!------------------------ dialog控件 ------------------------------------>
    <el-dialog class="materialDialogTable" :visible.sync="dialogMaterialVisible" width="1100px">
      <div slot="title"  style="margin: 0px">
        <el-form>
          <el-form-item >
            <el-input style="width: 180px; margin-right: 20px" v-model="materialQueryParams.precMaterialName" placeholder="开头物料名称精确查询">
            </el-input>
            <el-input style="width: 180px; margin-right: 20px" v-model="materialQueryParams.vagueMaterialName" placeholder="物料名称模糊查询">
            </el-input>
            <el-input style="width: 180px; margin-right: 20px" v-model="materialQueryParams.vagueModel" placeholder="规格模糊查询">
            </el-input>
            <el-button type="primary" size="small" @click="searchMaterial">查询物料</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div style="display: flex; flex-direction: row;">
        <div style="width: 700px">
          <el-table
            :data="materialDialogData"
            @selection-change="handleSelectionChange"
            ref="materialDialogData"
            :header-cell-style="{ background: '#eef1f6', color: '#606266', 'text-align': 'center', 'padding': '0px'}"
            :cell-style="{'text-align': 'center', 'padding': '5px 0px'}"
            highlight-selection-row
            :row-key="row => row.uid"
            :reserve-selection="true"
            border>
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              label="序号"
              type="index"
              width="55">
            </el-table-column>
            <el-table-column
              width="120"
              prop="prodCategory"
              label="产品大类">
            </el-table-column>
            <el-table-column
              width="120"
              prop="model"
              label="型号">
            </el-table-column>
            <el-table-column
              width="125"
              prop="specification"
              label="规格">
            </el-table-column>
            <el-table-column
              width="120"
              prop="voltLevel"
              label="电压">
            </el-table-column>
            <el-table-column
              width="102"
              prop="measureUnit"
              label="单位">
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="materialQueryParams.pageNum"
            :limit.sync="materialQueryParams.pageSize"
            @pagination="searchMaterial"
          />
        </div>
        <div style="flex-grow: 1; padding-left: 20px;">
          <div
            v-for="(selectedItem, index) in selectedMaterialItems"
            :key="index"
            class="selected-item"
          >
            {{ selectedItem.model }} , {{ selectedItem.specification }} , {{ selectedItem.voltLevel }}
            <el-button @click="removeSelectedItem(selectedItem)" type="text" class="remove-btn">&#10006;</el-button>
          </div>
        </div>
      </div>

      <div style="text-align: center; padding-top: 20px">
        <el-button-group>
          <el-button type="primary" size="small" style="margin-right: 80px" @click="addMaterialToTable">确认</el-button>
          <el-button type="warning" size="small" @click="closeMaterialDialog">取消</el-button>
        </el-button-group>
      </div>
    </el-dialog>
    <el-dialog class="matUsageDetDialogTable" :visible.sync="dialogMatUsageDetVisible" width="725px">
      <el-table
        :data="matUsageDetDialogData"
        ref="matUsageDetDialogData"
        height="550px"
        :header-cell-style="{ background: '#eef1f6', color: '#606266', 'text-align': 'center', 'padding': '0px'}"
        :cell-style="{'text-align': 'center', 'padding': '5px 0px'}"

        border>
        <el-table-column
          label="序号"
          type="index"
          width="55">
        </el-table-column>
        <el-table-column
          width="260"
          prop="materialName"
          label="关联用料">
        </el-table-column>
        <el-table-column
          width="120"
          prop="costClQty"
          label="用量1">
        </el-table-column>
        <el-table-column
          width="125"
          prop="costClQty2"
          label="用量2">
        </el-table-column>
        <el-table-column
          width="120"
          prop="materialPrice"
          label="单价">
        </el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import {queryMaterialListByParam, queryRedBCostByParams, queryRedBPriceByParams, queryRedBookVer, queryRedBookLocalVer } from "@/api/quote/quote";
import {getMaterial} from "@/api/material/material";
const commonRule = [
  { required: true, message: '不能为空值，可填0', trigger: 'blur' },
  { pattern: /^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{1,3})?$/, message: '格式有误，只能为数字格式', trigger: 'blur' }
];
let redBookVer = 0;     //红本版本号
let redBookLocalVer = 0;    //本地红本版本号

export default {
  name: "index-app",
  data() {
    return {
      formLabelAlign: {
        officeExpense: { value: 0.022, defaultValue: 0.022, fieldStatus: false },
        travelExpense: { value: 0.011, defaultValue: 0.011, fieldStatus: false },
        salaryInsur: { value: 0.394, defaultValue: 0.394, fieldStatus: false },
        otherMgmtExpense: { value: 0.373, defaultValue: 0.373, fieldStatus: false },
        carExpense: { value: 0.010, defaultValue: 0.010, fieldStatus: false },
        mgmtBizEntFee: { value: 0.156, defaultValue: 0.156, fieldStatus: false },
        mgmtDeprecExpense: { value: 0.016, defaultValue: 0.016, fieldStatus: false },
        consultAuditFee: { value: 0.026, defaultValue: 0.026, fieldStatus: false },
        tenderCost: { value: 0.023, defaultValue: 0.023, fieldStatus: false },
        rentExpense: { value: 0.052, defaultValue: 0.052, fieldStatus: false },
        salary: { value: 0.239, defaultValue: 0.239, fieldStatus: false },
        inspectFee: { value: 0.016, defaultValue: 0.016, fieldStatus: false },
        transTravelExpense: { value: 0.020, defaultValue: 0.020, fieldStatus: false },
        otherSalesExpense: { value: 0.073, defaultValue: 0.073, fieldStatus: false },
        biddingCost: { value: 0.134, defaultValue: 0.134, fieldStatus: false },
        bizFee: { value: 1.183, defaultValue: 1.183, fieldStatus: false },
        salesBizEntFee: { value: 0.098, defaultValue: 0.098, fieldStatus: false },
        transpHandlingFee: { value: 0.621, defaultValue: 0.621, fieldStatus: false },
        manufDeprecExpense: { value: 0.217, defaultValue: 0.217, fieldStatus: false },
        interestExpense: { value: 0.436, defaultValue: 0.436, fieldStatus: false },
        handlingFee: { value: 0.108, defaultValue: 0.108, fieldStatus: false },
        discInterest: { value: 0.363, defaultValue: 0.363, fieldStatus: false },
        otherFinExpenses: { value: 0.197, defaultValue: 0.197, fieldStatus: false },
        invOpCost: { value: 0.031, defaultValue: 0.031, fieldStatus: false },
        tax: { value: 1.5, defaultValue: 1.5, fieldStatus: false },                 //税金
      },
      totalForm: {
        totalFinExpenses: 0,
        totalFactoryAmount: 0,
        totalActualAmount: 0,
        totalDifferenceValue: 0
      },
      formRules: {
        'officeExpense.value': commonRule,
        'travelExpense.value': commonRule,
        'salaryInsur.value': commonRule,
        'otherMgmtExpense.value': commonRule,
        'carExpense.value': commonRule,
        'mgmtBizEntFee.value': commonRule,
        'mgmtDeprecExpense.value': commonRule,
        'tenderCost.value': commonRule,
        'rentExpense.value': commonRule,
        'salary.value': commonRule,
        'inspectFee.value': commonRule,
        'transTravelExpense.value': commonRule,
        'otherSalesExpense.value': commonRule,
        'biddingCost.value': commonRule,
        'bizFee.value': commonRule,
        'consultAuditFee.value': commonRule,
        'transpHandlingFee.value': commonRule,
        'manufDeprecExpense.value': commonRule,
        'interestExpense.value': commonRule,
        'handlingFee.value': commonRule,
        'discInterest.value': commonRule,
        'otherFinExpenses.value': commonRule,
        'invOpCost.value': commonRule,
        'tax.value': commonRule,
        'salesBizEntFee.value': commonRule
        // Add similar rules for other form fields
      },
      materialData: [

      ],
      dialogMaterialVisible: false,
      materialQueryParams: {
        pageNum: 1,
        pageSize: 10,
        precMaterialName: '',
        vagueMaterialName: '',
        vagueModel: '',
      },
      materialDialogData: [

      ],
      selectedMaterialItems: [], // 选中的数据
      savedSelectedMaterials: [], // 保存选中的数据
      total: 0,
      dialogMatUsageDetVisible: false,
      matUsageDetDialogData: [],
    }
  },
  computed: {

  },
  created() {
    this.getRedBookVersion();
    this.calculateTotal();
  },

  mounted() {

  },
  methods: {
    async init () {

    },
    /**-------------获取红本版本号---------------**/
    getRedBookVersion() {
      queryRedBookVer().then(response => {
        redBookVer = response.msg
        console.log("redBookVer:" + redBookVer)
      });
      queryRedBookLocalVer().then(response => {
        redBookLocalVer = response.msg
        console.log("redBookLocalVer:" + redBookLocalVer)
      });
    },
    /**--------------输入值改变则底色发生变化------------**/
    validateAndSetDefault(formLabelAlign, field) {
      if (formLabelAlign[field].value !== formLabelAlign[field].defaultValue) {
        this.$set(formLabelAlign, field, {
          ...formLabelAlign[field],
          fieldStatus: true
        });
      }
    },
    /**-----------恢复默认------------**/
    restoreDefaults() {
      for (const key in this.formLabelAlign) {
        if (this.formLabelAlign.hasOwnProperty(key)) {
          // 将value恢复为defaultValue
          this.$set(this.formLabelAlign, key, {
            value: this.formLabelAlign[key].defaultValue,
            defaultValue: this.formLabelAlign[key].defaultValue,
            fieldStatus: false,
          });
        }
      }
     this.calculatedData();
    },
    /**-------物料表格的cell样式----------**/
    cellStyle({row, column, rowIndex, columnIndex}) {
      if(columnIndex === 0) {
        return 'color : black; text-align : center; background : #E0E0E0; padding: 0px';
      } else if (columnIndex === 6 || columnIndex === 9) {
        return 'text-align : center; background : #F5F5F5; padding: 0px';
      } else {
        return ' text-align : center; padding: 0px';
      }
    },
    /**-------物料表格的删除操作----------**/
    handleDeleteClick(index){
      this.materialData.splice(index, 1)
    },
    /**-------------------点击查看物料材料用量详情------------------------**/
    handleviewDetails(row) {
      this.dialogMatUsageDetVisible = true;
      const uid = row.uid;
      getMaterial(uid).then(response => {
        console.log(response);
        this.matUsageDetDialogData = response.data.cmaterialCostList
      });
      console.log("当前行的UID: " + row.uid);
    },
    /**--------添加物料，打开物料dialog框---------**/
    addMaterial(){
      this.dialogMaterialVisible = true;
    },
    /**--------查询物料---------**/
    searchMaterial() {
      if(this.materialQueryParams.precMaterialName ===  '' && this.materialQueryParams.vagueMaterialName === ''
          && this.materialQueryParams.vagueModel === '') {
        this.$message({
          type: 'warning',
          message: "请输入查询条件。"
        });

      } else {
        queryMaterialListByParam(this.materialQueryParams).then(response => {
          if (response.rows.length === 0) {
            this.$message({
              type: 'warning',
              message: "查询结果为空，请检查查询条件。"
            });
          }
          this.materialDialogData = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }
    },
    /**-----------选择物料触发事件----------------**/
    handleSelectionChange(selection) {
      selection.forEach(item => {
        // 判断是否已经存在于已选列表中，避免重复添加
        if (!this.selectedMaterialItems.some(selectedItem => selectedItem.uid === item.uid)) {
          console.log(item)
          this.selectedMaterialItems.push(item);
        }
      });

    },
    /**-------------------删除物料dialog删除已选---------------------**/
    removeSelectedItem(selectedItem) {
      // 判断当前数据是否被选择
      const isSelected = this.$refs.materialDialogData.selection.includes(selectedItem);

      // 从已选列表中移除该项
      const index = this.selectedMaterialItems.findIndex(item => item.uid === selectedItem.uid);
      if (index !== -1) {
        this.selectedMaterialItems.splice(index, 1);
      }

      // 如果当前数据被选择，则取消 el-table 中该项的选择状态
      if (isSelected) {
        this.$refs.materialDialogData.toggleRowSelection(selectedItem, false);
      }

    },
    /**-------------dialog确认按钮，将物料添加进表格-----------------**/
    addMaterialToTable() {
      // 将选中的物料信息添加到表格中
      this.materialData = this.materialData.concat(this.selectedMaterialItems);
      console.log(this.materialData)
      // 清空选中的物料信息
      this.selectedMaterialItems = [];
      this.$refs.materialDialogData.clearSelection();
      this.dialogMaterialVisible = false;
    },
    /**---------------关闭选择物料弹出框--------------------**/
    closeMaterialDialog() {
      this.dialogMaterialVisible = false;
    },
    /**----------------计算红本价格--------------------**/
    calculateRedBookPrice() {
      const param = this.materialData.map(item => ({
        model: item.model,
        specification: item.specification,
        voltLevel: item.voltLevel,
        redBookVer: redBookVer
      }));
      queryRedBCostByParams(param).then(response => {
        for (let i = 0; i < this.materialData.length; i++) {
          for (let j = 0; j < response.data.length; j++) {
            // 检查型号、规格、电压等级是否相等
            if (
              this.materialData[i].model === response.data[j].model &&
              this.materialData[i].specification === response.data[j].specification &&
              this.materialData[i].voltLevel === response.data[j].voltLevel
            ) {
              // 将返回数据的 redBookCost 赋值给表格数据的对应行的 redBookCost
              this.materialData[i].redBookCost = response.data[j].redBookCost;
            }
          }
        }
      });
      queryRedBPriceByParams(param).then(response => {
        for (let i = 0; i < this.materialData.length; i++) {
          for (let j = 0; j < response.data.length; j++) {
            // 检查型号、规格、电压等级是否相等
            if (
              this.materialData[i].model === response.data[j].model &&
              this.materialData[i].specification === response.data[j].specification &&
              this.materialData[i].voltLevel === response.data[j].voltLevel
            ) {
              // 将返回数据的 redBookCost 赋值给表格数据的对应行的 redBookCost
              this.materialData[i].redBookPrice = response.data[j].redBookPrice;
              this.materialData[i].rbFacPrice = response.data[j].rbFacPrice;
            }
          }
        }
      });
    },
    /**---------------计算财务点数总和--------------------**/
    calculateTotal() {
      this.totalForm.totalFinExpenses =parseFloat(
        (
          parseFloat(this.formLabelAlign.officeExpense.value || '0') +
          parseFloat(this.formLabelAlign.travelExpense.value || '0') +
          parseFloat(this.formLabelAlign.salaryInsur.value || '0') +
          parseFloat(this.formLabelAlign.otherMgmtExpense.value || '0') +
          parseFloat(this.formLabelAlign.carExpense.value || '0') +
          parseFloat(this.formLabelAlign.mgmtBizEntFee.value || '0') +
          parseFloat(this.formLabelAlign.mgmtDeprecExpense.value || '0') +
          parseFloat(this.formLabelAlign.consultAuditFee.value || '0') +
          parseFloat(this.formLabelAlign.tenderCost.value || '0') +
          parseFloat(this.formLabelAlign.rentExpense.value || '0') +
          parseFloat(this.formLabelAlign.salary.value || '0') +
          parseFloat(this.formLabelAlign.inspectFee.value || '0') +
          parseFloat(this.formLabelAlign.transTravelExpense.value || '0') +
          parseFloat(this.formLabelAlign.otherSalesExpense.value || '0') +
          parseFloat(this.formLabelAlign.biddingCost.value || '0') +
          parseFloat(this.formLabelAlign.bizFee.value || '0') +
          parseFloat(this.formLabelAlign.salesBizEntFee.value || '0') +
          parseFloat(this.formLabelAlign.transpHandlingFee.value || '0') +
          parseFloat(this.formLabelAlign.manufDeprecExpense.value || '0') +
          parseFloat(this.formLabelAlign.interestExpense.value || '0') +
          parseFloat(this.formLabelAlign.handlingFee.value || '0') +
          parseFloat(this.formLabelAlign.discInterest.value || '0') +
          parseFloat(this.formLabelAlign.otherFinExpenses.value || '0') +
          parseFloat(this.formLabelAlign.invOpCost.value || '0') +
          parseFloat(this.formLabelAlign.tax.value || '0')
        ).toFixed(4))
      console.log(parseFloat(this.formLabelAlign.officeExpense || '0') )
    },
    /**----------------计算数据--------------------**/
    calculatedData() {
      if(redBookVer !== redBookLocalVer) {
        this.$message({
          type: 'warning',
          message: "调价结果未同步，请联系管理员进行同步再进行价格计算。"
        });
      } else {
        /**-------------计算财务总成本---------------**/
        this.calculateTotal();
        /**----------------------进行盘具、数量、人工、水电三个数值的验证---------------**/
        this.validationErrors = []; // 清空之前的错误信息
        this.materialData.forEach((row, index) => {
          const var1 = /^\d*\.?\d+$/.test(row.number);

          // 进行数量验证
          if (!var1) {
            this.validationErrors.push(`第 ${index + 1} 行数量不符合要求\n`);
          }

        });

        /**-----------------------验证完成进行运算，验证结果通过才进行计算--------------------------**/
        if (this.validationErrors.length === 0) {
          // 遍历表格数据进行计算
          this.materialData.forEach((row, index) => {
            this.validationErrors = []; // 清空之前的错误信息

            const redBookFacPrice = parseFloat(row.rbFacPrice);
            const materialCost = parseFloat(row.matCostPrice);
            const wdFSurcharge = parseFloat(row.wdFSurcharge) || 0; // 如果为空，默认为0
            const manuCost = parseFloat(row.manuCost) || 0; // 如果为空，默认为0
            const quantity = parseFloat(row.number) || 0; // 如果为空，默认为0
            const totalFinExpenses = (parseFloat(this.totalForm.totalFinExpenses)) / 100
            const num1 = (quantity * redBookFacPrice);
            const num2 = ((materialCost + materialCost * (manuCost + wdFSurcharge + totalFinExpenses)) * quantity)
            // 进行其他计算
            this.$set(this.materialData, index, {
              ...row,
              varRatio: ((redBookFacPrice - materialCost) / redBookFacPrice * 100).toFixed(2) + '%',
              totalFacPrice: (quantity * redBookFacPrice).toFixed(2),
              totalCost: ((materialCost + materialCost * (manuCost + wdFSurcharge + totalFinExpenses)) * quantity
              ).toFixed(2),
              totalVariance: (((num1 - num2) / num1) * 100).toFixed(2) + '%'
            });
          });
        } else {
          this.validationErrors.push("页面未进行运算，请改正所有错误再进行运算！！！！！");
          this.$message({
            type: 'error',
            dangerouslyUseHTMLString: true,
            message: this.validationErrors.join('<br>')
          });
        }

        // 计算厂价金额合计
        const totalFactoryAmount = this.materialData.reduce((sum, row) => sum + parseFloat(row.totalFacPrice), 0);
        this.totalForm.totalFactoryAmount = totalFactoryAmount.toFixed(2);

        // 计算实际金额合计
        const totalCost = this.materialData.reduce((sum, row) => sum + parseFloat(row.totalCost), 0);
        this.totalForm.totalActualAmount = totalCost.toFixed(2);

        const totalDifferenceValue = (((totalFactoryAmount - totalCost) / totalFactoryAmount) * 100)
        this.totalForm.totalDifferenceValue = totalDifferenceValue.toFixed(2)
      }
    },
  },
}
</script>

<style scoped lang="scss">
.container {
  margin-bottom: 30px;
}

.center-container {
  width: 100%;
}

.gray-background {
  width: 98%;
  margin: auto;
  background-color: #f0f0f0; /* 浅灰色背景 */
  border-radius: 10px; /* 可以根据需要调整边框圆角 */
  backdrop-filter: blur(10px); /* 调整模糊度 */
  -webkit-backdrop-filter: blur(10px); /* 兼容性处理，适用于一些WebKit浏览器 */

}



.form-box .el-col {
  height: 55px;
}

.total-box .el-col {
  height: 42px;
}

.button-box .el-button {
  margin: 10px 80px 10px 0px;
}

.button-box {
  align-items: center;
  text-align: center;
  width: 98%;
  margin: 5px 10px 5px 10px;
  background-color: #f0f0f0; /* 浅灰色背景 */
  border-radius: 10px; /* 可以根据需要调整边框圆角 */
  backdrop-filter: blur(10px); /* 调整模糊度 */
  -webkit-backdrop-filter: blur(10px); /* 兼容性处理，适用于一些WebKit浏览器 */
}

.changed-field {
  background-color: #add8e6; /* 更改后的背景颜色 */
}

::v-deep .materialDialogTable .el-dialog__header {
  padding-bottom: 0px;
}

::v-deep .materialDialogTable .el-dialog__body {
  padding-top: 0px;
}

.selected-item {
  background-color: #f0f0f0;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  margin-bottom: 5px;
  display: flex;
  justify-content: space-between;
}

.remove-btn {
  padding: 0px;
  color: red;
}

.table-box {
  width: 98%;
  margin: auto;
}

::v-deep .el-input__inner {

  height: 30px;
  /*font-family: Roboto, serif;*/
  font-size: 12px;
  line-height: 14px;
}

::v-deep .el-input-group {
  margin-top: 3px;
}

::v-deep .total-box input {
  background: #f0f0f0 !important;
  font-weight: bold !important;
  color: black !important;
}
</style>
