<template>
  <div class="detail-container">
    <el-page-header :content="listItem ? '编辑' : '新增'" @back="goBack" />

    <div class="main-title">
      <div class="title">工程订单</div>
    </div>

    <el-form
      ref="mainForm"
      :model="mainForm"
      :rules="mainFormRules"
      label-width="125px"
      size="small"
      label-position="right"
    >
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="工程订单" prop="orderNum">
            <el-input v-model="mainForm.orderNum" placeholder="系统自动生成" disabled />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8" style="height: 51px">
          <el-form-item label="单据日期" prop="orderDate">
            <el-date-picker
              v-model="mainForm.orderDate"
              disabled
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              placeholder="系统自动生成"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="销售类型" prop="saleType">
            <el-select
              v-model="mainForm.saleType"
              placeholder="选择销售类型"
              style="width: 100%"
              filterable
              clearable
              @change="changeSaleType"
            >
              <el-option v-for="item in salesTypeList" :key="item.id" :label="item.saleName" :value="item.id">
                <span>{{ item.saleName }}</span> <span style="color: #f00">{{ item.saleCode }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="经销商编码" prop="jxsNum">
            <el-input v-model="mainForm.jxsNum" placeholder="请输入经销商编码" disabled />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="16">
          <el-form-item label="经销商名称" prop="jxsName">
            <el-input v-model="mainForm.jxsName" placeholder="请输入经销商名称" disabled />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="工程登录编号" prop="loginNum">
            <div style="display: flex">
              <el-input v-model="mainForm.loginNum" placeholder="请引用工程登录" disabled />
              <el-button style="margin-left: 10px" @click="openShareDetail">引用</el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="项目类别" prop="enginName">
            <el-input v-model="mainForm.enginName" placeholder="请输入项目类别" :disabled="isDealer" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="行业类别" prop="loginType">
            <el-input v-model="mainForm.loginType" :disabled="isDealer" placeholder="请输入行业类别" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="跨区厂编号" prop="factoryNum">
            <el-input v-model="mainForm.factoryNum" placeholder="请输入跨区厂编号" :disabled="isDealer" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="使用单位" prop="company">
            <el-input v-model="mainForm.company" placeholder="请输入使用单位" :disabled="isDealer" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="业务员" prop="salesMan">
            <el-select
              v-model="mainForm.salesMan"
              placeholder="选择业务员"
              size="small"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in salesmanList"
                :key="item.adminUserId"
                :label="item.nickName"
                :value="item.adminUserId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="引用记录" prop="refCount">
            <el-input v-model="mainForm.refCount" placeholder="请输入引用记录" :disabled="isDealer" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="第几申报" prop="declareNo">
            <el-input v-model="mainForm.declareNo" placeholder="请输入第几申报" :disabled="isDealer" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="项目类型" prop="projectType">
            <el-input v-model="mainForm.projectType" placeholder="请输入项目类型" :disabled="isDealer" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="区域" prop="regionWork">
            <el-input v-model="mainForm.regionWork" placeholder="请输入区域" :disabled="isDealer" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="文件编号" prop="fileNum">
            <el-input v-model="mainForm.fileNum" placeholder="请输入文件编号" :disabled="isDealer" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="购买单位" prop="refBuyUnitName">
            <el-input v-model="mainForm.refBuyUnitName" placeholder="请输入购买单位" :disabled="isDealer" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="登录有效期" prop="refBuyUnitName">
            <el-input v-model="mainForm.refBuyUnitName" placeholder="请输入购买单位" :disabled="isDealer" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="联系人" prop="contactMan">
            <el-input v-model="mainForm.contactMan" placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="固定电话" prop="tel">
            <el-input v-model="mainForm.tel" placeholder="请输入固定电话" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="移动电话" prop="phone">
            <el-input v-model="mainForm.phone" placeholder="请输入移动电话" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="16" :lg="16">
          <el-form-item label="安装地址" prop="address">
            <el-input v-model="mainForm.address" placeholder="请输入安装地址" :disabled="isDealer" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="8" :lg="8">
          <el-form-item label="保证函" prop="refPromiseProvide">
            <el-select
              v-model="mainForm.refPromiseProvide"
              placeholder="选择保证函状态"
              :disabled="isDealer ? true : false"
              size="small"
              clearable
              style="width: 100%"
            >
              <el-option label="未保证" value="未保证" />
              <el-option label="已保证" value="已保证" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="跨区厂编号" prop="refBuyUnitName">
            <el-input v-model="mainForm.refBuyUnitName" placeholder="请输入购买单位" :disabled="isDealer" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="项目编号" prop="refProjectNo">
            <el-input v-model="mainForm.refProjectNo" placeholder="请输入项目编号" :disabled="isDealer" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="项目说明" prop="projectRemark">
            <el-input v-model="mainForm.projectRemark" placeholder="请输入项目说明" :disabled="isDealer" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="工程机转零售批复意见" prop="refToRetailIdea">
            <el-input v-model="mainForm.refToRetailIdea" placeholder="请输入其他附件审批意见" disabled />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="合同变更批复意见" prop="refContractIdea">
            <el-input v-model="mainForm.refContractIdea" placeholder="请输入其他附件审批意见" disabled />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="资料延期批复意见" prop="refDataDelayIdea">
            <el-input v-model="mainForm.refDataDelayIdea" placeholder="请输入其他附件审批意见" disabled />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="其他附件审批意见" prop="refOtherAnnexIdea">
            <el-input v-model="mainForm.refOtherAnnexIdea" placeholder="请输入其他附件审批意见" disabled />
          </el-form-item>
        </el-col>
        <el-col v-if="!isDealer" :xs="24" :sm="24" :lg="24">
          <el-form-item label="格力内部备注" prop="greeRemark">
            <el-input v-model="mainForm.greeRemark" placeholder="请输入格力内部备注" />
          </el-form-item>
        </el-col>
        <!-- <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="格力回复" prop="greeReply">
            <el-input v-model="mainForm.greeReply" placeholder="请输入格力回复"></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="mainForm.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="制单人" prop="createMan">
            <el-input v-model="mainForm.createMan" placeholder="请输入制单人" disabled />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8" style="height: 51px">
          <el-form-item label="制单日期" prop="createDate">
            <el-date-picker
              v-model="mainForm.createDate"
              disabled
              type="date"
              :default-value="getDate()"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <!--        <el-col :span="24" :sm="12" :lg="8">-->
        <!--          <el-form-item label="计划单" prop="isPlanOrder">-->
        <!--            <el-radio-group v-model="mainForm.isPlanOrder">-->
        <!--              <el-radio :label="true">是</el-radio>-->
        <!--              <el-radio :label="false">否</el-radio>-->
        <!--            </el-radio-group>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->

        <el-col v-if="mainForm.examineRemark" :xs="24" :sm="24" :lg="24">
          <el-form-item label="审批说明" prop="examineRemark">
            <el-input v-model="mainForm.examineRemark" placeholder="请输入审批说明" disabled />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="main-title">
      <div class="title">货品信息</div>
      <div>
        <el-select
          v-model="warehouseValue"
          placeholder="请选择发货仓库"
          size="small"
          style="margin-right: 10px"
          @change="handleWarehouseValue"
        >
          <el-option v-for="(item, index) in warehouseList" :key="index" :label="item.name" :value="item.id" />
        </el-select>
        <el-button type="primary" size="small" icon="el-icon-search" @click="checkStock">检查库存</el-button>
        <el-divider direction="vertical" />
        <el-button type="primary" size="small" icon="el-icon-plus" @click="openDialog">添加货品</el-button>
      </div>
    </div>

    <div class="table" style="margin-top: 20px">
      <el-table
        :data="goodsList"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        stripe
        max-height="400"
        show-summary
        :summary-method="$getSummaries"
      >
        <el-table-column align="center" label="序号" type="index" width="50" />
        <!-- <el-table-column align="center" label="引用记录" prop="useRefCount" min-width="160" show-overflow-tooltip></el-table-column> -->
        <el-table-column align="center" label="销售类型" prop="saleTypeName" min-width="120" show-overflow-tooltip />
        <el-table-column align="center" label="物料编码" prop="materialNumber" min-width="120" show-overflow-tooltip />
        <el-table-column
          align="center"
          label="产品编码"
          prop="materialOldNumber"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column align="center" label="产品名称" prop="materialName" min-width="160" show-overflow-tooltip />
        <el-table-column align="center" label="规格型号" prop="specification" min-width="300" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-if="listItem" v-model="scope.row.specification" size="small" />
            <div v-else>{{ scope.row.specification }}</div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="实装规格型号"
          prop="realSpecification"
          min-width="300"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.realSpecification"
              :class="scope.row.realSpecification !== scope.row.specification ? 'input' : ''"
              size="small"
              readonly
              @click.native="getRealMaterData(scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="数量" prop="qty" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.qty" size="small" type="number" @mousewheel.native.prevent />
          </template>
        </el-table-column>

        <el-table-column align="center" label="单价" prop="price" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.price" size="small" type="number" @mousewheel.native.prevent />
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单金额" prop="dida" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.price * scope.row.qty }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="工程登录数量" prop="enginNum" min-width="120" show-overflow-tooltip />
        <el-table-column align="center" label="现金钱包" prop="customerWalletId" min-width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.customerWalletId"
              placeholder="选择现金钱包"
              size="small"
              clearable
              @change="changeXjWallet(scope.$index)"
            >
              <el-option
                v-for="item in scope.row.wallets"
                :key="item.customerWalletId"
                :label="item.customerWalletName"
                :value="item.customerWalletId"
              />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column align="center" label="返利类型" prop="customerWalletId2" min-width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.customerWalletId2"
              placeholder="选择返利类型"
              size="small"
              clearable
              @change="changeFlWallet(scope.$index)"
            >
              <el-option
                v-for="item in scope.row.rebateWallets"
                :key="item.customerWalletId"
                :label="item.customerWalletName"
                :value="item.customerWalletId"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="返利金额" min-width="100" show-overflow-tooltip prop="compute_flAmount">
          <template slot-scope="scope">
            {{ (scope.row.price * scope.row.qty * (scope.row.rebateRate * 100)) / 100 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="格力折扣" prop="ko" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.qty * scope.row.discAmount }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="实付金额" min-width="100" show-overflow-tooltip prop="compute_sfAmount">
          <template slot-scope="scope">
            {{
              (scope.row.price * scope.row.qty * 100 -
                ((scope.row.price * scope.row.qty * (scope.row.rebateRate * 100)) / 100) * 100 -
                ((scope.row.qty * (scope.row.discAmount * 100)) / 100) * 100) /
                100
            }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="退订数量" prop="tdQty" min-width="100" show-overflow-tooltip />
        <el-table-column align="center" label="销售数量" prop="salesQty" min-width="100" show-overflow-tooltip />
        <el-table-column align="center" label="销售金额" prop="salesAmount" min-width="100" show-overflow-tooltip />
        <el-table-column align="center" label="是否直调" prop="isDirectTransfer" min-width="100">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.isDirectTransfer" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="直调数量" prop="directTransferQty" min-width="100" />
        <el-table-column align="center" label="已发货数量" prop="hasSendQty" min-width="100" show-overflow-tooltip />
        <el-table-column align="center" label="已退数量" prop="retiredQty" min-width="100" show-overflow-tooltip />
        <el-table-column align="center" label="备注" prop="remark" min-width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" size="small" />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="实装物料编号"
          prop="realMaterialNumber"
          min-width="150"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.realMaterialNumber"
              :class="scope.row.realMaterialNumber !== scope.row.materialNumber ? 'input' : ''"
              size="small"
              readonly
              @click.native="getRealMaterData(scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="实装厂产品编码"
          prop="realMaterialOldNumber"
          min-width="200"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.realMaterialOldNumber"
              :class="scope.row.realMaterialOldNumber !== scope.row.materialOldNumber ? 'input' : ''"
              size="small"
              readonly
              @click.native="getRealMaterData(scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="税率" prop="tax" min-width="100" show-overflow-tooltip />
        <!-- <el-table-column align="center" label="总仓库" prop="status1" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <div>{{ scope.row.status1 | status1Filter }}</div>
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="单位" prop="unit" min-width="100" show-overflow-tooltip />
        <el-table-column align="left" label="仓库" prop="correspondName" min-width="150" show-overflow-tooltip />

        <el-table-column align="center" label="仓库状态" prop="status2" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <div>{{ status2Filter(scope.row) }}</div>
          </template>
        </el-table-column>

        <!-- <el-table-column align="center" label="业务员" prop="serviceId" min-width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-select v-model="scope.row.serviceId" placeholder="选择业务员" size="small" clearable disabled>
              <el-option
                v-for="item in salesmanList"
                :key="item.adminUserId"
                :label="item.nickName"
                :value="item.adminUserId">
              </el-option>
            </el-select>
          </template>
        </el-table-column> -->

        <el-table-column align="center" label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="deleteItem(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-footer">
      <div class="footer">
        <el-button type="primary" :loading="formLoading" @click="clickSubmitForm(1)">保 存</el-button>
        <el-button type="primary" :loading="formLoading" @click="clickSubmitForm(2)">提交审核</el-button>
        <el-popconfirm v-if="!isDealer" title="确定关闭吗？" style="margin-left: 10px" @onConfirm="goBack">
          <el-button slot="reference">返回列表</el-button>
        </el-popconfirm>
      </div>
    </div>

    <!-- 工程登录列表 -->
    <el-dialog
      title="工程登录列表"
      append-to-body
      :visible.sync="isShowDialog"
      width="70%"
      :close-on-click-modal="false"
    >
      <el-form
        v-if="mainForm.examineStatus !== 'SAVE'"
        ref="screenForm"
        :model="screenForm"
        label-width="0"
        size="small"
        label-position="left"
      >
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item prop="loginNum">
              <el-input v-model="screenForm.loginNum" placeholder="工程登录编号" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item prop="enginName">
              <el-input v-model="screenForm.enginName" placeholder="工程类别" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item prop="company">
              <el-input v-model="screenForm.company" placeholder="使用单位" />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :lg="6" class="tr">
            <el-form-item label="">
              <el-button size="small" @click="resetScreenForm">清空</el-button>
              <el-button size="small" type="primary" @click="submitScreenForm">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="table" style="margin: 10px 0 20px">
        <el-table
          v-loading="dialogTable_listLoading"
          :data="dialogTable_dataList"
          element-loading-text="Loading"
          tooltip-effect="dark"
          style="width: 100%"
          max-height="270"
        >
          <el-table-column align="center" label="" width="100">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small"
                @click="chooseItem(scope.row.recordNo, scope.row.userid)"
              >选择
              </el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="checkTime" label="工程登录日期" show-overflow-tooltip />
          <el-table-column align="center" prop="recordNo" label="工程登录编号" show-overflow-tooltip />
          <el-table-column align="center" prop="projectName" label="项目类别" show-overflow-tooltip />
          <el-table-column align="center" prop="useUnit" label="使用单位" show-overflow-tooltip />
          <el-table-column align="center" prop="organizationName" label="经销商" show-overflow-tooltip />
        </el-table>
      </div>
      <div class="pagination clearfix">
        <div class="fr">
          <el-pagination
            :current-page="dialogTable_currentPage"
            :page-size="dialogTable_pageSize"
            background
            layout="prev, pager, next"
            :total="dialogTable_listTotal"
            @current-change="dialogTableCurrentChange"
          />
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowDialog = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="添加产品" append-to-body :visible.sync="isShowGoodsDialog" width="80%">
      <el-form ref="goodsScreenForm" :model="goodsScreenForm" size="small" label-position="left">
        <el-row :gutter="20">
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="proNum">
              <el-input v-model="goodsScreenForm.proNum" placeholder="请输入物料编码" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="proName">
              <el-input v-model="goodsScreenForm.proName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="proModel">
              <el-input v-model="goodsScreenForm.proModel" placeholder="请输入产品型号" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="price1" style="display: flex">
              <el-input v-model="goodsScreenForm.price1" placeholder="请输入价格" style="width: 46%" />
              <span> - </span>
              <el-input v-model="goodsScreenForm.price2" placeholder="请输入价格" style="width: 46%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24" class="tr">
            <el-form-item label="">
              <el-button size="small" @click="resetGoodsScreenForm">清空</el-button>
              <el-button size="small" type="primary" @click="submitGoodsScreenForm">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="tables">
        <div class="table">
          <el-table
            :data="leftGoodsList"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            stripe
            height="400"
            @selection-change="leftSelectionChange"
          >
            <el-table-column align="center" type="selection" width="55" :selectable="checkboxSelect" />

            <el-table-column align="center" label="销售类型" prop="saleName" min-width="100" show-overflow-tooltip />
            <el-table-column align="center" label="物料编码" prop="number" min-width="100" show-overflow-tooltip />
            <el-table-column align="center" label="产品名称" prop="name" min-width="160" show-overflow-tooltip />
            <el-table-column
              align="center"
              label="产品型号"
              prop="specification"
              min-width="160"
              show-overflow-tooltip
            />
            <el-table-column align="center" label="产品价格" prop="batchPrice" min-width="80" show-overflow-tooltip />
          </el-table>
          <div class="pagination clearfix" style="margin-top: 10px">
            <div class="fr">
              <el-pagination
                :current-page="currentPage"
                :page-size="10"
                background
                layout="prev, pager, next"
                :total="listTotal"
                @current-change="handleTableCurrentChange"
              />
            </div>
          </div>
        </div>
        <div class="buttons">
          <el-button size="small" type="primary" @click="addAllGoods">全部添加</el-button>
          <el-button size="small" type="primary" @click="addGoods">添&emsp;加</el-button>
          <el-button size="small" type="danger" @click="deleteGoods">删&emsp;除</el-button>
          <el-button size="small" type="danger" @click="deleteAllGoods">全部删除</el-button>
        </div>
        <div class="table">
          <el-table
            :data="rightGoodsList"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            stripe
            height="400"
            @selection-change="rightSelectionChange"
          >
            <el-table-column align="center" type="selection" width="55" />
            <el-table-column align="center" label="物料编码" prop="number" min-width="100" show-overflow-tooltip />
            <el-table-column align="center" label="产品名称" prop="name" min-width="160" show-overflow-tooltip />
            <el-table-column
              align="center"
              label="产品型号"
              prop="specification"
              min-width="160"
              show-overflow-tooltip
            />
            <el-table-column align="center" label="产品价格" prop="batchPrice" min-width="80" show-overflow-tooltip />
          </el-table>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitAddGoods">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="添加产品" append-to-body :visible.sync="isSetMaterial" width="80%">
      <el-form ref="goodsScreenForm" :model="goodsScreenForm" size="small" label-position="left">
        <el-row :gutter="20">
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="proNum">
              <el-input v-model="goodsScreenForm.proNum" placeholder="请输入物料编码" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="proName">
              <el-input v-model="goodsScreenForm.proName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="proModel">
              <el-input v-model="goodsScreenForm.proModel" placeholder="请输入产品型号" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="price1" style="display: flex">
              <el-input v-model="goodsScreenForm.price1" placeholder="请输入价格" style="width: 46%" />
              <span> - </span>
              <el-input v-model="goodsScreenForm.price2" placeholder="请输入价格" style="width: 46%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24" class="tr">
            <el-form-item label="">
              <el-button size="small" @click="resetGoodsScreenForm">清空</el-button>
              <el-button size="small" type="primary" @click="submitGoodsScreenForm">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div>
        <el-table :data="leftGoodsList" element-loading-text="Loading" border fit stripe height="400">
          <el-table-column align="center" width="55">
            <template slot-scope="scope">
              <el-radio v-model="currentRadio" :label="scope.row.id">{{ '' }}</el-radio>
            </template>
          </el-table-column>
          <el-table-column align="center" label="销售类型" prop="saleName" min-width="100" show-overflow-tooltip />
          <el-table-column align="center" label="物料编码" prop="number" min-width="100" show-overflow-tooltip />
          <el-table-column
            align="center"
            label="产品编码"
            prop="materialOldNumber"
            min-width="100"
            show-overflow-tooltip
          />
          <el-table-column align="center" label="产品名称" prop="name" min-width="160" show-overflow-tooltip />
          <el-table-column align="center" label="产品型号" prop="specification" min-width="160" show-overflow-tooltip />
          <el-table-column align="center" label="产品价格" prop="batchPrice" min-width="80" show-overflow-tooltip />
        </el-table>
        <div class="pagination clearfix" style="margin-top: 10px">
          <div class="fr">
            <el-pagination
              :current-page="currentPage"
              :page-size="10"
              background
              layout="prev, pager, next"
              :total="listTotal"
              @current-change="handleTableCurrentChange"
            />
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitPushGoods">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getOrderDetail,
  getHomeLoginList,
  getHomeLoginDetail,
  getWarehouseList,
  addHome,
  editHome,
  submitHome,
  checkStock,
  getRetailProductList
} from '@/api/supply/engin'
import { getDictList, getHomeTypeList, getSalesmanList } from '@/api/common'
import { findElem } from '@/utils/util'

let that
export default {
  name: 'HomeForm',
  componentName: 'HomeForm',
  filters: {
    status1Filter(val) {
      const STOCK_ORDER_START = that.stockList.find(o => o.dictCode == 'STOCK_ORDER_START').dictValue
      const STOCK_ORDER_END = that.stockList.find(o => o.dictCode == 'STOCK_ORDER_END').dictValue
      const STOCK_ORDER_HAVE_START = that.stockList.find(o => o.dictCode == 'STOCK_ORDER_HAVE_START').dictValue
      const STOCK_ORDER_HAVE_END = that.stockList.find(o => o.dictCode == 'STOCK_ORDER_HAVE_END').dictValue
      const STOCK_ORDER_ALL_NUM = that.stockList.find(o => o.dictCode == 'STOCK_ORDER_ALL_NUM').dictValue
      if (val === '' || val === null || val === undefined) {
        return '未检查'
      } else if (val <= 0) {
        return '无货'
      } else if (val > STOCK_ORDER_START && val <= STOCK_ORDER_END) {
        return val
      } else if (val >= STOCK_ORDER_HAVE_START && val <= STOCK_ORDER_HAVE_END) {
        return '有货'
      } else if (val > STOCK_ORDER_ALL_NUM) return '充足'
    }
  },
  props: ['listItem'],
  data() {
    return {
      editId: '',
      mainForm: {
        customerId: '',
        orderNum: '',
        orderDate: '',
        type: '',
        jxsNum: '',
        jxsName: '',
        loginNum: '',
        enginName: '',
        loginType: '',
        promiseStatus: '',
        factoryNum: '',
        company: '',
        saleType: '',
        contactMan: '',
        tel: '',
        phone: '',
        address: '',
        declareNo: '',
        greeRemark: '',
        greeReply: '',
        remark: '',
        createMan: '',
        createDate: '',
        fileNum: '',
        loginUserId: '',
        salesMan: '',
        projectRemark: '',
        projectType: '',
        examineRemark: '',
        refCount: '',
        regionWork: '',
        examineStatus: '',
        refBuyUnitName: '',
        refPromiseProvide: '',
        refOtherAnnexIdea: '',
        refToRetailIdea: '',
        refContractIdea: '',
        refDataDelayIdea: '',
        refProjectNo: '',
        isPlanOrder: this.listItem ? '' : true
      },
      mainFormRules: {
        // orderDate: [{ required: true, message: '请选择单据日期', trigger: 'change' }],
        jxsNum: [{ required: true, message: '请输入经销商编码', trigger: 'blur' }],
        jxsName: [{ required: true, message: '请输入经销商名称', trigger: 'blur' }],
        loginNum: [{ required: true, message: '请输入工程登录编号', trigger: 'blur' }],
        // enginName: [{ required: true, message: '请输入项目类别', trigger: 'blur' }],
        // loginType: [{ required: true, message: '请输入行业类别', trigger: 'blur' }],
        company: [{ required: true, message: '请输入使用单位', trigger: 'blur' }],
        saleType: [{ required: true, message: '请选择销售类型', trigger: 'change' }],
        // contactMan: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
        // tel: [{ required: true, message: '请输入固定电话', trigger: 'blur' }],
        // phone: [{ required: true, message: '请输入移动电话', trigger: 'blur' }],
        address: [{ required: true, message: '请输入安装地址', trigger: 'blur' }]
      },
      salesTypeList: [],
      // typeList: [],
      stockList: [],
      goodsList: [],
      correspondName: '',
      correspondId: '',
      isShowDialog: false, // 工程登录列表 - 弹窗
      screenForm: {
        loginNum: '',
        enginName: '',
        company: ''
      },
      dialogTable_dataList: null, // 工程登录列表 - 列表数据
      dialogTable_listLoading: true, // 工程登录列表 - 列表加载loading
      dialogTable_currentPage: 1, // 工程登录列表 - 当前页码
      dialogTable_pageSize: 10, // 工程登录列表 - 每页数量
      dialogTable_listTotal: 0, // 工程登录列表 - 列表总数

      warehouseList: [],
      warehouseValue: '',

      isShowGoodsDialog: false,
      goodsScreenForm: {
        proNum: '',
        proName: '',
        proModel: '',
        price1: '',
        price2: ''
      },
      currentPage: 1,
      listTotal: 0,

      leftGoodsList: [],
      rightGoodsList: [],

      leftSelection: [],
      rightSelection: [],

      formLoading: false,

      isFirst: false,
      salesmanList: [],
      oldSaleType: '',
      notInRefQueryGoodsList: '',
      isSetMaterial: false,
      currentId: '',
      currentRadio: ''
    }
  },

  computed: {
    isDealer() {
      return JSON.parse(localStorage.getItem('supply_user')).isCustomer
    },

    outSalesmanList() {
      const list = []
      if (this.goodsList && this.goodsList.length) {
        this.goodsList.forEach(item => {
          if (item.serviceId) {
            const hasItem = findElem(list, 'adminUserId', item.serviceId)
            if (hasItem < 0) {
              const obj = this.salesmanList.find(o => o.adminUserId == item.serviceId)
              if (obj) {
                list.push(obj)
              }
            }
          }
        })
        if (this.isFirst) {
          this.isFirst = false
        } else {
          this.mainForm.salesMan = this.goodsList[0].serviceId
        }
      }
      return list
    }
  },

  watch: {
    goodsList: {
      handler(newValue, oldValue) {
        if (newValue && newValue.length) {
          newValue.forEach((item, index) => {
            if (this.correspondId) {
              this.goodsList[index].correspondName = this.correspondName
              this.goodsList[index].correspondId = this.correspondId
            }
            this.goodsList[index].compute_sfAmount =
              (item.price * item.qty * 100 -
                ((item.price * item.qty * (item.rebateRate * 100)) / 100) * 100 -
                ((item.qty * (item.discAmount * 100)) / 100) * 100) /
              100
            this.goodsList[index].compute_flAmount = (item.price * item.qty * (item.rebateRate * 100)) / 100
            this.goodsList[index].ko = item.qty * item.discAmount
            this.goodsList[index].dida = item.price * item.qty
          })
          newValue.forEach(item => {
            // 'enginNum', 'directTransferQty', 'hasSendQty', 'retiredQty', 'ko'
            // 'price', 'compute_flAmount', 'compute_sfAmount'
            item.sums1 = ['qty']
            item.sums2 = ['dida']
          })
        }

        if (this.goodsList && this.goodsList.length) {
          if (this.isFirst) {
            this.isFirst = false
          } else {
            // this.mainForm.salesMan = this.goodsList[0].serviceId;
          }
        } else {
          this.mainForm.salesMan = ''
        }
      },
      immediate: true,
      deep: true
    },
    'mainForm.saleType': function(newValue, oldValue) {
      this.oldSaleType = oldValue
    }
  },

  beforeCreate() {
    that = this
  },

  async created() {
    await this.getSalesmanList()
    this.getDictList()
    this.getHomeTypeList()
    this.getWarehouseList()

    if (this.listItem) {
      this.isFirst = true
      this.editId = this.listItem.parentId
      this.getDetail()
    } else {
      this.mainForm.jxsNum = JSON.parse(localStorage.getItem('supply_user')).customerNumber
      this.mainForm.jxsName = JSON.parse(localStorage.getItem('supply_user')).customerName
      this.mainForm.createMan = JSON.parse(localStorage.getItem('supply_user')).nickName
      this.mainForm.createDate = this.getDate()
    }
  },

  methods: {
    // 返回列表
    goBack() {
      this.$emit('backListFormDetail')
    },

    getDate() {
      var date = new Date()
      var seperator1 = '-'
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var strDate = date.getDate()
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate
      return currentdate
    },

    // 获取产品大类列表
    getDictList() {
      // getDictList({sysDictEnum: 'PRODUCT_TYPE'}).then(res => {
      //   this.typeList = res.data;
      // })
      getDictList({ sysDictEnum: 'STOCK_ORDER' }).then(res => {
        this.stockList = res.data
      })
    },

    // 获取家用销售类型列表
    getHomeTypeList() {
      getHomeTypeList().then(res => {
        this.salesTypeList = res.data
        console.log(res.data)
      })
    },

    // 获取仓库列表
    getWarehouseList() {
      getWarehouseList({
        pageNum: 1,
        pageSize: -1
      }).then(res => {
        this.warehouseList = res.data.records
      })
    },

    async getSalesmanList() {
      const res = await getSalesmanList({
        pageNum: 1,
        pageSize: -1,
        isCustomer: 0,
        status: true
      })
      this.salesmanList = res.data.records
    },

    // 工程登录列表 - 获取列表
    getHomeLoginList() {
      getHomeLoginList({
        pageNum: this.dialogTable_currentPage,
        pageSize: this.dialogTable_pageSize,
        recordNo: this.screenForm.loginNum,
        projectName: this.screenForm.enginName,
        useUnit: this.screenForm.company,
        refEnginRecordNo: this.mainForm.loginNum,
        examineStatus: 'OK'
      }).then(res => {
        this.dialogTable_dataList = res.data.records
        this.dialogTable_listTotal = res.data.total
        this.dialogTable_listLoading = false
      })
    },

    // 工程登录列表 - 打开弹窗
    openShareDetail() {
      if (!this.mainForm.saleType) {
        return this.$errorMsg('请先选择销售类型')
      }
      this.isShowDialog = true
      this.dialogTable_currentPage = 1
      this.screenForm.loginNum = this.mainForm.loginNum
      this.getHomeLoginList()
    },

    // 工程登录列表 - 更改列表当前页
    dialogTableCurrentChange(val) {
      this.dialogTable_currentPage = val
      this.getHomeLoginList()
    },

    // 提交筛选表单
    submitScreenForm() {
      this.dialogTable_currentPage = 1
      this.getHomeLoginList()
    },

    // 重置筛选表单
    resetScreenForm() {
      this.$refs.screenForm.resetFields()
      this.dialogTable_currentPage = 1
      this.getHomeLoginList()
    },

    // 选择工程登录
    async chooseItem(id, uid, isChangeSaleType = false) {
      const isCustomer = JSON.parse(localStorage.getItem('supply_user')).isCustomer
      let customerId = JSON.parse(localStorage.getItem('supply_user')).customerId
      if (!isCustomer) {
        customerId = this.mainForm.customerId
      }
      getHomeLoginDetail({
        recordNo: id,
        saleTypeId: this.mainForm.saleType,
        userId: uid,
        enginOrderId: this.mainForm.orderNum,
        customerId: customerId,
        refEnginRecordNo: this.mainForm.loginNum
      })
        .then(async res => {
          // 复制当前明细数据
          const copyGoodsList = JSON.parse(JSON.stringify(this.goodsList))
          console.log('未刷新前', copyGoodsList)
          if (!isChangeSaleType) {
            this.setMainAndItem(res.data)
          } else {
            // 找出不属于引用单上的产品
            if (copyGoodsList && copyGoodsList.length > 0) {
              const notInRefGoodsList = []

              for (let i = 0; i < copyGoodsList.length; i++) {
                const goods = copyGoodsList[i]
                const index = res.data.items.findIndex(v => v.materialOldNumber === goods.materialOldNumber)
                if (index < 0) {
                  notInRefGoodsList.push(goods)
                }
              }

              if (notInRefGoodsList && notInRefGoodsList.length > 0) {
                const oldNumbers = []
                notInRefGoodsList.forEach(v => oldNumbers.push(v.materialOldNumber))
                console.log('请求前可选机型接口', notInRefGoodsList, oldNumbers)
                // 请求可选机型接口
                await this.querySaleTypeGoods(oldNumbers)
                console.log('返回新加明细', this.notInRefQueryGoodsList)
                if (!this.notInRefQueryGoodsList) {
                  console.log('结束执行下去')
                  return
                }
                this.addRefItems(res.data.items, notInRefGoodsList)
              }
              // 数量和价格不变更
              console.log('执行下去，数量和价格不变更')
            }
            console.log('替换前', res.data.items)
            res.data.items = this.replaceHistoryItems(res.data.items, copyGoodsList)
            console.log('替换后', res.data.items)
            this.setMainAndItem(res.data)
          }
        })
        .catch(() => {
          this.mainForm.saleType = this.oldSaleType
        })
    },

    // 选择销售类型
    changeSaleType() {
      if (this.mainForm.loginNum) {
        this.chooseItem(this.mainForm.loginNum, this.mainForm.loginUserId, true)
      }
    },

    // 删除产品
    deleteItem(index) {
      this.goodsList.splice(index, 1)
    },

    // 修改返利钱包
    changeFlWallet(index) {
      if (this.goodsList[index].customerWalletId2) {
        const obj = this.goodsList[index].rebateWallets.find(
          o => o.customerWalletId == this.goodsList[index].customerWalletId2
        )
        this.goodsList[index].rebateRate = obj.rebateRate
        this.goodsList[index].customerWalletName2 = obj.customerWalletName
      } else {
        this.goodsList[index].rebateRate = ''
        this.goodsList[index].customerWalletName2 = ''
      }
    },

    // 修改现金钱包
    changeXjWallet(index) {
      if (this.goodsList[index].customerWalletId) {
        const obj = this.goodsList[index].wallets.find(
          o => o.customerWalletId == this.goodsList[index].customerWalletId
        )
        this.goodsList[index].customerWalletName = obj.customerWalletName
        this.goodsList[index].serviceId = obj.serviceId
        this.goodsList[index].serviceName = obj.serviceName
      } else {
        this.goodsList[index].customerWalletName = ''
        this.goodsList[index].serviceId = ''
        this.goodsList[index].serviceName = ''
      }
    },
    handleWarehouseValue(e) {
      this.correspondName = this.warehouseList.find(k => {
        return k.id === e
      }).name
      this.correspondId = e
      if (!this.goodsList.length) return

      this.goodsList.forEach(k => {
        this.$set(k, 'correspondName', this.correspondName)
        this.$set(k, 'correspondId', this.correspondId)
      })
      console.log(this.goodsList)
    },
    // 获取详情
    getDetail() {
      getOrderDetail({ id: this.editId }).then(res => {
        const data = res.data
        this.mainForm.customerId = data.customerId
        this.mainForm.orderNum = data.enginOrderId
        this.mainForm.orderDate = data.orderDate
        this.mainForm.type = data.mainId
        this.mainForm.jxsNum = data.customerNumber
        this.mainForm.jxsName = data.customerName
        this.mainForm.loginNum = data.refEnginRecordNo
        this.mainForm.enginName = data.refProjectCategory
        this.mainForm.loginType = data.refTradeCategory
        this.mainForm.promiseStatus = data.refPromiseStatus
        this.mainForm.factoryNum = data.refFactoryNo
        this.mainForm.company = data.refUseUnit
        this.mainForm.saleType = data.saleTypeId
        this.mainForm.contactMan = data.refLinkman
        this.mainForm.tel = data.refTel
        this.mainForm.phone = data.refPhone
        this.mainForm.address = data.refInstallAddress
        this.mainForm.declareNo = data.refDeclareNo
        this.mainForm.refCount = data.refCount
        this.mainForm.greeRemark = data.geLiInerNote
        this.mainForm.greeReply = data.note1
        this.mainForm.remark = data.remark
        this.mainForm.createMan = data.createName
        this.mainForm.createDate = data.createTime
        this.mainForm.fileNum = data.fileNo
        this.mainForm.salesMan = data.serviceId
        this.mainForm.projectRemark = data.refProjectNote
        this.mainForm.projectType = data.refProjectType
        this.mainForm.examineRemark = data.examineNote
        this.mainForm.loginUserId = data.loginUserId
        this.mainForm.regionWork = data.refRegionWork
        this.mainForm.examineStatus = data.examineStatus
        this.mainForm.refBuyUnitName = data.refBuyUnitName
        this.mainForm.refPromiseProvide = data.refPromiseProvide
        this.mainForm.refProjectNo = data.refProjectNo
        this.mainForm.refToRetailIdea = data.refToRetailIdea
        this.mainForm.refContractIdea = data.refContractIdea
        this.mainForm.refDataDelayIdea = data.refDataDelayIdea
        this.mainForm.refBillsExpireDate = data.refBillsExpireDate
        this.mainForm.refBuyUnitCallMen = data.refBuyUnitCallMen
        this.correspondName = data.correspondName
        this.warehouseValue = data.correspondId
        this.mainForm.isPlanOrder = data.isPlanOrder
        data.items.forEach(item => {
          item.correspondName = data.correspondName
          item.warehouseValue = data.correspondId
          item.status1 = ''
          item.status2 = ''
          item.rebateWallets = item.customerWalletList.filter(item => {
            return item.type === 'REBATE'
          })
          item.wallets = item.customerWalletList.filter(item => {
            return item.type === 'COMMONLY'
          })
        })
        this.goodsList = data.items
      })
    },

    // 获取商品列表
    getGoodsList() {
      getRetailProductList({
        pageNum: this.currentPage,
        pageSize: 10,
        saleId: this.mainForm.saleType,
        billType: 'HOME',
        materialCode: this.goodsScreenForm.proNum,
        materialName: this.goodsScreenForm.proName,
        specification: this.goodsScreenForm.proModel,
        price1: this.goodsScreenForm.price1,
        price2: this.goodsScreenForm.price2,
        refEnginRecordNo: this.mainForm.loginNum,
        customerId: this.listItem ? this.listItem.customerId : ''
      }).then(res => {
        const oldGoodsList = this.goodsList
        const newGoodsList = res.data.records
        for (let i = 0; i < oldGoodsList.length; i++) {
          const oldItem = oldGoodsList[i]
          for (let j = 0; j < newGoodsList.length; j++) {
            const newItem = newGoodsList[j]
            if (newItem.id === oldItem.id) {
              newGoodsList[j].selected = true
              break
            }
          }
        }
        res.data.records.forEach(item => {
          item.materialName = item.name
          item.materialCode = item.number
          item.saleTypeName = item.saleName
          item.unit = item.baseUnit
          item.enginNum = 0
          item.qty = 0
          item.price = item.batchPrice
          item.tax = item.taxRate
          item.isDirectTransfer = false
          item.directTransferQty = ''
          item.status1 = ''
          item.status2 = ''
          item.rebateAmount = ''
          item.rebateRate = ''
          item.productPriceId = item.id
          item.customerWalletId = item.wallets && item.wallets.length ? item.wallets[0].customerWalletId : ''
        })
        this.leftGoodsList = res.data.records
        this.listTotal = res.data.total
      })
    },

    // 查询重复值并禁选
    checkboxSelect(row, rowIndex) {
      if (row.selected) {
        return false // 禁用
      } else {
        return true // 不禁用
      }
    },

    // 点击 选择商品
    openDialog() {
      if (!this.mainForm.saleType) {
        return this.$errorMsg('请先选择销售类型')
      }
      this.isShowGoodsDialog = true
      this.getGoodsList()
    },

    // 提交筛选表单
    submitGoodsScreenForm() {
      this.currentPage = 1
      this.getGoodsList()
    },

    // 重置筛选表单
    resetGoodsScreenForm() {
      this.$refs.goodsScreenForm.resetFields()
      this.currentRadio = ''
      this.currentPage = 1
      this.getGoodsList()
    },

    // 更改列表当前页
    handleTableCurrentChange(val) {
      this.currentPage = val
      this.getGoodsList()
    },

    // 关闭 弹窗
    closeDialog() {
      this.isShowGoodsDialog = false
      this.isSetMaterial = false
    },

    // 左侧列表选择
    leftSelectionChange(val) {
      this.leftSelection = val
    },

    // 右侧列表选择
    rightSelectionChange(val) {
      this.rightSelection = val
    },

    // 数组去重
    delRepeat(arr1, arr2) {
      const allArr = arr1.concat(arr2) // 两个数组对象合并
      const newArr = [] // 存放去重后数据的新数组
      for (let i = 0; i < allArr.length; i++) {
        // 循环allArr数组对象的内容
        let flag = true // 建立标记，判断数据是否重复，true为不重复
        for (let j = 0; j < newArr.length; j++) {
          // 循环新数组的内容
          if (allArr[i].id == newArr[j].id) {
            // 让allArr数组对象的内容与新数组的内容作比较，相同的话，改变标记为false
            flag = false
          }
        }
        if (flag) {
          // 判断是否重复
          newArr.push(allArr[i]) // 不重复的放入新数组。  新数组的内容会继续进行上边的循环。
        }
      }
      return newArr
    },

    // 全部添加
    addAllGoods() {
      this.rightGoodsList = this.delRepeat(this.leftGoodsList, this.rightGoodsList)
    },

    // 添加
    addGoods() {
      this.rightGoodsList = this.delRepeat(this.leftSelection, this.rightGoodsList)
    },

    // 删除
    deleteGoods() {
      const rightGoodsList = this.rightGoodsList
      const rightSelection = this.rightSelection
      for (let i = 0; i < rightGoodsList.length; i++) {
        for (let j = 0; j < rightSelection.length; j++) {
          if (rightSelection[j].materialId == rightGoodsList[i].materialId) {
            this.rightGoodsList.splice(i, 1)
          }
        }
      }
    },

    // 全部删除
    deleteAllGoods() {
      this.rightGoodsList = []
    },

    // 确定 添加产品
    submitAddGoods() {
      // this.goodsList = this.delRepeat(this.rightGoodsList, this.goodsList);

      this.goodsList = this.goodsList.concat(this.rightGoodsList)
      this.goodsList.forEach((k, i) => {
        this.$set(this.goodsList[i], 'realMaterialId', k.materialId)
        this.$set(this.goodsList[i], 'realMaterialName', k.materialName)
        this.$set(this.goodsList[i], 'realMaterialNumber', k.materialNumber)
        this.$set(this.goodsList[i], 'realMaterialOldNumber', k.materialOldNumber)
        this.$set(this.goodsList[i], 'realSpecification', k.specification)
        if (!this.listItem) {
          const str = `实装物料编号:${k.materialNumber}实装厂产品编码:${k.materialOldNumber}`
          let remark
          if (!this.goodsList[i].remark) {
            remark = str
          } else {
            remark = this.goodsList[i].remark.replace(/str/g, str)
          }
          this.$set(this.goodsList[i], 'remark', remark)
        }
      })
      this.isShowGoodsDialog = false
      this.leftGoodsList = []
      this.rightGoodsList = []
    },
    getRealMaterData(id) {
      this.currentId = id
      this.isSetMaterial = true
      this.getGoodsList()
    },
    submitPushGoods() {
      //    realMaterialId
      // 实装金蝶物料id
      //        realMaterialName
      // 实装金蝶物料名称
      //        realMaterialNumber
      // 实装金蝶物料编码
      //        realMaterialOldNumber
      // 实装金蝶物料旧编码
      //        realSpecification
      // 实装规格型号
      const currentData = this.leftGoodsList.find(e => e.id === this.currentRadio)
      this.$set(this.goodsList[this.currentId], 'realMaterialId', currentData.materialId)
      this.$set(this.goodsList[this.currentId], 'realMaterialName', currentData.materialName)
      this.$set(this.goodsList[this.currentId], 'realMaterialNumber', currentData.materialNumber)
      this.$set(this.goodsList[this.currentId], 'realMaterialOldNumber', currentData.materialOldNumber)
      this.$set(this.goodsList[this.currentId], 'realSpecification', currentData.specification)
      if (!this.listItem) {
        const str = `实装物料编号:${currentData.materialNumber}实装厂产品编码:${currentData.materialOldNumber}`
        let remark
        if (!this.goodsList[this.currentId].remark) {
          remark = str
        } else {
          remark = this.goodsList[this.currentId].remark.replace(/str/g, str)
        }
        this.$set(this.goodsList[this.currentId], 'remark', remark)
      }
      this.isSetMaterial = false
    },
    // 检查库存
    checkStock() {
      if (!this.warehouseValue) {
        return this.$errorMsg('请选择仓库')
      }
      if (!this.goodsList) {
        return this.$errorMsg('请添加货品')
      }
      const ids = []
      this.goodsList.forEach(item => {
        ids.push(item.materialId)
      })
      checkStock({
        correspondId: this.warehouseValue,
        materialId: ids.join(',')
      }).then(res => {
        if (res.data) {
          this.goodsList.forEach((item, index) => {
            item.status1 = res.data[index].allStockNum
            item.status2 = res.data[index].stockNum
          })
        }
      })
    },

    status2Filter(item) {
      if (item.status2 === '' || item.status2 === null || item.status2 === undefined) {
        return '未检查'
      } else if (item.status2 <= 0) return '无货'
      if (item.status2 <= 0) {
        return '无货'
      } else if (item.status2 >= 1 && item.status2 <= 30) {
        return item.status2
      } else if (item.status2 >= 31 && item.status2 <= 1000) {
        return '有货'
      } else {
        return '充足'
      }
    },

    // 保存 / 提交审核
    clickSubmitForm(type) {
      this.$refs.mainForm.validate(valid => {
        if (valid) {
          for (let i = 0; i < this.goodsList.length; i++) {
            if (!this.goodsList[i].customerWalletId) {
              this.$errorMsg('请选择现金钱包')
              return
            }

            if (!Number(this.goodsList[i].qty)) {
              this.$errorMsg('不允许数量为0')
              return
            }
          }
          // if (!this.mainForm.isPlanOrder && !this.correspondId) {
          //   this.$errorMsg(`仓库必选`)
          //   return
          // }
          const goodsList = JSON.parse(JSON.stringify(this.goodsList))

          goodsList.forEach(item => {
            delete item.rebateWallets
            delete item.wallets
          })

          const saleTypeItem = this.salesTypeList.find(o => o.id == this.mainForm.saleType)
          const saleManItem = this.mainForm.salesMan
            ? this.salesmanList.find(o => o.adminUserId == this.mainForm.salesMan)
            : ''
          const params = {
            isPlanOrder: this.mainForm.isPlanOrder,
            correspondName: this.correspondName,
            correspondId: this.correspondId,
            enginOrderId: this.mainForm.orderNum,
            loginUserId: this.mainForm.loginUserId,
            refEnginRecordNo: this.mainForm.loginNum || '',
            refProjectCategory: this.mainForm.enginName || '',
            refTradeCategory: this.mainForm.loginType || '',
            refPromiseStatus: this.mainForm.promiseStatus || '',
            refUseUnit: this.mainForm.company || '',
            refLinkman: this.mainForm.contactMan || '',
            refTel: this.mainForm.tel || '',
            refPhone: this.mainForm.phone || '',
            refInstallAddress: this.mainForm.address || '',
            refDeclareNo: this.mainForm.declareNo || '',
            refCount: this.mainForm.refCount || '',
            saleTypeId: this.mainForm.saleType,
            saleTypeCode: saleTypeItem.saleCode,
            saleTypeName: saleTypeItem.saleName,
            geLiInerNote: this.mainForm.greeRemark || '',
            geLiNote: this.mainForm.greeReply || '',
            remark: this.mainForm.remark || '',
            fileNo: this.mainForm.fileNum || '',
            serviceId: this.mainForm.salesMan,
            serviceName: saleManItem ? saleManItem.nickName : goodsList[0].serviceName,
            refProjectNote: this.mainForm.projectRemark,
            refProjectType: this.mainForm.projectType,
            refRegionWork: this.mainForm.regionWork,
            refPromiseProvide: this.mainForm.refPromiseProvide,
            refOtherAnnexIdea: this.mainForm.refOtherAnnexIdea,
            refProjectNo: this.mainForm.refProjectNo,
            contactMan: this.mainForm.contactMan,
            tel: this.mainForm.tel,
            refToRetailIdea: this.mainForm.refToRetailIdea,
            refContractIdea: this.mainForm.refContractIdea,
            refDataDelayIdea: this.mainForm.refDataDelayIdea,
            refToRetailResult: this.mainForm.refToRetailResult,
            refToRetailldea: this.mainForm.refToRetailldea,
            refDataDelayResult: this.mainForm.refDataDelayResult,
            refDataDelayldea: this.mainForm.refDataDelayldea,
            refOtherAnnexResult: this.mainForm.refOtherAnnexResult,
            refOtherAnnexldea: this.mainForm.refOtherAnnexldea,
            refBuyUnitPhone: this.mainForm.refBuyUnitPhone,
            refBuyUnitName: this.mainForm.refBuyUnitName,
            refBuyUnitTel: this.mainForm.refBuyUnitTel,
            refFactoryNo: this.mainForm.refFactoryNo,
            refBillsExpireDate: this.mainForm.refBillsExpireDate,
            refContractResult: this.mainForm.refContractResult,
            refContractldea: this.mainForm.refContractldea,
            refBuyUnitCallMen: this.mainForm.refBuyUnitCallMen,
            // refToRetailResult: this.mainForm.refToRetailResult,
            // refToRetailldea: this.mainForm.refToRetailldea,
            // refDataDelayResult: this.mainForm.refDataDelayResult,
            // refDataDelayldea: this.mainForm.refDataDelayldea,
            // refOtherAnnexResult: this.mainForm.refOtherAnnexResult,
            // refOtherAnnexldea: this.mainForm.refOtherAnnexldea,
            // refBuyUnitPhone: this.mainForm.refBuyUnitPhone,
            // refBuyUnitName: this.mainForm.refBuyUnitName,
            // refBuyUnitTel: this.mainForm.refBuyUnitTel,
            // refFactoryNo: this.mainForm.refFactoryNo,
            // refBillsExpireDate: this.mainForm.refBillsExpireDate,
            items: goodsList
          }
          if (this.mainForm.examineStatus === 'WAIT') {
            params.takeDeposit = false
          }

          this.formLoading = true
          if (type === 1) {
            if (this.listItem) {
              editHome(params)
                .then(res => {
                  this.$successMsg('编辑成功')
                  this.goBack()
                })
                .finally(res => {
                  this.formLoading = false
                })
            } else {
              addHome(params)
                .then(res => {
                  this.$successMsg('新增成功')
                  this.goBack()
                })
                .finally(res => {
                  this.formLoading = false
                })
            }
          } else if (type === 2) {
            submitHome(params)
              .then(res => {
                this.$successMsg('提交审核成功')
                this.goBack()
              })
              .finally(res => {
                this.formLoading = false
              })
          }
        }
      })
    },

    setMainAndItem(data) {
      this.isShowDialog = false
      this.mainForm.type = data.productCategory
      this.mainForm.loginUserId = data.userid
      // this.mainForm.saleType = '';
      this.mainForm.loginNum = data.recordNo
      this.mainForm.enginName = data.projectName
      this.mainForm.loginType = data.tradeCategory
      this.mainForm.factoryNum = data.factoryNo
      this.mainForm.promiseStatus = data.promiseStatus
      this.mainForm.company = data.useUnit
      this.mainForm.contactMan = data.buyUnitCallMen
      this.mainForm.tel = data.buyUnitTel
      this.mainForm.phone = data.buyUnitPhone
      this.mainForm.address = data.installAddress
      this.mainForm.declareNo = data.declareNo
      this.mainForm.projectRemark = data.buChonShuoMing
      this.mainForm.projectType = data.govBuyType
      this.mainForm.refCount = data.refCount
      this.mainForm.regionWork = data.regionWork
      this.mainForm.refBuyUnitName = data.buyUnitName
      this.mainForm.refPromiseProvide = data.promiseProvide === 1 ? '已保证' : '未保证'
      this.mainForm.refOtherAnnexIdea = data.otherAnnexIdea
      this.mainForm.refProjectNo = data.projectNo
      this.mainForm.refToRetailIdea = data.toRetailIdea
      this.mainForm.refContractIdea = data.contractIdea
      this.mainForm.refDataDelayIdea = data.dataDelayIdea
      this.mainForm.refContractResult = data.contractResult
      this.mainForm.refContractldea = data.contractldea
      this.mainForm.refToRetailResult = data.toRetailResult
      this.mainForm.refToRetailldea = data.toRetailldea
      this.mainForm.refDataDelayResult = data.dataDelayResult
      this.mainForm.refDataDelayldea = data.dataDelayldea
      this.mainForm.refOtherAnnexResult = data.otherAnnexResult
      this.mainForm.refOtherAnnexldea = data.otherAnnexldea
      this.mainForm.refBuyUnitPhone = data.buyUnitPhone
      this.mainForm.refBuyUnitName = data.buyUnitName
      this.mainForm.refBuyUnitTel = data.buyUnitTel
      this.mainForm.refFactoryNo = data.factoryNo
      this.mainForm.refBillsExpireDate = data.billsExpireDate
      this.mainForm.refBuyUnitCallMen = data.buyUnitCallMen
      const saleTypeItem = this.salesTypeList.find(o => o.id === this.mainForm.saleType)

      this.goodsList = data.items.map(item => {
        return {
          useRefCount: item.useRefCount,
          saleTypeId: saleTypeItem.id,
          saleTypeCode: saleTypeItem.saleCode,
          saleTypeName: saleTypeItem.saleName,
          materialId: item.materialId,
          materialNumber: item.materialNumber,
          materialOldNumber: item.materialOldNumber,
          materialName: item.materialName,
          specification: item.machine,
          enginNum: item.num,
          enginPrice: item.price,
          enginTotality: item.totality,
          historyHasDeliverQty: item.hasDeliverQty,
          unit: item.unit,
          price: item.price,
          qty: item.num,
          customerWalletId2: '',
          rebateRate: '',
          discAmount: '',
          customerWalletId: '',
          isDirectTransfer: false,
          directTransferQty: '',
          hasSendQty: '',
          tdQty: 0,
          salesQty: 0,
          salesAmount: 0,
          remark: item.discri,
          tax: '',
          status1: '',
          status2: '',
          rebateWallets: item.customerWalletList.filter(item => {
            return item.type === 'REBATE'
          }),
          wallets: item.customerWalletList.filter(item => {
            return item.type === 'COMMONLY'
          })
        }
      })
      this.goodsList.forEach((k, i) => {
        this.$set(this.goodsList[i], 'realMaterialId', k.materialId)
        this.$set(this.goodsList[i], 'realMaterialName', k.materialName)
        this.$set(this.goodsList[i], 'realMaterialNumber', k.materialNumber)
        this.$set(this.goodsList[i], 'realMaterialOldNumber', k.materialOldNumber)
        this.$set(this.goodsList[i], 'realSpecification', k.specification)
        if (!this.listItem) {
          const str = `实装物料编号:${k.materialNumber}实装厂产品编码:${k.materialOldNumber}`
          let remark
          if (!this.goodsList[i].remark) {
            remark = str
          } else {
            remark = this.goodsList[i].remark.replace(/str/g, str)
          }
          this.$set(this.goodsList[i], 'remark', remark)
        }
      })
      this.goodsList.forEach(item => {
        item.customerWalletId = item.wallets && item.wallets.length ? item.wallets[0].customerWalletId : ''
        item.serviceId = item.wallets && item.wallets.length ? item.wallets[0].serviceId : ''
        item.serviceName = item.wallets && item.wallets.length ? item.wallets[0].serviceName : ''
      })
    },
    async querySaleTypeGoods(oldNumbers) {
      await getRetailProductList({
        pageNum: 1,
        pageSize: -1,
        saleId: this.mainForm.saleType,
        billType: 'HOME',
        oldNumbers: oldNumbers.join(','),
        customerId: this.mainForm.customerId
      }).then(res => {
        console.log('请求后可选机型接口', res.data.records)
        if (!res.data.records || res.data.records.length === 0) {
          this.mainForm.saleType = this.oldSaleType
          console.log(1)
          this.$errorMsg(oldNumbers.join(',') + ' 产品无此销售类型')
          this.notInRefQueryGoodsList = ''
          return
        }
        if (res.data.records.length < oldNumbers.length) {
          const notInOldNumbers = []
          for (let i = 0; i < oldNumbers.length; i++) {
            const oldNumber = oldNumbers[i]
            const index = res.data.records.findIndex(v => v.materialOldNumber === oldNumber)
            if (index < 0) {
              notInOldNumbers.push(oldNumber)
            }
          }
          this.mainForm.saleType = this.oldSaleType
          console.log(2)
          this.$errorMsg(notInOldNumbers.join(',') + ' 产品无此销售类型')
          this.notInRefQueryGoodsList = ''
          return
        }
        this.notInRefQueryGoodsList = res.data.records
      })
    },
    replaceHistoryItems(items, copyGoodsList) {
      if (items && copyGoodsList) {
        for (let i = 0; i < items.length; i++) {
          const index = copyGoodsList.findIndex(v => v.materialOldNumber === items[i].materialOldNumber)
          if (index >= 0) {
            items[i].price = copyGoodsList[index].price
            items[i].num = copyGoodsList[index].qty
            items[i].discri = copyGoodsList[index].remark
          }
        }
      }
      return items
    },
    addRefItems(items, notInRefGoodsList) {
      if (notInRefGoodsList && this.notInRefQueryGoodsList) {
        for (let i = 0; i < notInRefGoodsList.length; i++) {
          const index = this.notInRefQueryGoodsList.findIndex(
            v => v.materialOldNumber === notInRefGoodsList[i].materialOldNumber
          )
          if (index >= 0) {
            this.notInRefQueryGoodsList[index].batchPrice = notInRefGoodsList[i].price
            this.notInRefQueryGoodsList[index].qty = notInRefGoodsList[i].qty
            this.notInRefQueryGoodsList[index].remark = notInRefGoodsList[i].remark
          }
        }
        console.log('非引用单产品', this.notInRefQueryGoodsList)
        for (let i = 0; i < this.notInRefQueryGoodsList.length; i++) {
          const goods = this.notInRefQueryGoodsList[i]
          const customerWalletList = [].concat(goods.rebateWallets).concat(goods.wallets)

          items.push({
            saleTypeId: goods.saleTypeId,
            saleTypeCode: goods.saleTypeCode,
            saleTypeName: goods.saleTypeName,
            materialId: goods.materialId,
            materialNumber: goods.materialNumber,
            materialOldNumber: goods.materialOldNumber,
            materialName: goods.materialName,
            machine: goods.specification,
            num: goods.qty,
            batchPrice: goods.batchPrice,
            discri: goods.remark,
            customerWalletList: customerWalletList
          })
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .input .el-input__inner {
  color: blue;
}

.detail-container {
  width: 100%;
  height: 100%;
}

.main-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  height: 60px;
  border-bottom: 1px solid #dcdfe6;
  margin-bottom: 20px;

  .title {
    font-size: 16px;
    font-weight: 600;
    padding-left: 10px;
  }
}

.tables {
  display: flex;
  margin-top: 10px;

  .table {
    width: 45%;
  }

  .buttons {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 0 10px;

    button {
      margin: 0;
      margin-top: 10px;
    }
  }
}

::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}

::v-deep input[type='number'] {
  -moz-appearance: textfield;
}
</style>
