<template>
  <div class="page-body">



    <div class="topbar">
      <a-button @click="selectScheme">选择主柜/抽屉</a-button>
      <a-button @click="print">打印</a-button>
      <a-button @click="toggleAll">收缩/展开</a-button>

      <vxe-switch v-model="showExp" open-label="显示公式" :open-value="true" close-label="显示数值"
        :close-value="false"></vxe-switch>

      <a-radio-group :value="showType" @change="showTypeChange">
        <a-radio-button value="1">
          显示全部
        </a-radio-button>
        <a-radio-button value="2">
          免漆
        </a-radio-button>
        <a-radio-button value="3">
          油漆
        </a-radio-button>
      </a-radio-group>

    </div>

    <a-tabs v-model="tabKey" hide-add @edit="onTabEdit" @change="tabChange">
      <a-tab-pane key="main" :tab="mainTabTitle">


        <a-button @click="reloadMain()" style="margin-bottom: 5px;">重新加载方案</a-button>
        <a-collapse v-model="groupbox1_activeKey">
          <a-collapse-panel key="1" header="基本信息">

            <vxe-form :data="formOptions.data" ref="xForm" :title-width="formOptions.titleWidth"
              :title-align="formOptions.titleAlign" :rules="formOptions.rules" :items="formOptions.items" titleColon>
            </vxe-form>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="部件部分">

            <div slot="extra">
              （合计）板材数量：{{ parseFloat(formOptions.data.fittings_total_quantity || 0).toFixed(0) }}
              封边用量：{{ parseFloat(formOptions.data.fittings_total_seal || 0).toFixed(2) }}
              板材用量：{{ parseFloat(formOptions.data.fittings_total_board_length || 0).toFixed(3) }}
              油漆面积：{{ parseFloat(formOptions.data.fittings_total_paint_area || 0).toFixed(3) }}
            </div>

            <vxe-table border show-overflow keep-source ref="fittings_xTable" :data="fittings_detailsData"
              :keyboard-config="{
                isArrow: true, isDel: true,
                isEnter: false, isTab: true, isEdit: true, isChecked: true
              }" :mouse-config="{ selected: true }" @pulldownSelected="fittings_onPulldownSelected" show-footer
              :footer-method="fittings_footerMethod" :footer-cell-class-name="fittings_footerCellClassName"
              @popupSelected="fittings_onPopupSelected" :export-config="{}" @edit-closed="fittings_afterEditEvent"
              @edit-actived="fittings_beforeEditEvent"
              :edit-config="{ trigger: 'click', mode: 'cell', icon: 'vxe-icon-edit', showStatus: false, beforeEditMethod: fittings_beforeEditMethod }">
              <vxe-column width="60" v-if="!isReadonly">
                <template #default="{ row }">
                  <div class="oplinks2">
                    <a @click.stop="fittings_pageAdd(row)" title="新增">
                      <a-icon type="plus-circle" />
                    </a>
                    <a @click.stop="fittings_pageDelete(row)" title="删除">
                      <a-icon type="delete" />
                    </a>
                  </div>
                </template>
              </vxe-column>
              <vxe-column type="seq" title="序号" width="48"></vxe-column>
              <vxe-column field="fittings" title="部件" width="160" :params="editorFittings" formatter="formatRef"
                :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>
              <vxe-column field="material" title="材料（免漆）" width="160" :params="editorMaterial" formatter="formatRef"
                :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>
              <vxe-column field="paint_material" title="材料（油漆）" width="160" :params="editorMaterial" formatter="formatRef"
                :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>

              <vxe-column field="long_formula" title="长" width="160" :edit-render="{ name: 'EditExpressions' }"
                :params="{ moreExpressionsList: getMoreExpressionsList }">
                <template #default="{ row }">
                  <a-tooltip>
                    <template slot="title">
                      {{ row.long_formula || '' }}
                    </template>
                    <span v-if="showExp">
                      {{ row.long_formula || '' }}
                    </span>
                    <span v-else v-html="formatShowNumber(row.long, 0)"></span>
                  </a-tooltip>
                </template>
              </vxe-column>
              <vxe-column field="width_formula" title="宽" width="160" :edit-render="{ name: 'EditExpressions' }"
                :params="{ moreExpressionsList: getMoreExpressionsList }">
                <template #default="{ row }">
                  <a-tooltip>
                    <template slot="title">
                      {{ row.width_formula || '' }}
                    </template>
                    <span v-if="showExp">
                      {{ row.width_formula || '' }}
                    </span>
                    <span v-else v-html="formatShowNumber(row.width, 0)"></span>
                  </a-tooltip>
                </template>
              </vxe-column>
              <vxe-column field="height_formula" title="厚" width="160" :edit-render="{ name: 'EditExpressions' }"
                :params="{ moreExpressionsList: getMoreExpressionsList }">
                <template #default="{ row }">
                  <a-tooltip>
                    <template slot="title">
                      {{ row.height_formula || '' }}
                    </template>
                    <span v-if="showExp">
                      {{ row.height_formula || '' }}
                    </span>

                    <span v-else v-html="formatShowNumber(row.height, 0)"></span>
                  </a-tooltip>
                </template>
              </vxe-column>
              <vxe-column field="quantity" title="数量" width="80"
                :edit-render="{ name: '$input', props: { type: 'number' } }"></vxe-column>

              <vxe-column field="banding" title="封边" width="160" :params="editorBanding" formatter="formatRef"
                :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>

              <vxe-column field="seal_formula" title="封边用量" width="180" :edit-render="{ name: 'EditExpressions' }">
                <template #default="{ row }">
                  <a-tooltip>
                    <template slot="title">
                      {{ row.seal_formula || '' }}
                    </template>
                    <span v-if="showExp">
                      {{ row.seal_formula || '' }}
                    </span>
                    <span v-else v-html="formatShowNumber(row.seal, 2)"></span>
                  </a-tooltip>
                </template>
              </vxe-column>
              <vxe-column type="seq" title="序号" width="48"></vxe-column>
              <vxe-column field="rate_materials" title="主材利用率" width="80"
                :edit-render="{ name: '$input', props: { type: 'number' } }"></vxe-column>
              <vxe-column field="paint_number" title="油漆面" width="80"
                :edit-render="{ name: '$input', props: { type: 'number' } }"></vxe-column>
              <vxe-column field="board_length_formula" title="板材用量(块)" width="220"
                :edit-render="{ name: 'EditExpressions' }">
                <template #default="{ row }">
                  <a-tooltip>
                    <template slot="title">
                      {{ row.board_length_formula || '' }}
                    </template>
                    <span v-if="showExp">
                      {{ row.board_length_formula || '' }}
                    </span>
                    <span v-else v-html="formatShowNumber(row.board_length, 3)"></span>
                  </a-tooltip>
                </template>

              </vxe-column>
              <vxe-column field="paint_area_formula" title="油漆面积(㎡)" width="220"
                :edit-render="{ name: 'EditExpressions' }">
                <template #default="{ row }">
                  <a-tooltip>
                    <template slot="title">
                      {{ row.paint_area_formula || '' }}
                    </template>
                    <span v-if="showExp">
                      {{ row.paint_area_formula || '' }}
                    </span>
                    <span v-else>
                      {{ parseFloat(row.paint_area || 0).toFixed(3) }}
                    </span>
                  </a-tooltip>
                </template>
              </vxe-column>
              <vxe-column field="real_quantity" title="实木用量(立方)" width="80"
                :edit-render="{ name: '$input', props: { type: 'number' } }"></vxe-column>
              <vxe-column field="remark" title="备注" width="120" :edit-render="{ name: 'textarea' }"></vxe-column>

            </vxe-table>

          </a-collapse-panel>
          <a-collapse-panel key="3" header="配件部分">

            <div slot="extra">
              （合计）金额：{{ parseFloat(formOptions.data.parts_total_amount || 0).toFixed(2) }}
            </div>
            <vxe-table border show-overflow keep-source ref="parts_xTable" :data="parts_detailsData" :keyboard-config="{
              isArrow: true, isDel: true,
              isEnter: false, isTab: true, isEdit: true, isChecked: true
            }" :mouse-config="{ selected: true }" @pulldownSelected="parts_onPulldownSelected"
              @popupSelected="parts_onPopupSelected" :export-config="{}" @edit-closed="parts_afterEditEvent"
              @edit-actived="parts_beforeEditEvent" show-footer :footer-method="parts_footerMethod"
              :footer-cell-class-name="parts_footerCellClassName"
              :edit-config="{ trigger: 'click', mode: 'cell', icon: 'vxe-icon-edit', showStatus: false, beforeEditMethod: parts_beforeEditMethod }">
              <vxe-column width="60" v-if="!isReadonly">
                <template #default="{ row }">
                  <div class="oplinks2">
                    <a @click.stop="parts_pageAdd(row)" title="新增">
                      <a-icon type="plus-circle" />
                    </a>
                    <a @click.stop="parts_pageDelete(row)" title="删除">
                      <a-icon type="delete" />
                    </a>
                  </div>
                </template>
              </vxe-column>
              <vxe-column type="seq" title="序号" width="48"></vxe-column>
              <vxe-column field="parts" title="配件" width="260" :params="editorParts" formatter="formatRef"
                :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>
              <vxe-column field="spec" title="规格" width="120" :edit-render="{ name: '$input' }"></vxe-column>
              <vxe-column field="quantity" title="数量" width="120"
                :edit-render="{ name: '$input', props: { type: 'integer' } }"></vxe-column>
              <vxe-column field="price" title="单价" width="120"
                :edit-render="{ name: '$input', props: { type: 'number' } }"></vxe-column>

              <vxe-column field="amount_formula" title="金额" width="220" :edit-render="{ name: 'EditExpressions' }"
                :params="{ moreExpressionsList: getMoreExpressionsList }">
                <template #default="{ row }">
                  <a-tooltip>
                    <template slot="title">
                      {{ row.amount_formula || '' }}
                    </template>
                    <span v-if="showExp">
                      {{ row.amount_formula || '' }}
                    </span>

                    <span v-else v-html="formatShowNumber(row.amount, 2)"></span>
                  </a-tooltip>
                </template>

              </vxe-column>


            </vxe-table>

          </a-collapse-panel>

          <a-collapse-panel key="4" header="包装部分">
            <div slot="extra">
              （合计）金额：{{ parseFloat(formOptions.data.packaging_total_amount || 0).toFixed(2) }}
            </div>
            <vxe-table border show-overflow keep-source ref="packaging_xTable" :data="packaging_detailsData"
              :keyboard-config="{
                isArrow: true, isDel: true,
                isEnter: false, isTab: true, isEdit: true, isChecked: true
              }" :mouse-config="{ selected: true }" @pulldownSelected="packaging_onPulldownSelected"
              @popupSelected="packaging_onPopupSelected" :export-config="{}" @edit-closed="packaging_afterEditEvent"
              @edit-actived="packaging_beforeEditEvent" show-footer :footer-method="packaging_footerMethod"
              :footer-cell-class-name="packaging_footerCellClassName"
              :edit-config="{ trigger: 'click', mode: 'cell', icon: 'vxe-icon-edit', showStatus: false, beforeEditMethod: packaging_beforeEditMethod }">
              <vxe-column width="60" v-if="!isReadonly">
                <template #default="{ row }">
                  <div class="oplinks2">
                    <a @click.stop="packaging_pageAdd(row)" title="新增">
                      <a-icon type="plus-circle" />
                    </a>
                    <a @click.stop="packaging_pageDelete(row)" title="删除">
                      <a-icon type="delete" />
                    </a>
                  </div>
                </template>
              </vxe-column>
              <vxe-column type="seq" title="序号" width="48"></vxe-column>
              <vxe-column field="packaging" title="包装" width="260" :params="editorPackaging" formatter="formatRef"
                :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>
              <vxe-column field="long_formula" title="长" width="200" :edit-render="{ name: 'EditExpressions' }">
                <template #default="{ row }">
                  <a-tooltip>
                    <template slot="title">
                      {{ row.long_formula || '' }}
                    </template>
                    <span v-if="showExp">
                      {{ row.long_formula || '' }}
                    </span>

                    <span v-else v-html="formatShowNumber(row.long, 1)"></span>
                  </a-tooltip>
                </template>
              </vxe-column>
              <vxe-column field="width_formula" title="宽" width="200" :edit-render="{ name: 'EditExpressions' }">
                <template #default="{ row }">
                  <a-tooltip>
                    <template slot="title">
                      {{ row.width_formula || '' }}
                    </template>
                    <span v-if="showExp">
                      {{ row.width_formula || '' }}
                    </span>
                    <span v-else v-html="formatShowNumber(row.width, 1)"></span>
                  </a-tooltip>
                </template>
              </vxe-column>
              <vxe-column field="height_formula" title="高" width="200" :edit-render="{ name: 'EditExpressions' }">
                <template #default="{ row }">
                  <a-tooltip>
                    <template slot="title">
                      {{ row.height_formula || '' }}
                    </template>
                    <span v-if="showExp">
                      {{ row.height_formula || '' }}
                    </span>
                    <span v-else v-html="formatShowNumber(row.height, 1)"></span>
                  </a-tooltip>
                </template>
              </vxe-column>

              <vxe-column field="quantity_formula" title="数量" width="200" :edit-render="{ name: 'EditExpressions' }">
                <template #default="{ row }">
                  <a-tooltip>
                    <template slot="title">
                      {{ row.quantity_formula || '' }}
                    </template>
                    <span v-if="showExp">
                      {{ row.quantity_formula || '' }}
                    </span>
                    <span v-else v-html="formatShowNumber(row.quantity, 1)"></span>
                  </a-tooltip>
                </template>
              </vxe-column>


              <vxe-column field="price_formula" title="单价" width="200" :edit-render="{ name: 'EditExpressions' }">
                <template #default="{ row }">
                  <a-tooltip>
                    <template slot="title">
                      {{ row.price_formula || '' }}
                    </template>
                    <span v-if="showExp">
                      {{ row.price_formula || '' }}
                    </span>
                    <span v-else v-html="formatShowNumber(row.price, 2)"></span>
                  </a-tooltip>
                </template>
              </vxe-column>



              <vxe-column field="amount_formula" title="金额" width="200" :edit-render="{ name: 'EditExpressions' }">
                <template #default="{ row }">
                  <a-tooltip>
                    <template slot="title">
                      {{ row.amount_formula || '' }}
                    </template>
                    <span v-if="showExp">
                      {{ row.amount_formula || '' }}
                    </span>
                    <span v-else v-html="formatShowNumber(row.amount, 2)"></span>
                  </a-tooltip>
                </template>
              </vxe-column>

            </vxe-table>

          </a-collapse-panel>


          <a-collapse-panel key="5" header="抽屉部分">

            <div slot="extra">
              （合计）金额：{{ parseFloat(formOptions.data.drawer_total_amount || 0).toFixed(2) }}
            </div>
            <vxe-table border show-overflow keep-source ref="drawer_xTable" :data="drawer_detailsData" :keyboard-config="{
              isArrow: true, isDel: true,
              isEnter: false, isTab: true, isEdit: true, isChecked: true
            }" :mouse-config="{ selected: true }" @pulldownSelected="drawer_onPulldownSelected"
              @popupSelected="drawer_onPopupSelected" :export-config="{}" @edit-closed="drawer_afterEditEvent"
              @edit-actived="drawer_beforeEditEvent" :footer-cell-class-name="drawer_footerCellClassName"
              :edit-config="{ trigger: 'click', mode: 'cell', icon: 'vxe-icon-edit', showStatus: false, beforeEditMethod: drawer_beforeEditMethod }">
              <vxe-column type="seq" title="序号" width="48"></vxe-column>
              <vxe-column field="name" title="抽屉" width="260"></vxe-column>
              <vxe-column field="quantity" title="数量" width="200"
                :edit-render="{ name: '$input', props: { type: 'integer' } }"></vxe-column>
              <vxe-column field="expense" formatter="formatNumber" title="单价（免漆）" width="200"></vxe-column>
              <vxe-column field="paint_expense" formatter="formatNumber" title="单价（油漆）" width="200"></vxe-column>

              <vxe-column field="amount" formatter="formatNumber" title="费用（免漆）" width="200"></vxe-column>
              <vxe-column field="paint_amount" formatter="formatNumber" title="费用（油漆）" width="200"></vxe-column>

            </vxe-table>

          </a-collapse-panel>

        </a-collapse>



        <div class="groupbox" v-if="showType == '1' || showType == '2'">
          <h3>核算表（免漆）</h3>
          <a-collapse v-model="groupbox2_activeKey">
            <a-collapse-panel key="1" header="材料">

              <div slot="extra">
                （合计）金额：{{ parseFloat(formOptions.data.material_total_amount || 0).toFixed(2) }}
              </div>

              <vxe-table border show-overflow keep-source ref="material_xTable" :data="material_detailsData"
                :keyboard-config="{
                  isArrow: true, isDel: true,
                  isEnter: false, isTab: true, isEdit: true, isChecked: true
                }" :mouse-config="{ selected: true }" @pulldownSelected="material_onPulldownSelected"
                @popupSelected="material_onPopupSelected" :export-config="{}" @edit-closed="material_afterEditEvent"
                :footer-cell-class-name="material_footerCellClassName"
                :edit-config="{ trigger: 'click', mode: 'cell', icon: 'vxe-icon-edit', showStatus: false, beforeEditMethod: material_beforeEditMethod }">
                <vxe-column width="60" v-if="!isReadonly">
                  <template #default="{ row }">
                    <div class="oplinks2">
                      <a @click.stop="material_pageAdd(row)" title="新增">
                        <a-icon type="plus-circle" />
                      </a>
                      <a @click.stop="material_pageDelete(row)" title="删除">
                        <a-icon type="delete" />
                      </a>
                    </div>
                  </template>
                </vxe-column>
                <vxe-column type="seq" title="序号" width="48"></vxe-column>
                <vxe-column field="material" title="材料" width="260" :params="editorMaterial2" formatter="formatRef"
                  :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>

                <vxe-column field="quantity_formula" title="总用量" width="200" :params="{ hasTotalQuantity: true }"
                  :edit-render="{ name: 'EditExpressions' }">
                  <template #default="{ row }">
                    <a-tooltip>
                      <template slot="title">
                        {{ row.quantity_formula || '' }}
                      </template>
                      <span v-if="showExp">
                        {{ row.quantity_formula || '' }}
                      </span>
                      <span v-else v-html="formatShowNumber(row.quantity, 3)"></span>
                    </a-tooltip>
                  </template>

                </vxe-column>
                <vxe-column field="price" title="单价" width="120"
                  :edit-render="{ name: '$input', props: { type: 'number' } }"></vxe-column>


                <vxe-column field="amount_formula" title="金额" width="200" :edit-render="{ name: 'EditExpressions' }">
                  <template #default="{ row }">
                    <a-tooltip>
                      <template slot="title">
                        {{ row.amount_formula || '' }}
                      </template>
                      <span v-if="showExp">
                        {{ row.amount_formula || '' }}
                      </span>
                      <span v-else v-html="formatShowNumber(row.amount, 2)"></span>
                    </a-tooltip>
                  </template>
                </vxe-column>

              </vxe-table>


            </a-collapse-panel>
            <a-collapse-panel key="2" header="人工" :disabled="false">

              <div slot="extra">
                （合计）金额：{{ parseFloat(formOptions.data.labor_total_amount || 0).toFixed(2) }}
              </div>
              <vxe-table border show-overflow keep-source ref="labor_xTable" :data="labor_detailsData" :keyboard-config="{
                isArrow: true, isDel: true,
                isEnter: false, isTab: true, isEdit: true, isChecked: true
              }" :mouse-config="{ selected: true }" @pulldownSelected="labor_onPulldownSelected"
                @popupSelected="labor_onPopupSelected" :export-config="{}" @edit-closed="labor_afterEditEvent"
                @edit-actived="labor_beforeEditEvent" :footer-cell-class-name="labor_footerCellClassName"
                :edit-config="{ trigger: 'click', mode: 'cell', icon: 'vxe-icon-edit', showStatus: false, beforeEditMethod: labor_beforeEditMethod }">
                <vxe-column width="60" v-if="!isReadonly">
                  <template #default="{ row }">
                    <div class="oplinks2">
                      <a @click.stop="labor_pageAdd(row)" title="新增">
                        <a-icon type="plus-circle" />
                      </a>
                      <a @click.stop="labor_pageDelete(row)" title="删除">
                        <a-icon type="delete" />
                      </a>
                    </div>
                  </template>
                </vxe-column>
                <vxe-column type="seq" title="序号" width="48"></vxe-column>
                <vxe-column field="labor" title="项目" width="260" :params="editorLabor" formatter="formatRef"
                  :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>

                <vxe-column field="amount_formula" title="金额" width="200" :edit-render="{ name: 'EditExpressions' }">

                  <template #default="{ row }">
                    <a-tooltip>
                      <template slot="title">
                        {{ row.amount_formula || '' }}
                      </template>
                      <span v-if="showExp">
                        {{ row.amount_formula || '' }}
                      </span>
                      <span v-else v-html="formatShowNumber(row.amount, 2)"></span>
                    </a-tooltip>
                  </template>
                </vxe-column>

              </vxe-table>



            </a-collapse-panel>

            <a-collapse-panel key="3" header="其他费用" :disabled="false">

              <div slot="extra">
                （合计）金额：{{ parseFloat(formOptions.data.expense_total_amount || 0).toFixed(2) }}
              </div>
              <vxe-table border show-overflow keep-source ref="expense_xTable" :data="expense_detailsData"
                :keyboard-config="{
                  isArrow: true, isDel: true,
                  isEnter: false, isTab: true, isEdit: true, isChecked: true
                }" :mouse-config="{ selected: true }" @pulldownSelected="expense_onPulldownSelected"
                @popupSelected="expense_onPopupSelected" :export-config="{}" @edit-closed="expense_afterEditEvent"
                @edit-actived="expense_beforeEditEvent" :footer-cell-class-name="expense_footerCellClassName"
                :edit-config="{ trigger: 'click', mode: 'cell', icon: 'vxe-icon-edit', showStatus: false, beforeEditMethod: expense_beforeEditMethod }">
                <vxe-column width="60" v-if="!isReadonly">
                  <template #default="{ row }">
                    <div class="oplinks2">
                      <a @click.stop="expense_pageAdd(row)" title="新增">
                        <a-icon type="plus-circle" />
                      </a>
                      <a @click.stop="expense_pageDelete(row)" title="删除">
                        <a-icon type="delete" />
                      </a>
                    </div>
                  </template>
                </vxe-column>
                <vxe-column type="seq" title="序号" width="48"></vxe-column>
                <vxe-column field="item_name" title="项目" width="220" :edit-render="{ name: '$input' }"></vxe-column>
                <vxe-column field="amount_formula" title="金额" width="220" :edit-render="{ name: 'EditExpressions' }">
                  <template #default="{ row }">
                    <a-tooltip>
                      <template slot="title">
                        {{ row.amount_formula || '' }}
                      </template>
                      <span v-if="showExp">
                        {{ row.amount_formula || '' }}
                      </span>
                      <span v-else v-html="formatShowNumber(row.amount, 2)"></span>
                    </a-tooltip>
                  </template>
                </vxe-column>

              </vxe-table>



            </a-collapse-panel>
          </a-collapse>
        </div>


        <div class="groupbox" v-if="showType == '1' || showType == '3'">
          <h3>核算表（油漆）</h3>
          <a-collapse v-model="groupbox3_activeKey">
            <a-collapse-panel key="1" header="材料">

              <div slot="extra">
                （合计）金额：{{ parseFloat(formOptions.data.paintMaterial_total_amount || 0).toFixed(2) }}
              </div>
              <vxe-table border show-overflow keep-source ref="paintMaterial_xTable" :data="paintMaterial_detailsData"
                :keyboard-config="{
                  isArrow: true, isDel: true,
                  isEnter: false, isTab: true, isEdit: true, isChecked: true
                }" :mouse-config="{ selected: true }" @pulldownSelected="paintMaterial_onPulldownSelected"
                @popupSelected="paintMaterial_onPopupSelected" :export-config="{}"
                @edit-closed="paintMaterial_afterEditEvent" :footer-cell-class-name="paintMaterial_footerCellClassName"
                :edit-config="{ trigger: 'click', mode: 'cell', icon: 'vxe-icon-edit', showStatus: false, beforeEditMethod: paintMaterial_beforeEditMethod }">
                <vxe-column width="60" v-if="!isReadonly">
                  <template #default="{ row }">
                    <div class="oplinks2">
                      <a @click.stop="paintMaterial_pageAdd(row)" title="新增">
                        <a-icon type="plus-circle" />
                      </a>
                      <a @click.stop="paintMaterial_pageDelete(row)" title="删除">
                        <a-icon type="delete" />
                      </a>
                    </div>
                  </template>
                </vxe-column>
                <vxe-column type="seq" title="序号" width="48"></vxe-column>
                <vxe-column field="material" title="材料" width="260" :params="editorMaterial2" formatter="formatRef"
                  :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>

                <vxe-column field="quantity_formula" title="总用量" width="200" :params="{ hasTotalQuantity: true }"
                  :edit-render="{ name: 'EditExpressions' }">
                  <template #default="{ row }">
                    <a-tooltip>
                      <template slot="title">
                        {{ row.quantity_formula || '' }}
                      </template>
                      <span v-if="showExp">
                        {{ row.quantity_formula || '' }}
                      </span>
                      <span v-else v-html="formatShowNumber(row.quantity, 3)"></span>
                    </a-tooltip>
                  </template>
                </vxe-column>
                <vxe-column field="price" title="单价" width="120"
                  :edit-render="{ name: '$input', props: { type: 'number' } }"></vxe-column>
                <vxe-column field="amount_formula" title="金额" width="200" :edit-render="{ name: 'EditExpressions' }">
                  <template #default="{ row }">
                    <a-tooltip>
                      <template slot="title">
                        {{ row.amount_formula || '' }}
                      </template>
                      <span v-if="showExp">
                        {{ row.amount_formula || '' }}
                      </span>
                      <span v-else v-html="formatShowNumber(row.amount, 2)"></span>
                    </a-tooltip>
                  </template>
                </vxe-column>

              </vxe-table>


            </a-collapse-panel>
            <a-collapse-panel key="2" header="人工" :disabled="false">

              <div slot="extra">
                （合计）金额：{{ parseFloat(formOptions.data.paintLabor_total_amount || 0).toFixed(2) }}
              </div>
              <vxe-table border show-overflow keep-source ref="paintLabor_xTable" :data="paintLabor_detailsData"
                :keyboard-config="{
                  isArrow: true, isDel: true,
                  isEnter: false, isTab: true, isEdit: true, isChecked: true
                }" :mouse-config="{ selected: true }" @pulldownSelected="paintLabor_onPulldownSelected"
                @popupSelected="paintLabor_onPopupSelected" :export-config="{}" @edit-closed="paintLabor_afterEditEvent"
                @edit-actived="paintLabor_beforeEditEvent" :footer-cell-class-name="paintLabor_footerCellClassName"
                :edit-config="{ trigger: 'click', mode: 'cell', icon: 'vxe-icon-edit', showStatus: false, beforeEditMethod: paintLabor_beforeEditMethod }">
                <vxe-column width="60" v-if="!isReadonly">
                  <template #default="{ row }">
                    <div class="oplinks2">
                      <a @click.stop="paintLabor_pageAdd(row)" title="新增">
                        <a-icon type="plus-circle" />
                      </a>
                      <a @click.stop="paintLabor_pageDelete(row)" title="删除">
                        <a-icon type="delete" />
                      </a>
                    </div>
                  </template>
                </vxe-column>
                <vxe-column type="seq" title="序号" width="48"></vxe-column>
                <vxe-column field="labor" title="项目" width="260" :params="editorLabor" formatter="formatRef"
                  :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>

                <vxe-column field="amount_formula" title="金额" width="200" :edit-render="{ name: 'EditExpressions' }">
                  <template #default="{ row }">
                    <a-tooltip>
                      <template slot="title">
                        {{ row.amount_formula || '' }}
                      </template>
                      <span v-if="showExp">
                        {{ row.amount_formula || '' }}
                      </span>
                      <span v-else v-html="formatShowNumber(row.amount, 2)"></span>
                    </a-tooltip>
                  </template>
                </vxe-column>

              </vxe-table>



            </a-collapse-panel>

            <a-collapse-panel key="3" header="其他费用" :disabled="false">
              <div slot="extra">
                （合计）金额：{{ parseFloat(formOptions.data.paintExpense_total_amount || 0).toFixed(2) }}
              </div>
              <vxe-table border show-overflow keep-source ref="paintExpense_xTable" :data="paintExpense_detailsData"
                :keyboard-config="{
                  isArrow: true, isDel: true,
                  isEnter: false, isTab: true, isEdit: true, isChecked: true
                }" :mouse-config="{ selected: true }" @pulldownSelected="paintExpense_onPulldownSelected"
                @popupSelected="paintExpense_onPopupSelected" :export-config="{}"
                @edit-closed="paintExpense_afterEditEvent" @edit-actived="paintExpense_beforeEditEvent"
                :footer-cell-class-name="paintExpense_footerCellClassName"
                :edit-config="{ trigger: 'click', mode: 'cell', icon: 'vxe-icon-edit', showStatus: false, beforeEditMethod: paintExpense_beforeEditMethod }">
                <vxe-column width="60" v-if="!isReadonly">
                  <template #default="{ row }">
                    <div class="oplinks2">
                      <a @click.stop="paintExpense_pageAdd(row)" title="新增">
                        <a-icon type="plus-circle" />
                      </a>
                      <a @click.stop="paintExpense_pageDelete(row)" title="删除">
                        <a-icon type="delete" />
                      </a>
                    </div>
                  </template>
                </vxe-column>
                <vxe-column type="seq" title="序号" width="48"></vxe-column>
                <vxe-column field="item_name" title="项目" width="220" :edit-render="{ name: '$input' }"></vxe-column>
                <vxe-column field="amount_formula" title="金额" width="200" :edit-render="{ name: 'EditExpressions' }">
                  <template #default="{ row }">
                    <a-tooltip>
                      <template slot="title">
                        {{ row.amount_formula || '' }}
                      </template>
                      <span v-if="showExp">
                        {{ row.amount_formula || '' }}
                      </span>
                      <span v-else v-html="formatShowNumber(row.amount, 2)"></span>
                    </a-tooltip>
                  </template>
                </vxe-column>

              </vxe-table>



            </a-collapse-panel>

          </a-collapse>
        </div>




      </a-tab-pane>
      <a-tab-pane v-for="(item, index) in drawer_detailsData" :key="index" :tab="item.name">
        <a-button @click="onTabEdit(index)" style="margin-bottom: 5px;">移除</a-button>
        <a-button @click="reloadDrawer(index)" style="margin-bottom: 5px;margin-left: 5px;">重新加载方案</a-button>

        <drawer :item="item" ref="drawer" :index="index" @update="calculateAll()"></drawer>
      </a-tab-pane>
    </a-tabs>





    <div class="footerbar">
      <a-button type="primary" @click="ok" v-if="!isPreview">保存</a-button>
      <a-button @click="cancel">关闭</a-button>
    </div>

    <vxe-modal show-footer class-name="vxe-table--ignore-clear edit-popup-box" title="选择数据" width="800" height="600"
      v-model="modalVisible" @confirm="confirmSelectScheme">
      <template #default>
        <vxe-grid :keyboard-config="{ isArrow: true }" auto-resize height="400" ref="scheme_grid"
          @cell-dblclick="dblClickEvent" :row-config="{ isCurrent: true, isHover: true }" :loading="scheme_loading"
          :pager-config="scheme_tablePage" :data="scheme_tableData" :columns="scheme_tableColumn"
          @page-change="scheme_pageChangeEvent">
        </vxe-grid>
      </template>
    </vxe-modal>

  </div>
</template>

<script>
import BASE_URL from '@/services/Middle/bathroom/BathroomQuotation/api.js';
const settings = require('../../basic/settings.js');

import Vue from 'vue'
import VXETable from 'vxe-table'
import EditExpressions from '../../basic/EditExpressions.vue'
Vue.component(EditExpressions.name, EditExpressions)
// 创建一个下拉表格渲染
VXETable.renderer.add('EditExpressions', {
  autofocus: '.vxe-input--inner',
  renderEdit(h, renderOpts, params) {
    return <edit-expressions params={params}></edit-expressions>
  }
})

import drawer from './drawer'

export default {

  name: 'BathroomQuotationUpdate',
  i18n: require('./i18n'),
  components: { drawer },
  props: {
    pageMode: {
      type: String,
      default: "edit"
    },
    dataId: {
    }
  },

  data() {
    // 页面数据变量
    var pageData = {
      // 当前项目名称
      currentConfigName: "",
      mainTabTitle: '主柜',
      // 当前项目ID
      currentBeid: 0, // 当前项目ID
      settignsValues: {}, // 当前项目配置
      tabKey: 'main', // 当前tab页
      showAll: false, // 是否显示全部
      showExp: false, // 是否显示公式
      showType: "1", // 显示类型
      modalVisible: false, // 弹出框是否显示
      isPreview: false, // 是否预览
      scheme_loading: false, // 加载中
      scheme_tableData: [], // 表格数据
      scheme_tableColumn: [ // 表格列
        { field: 'type', sortable: true, title: '类型', params: settings.options_schemeType, formatter: 'formatEnum' }, // 类型:1.主柜,2.抽屉
        { field: 'name', sortable: true, title: '设计方案名称' }, // 设计方案名称
      ],
      scheme_tablePage: { // 表格分页
        total: 0, // 总数
        currentPage: 1, // 当前页
        pageSize: 100 // 每页显示条数
      },
      groupbox1_activeKey: ["1", "2", "3", "4"],
      groupbox2_activeKey: ["1", "2", "3", "4"],
      groupbox3_activeKey: ["1", "2", "3", "4"],

      isReadonly: false,
      fittings_detailsData: [],
      parts_detailsData: [],
      drawer_detailsData: [],

      editorFittings: {
        dataUrl: `${BASE_URL.BASE_URL}/BathroomFittings/v1/bathroom/fittings/list`,
        listdataFieldName: 'BathroomFittings',
        columns: [
          { field: 'name', title: '名称' },
          { field: 'remark', title: '备注' }
        ],
        placeholder: "请输入名称",
        searchFieldNames: ['name'],
        textField: 'name'
      },
      editorMaterial: {
        dataUrl: `${BASE_URL.BASE_URL}/BathroomMaterial/v1/bathroom/material/list`,
        listdataFieldName: 'BathroomMaterial',
        columns: [
          { field: 'name', title: '名称' },
          { field: 'remark', title: '备注' }
        ],
        placeholder: "请输入名称",
        searchFieldNames: ['name'],
        textField: 'name'
      },

      editorMaterial2: {
        dataUrl: `${BASE_URL.BASE_URL}/BathroomMaterial/v1/bathroom/material/list`,
        listdataFieldName: 'BathroomMaterial',
        columns: [
          { field: 'name', title: '名称' },
          { field: 'remark', title: '备注' }
        ],
        placeholder: "请输入名称",
        searchFieldNames: ['name'],
        extendData: [{ id: '封边条', name: '封边条' }],
        textField: 'name'
      },
      editorBanding: {
        dataUrl: `${BASE_URL.BASE_URL}/BathroomBanding/v1/bathroom/banding/list`,
        listdataFieldName: 'BathroomBanding',
        columns: [
          { field: 'name', title: '名称' },
          { field: 'remark', title: '备注' }
        ],
        placeholder: "请输入名称",
        searchFieldNames: ['name'],
        textField: 'name'
      },
      editorParts: {
        dataUrl: `${BASE_URL.BASE_URL}/BathroomParts/v1/bathroom/parts/list`,
        listdataFieldName: 'BathroomParts',
        columns: [
          { field: 'name', title: '名称' },
          { field: 'remark', title: '备注' }
        ],
        placeholder: "请输入名称",
        searchFieldNames: ['name'],
        textField: 'name'
      },
      editorPackaging: {
        dataUrl: `${BASE_URL.BASE_URL}/BathroomPackaging/v1/bathroom/packaging/list`,
        listdataFieldName: 'BathroomPackaging',
        columns: [
          { field: 'name', title: '名称' },
          { field: 'remark', title: '备注' }
        ],
        placeholder: "请输入名称",
        searchFieldNames: ['name'],
        textField: 'name'
      },
      editorLabor: {
        dataUrl: `${BASE_URL.BASE_URL}/BathroomLabor/v1/bathroom/labor/list`,
        listdataFieldName: 'BathroomLabor',
        columns: [
          { field: 'name', title: '名称' },
          { field: 'remark', title: '备注' }
        ],
        placeholder: "请输入名称",
        searchFieldNames: ['name'],
        textField: 'name'
      },




      packaging_detailsData: [], // 包装


      material_detailsData: [], // 材料
      labor_detailsData: [], // 人工
      paintMaterial_detailsData: [], // 油漆材料
      paintLabor_detailsData: [], // 油漆人工
      bathroomMaterial_list: [],//材料的数据
      fittings_list: [],//材料的数据
      moreExpressionsList_material_height: [],//材料的厚度 变量列表
      moreExpressionsList_fittings: [],
      expense_detailsData: [ // 费用结算

      ],
      paintExpense_detailsData: [ // 油漆费用结算


      ],

      uploadDefaultImg: null, // 默认图片
      detailDataFieldName: "bathroom_quotation", // 详情数据字段名称

      actions: {
        // =============================== 接口地址 自动生成 Start ===============================
        BathroomQuotationList: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/list`, // 报价单列表
        BathroomQuotationDetail: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/detail`, // 报价单详情
        BathroomQuotationCreate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/create`, // 创建报价单
        BathroomQuotationUpdate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/update`, // 更新报价单
        BathroomQuotationDelete: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/detele`, // 删除报价单
        BathroomQuotationBatchDelete: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/batchDelete`, // 批量删除报价单
        BathroomQuotationBatchUpdate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/batchUpdate`, // 批量更新报价单
        BathroomQuotationBatchCreate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/batchCreate`, // 批量创建报价单
        BathroomQuotationExportExcel: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/export/excel`, // 导出报价单数据到EXCEL
        BathroomQuotationImportExcel: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/import/excel`, // 批量导入EXCEL报价单数据
        BathroomQuotationFittingsList: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/fittings/list`, // 报价单部件列表
        BathroomQuotationFittingsDetail: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/fittings/detail`, // 报价单部件详情
        BathroomQuotationFittingsCreate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/fittings/create`, // 创建报价单部件
        BathroomQuotationFittingsUpdate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/fittings/update`, // 更新报价单部件
        BathroomQuotationFittingsDelete: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/fittings/detele`, // 删除报价单部件
        BathroomQuotationFittingsBatchDelete: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/fittings/batchDelete`, // 批量删除报价单部件
        BathroomQuotationFittingsBatchUpdate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/fittings/batchUpdate`, // 批量更新报价单部件
        BathroomQuotationFittingsBatchCreate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/fittings/batchCreate`, // 批量创建报价单部件
        BathroomQuotationFittingsExportExcel: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/fittings/export/excel`, // 导出报价单部件数据到EXCEL
        BathroomQuotationFittingsImportExcel: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/fittings/import/excel`, // 批量导入EXCEL报价单部件数据
        BathroomQuotationPartsList: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/parts/list`, // 报价单配件列表
        BathroomQuotationPartsDetail: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/parts/detail`, // 报价单配件详情
        BathroomQuotationPartsCreate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/parts/create`, // 创建报价单配件
        BathroomQuotationPartsUpdate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/parts/update`, // 更新报价单配件
        BathroomQuotationPartsDelete: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/parts/detele`, // 删除报价单配件
        BathroomQuotationPartsBatchDelete: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/parts/batchDelete`, // 批量删除报价单配件
        BathroomQuotationPartsBatchUpdate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/parts/batchUpdate`, // 批量更新报价单配件
        BathroomQuotationPartsBatchCreate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/parts/batchCreate`, // 批量创建报价单配件
        BathroomQuotationPartsExportExcel: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/parts/export/excel`, // 导出报价单配件数据到EXCEL
        BathroomQuotationPartsImportExcel: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/parts/import/excel`, // 批量导入EXCEL报价单配件数据
        BathroomQuotationMaterialList: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/material/list`, // 报价单材料列表
        BathroomQuotationMaterialDetail: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/material/detail`, // 报价单材料详情
        BathroomQuotationMaterialCreate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/material/create`, // 创建报价单材料
        BathroomQuotationMaterialUpdate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/material/update`, // 更新报价单材料
        BathroomQuotationMaterialDelete: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/material/detele`, // 删除报价单材料
        BathroomQuotationMaterialBatchDelete: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/material/batchDelete`, // 批量删除报价单材料
        BathroomQuotationMaterialBatchUpdate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/material/batchUpdate`, // 批量更新报价单材料
        BathroomQuotationMaterialBatchCreate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/material/batchCreate`, // 批量创建报价单材料
        BathroomQuotationMaterialExportExcel: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/material/export/excel`, // 导出报价单材料数据到EXCEL
        BathroomQuotationMaterialImportExcel: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/material/import/excel`, // 批量导入EXCEL报价单材料数据
        BathroomQuotationLaborList: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/labor/list`, // 报价单人工费用列表
        BathroomQuotationLaborDetail: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/labor/detail`, // 报价单人工费用详情
        BathroomQuotationLaborCreate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/labor/create`, // 创建报价单人工费用
        BathroomQuotationLaborUpdate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/labor/update`, // 更新报价单人工费用
        BathroomQuotationLaborDelete: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/labor/detele`, // 删除报价单人工费用
        BathroomQuotationLaborBatchDelete: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/labor/batchDelete`, // 批量删除报价单人工费用
        BathroomQuotationLaborBatchUpdate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/labor/batchUpdate`, // 批量更新报价单人工费用
        BathroomQuotationLaborBatchCreate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/labor/batchCreate`, // 批量创建报价单人工费用
        BathroomQuotationLaborExportExcel: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/labor/export/excel`, // 导出报价单人工费用数据到EXCEL
        BathroomQuotationLaborImportExcel: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/labor/import/excel`, // 批量导入EXCEL报价单人工费用数据
        BathroomQuotationProcessList: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/process/list`, // 报价单工序列表
        BathroomQuotationProcessDetail: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/process/detail`, // 报价单工序详情
        BathroomQuotationProcessCreate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/process/create`, // 创建报价单工序
        BathroomQuotationProcessUpdate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/process/update`, // 更新报价单工序
        BathroomQuotationProcessDelete: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/process/detele`, // 删除报价单工序
        BathroomQuotationProcessBatchDelete: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/process/batchDelete`, // 批量删除报价单工序
        BathroomQuotationProcessBatchUpdate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/process/batchUpdate`, // 批量更新报价单工序
        BathroomQuotationProcessBatchCreate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/process/batchCreate`, // 批量创建报价单工序
        BathroomQuotationProcessExportExcel: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/process/export/excel`, // 导出报价单工序数据到EXCEL
        BathroomQuotationProcessImportExcel: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/process/import/excel`, // 批量导入EXCEL报价单工序数据
        BathroomQuotationPackagingList: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/packaging/list`, // 包装材料列表
        BathroomQuotationPackagingDetail: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/packaging/detail`, // 包装材料详情
        BathroomQuotationPackagingCreate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/packaging/create`, // 创建包装材料
        BathroomQuotationPackagingUpdate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/packaging/update`, // 更新包装材料
        BathroomQuotationPackagingDelete: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/packaging/detele`, // 删除包装材料
        BathroomQuotationPackagingBatchDelete: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/packaging/batchDelete`, // 批量删除包装材料
        BathroomQuotationPackagingBatchUpdate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/packaging/batchUpdate`, // 批量更新包装材料
        BathroomQuotationPackagingBatchCreate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/packaging/batchCreate`, // 批量创建包装材料
        BathroomQuotationPackagingExportExcel: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/packaging/export/excel`, // 导出包装材料数据到EXCEL
        BathroomQuotationPackagingImportExcel: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/packaging/import/excel`, // 批量导入EXCEL包装材料数据
        BathroomQuotationOutsourcingList: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/outsourcing/list`, // 外购产品列表
        BathroomQuotationOutsourcingDetail: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/outsourcing/detail`, // 外购产品详情
        BathroomQuotationOutsourcingCreate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/outsourcing/create`, // 创建外购产品
        BathroomQuotationOutsourcingUpdate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/outsourcing/update`, // 更新外购产品
        BathroomQuotationOutsourcingDelete: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/outsourcing/detele`, // 删除外购产品
        BathroomQuotationOutsourcingBatchDelete: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/outsourcing/batchDelete`, // 批量删除外购产品
        BathroomQuotationOutsourcingBatchUpdate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/outsourcing/batchUpdate`, // 批量更新外购产品
        BathroomQuotationOutsourcingBatchCreate: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/outsourcing/batchCreate`, // 批量创建外购产品
        BathroomQuotationOutsourcingExportExcel: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/outsourcing/export/excel`, // 导出外购产品数据到EXCEL
        BathroomQuotationOutsourcingImportExcel: `${BASE_URL.BASE_URL}/BathroomQuotation/v1/bathroom/quotation/outsourcing/import/excel`, // 批量导入EXCEL外购产品数据

        // =============================== 接口地址 自动生成 End ===============================

        BathroomSchemeList: `${BASE_URL.BASE_URL}/BathroomScheme/v1/bathroom/scheme/list`, // 设计方案列表
      },

      keyName: 'id',
      // 是否编辑模式
      isEdit: false,
      // 表单数据
      formOptions: {
        data: {
          // =============================== 表单数据 自动生成 Start ===============================

          id: 0, // 报价单ID
          code: "", // 报价单编号
          order_code: "", // 订单编号
          customer: "", // 客户名称
          phone: "", // 联系电话
          address: "", // 地址
          model_id: 0, // 型号ID
          design_id: 0, // 设计方案ID
          project_name: "", // 工程名
          main_cabinet_length: "", // 主柜规格 长
          main_cabinet_width: "", // 宽
          main_cabinet_height: "", // 高
          create_uid: 0, // 创建人
          update_uid: 0, // 更新人
          create_time: new Date(2100, 1, 1).getTime() / 10000, // 创建时间
          update_time: new Date(2100, 1, 1).getTime() / 10000, // 更新时间

          // =============================== 表单数据 自动生成 End ===============================
        },
        // 标题宽度
        titleWidth: 120, // 标题宽度
        // 标题对齐方式 
        titleAlign: 'right', // 标题对齐方式

        // 表单校验规则
        rules: {
          // =============================== 表单校验 自动生成 Start ===============================


          project_name: [
            { required: true, message: '请输入工程名' },
          ],
          main_cabinet_length: [
            { required: true, message: '主柜规格 长' },
          ],
          main_cabinet_width: [
            { required: true, message: '主柜规格 宽' },
          ],
          main_cabinet_height: [
            { required: true, message: '主柜规格 高' },
          ]
          // =============================== 表单校验 自动生成 End ===============================
        },
        // 表单项
        items: [

          {
            title: '左侧',
            span: 19,
            children: [
              { field: 'project_name', title: '工程名', span: 8, itemRender: { name: '$input' } },
              { field: 'mode_name', title: '型号', span: 8, itemRender: { name: '$input' } },
              { field: 'customer', title: '客户名称', span: 8, itemRender: { name: '$input' } },

              { field: 'main_cabinet_length', title: '主柜规格 长', span: 8, itemRender: { name: '$input', events: { change: this.calculateAll } } },
              { field: 'main_cabinet_width', title: '宽', span: 8, itemRender: { name: '$input', events: { change: this.calculateAll } } },
              { field: 'main_cabinet_height', title: '高', span: 8, itemRender: { name: '$input', events: { change: this.calculateAll } } },
              {
                title: '下侧',
                span: 16,
                children: [
                  { field: '报价日期', title: '报价日期', span: 12, itemRender: { name: '$input', props: { type: "date" } } },
                  { field: '报价有效日期', title: '报价有效日期', span: 12, itemRender: { name: '$input', props: { type: "date" } } },

                  { field: 'show_expense', title: '总费用(免漆)', span: 12, itemRender: { name: '$input' } },
                  { field: 'show_paint_expense', title: '总费用(油漆)', span: 12, itemRender: { name: '$input' } },

                  {
                    title: '创建人', span: 12,
                    field: 'user_detail',
                    itemRender: {
                      name: 'MkFormInputShow', props: {
                        params: {
                          dataType: "object",
                          valueField: "id",
                          textField: "name"
                        }
                      }
                    }
                  },


                ]
              },
            ]
          },
          {
            title: '右侧',
            span: 5,
            children: [
              {
                field: 'image', span: 24, itemRender: {
                  name: 'MkFormUploader', props: {
                  }
                }
              },
            ]
          },




        ]
      },
      // 新增模式表单项
      addModeItems: [

      ],


    };

    pageData.actions.get = pageData.actions.BathroomQuotationDetail; // 详情接口
    pageData.actions.create = pageData.actions.BathroomQuotationCreate; // 新增接口
    pageData.actions.update = pageData.actions.BathroomQuotationUpdate; // 更新接口

    // 合并表单数据及配置
    pageData.formOptions = Object.assign({}, this.$mk.config.defaults.formOptions, pageData.formOptions);

    return pageData;
  },

  computed: {
    desc() {
      return this.$t('editPageDesc')
    }
  },


  created() {
    this.loadSettings(); // 加载设置

    // 获取路由的id参数
    let dataId = this.getDataId(); // 获取路由的id参数
    if (dataId && dataId.indexOf && dataId.indexOf('d') == 0) { // 如果有id参数，说明是预览模式
      this.isPreview = true; // 设置预览模式 
      this.loadSchemeDataById(dataId.substr(1)); // 加载方案数据
    }
    // 如果有id参数，说明是编辑模式
    else if (dataId) {
      const json = `{"id":${dataId}}`; // 构造json
      this.$mk.post({ // 获取详情数据
        url: this.actions.get, // 详情接口地址
        loading: "加载中...",
        data: json,
        config: {
          headers: {
            'Content-Type': 'application/json'
          }
        }
      }).then(a => {
        // =============================== 时间字段判断 自动生成 Start ===============================

        if (a.data[this.detailDataFieldName].create_time) { // 如果有create_time字段
          a.data[this.detailDataFieldName].create_time = new Date(a.data[this.detailDataFieldName].create_time * 1000);
        }
        if (a.data[this.detailDataFieldName].update_time) { // 如果有update_time字段
          a.data[this.detailDataFieldName].update_time = new Date(a.data[this.detailDataFieldName].update_time * 1000);
        }

        // =============================== 时间字段判断 自动生成 End ===============================
        let data = a.data[this.detailDataFieldName]

        this.formOptions.data = data; // 设置表单数据

        this.fittings_detailsData = JSON.parse(data.fittingsList || "[]"); // 部件
        this.parts_detailsData = JSON.parse(data.partsList || "[]"); // 配件
        this.packaging_detailsData = JSON.parse(data.packagingList || "[]"); // 包装


        this.labor_detailsData = JSON.parse(data.laborList || "[]"); // 人工
        this.material_detailsData = JSON.parse(data.materialList || "[]"); // 材料
        this.paintLabor_detailsData = JSON.parse(data.paint_laborList || "[]"); // 油漆人工
        this.paintMaterial_detailsData = JSON.parse(data.paint_materialList || "[]"); // 油漆材料


        this.expense_detailsData = JSON.parse(data.expense_list || "[]"); // 费用结算
        this.paintExpense_detailsData = JSON.parse(data.paint_expenseList || "[]"); // 油漆费用结算

        this.drawer_detailsData = JSON.parse(data.drawer_list || "[]"); // 抽屉

        this.materialHeightInit(); // 初始化材料高度
        this.fittingsListInit();
        this.detailDataInit(); // 初始化详情数据

        if (this.fittings_detailsData[0] && this.fittings_detailsData[0].scheme_id) {
          this.loadSchemeDataById(this.fittings_detailsData[0].scheme_id, (row) => {
            this.mainTabTitle = row.type == '1' ? '主柜' : '镜柜';
          });
        }


        this.calculateAll(); // 计算所有数据

      }).catch((a) => {
        this.$mk.error(a.data.msg);
      });

      this.isEdit = true; // 设置编辑模式
    } else {
      // 如果没有id参数，说明是新增模式
      this.addModeItems.forEach(item => {
        this.formOptions.items.push(item); // 添加新增模式表单项
      });
      this.detailDataInit();

    }




  },
  // 函数
  methods: {


    fittingsListInit() { // 获取部件数据

      this.$mk.post({ // 获取材料列表
        url: `${BASE_URL.BASE_URL}//BathroomFittings/v1/bathroom/fittings/list`,
        data: { "page": 1, "limit": 100, "order_bys": [], "search_rules": [] }
      }).then(a => {

        this.fittings_list = a.data.BathroomFittings || [];
        this.moreExpressionsList_fittings = [];


        this.fittings_list.forEach(o => {
          if (o.IsShowExpression) {
            this.moreExpressionsList_fittings.push(this.formatName(o.name) + "的长");
            this.moreExpressionsList_fittings.push(this.formatName(o.name) + "的宽");
            this.moreExpressionsList_fittings.push(this.formatName(o.name) + "的厚");
          }


        });

      });
    },
    materialHeightInit() { // 初始化材料高度

      this.$mk.post({ // 获取材料列表
        url: `${BASE_URL.BASE_URL}/BathroomMaterial/v1/bathroom/material/list`,
        data: { "page": 1, "limit": 100, "order_bys": [], "search_rules": [] }
      }).then(a => {

        this.bathroomMaterial_list = a.data.BathroomMaterial || [];
        this.moreExpressionsList_material_height = [];

        this.bathroomMaterial_list.forEach(o => { // 遍历材料列表
          this.fittings_detailsData.forEach(item => {  // 遍历部件列表


            if (item.material && item.material[0] && item.material[0].toString() == o.id.toString()) { // 如果部件的材料id和材料列表的id相同

              item.material_default_height = o.spec || "15"; // 设置部件的默认高度
            }
          });

        });


        this.bathroomMaterial_list.forEach(o => { // 遍历材料列表

          this.moreExpressionsList_material_height.push(this.formatName(o.name) + "的厚度");

        });

      });
    },

    getMoreExpressionsList() {
      return [...this.moreExpressionsList_material_height, ...this.moreExpressionsList_fittings]
    },


    loadSettings() { // 加载设置

      this.$mk.post({ // 获取设置列表
        url: `${BASE_URL.BASE_URL}/BathroomScheme/v1/settings/list`,
        data: {
        }
      }).then(a => {

        let data = {};
        let getName = (info) => {
          for (let name in info) {
            return name;
          }
          return null;
        }
        a.data.settings.forEach(o => {
          let name = getName(o.setting);
          if (!name) return;
          data[name] = o.setting[name];
        });

        this.settignsValues = data;
      }).catch((a) => {
        this.$mk.error(a.data.msg);
      });
    },
    formatShowNumber(value, points) { // 格式化显示数字
      if (!value) {
        return '<span >' + (0.0).toFixed(points || 0) + '</span>';
      }
      return parseFloat(value).toFixed(points || 0)
    },
    toggleAll() { // 展开/收起

      if (this.tabKey == "main") {
        this.showAll = !this.showAll;
        if (this.showAll) {
          this.groupbox1_activeKey = ["1", "2", "3", "4", "5"];
          this.groupbox2_activeKey = ["1", "2", "3"];
          this.groupbox3_activeKey = ["1", "2", "3"];
        } else {

          this.groupbox1_activeKey = [];
          this.groupbox2_activeKey = [];
          this.groupbox3_activeKey = [];
        }

      } else {

        let index = parseInt(this.tabKey); // 获取当前tab的索引

        let drawers = this.$refs['drawer']; // 获取抽屉组件

        if (drawers && drawers[index] && drawers[index].toggleAll) { // 如果有抽屉组件
          drawers[index].toggleAll(); // 调用抽屉组件的展开/收起方法
        }


      }

    },
    print() { // 打印

      if (this.tabKey != "main") {


        let index = parseInt(this.tabKey); // 获取当前tab的索引

        let drawers = this.$refs['drawer']; // 获取抽屉组件

        if (drawers && drawers[index] && drawers[index].print) { // 如果有抽屉组件
          drawers[index].print();
        }
        return;

      }

      let hiprint = this.$hiPrint; // 获取打印组件
      let tdata = JSON.parse(JSON.stringify(this.formOptions.data)); // 复制表单数据



      tdata.fittings = this.printFormatListData(this.fittings_detailsData); // 格式化部件数据
      tdata.parts = this.printFormatListData(this.parts_detailsData); // 格式化配件数据
      tdata.packaging = this.printFormatListData(this.packaging_detailsData); // 格式化包装数据
      tdata.labor = this.printFormatListData(this.labor_detailsData); // 格式化人工数据
      tdata.material = this.printFormatListData(this.material_detailsData); // 格式化材料数据
      tdata.paintLabor = this.printFormatListData(this.paintLabor_detailsData); // 格式化油漆人工数据
      tdata.paintMaterial = this.printFormatListData(this.paintMaterial_detailsData); // 格式化油漆材料数据
      tdata.expense = this.printFormatListData(this.expense_detailsData); // 格式化费用结算数据
      tdata.paintExpense = this.printFormatListData(this.paintExpense_detailsData); // 格式化油漆费用结算数据

      hiprint.init(); // 初始化打印组件
      var hiprintTemplate = new hiprint.PrintTemplate({ // 创建打印模板
        template: settings.printTemplate // 模板内容
      });
      hiprintTemplate.print(tdata, { printer: '', title: '报价单' }); // 打印
    },
    printFormatListData(detailsData) { // 格式化打印列表数据

      let data = JSON.parse(JSON.stringify(detailsData)); // 复制数据
      data.forEach(item => { // 遍历数据

        for (let name in item) { // 遍历数据的每个字段
          let o = item[name]; // 获取字段值
          if (Array.isArray(o) && o[1]) { // 如果字段值是数组
            item[name] = o[1]; // 设置字段值为数组的第二个元素
          }
          if (typeof (o) == "number") { // 如果字段值是数字
            item[name] = parseFloat(o || 0).toFixed(2) // 设置字段值为数字的字符串
          }
        }
      });
      return data; // 返回数据
    },


    showTypeChange(e) { // 显示类型改变
      this.showType = e.target.value; // 设置显示类型


      let drawers = this.$refs['drawer']; // 获取抽屉组件

      if (drawers) { // 如果有抽屉组件
        drawers.forEach(drawer => { // 遍历抽屉组件
          if (drawer.setShowType) { // 如果有设置显示类型的方法

            drawer.setShowType(this.showType); // 设置显示类型
          }
        })
      }

    },
    selectScheme() { // 选择方案
      this.modalVisible = true; // 显示模态框
      this.scheme_load(); // 加载方案列表
    },

    dblClickEvent() { // 双击事件
      this.confirmSelectScheme(); // 确认选择方案
    },
    confirmSelectScheme() { // 确认选择方案
      let row = this.$refs.scheme_grid.getCurrentRecord(); // 获取当前行 

      this.loadSchemeData(row); // 加载方案数据

      this.modalVisible = false; // 隐藏模态框
    },
    reloadMain() {
      if (!this.fittings_detailsData.length) {
        return;
      }
      let scheme_id = this.fittings_detailsData[0].scheme_id;
      this.loadSchemeDataById(scheme_id);
    },
    reloadDrawer(index) {

      let drawers = this.$refs['drawer']; // 获取抽屉组件

      if (drawers && drawers[index] && drawers[index].reloadDrawer) {
        drawers[index].reloadDrawer();
      }


    },

    loadSchemeDataById(dataId, callback) { // 加载方案数据
      const json = `{"id":${dataId}}`; // 构造json
      this.$mk.post({ // 获取详情数据
        url: `${BASE_URL.BASE_URL}/BathroomScheme/v1/bathroom/scheme/detail`, // 详情接口地址
        loading: "加载中...",
        data: json,
        config: {
          headers: {
            'Content-Type': 'application/json'
          }
        }
      }).then(a => {
        if (callback) {
          callback(a.data.bathroom_scheme); // 加载方案数据
        } else {
          this.loadSchemeData(a.data.bathroom_scheme); // 加载方案数据
        }


      });
    },
    loadSchemeData(row) { // 加载方案数据

      let scheme_id = row.id.toString() // 获取方案id

      let fittingsList = JSON.parse(row.fittingsList || "[]"); // 获取部件列表
      fittingsList = fittingsList.filter(a => a.fittings && a.fittings[0]); // 过滤部件列表
      let partsList = JSON.parse(row.partsList || "[]"); // 获取配件列表
      partsList = partsList.filter(a => a.parts && a.parts[0]); // 过滤配件列表
      let packagingList = JSON.parse(row.packagingList || "[]"); // 获取包装列表
      packagingList = packagingList.filter(a => a.packaging && a.packaging[0]); // 过滤包装列表

      let laborList = JSON.parse(row.laborList || "[]"); // 获取人工列表
      laborList = laborList.filter(a => a.labor && a.labor[0]); // 过滤人工列表
      let materialList = JSON.parse(row.materialList || "[]"); // 获取材料列表
      materialList = materialList.filter(a => a.material && a.material[0]); // 过滤材料列表


      let paintLaborList = JSON.parse(row.paintLaborList || "[]"); // 获取油漆人工列表
      paintLaborList = paintLaborList.filter(a => a.labor && a.labor[0]); // 过滤油漆人工列表
      let paintMaterialList = JSON.parse(row.paintMaterialList || "[]"); // 获取油漆材料列表
      paintMaterialList = paintMaterialList.filter(a => a.material && a.material[0]); // 过滤油漆材料列表


      console.log(row.expense_list);
      console.log(row.paint_expenseList);

      let expense_list = JSON.parse(row.expense_list || "[]");
      expense_list = expense_list.filter(a => a.item_name);

      let paint_expenseList = JSON.parse(row.paint_expenseList || "[]");
      paint_expenseList = paint_expenseList.filter(a => a.item_name);

      if (row.type != '1' && row.type != '3') { //抽屉 如果不是主柜

        this.drawer_detailsData.push({ // 添加抽屉数据
          scheme_id: scheme_id,
          name: row.name, // 名称
          quantity: 1, // 数量
          fittingsList, // 部件列表
          partsList, // 配件列表
          packagingList, // 包装列表
          laborList, // 人工列表
          materialList,   // 材料列表
          paint_laborList: paintLaborList, // 油漆人工列表
          paint_materialList: paintMaterialList, // 油漆材料列表
          expense_list: expense_list,
          paint_expenseList: paint_expenseList
        });


        this.materialHeightInit(); // 初始化材料高度
        this.fittingsListInit();
        this.tabKey = this.drawer_detailsData.length - 1;
        this.$forceUpdate(); // 强制更新

      } else { //主柜 或者 镜柜


        this.mainTabTitle = row.type == '1' ? '主柜' : '镜柜';

        this.addToList({ scheme_id, listData: fittingsList, detailsData: this.fittings_detailsData }); // 把来源数据添加到目标表格数据
        this.addToList({ scheme_id, listData: partsList, detailsData: this.parts_detailsData }); // 把来源数据添加到目标表格数据
        this.addToList({ scheme_id, listData: packagingList, detailsData: this.packaging_detailsData }); // 把来源数据添加到目标表格数据
        this.addToList({ scheme_id, listData: laborList, detailsData: this.labor_detailsData }); // 把来源数据添加到目标表格数据
        this.addToList({ scheme_id, listData: materialList, detailsData: this.material_detailsData }); // 把来源数据添加到目标表格数据
        this.addToList({ scheme_id, listData: paintLaborList, detailsData: this.paintLabor_detailsData }); // 把来源数据添加到目标表格数据
        this.addToList({ scheme_id, listData: paintMaterialList, detailsData: this.paintMaterial_detailsData }); // 把来源数据添加到目标表格数据
        this.addToList({ scheme_id, listData: expense_list, detailsData: this.expense_detailsData });
        this.addToList({ scheme_id, listData: paint_expenseList, detailsData: this.paintExpense_detailsData });

        this.materialHeightInit(); // 初始化材料高度
        this.fittingsListInit();
        this.calculateAll(); // 计算所有数据


      }
    },

    //把来源数据添加到目标表格数据
    addToList({ listData, scheme_id, detailsData }) { // 把来源数据添加到目标表格数据

      let newInfos = []; // 新的数据
      listData.forEach(item => { // 遍历来源数据
        let info = JSON.parse(JSON.stringify(item)); // 复制数据
        let source = JSON.parse(JSON.stringify(item)); // 复制数据
        info.source = source; // 设置来源数据
        info.scheme_id = scheme_id; // 设置方案id

        //第二次选择 方案 的时候 ，先找到原来行，
        let oldDetailItem = detailsData.filter(a => a.scheme_id == scheme_id && a.source && a.source.id == item.id); // 过滤目标表格数据

        if (oldDetailItem.length) { // 如果有原来行
          //覆盖 更新 原来行的数据 
          Object.assign(oldDetailItem[0], info);
        } else { // 如果没有原来行
          //准备 要附加进去的行
          newInfos.push(info);
        }
      });


      let j = 0; // 新的数据的索引
      for (let i = 0; i < detailsData.length && j < newInfos.length; i++) { // 遍历目标表格数据
        let item = detailsData[i]; // 获取目标表格数据的每一行

        //没有选择部件的行，覆盖数据
        if (!item.fittings || !item.fittings[0]) {
          Object.assign(detailsData[i], newInfos[j]); // 覆盖数据 
          j++; // 新的数据的索引+1
        }
      }
      //剩下的行，直接push进去
      for (; j < newInfos.length; j++) {
        detailsData.push(newInfos[j]); // 添加数据
      }
    },

    scheme_pageChangeEvent({ currentPage, pageSize }) { // 分页改变事件
      this.scheme_tablePage.currentPage = currentPage // 设置当前页
      this.scheme_tablePage.pageSize = pageSize // 设置每页条数
      this.scheme_loading = true // 设置加载状态
      this.scheme_load(); // 加载数据
    },
    scheme_load() { // 加载数据
      let parms = { // 请求参数
        "page": this.scheme_tablePage.currentPage, // 当前页
        "limit": this.scheme_tablePage.pageSize, // 每页条数
        "order_bys": [ // 排序
        ],
        "search_rules": [ // 查询条件
        ],
        "start_time": 0, // 开始时间
        "end_time": 0 // 结束时间
      };

      this.$mk.post({ // 发送请求
        url: this.actions.BathroomSchemeList, // 地址
        data: parms // 参数
      }).then(r => {
        this.scheme_loading = false // 设置加载状态
        let data = r.data; // 获取数据 
        this.scheme_tablePage.total = data.total; // 设置总条数
        this.scheme_tableData = data.BathroomScheme; // 设置表格数据
      });
    },

    detailDataInit() { // 初始化详情数据
      for (let i = this.fittings_detailsData.length; i < settings.table_min_count; i++) { // 遍历部件列表
        this.fittings_detailsData.push({});
      }


      for (let i = this.parts_detailsData.length; i < settings.table_min_count; i++) { // 遍历配件列表
        this.parts_detailsData.push({});
      }

      for (let i = this.packaging_detailsData.length; i < settings.table_min_count; i++) { // 遍历包装列表
        this.packaging_detailsData.push({});
      }


      for (let i = this.material_detailsData.length; i < settings.table_min_count; i++) { // 遍历材料列表
        this.material_detailsData.push({});
      }
      for (let i = this.labor_detailsData.length; i < settings.table_min_count; i++) { // 遍历人工列表
        this.labor_detailsData.push({});
      }
      for (let i = this.paintMaterial_detailsData.length; i < settings.table_min_count; i++) { // 遍历油漆材料列表
        this.paintMaterial_detailsData.push({});
      }
      for (let i = this.paintLabor_detailsData.length; i < settings.table_min_count; i++) { // 遍历油漆人工列表
        this.paintLabor_detailsData.push({});
      }

      for (let i = this.expense_detailsData.length; i < settings.table_min_count; i++) { // 遍历费用结算列表
        this.expense_detailsData.push({});
      }
      for (let i = this.paintExpense_detailsData.length; i < settings.table_min_count; i++) { // 遍历油漆费用结算列表
        this.paintExpense_detailsData.push({});
      }


    },
    // 获取路由的id参数
    getDataId() {
      let dataId = this.dataId;
      if (this.$route.params.id) {
        dataId = this.$route.params.id;
      }
      if (!dataId) {
        dataId = 0;
      }
      return dataId;
    },



    // 返回
    back() {
      // 如果是新增模式，关闭当前页面
      if (!this.isEdit) {
        this.$closePage({
          closeRoute: "/BathroomQuotation/BathroomQuotationAdd"
        });
      } else {
        // 如果是编辑模式，关闭当前页面
        this.$closePage({
          closeRoute: "/BathroomQuotation/BathroomQuotationUpdate"
        });
      }
      // 打开列表页面
      this.$openPage('/BathroomQuotation/BathroomQuotationList')
    },
    // 部件下拉选择事件
    fittings_onPulldownSelected({ row, selectedData, column }) {  // row 当前行 selectedData 选择的数据 column 当前列

      if (column.field == "banding") { // 如果是封边
        if (selectedData.formula) { // 如果有公式
          row.seal_formula = selectedData.formula; // 设置封边公式
        }

      }
      if (column.field == "paint_material") {  // 如果是油漆材料
        this.resetPaintMaterial(); // 重置油漆材料
      }
      if (column.field == "material") { // 如果是材料
        this.resetMaterial(); // 重置材料

        if (selectedData && selectedData.spec) { // 如果有规格
          row.material_default_height = selectedData.spec; // 设置默认高度
        }
      }

      if (!row.rate_materials && this.settignsValues.Main_material_utilization_rate) { // 如果没有主材利用率
        row.rate_materials = this.settignsValues.Main_material_utilization_rate; // 设置主材利用率
      }
      if (!row.paint_number && this.settignsValues.Default_rate_of_paint_surface) { // 如果没有油漆面
        row.paint_number = this.settignsValues.Default_rate_of_paint_surface; // 设置油漆面
      }
      if (!row.board_length_formula) { // 如果没有板材长度公式
        row.board_length_formula = this.settignsValues.Default_board_length_formula || '{板材的长}*{板材的宽}*{部件的数量}/{主材利用率}/1000000/2.96';
      }

      if (!row.paint_area_formula) { // 如果没有油漆面公式
        row.paint_area_formula = this.settignsValues.Default_paint_area_formula || '{板材的长}*{板材的宽}*{部件的数量}*{油漆面}/1000000';
      }
    },
    // 部件弹出选择事件
    fittings_onPopupSelected({ rows, name, params }) { // rows 当前行 name 当前列 params 参数
      console.log(rows, name, params); // 打印参数

    },
    // 部件编辑前事件
    fittings_beforeEditMethod({ column, row }) { // column 当前列 row 当前行
      console.log(row, column);
      return true;
    },

    // 部件编辑后事件
    fittings_afterEditEvent({ column, row }) { // column 当前列 row 当前行
      console.log(row, column);

      this.calculateAll();
    },
    // 部件编辑前事件
    fittings_beforeEditEvent({ column, row }) { // column 当前列 row 当前行
      console.log(row, column);
    },

    // 部件表格添加事件
    fittings_footerCellClassName({ columnIndex }) { // columnIndex 当前列索引
      if (columnIndex === 0) {
        return 'col-blue'
      }
    },
    // 部件表格合计事件
    fittings_footerMethod({ columns }) { // columns 当前列
      const sums = [] // 合计数组
      columns.forEach((column, columnIndex) => { // 遍历列
        if (columnIndex === 0) { // 如果是第一列
          sums.push('') // 添加空字符串
        } else { // 如果不是第一列
          let sumCell = '' // 合计单元格
          switch (column.field) {  // 判断列字段
            case 'quantity': // 数量
              sumCell = parseFloat(this.formOptions.data.fittings_total_quantity || 0).toFixed(0) // 设置合计单元格
              break
            case 'seal_formula': // 封边公式
              sumCell = parseFloat(this.formOptions.data.fittings_total_seal || 0).toFixed(2) // 设置合计单元格
              break
            case 'board_length_formula': // 板材长度公式
              sumCell = parseFloat(this.formOptions.data.fittings_total_board_length || 0).toFixed(3) // 设置合计单元格
              break
            case 'paint_area_formula': // 油漆面公式
              sumCell = parseFloat(this.formOptions.data.fittings_total_paint_area || 0).toFixed(3) // 设置合计单元格
              break


          }
          sums.push(sumCell) // 添加合计单元格
        }
      })
      // 返回一个二维数组的表尾合计
      return [sums]
    },
    // 部件表格添加事件
    fittings_pageAdd(row) {  // row 当前行
      const $table = this.$refs.fittings_xTable // 获取表格
      const record = { // 新的数据
      }
      if (row) { // 如果有行

        this.fittings_detailsData.splice($table.getRowSeq(row), 0, record); // 添加数据 
      } else { // 如果没有行
        this.fittings_detailsData.push(record) // 添加数据
      }
    },

    // 部件表格删除事件
    fittings_pageDelete(row) { // row 当前行
      const $table = this.$refs.fittings_xTable; // 获取表格
      this.fittings_detailsData.splice($table.getRowSeq(row) - 1, 1); // 删除数据
      this.resetMaterial(); // 重置材料
      this.resetPaintMaterial(); // 重置油漆材料
    },


    // 配件下拉选择事件
    parts_onPulldownSelected({ selectedData, row }) { // selectedData 选择的数据 row 当前行
      console.log(row, selectedData);
      if (selectedData.spec) { // 如果有规格
        row.spec = selectedData.spec; // 设置规格
      }
      if (selectedData.price) { // 如果有价格
        row.price = selectedData.price; // 设置价格

      }

    },
    // 配件弹出选择事件
    parts_onPopupSelected({ rows, name, params }) { // rows 当前行 name 当前列 params 参数
      console.log(rows, name, params);
    },
    // 配件编辑前事件
    parts_beforeEditMethod({ column, row }) {
      console.log(row, column);
      return true;
    },
    // 配件编辑后事件
    parts_afterEditEvent() {

      this.calculateAll();
    },
    // 配件编辑前事件
    parts_beforeEditEvent({ column, row }) {
      console.log(row, column);
    },
    // 配件表格添加事件
    parts_pageAdd(row) {
      const $table = this.$refs.parts_xTable
      const record = {
      }
      if (row) {
        this.parts_detailsData.splice($table.getRowSeq(row), 0, record);
      } else {
        this.parts_detailsData.push(record)
      }
    },
    // 配件表格删除事件
    parts_pageDelete(row) {
      const $table = this.$refs.parts_xTable;
      this.parts_detailsData.splice($table.getRowSeq(row) - 1, 1);
      this.calculateAll();
    },
    // 配件表格添加事件
    parts_footerCellClassName({ columnIndex }) {
      if (columnIndex === 0) {
        return 'col-blue'
      }
    },
    // 配件表格合计事件
    parts_footerMethod({ columns, data }) {
      console.log(data)
      const sums = []
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums.push('')
        } else {
          let sumCell = ''
          switch (column.field) {
            case 'amount_formula':
              sumCell = parseFloat(this.formOptions.data.parts_total_amount || 0).toFixed(2)
              break
          }
          sums.push(sumCell)
        }
      })
      return [sums]
    },


    // 包装下拉选择事件
    packaging_onPulldownSelected({ row, name, column, params, selectedData }) {
      console.log(row, name, params);

      if (column.field == "packaging") {

        if (selectedData && selectedData.default_quantity) {
          row.quantity = selectedData.default_quantity; // 设置默认数量
          row.quantity_formula = selectedData.default_quantity;
        }
      }

    },
    // 包装弹出选择事件
    packaging_onPopupSelected({ rows, name, params }) {
      console.log(rows, name, params);
    },
    // 包装编辑前事件
    packaging_beforeEditMethod({ column, row }) {
      console.log(row, column);
      return true;
    },
    // 包装编辑后事件
    packaging_afterEditEvent({ column, row }) {
      console.log(row, column);

      this.calculateAll();
    },
    // 包装编辑前事件
    packaging_beforeEditEvent({ column, row }) {
      console.log(row, column);
    },
    // 包装表格添加事件
    packaging_pageAdd(row) {
      const $table = this.$refs.packaging_xTable
      const record = {
      }
      if (row) {
        this.packaging_detailsData.splice($table.getRowSeq(row), 0, record);
      } else {
        this.packaging_detailsData.push(record)
      }
    },
    // 包装表格删除事件
    packaging_pageDelete(row) {
      const $table = this.$refs.packaging_xTable;
      this.packaging_detailsData.splice($table.getRowSeq(row) - 1, 1);
    },
    // 包装表格添加事件
    packaging_footerCellClassName({ columnIndex }) {
      if (columnIndex === 0) {
        return 'col-blue'
      }
    },
    // 包装表格合计事件
    packaging_footerMethod({ columns, data }) {
      console.log(data)
      const sums = []
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums.push('')
        } else {
          let sumCell = ''
          switch (column.field) {
            case 'amount_formula':
              sumCell = parseFloat(this.formOptions.data.packaging_total_amount || 0).toFixed(2)
              break
          }
          sums.push(sumCell)
        }
      })
      return [sums]
    },

    // 油漆材料下拉选择事件
    material_onPulldownSelected({ row, name, params }) {
      console.log(row, name, params);

    },
    // 油漆材料弹出选择事件
    material_onPopupSelected({ rows, name, params }) {
      console.log(rows, name, params);
    },
    // 油漆材料编辑前事件
    material_beforeEditMethod({ column, row }) {
      console.log(row, column);
      return true;
    },
    // 油漆材料编辑后事件
    material_afterEditEvent({ column, row }) {
      console.log(row, column);

      this.calculateAll();
    },
    // 油漆材料编辑前事件
    material_pageAdd(row) {
      const $table = this.$refs.material_xTable
      const record = {

      }
      if (row) {
        this.material_detailsData.splice($table.getRowSeq(row), 0, record);
      } else {
        this.material_detailsData.push(record)
      }
    },
    // 油漆材料表格删除事件
    material_pageDelete(row) {
      const $table = this.$refs.material_xTable;
      this.material_detailsData.splice($table.getRowSeq(row) - 1, 1);
    },
    // 油漆材料表格添加事件
    material_footerCellClassName({ columnIndex }) {
      if (columnIndex === 0) {
        return 'col-blue'
      }
    },
    // 油漆材料表格合计事件
    material_footerMethod({ columns }) {
      const sums = []
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums.push('')
        } else {
          let sumCell = ''
          switch (column.field) {
            case 'amount_formula':
              sumCell = parseFloat(this.formOptions.data.material_total_amount || 0).toFixed(2)
              break
          }
          sums.push(sumCell)
        }
      })
      return [sums]
    },


    // 人工下拉选择事件
    labor_onPulldownSelected({ row, name, params }) {
      console.log(row, name, params);

    },
    // 人工弹出选择事件
    labor_onPopupSelected({ rows, name, params }) {
      console.log(rows, name, params);
    },
    // 人工编辑前事件
    labor_beforeEditMethod({ column, row }) {
      console.log(row, column);
      return true;
    },
    // 人工编辑后事件
    labor_afterEditEvent({ column, row }) {
      console.log(row, column);

      this.calculateAll();
    },
    // 人工编辑前事件
    labor_beforeEditEvent({ column, row }) {
      console.log(row, column);
    },
    // 人工表格添加事件
    labor_pageAdd(row) {
      const $table = this.$refs.labor_xTable
      const record = {
      }
      if (row) {

        this.labor_detailsData.splice($table.getRowSeq(row), 0, record);
      } else {
        this.labor_detailsData.push(record)
      }
    },
    // 人工表格删除事件
    labor_pageDelete(row) {
      const $table = this.$refs.labor_xTable;
      this.labor_detailsData.splice($table.getRowSeq(row) - 1, 1);
    },
    // 人工表格添加事件
    labor_footerCellClassName({ columnIndex }) {
      if (columnIndex === 0) {
        return 'col-blue'
      }
    },
    // 人工表格合计事件
    labor_footerMethod({ columns }) {
      const sums = []
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums.push('')
        } else {
          let sumCell = ''
          switch (column.field) {
            case 'amount_formula':
              sumCell = parseFloat(this.formOptions.data.labor_total_amount || 0).toFixed(2)
              break
          }
          sums.push(sumCell)
        }
      })
      return [sums]
    },


    // 油漆人工下拉选择事件
    expense_onPulldownSelected({ row, name, params }) {
      console.log(row, name, params);

    },
    // 油漆人工弹出选择事件
    expense_onPopupSelected({ rows, name, params }) {
      console.log(rows, name, params);
    },
    // 油漆人工编辑前事件
    expense_beforeEditMethod({ column, row }) {
      console.log(row, column);
      return true;
    },
    // 油漆人工编辑后事件
    expense_afterEditEvent({ column, row }) {
      console.log(row, column);
      this.calculateAll();
    },
    // 油漆人工编辑前事件
    expense_beforeEditEvent({ column, row }) {
      console.log(row, column);
    },
    // 油漆人工表格添加事件
    expense_pageAdd(row) {
      const $table = this.$refs.expense_xTable
      const record = {
      }
      if (row) {
        this.expense_detailsData.splice($table.getRowSeq(row), 0, record);
      } else {
        this.expense_detailsData.push(record)
      }
    },
    // 油漆人工表格删除事件
    expense_pageDelete(row) {
      const $table = this.$refs.expense_xTable;
      this.expense_detailsData.splice($table.getRowSeq(row) - 1, 1);
    },
    // 油漆人工表格添加事件
    expense_footerCellClassName({ columnIndex }) {
      if (columnIndex === 0) {
        return 'col-blue'
      }
    },
    expense_footerMethod({ columns }) {
      const sums = []
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums.push('')
        } else {
          let sumCell = ''
          switch (column.field) {
            case 'amount_formula':
              sumCell = parseFloat(this.formOptions.data.expense_total_amount || 0).toFixed(2)
              break
          }
          sums.push(sumCell)
        }
      })
      return [sums]
    },



    paintMaterial_onPulldownSelected({ row, name, params }) {
      console.log(row, name, params);

    },
    paintMaterial_onPopupSelected({ rows, name, params }) {
      console.log(rows, name, params);
    },
    paintMaterial_beforeEditMethod({ column, row }) {
      console.log(row, column);
      return true;
    },
    paintMaterial_afterEditEvent({ column, row }) {
      console.log(row, column);
      this.calculateAll();
    },
    paintMaterial_pageAdd(row) {
      const $table = this.$refs.paintMaterial_xTable
      const record = {

      }
      if (row) {

        this.paintMaterial_detailsData.splice($table.getRowSeq(row), 0, record);
      } else {
        this.paintMaterial_detailsData.push(record)
      }
    },
    paintMaterial_pageDelete(row) {
      const $table = this.$refs.paintMaterial_xTable;
      this.paintMaterial_detailsData.splice($table.getRowSeq(row) - 1, 1);
    },
    paintMaterial_footerCellClassName({ columnIndex }) {
      if (columnIndex === 0) {
        return 'col-blue'
      }
    },
    paintMaterial_footerMethod({ columns }) {
      const sums = []
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums.push('')
        } else {
          let sumCell = ''
          switch (column.field) {
            case 'amount_formula':
              sumCell = parseFloat(this.formOptions.data.paintMaterial_total_amount || 0).toFixed(2)
              break
          }
          sums.push(sumCell)
        }
      })
      return [sums]
    },


    paintLabor_onPulldownSelected({ row, name, params }) {
      console.log(row, name, params);

    },
    paintLabor_onPopupSelected({ rows, name, params }) {
      console.log(rows, name, params);
    },
    paintLabor_beforeEditMethod({ column, row }) {
      console.log(row, column);
      return true;
    },
    paintLabor_afterEditEvent({ column, row }) {
      console.log(row, column);
      this.calculateAll();
    },
    paintLabor_beforeEditEvent({ column, row }) {
      console.log(row, column);
    },
    paintLabor_pageAdd(row) {
      const $table = this.$refs.paintLabor_xTable
      const record = {
      }
      if (row) {

        this.paintLabor_detailsData.splice($table.getRowSeq(row), 0, record);
      } else {
        this.paintLabor_detailsData.push(record)
      }
    },
    paintLabor_pageDelete(row) {
      const $table = this.$refs.paintLabor_xTable;
      this.paintLabor_detailsData.splice($table.getRowSeq(row) - 1, 1);
    },
    paintLabor_footerCellClassName({ columnIndex }) {
      if (columnIndex === 0) {
        return 'col-blue'
      }
    },
    paintLabor_footerMethod({ columns }) {
      const sums = []
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums.push('')
        } else {
          let sumCell = ''
          switch (column.field) {
            case 'amount_formula':
              sumCell = parseFloat(this.formOptions.data.paintLabor_total_amount || 0).toFixed(2)
              break
          }
          sums.push(sumCell)
        }
      })
      return [sums]
    },


    paintExpense_onPulldownSelected({ row, name, params }) {
      console.log(row, name, params);

    },
    paintExpense_onPopupSelected({ rows, name, params }) {
      console.log(rows, name, params);
    },
    paintExpense_beforeEditMethod({ column, row }) {
      console.log(row, column);
      return true;
    },
    paintExpense_afterEditEvent({ column, row }) {
      console.log(row, column);
      this.calculateAll();
    },
    paintExpense_beforeEditEvent({ column, row }) {
      console.log(row, column);
    },
    paintExpense_pageAdd(row) {
      const $table = this.$refs.paintExpense_xTable
      const record = {
      }
      if (row) {
        this.paintExpense_detailsData.splice($table.getRowSeq(row), 0, record);
      } else {
        this.paintExpense_detailsData.push(record)
      }
    },
    paintExpense_pageDelete(row) {
      const $table = this.$refs.paintExpense_xTable;
      this.paintExpense_detailsData.splice($table.getRowSeq(row) - 1, 1);
    },
    paintExpense_footerCellClassName({ columnIndex }) {
      if (columnIndex === 0) {
        return 'col-blue'
      }
    },
    paintExpense_footerMethod({ columns }) {
      const sums = []
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums.push('')
        } else {
          let sumCell = ''
          switch (column.field) {
            case 'amount_formula':
              sumCell = parseFloat(this.formOptions.data.paintExpense_total_amount || 0).toFixed(2)
              break
          }
          sums.push(sumCell)
        }
      })
      return [sums]
    },




    drawer_onPulldownSelected({ row, name, params }) {
      console.log(row, name, params);

    },
    drawer_onPopupSelected({ rows, name, params }) {
      console.log(rows, name, params);
    },
    drawer_beforeEditMethod({ column, row }) {
      console.log(row, column);
      return true;
    },
    drawer_afterEditEvent({ column, row }) {
      console.log(row, column);


      row.amount = parseFloat(row.quantity || 0) * parseFloat(row.expense || 0);
      row.paint_amount = parseFloat(row.quantity || 0) * parseFloat(row.paint_expense || 0);


      this.calculateAll();
    },
    drawer_beforeEditEvent({ column, row }) {
      console.log(row, column);
    },
    drawer_pageAdd(row) {
      const $table = this.$refs.drawer_xTable
      const record = {
      }
      if (row) {
        this.drawer_detailsData.splice($table.getRowSeq(row), 0, record);
      } else {
        this.drawer_detailsData.push(record)
      }
    },
    drawer_pageDelete(row) {
      const $table = this.$refs.drawer_xTable;
      this.drawer_detailsData.splice($table.getRowSeq(row) - 1, 1);
    },
    drawer_footerCellClassName({ columnIndex }) {
      if (columnIndex === 0) {
        return 'col-blue'
      }
    },
    drawer_footerMethod({ columns, data }) {
      console.log(data)
      const sums = []
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums.push('')
        } else {
          let sumCell = ''
          switch (column.field) {
            case 'amount':
              sumCell = parseFloat(this.formOptions.data.drawer_total_amount || 0).toFixed(2)
              break
            case 'paint_amount':
              sumCell = parseFloat(this.formOptions.data.drawer_total_paint_amount || 0).toFixed(2)
              break
          }
          sums.push(sumCell)
        }
      })
      return [sums]
    },



    formatName(v) {
      return (v || "").replace("\r", "").replace("\n", "").replace("\t", "").replace(" ", "");
    },



    resetMaterial() {
      let material_items = [];

      this.fittings_detailsData.forEach(item => {

        if (item.material && item.material[0]) {

          if (material_items.filter(a => a && a[0] == item.material[0]).length == 0) {
            material_items.push(item.material);
          }

        }
      });

      let material_list = [];
      material_items.forEach(item => {

        let name = this.formatName(item[1]);
        let old = this.material_detailsData.filter(a => a.material && a.material[0] == item[0] ? true : false);
        let info = {
          isMain: true,
          material: item,
          quantity_formula: `{${name}的总用量}`,
          price: 0
        };
        if (old.length) {
          info.quantity_formula = `{${name}的总用量}`;
          info.price = old[0].price;
          info.amount_formula = old[0].amount_formula;
        }
        material_list.push(info)
      })


      var b1 = true;
      if (b1) {
        let info = {
          isBanding: true,
          material: ['封边条', '封边条'],
          quantity_formula: '',
          price: 0
        };
        let old = this.material_detailsData.filter(a => a.isBanding ? true : false);

        if (old.length) {
          info.quantity_formula = old[0].quantity_formula;
          info.amount_formula = old[0].amount_formula;
          info.price = old[0].price;
        }
        material_list.push(info)
      }


      let ds = [];
      this.material_detailsData.forEach(item => {
        if (item.isMain) return;
        if (item.isBanding) return;
        ds.push(item);
      });
      this.material_detailsData = [...material_list, ...ds];

    },



    resetPaintMaterial() {
      let material_items = [];

      this.fittings_detailsData.forEach(item => {

        if (item.paint_material && item.paint_material[0]) {

          if (material_items.filter(a => a && a[0] == item.paint_material[0]).length == 0) {
            material_items.push(item.paint_material);
          }

        }
      });

      let material_list = [];
      material_items.forEach(item => {
        let name = this.formatName(item[1]);
        let old = this.paintMaterial_detailsData.filter(a => a.material && a.material[0] == item[0] ? true : false);
        let info = {
          isMain: true,
          material: item,
          quantity_formula: `{${name}的总用量}`,
          price: 0
        };
        if (old.length) {
          info.quantity_formula = `{${name}的总用量}`;
          info.price = old[0].price;
          info.amount_formula = old[0].amount_formula;
        }
        material_list.push(info)
      })


      var b1 = true;
      if (b1) {
        let info = {
          isBanding: true,
          material: ['封边条', '封边条'],
          quantity_formula: '',
          price: 0
        };
        let old = this.paintMaterial_detailsData.filter(a => a.isBanding ? true : false);

        if (old.length) {
          info.quantity_formula = old[0].quantity_formula;
          info.amount_formula = old[0].amount_formula;
          info.price = old[0].price;
        }
        material_list.push(info)
      }


      let ds = [];
      this.paintMaterial_detailsData.forEach(item => {
        if (item.isMain) return;
        if (item.isBanding) return;
        ds.push(item);
      });
      this.paintMaterial_detailsData = [...material_list, ...ds];

    },



    formatDetailsData(data) {

      if (!data) return;
      data.forEach(item => {
        delete item._X_ROW_KEY
        if (!item.id) {
          item.id = settings.getGuid();
        }
      });
    },
    // 保存update
    ok() {

      let save = () => {


        // 如果是新增模式，提交新增接口 如果是编辑模式，提交编辑接口
        let action = !this.isEdit ? this.actions.create : this.actions.update;
        // 如果是新增模式，提交的数据中加入id 如果是编辑模式，提交的数据中不加入id
        let postdata = Object.assign({}, this.formOptions.data);
        // 如果是编辑模式
        if (this.isEdit) {
          postdata.id = this.$mk.toBigInt(postdata.id)
          // postdata = { BathroomQuotation: postdata }
        }


        postdata.fittingsList = JSON.parse(JSON.stringify(this.fittings_detailsData));
        postdata.partsList = JSON.parse(JSON.stringify(this.parts_detailsData));
        postdata.packagingList = JSON.parse(JSON.stringify(this.packaging_detailsData));
        postdata.laborList = JSON.parse(JSON.stringify(this.labor_detailsData));
        postdata.materialList = JSON.parse(JSON.stringify(this.material_detailsData));
        postdata.paint_laborList = JSON.parse(JSON.stringify(this.paintLabor_detailsData));
        postdata.paint_materialList = JSON.parse(JSON.stringify(this.paintMaterial_detailsData));
        postdata.expense_list = JSON.parse(JSON.stringify(this.expense_detailsData));
        postdata.paint_expenseList = JSON.parse(JSON.stringify(this.paintExpense_detailsData));


        postdata.fittingsList = postdata.fittingsList.filter(item => item.fittings && item.fittings[1] ? true : false);
        postdata.partsList = postdata.partsList.filter(item => item.parts && item.parts[1] ? true : false);
        postdata.packagingList = postdata.packagingList.filter(item => item.packaging && item.packaging[1] ? true : false);
        postdata.laborList = postdata.laborList.filter(item => item.labor && item.labor[1] ? true : false);
        postdata.materialList = postdata.materialList.filter(item => item.material && item.material[1] ? true : false);


        postdata.paint_laborList = postdata.paint_laborList.filter(item => item.labor && item.labor[1] ? true : false);
        postdata.paint_materialList = postdata.paint_materialList.filter(item => item.material && item.material[1] ? true : false);

        postdata.expense_list = postdata.expense_list.filter(item => item.item_name ? true : false);
        postdata.paint_expenseList = postdata.paint_expenseList.filter(item => item.item_name ? true : false);

        postdata.expense = parseFloat(this.formOptions.data.expense_total_amount || 0) +
          parseFloat(this.formOptions.data.material_total_amount || 0) +
          parseFloat(this.formOptions.data.labor_total_amount || 0) +
          parseFloat(this.formOptions.data.parts_total_amount || 0) +
          parseFloat(this.formOptions.data.packaging_total_amount || 0);


        postdata.paint_expense = parseFloat(this.formOptions.data.paintExpense_total_amount || 0) +
          parseFloat(this.formOptions.data.paintMaterial_total_amount || 0) +
          parseFloat(this.formOptions.data.paintLabor_total_amount || 0) +
          parseFloat(this.formOptions.data.parts_total_amount || 0) +
          parseFloat(this.formOptions.data.packaging_total_amount || 0);

        this.formatDetailsData(postdata.fittingsList);
        this.formatDetailsData(postdata.partsList);
        this.formatDetailsData(postdata.packagingList);
        this.formatDetailsData(postdata.laborList);
        this.formatDetailsData(postdata.materialList);
        this.formatDetailsData(postdata.paint_laborList);
        this.formatDetailsData(postdata.paint_materialList);
        this.formatDetailsData(postdata.expense_list);
        this.formatDetailsData(postdata.paint_expenseList);


        postdata.fittingsList = JSON.stringify(postdata.fittingsList);
        postdata.partsList = JSON.stringify(postdata.partsList);
        postdata.packagingList = JSON.stringify(postdata.packagingList);
        postdata.laborList = JSON.stringify(postdata.laborList);
        postdata.materialList = JSON.stringify(postdata.materialList);
        postdata.paint_laborList = JSON.stringify(postdata.paint_laborList);
        postdata.paint_materialList = JSON.stringify(postdata.paint_materialList);
        postdata.expense_list = JSON.stringify(postdata.expense_list);
        postdata.paint_expenseList = JSON.stringify(postdata.paint_expenseList);


        postdata.drawer_list = JSON.stringify(this.drawer_detailsData);

        // 格式化提交的数据
        this.$mk.formatFormData({ data: postdata, rules: this.formOptions.items });


        // 提交数据
        this.$mk.post({
          url: action,
          loading: "保存中...",
          data: postdata,
          useBigInt: true,
        }).then(() => { // 成功回调
          this.$mk.success("保存成功");
          if (!this.isEdit) { // 如果是新增模式，关闭当前页面
            this.back();
          }
        }).catch((a) => { // 失败回调
          this.$mk.error(a.data.msg); // 显示错误信息
        });


      };


      // 验证表单
      this.$mk.validateForm({ form: this.$refs.xForm }).then(() => { // 验证表单
        save(); // 提交保存
      }).catch(count => { // 验证失败
        this.$mk.error(`存在${count}项错误，请检查`);
      });


    },


    // 取消 返回
    cancel() {
      this.back();
    },

    onTabEdit(index) {

      this.drawer_detailsData.splice(index, 1);

      this.calculateAll();
    },
    tabChange() {
      setTimeout(() => {
        let drawers = this.$refs['drawer'];

        if (drawers) {
          drawers.forEach(drawer => {
            if (drawer.setShowType) {

              drawer.setShowType(this.showType);
            }
          })
        }
      }, 500);
    },

    getExpressionItemValue({ name, row, defaultValue }) {

      if (!name) return '';
      //计算材料的总用量
      if (name.indexOf('的总用量') > 0) {

        name = this.formatName(name);
        let sum = 0;
        this.fittings_detailsData.forEach(item => {
          if (item.material && item.material[1]) {
            let name_current = this.formatName(item.material[1]);
            if (name == name_current + "的总用量") {
              sum += parseFloat(item.board_length || 0);
              return;
            }
          }
          if (item.paint_material && item.paint_material[1]) {
            let name_current = this.formatName(item.paint_material[1]);
            if (name == name_current + "的总用量") {
              sum += parseFloat(item.board_length || 0);
              return;
            }
          }

        });
        return sum;

      }
      //计算材料的厚度
      if (name.indexOf('的厚度') > 0) {

        name = this.formatName(name);
        name = name.substr(0, name.length - 3);
        console.log(name);
        let v = 0;
        this.bathroomMaterial_list.forEach(o => { // 遍历材料列表

          if (name == this.formatName(o.name)) {

            v = parseFloat(o.spec || 15);
          }


        });
        return v;

      }
      let nn = [{ n: '的长', name: 'long' }, { n: '的宽', name: 'width' }, { n: '的厚', name: 'height' }];
      for (let i = 0; i < nn.length; i++) {

        if (name.indexOf(nn[i].n) > 0 &&
          this.fittings_list.filter(a => this.formatName(a.name) + nn[i].n == name).length) {
          name = this.formatName(name);
          name = name.substr(0, name.length - 2);
          console.log(name);
          let v = 0;
          this.fittings_detailsData.forEach(o => {
            if (o.fittings && name == this.formatName(o.fittings[1])) {
              v = parseFloat(o[nn[i].name] || 0);
            }
          });
          return v;
        }

      }


      let fun = settings.expressionsDefines[name];
      if (!fun) {
        return defaultValue || 0;
      }
      var v = fun({ data: this.formOptions.data, row: row }) || defaultValue;

      return parseFloat(v || 0);
    },

    //根据表达式计算出值
    getExpressionValue({ row, exp, defaultValue }) {

      try {
        let value = exp.toString();

        value = value.replace(/{([\u4e00-\u9fa5_a-zA-Z0-9]+)}/g, (n) => {
          let name = n.substr(1, n.length - 2);
          return this.getExpressionItemValue({ row, name, defaultValue })
        });

        value = value.replace("/，/g", ",");
        value = value.replace("/？/g", "?");
        value = value.replace("/：/g", ":");

        eval("value = " + value)
        return value;
      } catch {
        return defaultValue || 0;
      }

    },




    calculateAll() { // 计算所有

      this._calculateAll(); // 计算所有
      this.$forceUpdate(); // 强制刷新

    },

    _calculateAll() { // 计算所有

      this.totalRows({ detailsData: this.drawer_detailsData, names: ["amount", "paint_amount"], totalPrev: "drawer" }); // 计算所有 抽屉

      // 计算所有 五金  配件
      this.calculateRows({ detailsData: this.fittings_detailsData, names: ["long", "width", "height", "seal", "board_length", "paint_area"], totalPrev: "fittings" });
      // 计算所有 部件
      this.totalRows({ detailsData: this.fittings_detailsData, names: ["quantity"], totalPrev: "fittings" });

      // 计算所有 配件
      this.calculateRows({ detailsData: this.parts_detailsData, names: ["amount"], totalPrev: "parts" });
      // 计算所有 包装
      this.calculateRows({ detailsData: this.packaging_detailsData, names: ["long", "width", "height", "quantity", "amount", "price"], totalPrev: "packaging" });
      // 计算所有 材料
      this.calculateRows({ detailsData: this.material_detailsData, names: ["quantity", "amount"], totalPrev: "material" });
      // 计算所有 人工
      this.calculateRows({ detailsData: this.labor_detailsData, names: ["amount"], totalPrev: "labor" });
      // 计算所有 油漆材料
      this.calculateRows({ detailsData: this.paintMaterial_detailsData, names: ["quantity", "amount"], totalPrev: "paintMaterial" });
      // 计算所有 油漆人工
      this.calculateRows({ detailsData: this.paintLabor_detailsData, names: ["amount"], totalPrev: "paintLabor" });

      // 计算所有 费用
      this.calculateRows({ detailsData: this.expense_detailsData, names: ["amount"], totalPrev: "expense" });
      // 计算所有 油漆费用
      this.calculateRows({ detailsData: this.paintExpense_detailsData, names: ["amount"], totalPrev: "paintExpense" });

      console.log("this.formOptions.data.expense_total_amount:" + this.formOptions.data.expense_total_amount)



      this.calculateTotal();
    },

    calculateTotal() {

      this.formOptions.data.expense = parseFloat(this.formOptions.data.expense_total_amount || 0) +
        parseFloat(this.formOptions.data.material_total_amount || 0) +
        parseFloat(this.formOptions.data.labor_total_amount || 0) +
        parseFloat(this.formOptions.data.parts_total_amount || 0) +
        parseFloat(this.formOptions.data.packaging_total_amount || 0) +
        parseFloat(this.formOptions.data.drawer_total_amount || 0);


      this.formOptions.data.paint_expense = parseFloat(this.formOptions.data.paintExpense_total_amount || 0) +
        parseFloat(this.formOptions.data.paintMaterial_total_amount || 0) +
        parseFloat(this.formOptions.data.paintLabor_total_amount || 0) +
        parseFloat(this.formOptions.data.parts_total_amount || 0) +
        parseFloat(this.formOptions.data.packaging_total_amount || 0) +
        parseFloat(this.formOptions.data.drawer_total_amount || 0);


      this.formOptions.data.show_expense = parseFloat(this.formOptions.data.expense || 0).toFixed(2); // 计算所有 费用 
      this.formOptions.data.show_paint_expense = parseFloat(this.formOptions.data.paint_expense || 0).toFixed(2); // 计算所有 油漆费用

      this.formOptions.data = JSON.parse(JSON.stringify(this.formOptions.data)) // 强制刷新
    },

    // 计算行
    calculateRows({ detailsData, names, totalPrev }) {

      let totals = {};
      detailsData.forEach(row => {
        names.forEach(name => {

          let formula = row[name + '_formula'];
          if (!formula) {
            return;
          }
          row[name] = this.getExpressionValue({ row, exp: formula });
          totals[name] = totals[name] || 0;
          totals[name] = totals[name] + row[name];
        })
      });

      names.forEach(name => {
        let total = totals[name];
        this.formOptions.data[totalPrev + "_total_" + name] = total;

      });



    },
    // 统计行
    totalRows({ detailsData, names, totalPrev }) {

      let totals = {};
      detailsData.forEach(row => {
        names.forEach(name => {

          totals[name] = totals[name] || 0;
          totals[name] = totals[name] + parseFloat(row[name] || 0);
        })
      });

      names.forEach(name => {
        let total = totals[name];
        this.formOptions.data[totalPrev + "_total_" + name] = total;

      });



    },

  },
  // 监听属性
  watch: {

  }
};

</script>


<style scoped lang="less">
.page-body {
  padding: 30px;
  background: @base-bg-color;
}

.formtabs .ant-tabs-tabpane {
  /* background: white; */
  padding: 12px;
}

.gridPanel {
  height: calc(100vh - 600px);
}

.footerbar {
  padding-left: 10px;
}

.imagePanel {
  cursor: pointer;
  padding: 10px;
  width: 100px;

  img {
    width: 80px;
    height: 80px;
  }
}

p.tip {
  padding: 12px 20px 12px 20px;
  margin: 8px 0;
  background-color: #f8f8f8;
  border-left: 4px solid #409eff;
}

.oplinks2 a {
  margin-left: 6px;
}

.mytable-footer .col-blue {
  background-color: #2db7f5 !important;
  color: #fff !important;
}

.groupbox {
  margin: 8px;
  border: 1px solid #ddd;
  padding: 10px;

  h3 {
    font-weight: bold;
  }
}

.topbar {
  margin-bottom: 10px;

  button {
    margin-right: 8px;
  }
}
</style>
