<template>
  <div class="borderless" v-loading="pageLoading">
    <div class="customer-head">
      <div class="customer-back">
        <!--        <i class="back-icon el-icon-arrow-left"></i><i style="font-style:normal">返回管理列表</i>-->
        <el-button type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left"
                   @click="backToList">返回列表
        </el-button>
      </div>
      <div class="add-customer-btn">
        <el-button
          v-if="detailData.seeDisabled"
          size="small"
          @click="editHandle"
          type="primary"
        >编 辑</el-button>
        <el-button
          class="el-button--small-yh"
          type="primary"
          size="small"
          :disabled="detailData.seeDisabled"
          v-if="form.deliveryStatus == '已到货'"
          :loading="saveLoading"
          @click="cancelArrival"
        >撤销到货</el-button>
        <el-button
          class="el-button--small-yh"
          type="primary"
          size="small"
          :disabled="detailData.seeDisabled || arrivalDisabled"
          v-if="form.deliveryStatus == '已发货'"
          :loading="saveLoading"
          @click="confirmArrival"
        >确认到货</el-button>
        <el-button
          class="el-button--small-yh"
          type="primary"
          @click="revokeOutGoods"
          size="small"
          v-if="form.deliveryStatus == '已发货'"
          :loading="saveLoading"
          :disabled="detailData.seeDisabled || arrivalDisabled"
        >撤销发货</el-button>
        <el-button
          class="el-button--small-yh"
          type="primary"
          @click="sendOutGoods"
          size="small"
          v-if="form.deliveryStatus == '录入'"
          :loading="saveLoading"
          :disabled="detailData.seeDisabled || !form.id || arrivalDisabled"
        >确认发货</el-button>
        <el-button
          class="el-button--small-yh"
          size="small"
          type="success" @click="copyOrder"
          :loading="saveLoading"
          :disabled="detailData.seeDisabled || !form.id || arrivalDisabled">
          复制单据
        </el-button>
        <el-button
          class="el-button--small-yh"
          type="primary"
          :disabled="disabled || detailData.seeDisabled || arrivalDisabled"
          @click="editCustomer(false)"
          :loading="saveLoading"
          size="small"
        >保 存
        </el-button>
      </div>
    </div>
    <div class="customer-main">
      <el-form :model="form" ref="form" label-width="130px" class="demo-ruleForm">
        <containerTitle title="基础资料"></containerTitle>
        <basic-container style="margin-bottom: 10px">
          <el-row>
            <el-col v-for="(item,index) in basicData.column" :key="index" :span="item.span?item.span:8">
              <el-form-item :label="item.label" :prop="item.prop" :rules="item.rules">
                <!--                <avue-input-tree v-if="item.prop === 'corpsTypeId'"  leaf-only multiple :props="{label:'title'}" v-model="form[item.prop]" placeholder="请选择内容" type="tree" :dic="dic"-->
                <!--                ></avue-input-tree>-->
                <el-date-picker v-if="item.type === 'datetime'" style="width: 100%;" v-model="form[item.prop]"
                                size="small" type="datetime" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss" :disabled="item.disabled || detailData.seeDisabled || arrivalDisabled || deliverDisabled"/>
                <el-date-picker v-else-if="item.type === 'date'" style="width: 100%;" v-model="form[item.prop]"
                                size="small" type="date" placeholder="选择日期"
                                :disabled="detailData.seeDisabled || arrivalDisabled || deliverDisabled"/>
                <crop-select
                  v-else-if="item.prop === 'corpId'"
                  v-model="form[item.prop]"
                  corpType="KH"
                  :disabled="detailData.seeDisabled || arrivalDisabled || deliverDisabled || form.srcOrderNo"
                  style="width: 100%"
                  @getCorpData="returnBack"
                ></crop-select>
                <crop-select
                  v-else-if="item.prop === 'salesCompany'"
                  v-model="form[item.prop]"
                  corpType="GS"
                  :disabled="detailData.seeDisabled || arrivalDisabled || deliverDisabled"
                  @getCorpData="getGSName"
                ></crop-select>
                <el-select v-else-if="item.prop === 'deliveryStatus'" v-model="form[item.prop]" placeholder="请选择" clearable filterable style="width: 100%" size="small" :disabled="item.disabled || detailData.seeDisabled || arrivalDisabled || deliverDisabled">
                  <el-option v-for="(item,index) in statusOption" :key="index" :label="item.dictValue" :value="item.dictValue" size="small"></el-option>
                </el-select>
                <el-select v-else-if="item.prop === 'warehouseType'" v-model="form[item.prop]" placeholder="请选择" clearable filterable style="width: 100%" size="small" :disabled="detailData.seeDisabled || arrivalDisabled || deliverDisabled">
                  <el-option v-for="(item,index) in warehouseTypeOption" :key="index" :label="item.dictValue" :value="item.dictValue"></el-option>
                </el-select>
                <warehouse-select v-else-if="item.prop === 'storageId'" v-model="form[item.prop]"
                                 :configuration="configurationWarehouse" style="width: 100%" :disabled="detailData.seeDisabled || arrivalDisabled || deliverDisabled"/>
                <el-select v-else-if="item.prop === 'chargeMember'"
                           v-model="form[item.prop]" placeholder="请选择"
                           filterable
                           size="small"
                           style="width: 100%;"
                           :disabled="detailData.seeDisabled">
                  <el-option v-for="(item,index) in userList" :key="index" :label="item.realName" :value="item.realName"></el-option>
                </el-select>
                <el-input
                  v-else-if="item.type == 'number'"
                  placeholder="请输入"
                  v-input-limit="2"
                  size="small"
                  :disabled="item.disabled || detailData.seeDisabled || arrivalDisabled || deliverDisabled"
                  v-model.trim="form[item.prop]"
                />
                <el-input type="textarea" v-else-if="item.type === 'textarea'" v-model.trim="form[item.prop]" size="small" autocomplete="off" :disabled="item.disabled || detailData.seeDisabled || arrivalDisabled"></el-input>
                <el-input type="age" v-else v-model.trim="form[item.prop]" size="small" autocomplete="off" :disabled="item.disabled || detailData.seeDisabled || arrivalDisabled || deliverDisabled"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </basic-container>
        <containerTitle title="商品信息"></containerTitle>
        <basic-container style="margin-bottom: 10px">
          <avue-crud
              :option="customerContact"
              v-model="contactsForm"
              :data="goodsShowData"
              ref="crudContact"
              @row-save="rowSave"
              @row-click="handleRowClick"
              @row-update="rowUpdate"
              @row-del="rowDel"
              @saveColumn="saveColumn('goods')"
              @resetColumn="resetColumn"
              :cell-style="goodsRowClassName"
          >
            <template slot="code" slot-scope="{row,index}">
<!--              <el-button type="text" size="mini" style="padding:4px 10px;float:left" @click="commodityChoice(row)" :disabled="detailData.seeDisabled || !row.$cellEdit || arrivalDisabled || deliverDisabled">选择</el-button>-->
              <span>{{ row.code }}</span>
            </template>
            <template slot-scope="{row,index}" slot="menu">
              <el-button
                  type="text"
                  size="small"
                  @click="rowCell(row,index)"
                  :disabled="detailData.seeDisabled || arrivalDisabled"
              >{{ row.$cellEdit ? '保存' : '修改' }}
              </el-button>
              <el-button
                size="small"
                icon="el-icon-delete"
                type="text"
                @click="rowDel(row, index)"
                :disabled="detailData.seeDisabled || arrivalDisabled || deliverDisabled"
                v-if="!row.$cellEdit"
              >删 除</el-button>
            </template>
            <template slot="menuLeft" slot-scope="{size}">
              <el-tabs v-model="goodsActives" @tab-click="handleClick">
                <el-tab-pane label="商品" name="goods" :key="'first'" :disabled="goodsDisabled">
                </el-tab-pane>
                <el-tab-pane label="赠品" name="gift" :key="'second'" :disabled="goodsDisabled">
                </el-tab-pane>
              </el-tabs>
              <el-button type="primary"
                         icon="el-icon-plus"
                         size="small"
                         @click="marketDialog = true"
                         :disabled="detailData.seeDisabled || arrivalDisabled || deliverDisabled"
                         v-if="goodsActives == 'goods'"
              >录入明细
              </el-button>
              <el-button type="primary"
                         icon="el-icon-plus"
                         size="small"
                         @click="commoditySelection"
                         :disabled="detailData.seeDisabled || arrivalDisabled || deliverDisabled"
                         v-if="goodsActives == 'gift'"
              >录入明细
              </el-button>
              <el-button type="info" :size="size" icon="el-icon-printer" @click.stop="openReport()">报 表</el-button>
              <el-button
                type="warning"
                icon="el-icon-refresh"
                size="small"
                @click="resetStock"
              >库存刷新</el-button>
            </template>
            <template slot="actualQuantity" slot-scope="{ row }">
              <el-input
                v-if="row.$cellEdit"
                v-model.trim="row.actualQuantity"
                v-input-limit="0"
                @change="actualQuantityChange(row)"
                :disabled="detailData.seeDisabled || arrivalDisabled || deliverDisabled"
              ></el-input>
              <span v-else>{{ row.actualQuantity | IntegerFormat }}</span>
            </template>
<!--            到货数量-->
            <template slot="arrivalQuantity" slot-scope="{ row }">
              <el-input
                v-if="row.$cellEdit"
                v-model.trim="row.arrivalQuantity"
                v-input-limit="0"
                @input="arrivalQuantityChange(row)"
              ></el-input>
              <span v-else>{{ row.arrivalQuantity | IntegerFormat }}</span>
            </template>
            <template slot="corpId" slot-scope="{ row, index }">
              <crop-select
                v-if="row.$cellEdit"
                v-model="row.corpId"
                :cropIndex="index"
                corpType="GYS"
                @getCorpData="getcorpId"
                :disabled="detailData.seeDisabled || arrivalDisabled || deliverDisabled"
              ></crop-select>
              <span v-else>{{ row.corpName }}</span>
            </template>
          </avue-crud>
        </basic-container>
        <fee-info
          ref="feeInfo"
          :orderFeesList="advantageProjectData"
          :disabled="detailData.seeDisabled || arrivalDisabled"
          :srcType="3"
          optionType="GN"
          itemType="发货"
          feeUrl="/blade-deliver-goods/deliveryfees/update"
          @beforeFinance="beforeFinance"
          :corpId="form.corpId"
        />
        <containerTitle title="附件上传"></containerTitle>
        <c-upload
          :data="bankOfDepositData"
          deleteUrl="/api/blade-deliver-goods/deliveryfiles/update"
          :enumerationValue="77"
        />
      </el-form>
    </div>
    <el-dialog
        title="导入商品"
        append-to-body
        class="el-dialogDeep"
        :visible.sync="dialogVisible"
        width="80%"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        :close-on-press-escape="false"
        @close="closeGoods">
      <el-row :style="{height: rowHeight}">
        <el-col :span="5" style="height: 100%;overflow-y: auto">
          <div>
            <el-scrollbar>
              <basic-container>
                <avue-tree :option="treeOption" :data="treeDataGoods" @node-click="nodeClick"/>
              </basic-container>
            </el-scrollbar>
          </div>
        </el-col>
        <el-col :span="19">
          <basic-container>
            <avue-crud :option="optionTwo"
                       :table-loading="loading"
                       :data="data"
                       ref="crud"
                       @refresh-change="refreshChange"
                       @selection-change="selectionChange"
                       :page.sync="page"
                       @search-change="goodsSearch"
                       @on-load="onLoad"></avue-crud>
          </basic-container>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="importGoods" v-if="commodityData !== true">导入</el-button>
          <el-button type="primary" @click="importChoice" v-if="commodityData === true"
                     :disabled="tableData.length !== 1">导入</el-button>
        </span>
    </el-dialog>
    <el-dialog
        title="导入费用"
        append-to-body
        class="el-dialogDeep"
        :visible.sync="dialogCost"
        width="80%"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        :close-on-press-escape="false"
        @close="closeFees">
      <el-row :style="{height: rowHeight}">
        <el-col :span="5" style="height: 100%;overflow-y: auto">
          <div>
            <el-scrollbar>
              <basic-container>
                <avue-tree :option="treeOptionCost" :data="treeData" @node-click="nodeClickCost"/>
              </basic-container>
            </el-scrollbar>
          </div>
        </el-col>
        <el-col :span="19">
          <basic-container>
            <avue-crud :option="optionTwoCost"
                       :table-loading="loadingCost"
                       :data="dataCost"
                       ref="crud"
                       @refresh-change="refreshChangeCost"
                       @selection-change="selectionChangeCost"
                       :page.sync="pageCost"
                       @searchChange="feesSearch"
                       @on-load="onLoadCost">
            </avue-crud>
          </basic-container>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogCost = false">取 消</el-button>
          <el-button type="primary" @click="importCost" v-if="choiceData !== true">导入</el-button>
          <el-button type="primary" @click="choiceCost" v-if="choiceData === true"
                     :disabled="tableDataCost.length !== 1">导入</el-button>
        </span>
    </el-dialog>
<!--    导入销售明细-->
    <el-dialog
      title="导入销售"
      append-to-body
      class="el-dialogDeep"
      :visible.sync="marketDialog"
      width="60%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :modal-append-to-body='false'
      :close-on-press-escape="false"
      v-dialog-drag>
      <market-detail
        @importMarket="importMarket"
        @close="closeMarkeDialog"
        systemType="GN"
      >
      </market-detail>
    </el-dialog>
    <report-dialog
      :switchDialog="switchDialog"
      :reportId="form.id"
      reportName="客户收货确认"
      @onClose="onClose()"
    ></report-dialog>
  </div>
</template>

<script>
import {
  typeSave, detail,
  corpstypeTree,
  corpsattn,
  corpsbank,
  corpsitem,
  // getList,
  sendOutGoods,
  revokeOutGoods,
  confirmArrival,
  cancelArrival
} from "@/api/basicData/deliveryNotice"
import {getList} from "@/api/basicData/commodityType";
import customerContact from "./configuration/customerContact.json"
import advantageProject from "./configuration/advantageProject.json"
import bankOfDeposit from "./configuration/bankOfDeposit.json"
import commodity from "./configuration/commodity.json"
import optionTwoCost from "./configuration/mainListCost.json"
import {getDeptLazyTree,getDeptLazyTreeTwo, customerList} from "@/api/basicData/basicFeesDesc";
import {customerList as wareHouseType} from "@/api/basicData/basicStorageType"
import {customerList as selectWareHouse} from "@/api/basicData/basicStorageDesc"
import {selectGoodsNum} from "@/api/basicData/inventoryAccount"
import { contrastObj, contrastList } from "@/util/contrastData";
import  marketDetail from "@/components/procurement/market";
import feeInfo from "@/components/fee-info/main";
import {
  isDiscount,
  isPercentage,
  micrometerFormat,
  IntegerFormat
} from "@/util/validate";
import reportDialog from "@/components/report-dialog/main";
import { gainUser } from "@/api/basicData/customerInquiry";

export default {
  name: "detailsPage",
  props: {
    detailData: {
      type: Object
    }
  },
  components: {
    marketDetail,
    feeInfo,
    reportDialog,
  },
  data() {
    return {
      configuration: {
        multipleChoices: false,
        multiple: false,
        collapseTags: false,
        placeholder: '请点击右边按钮选择',
        dicData: []
      },
      companyConfiguration: {
        multipleChoices: false,
        multiple: false,
        collapseTags: false,
        placeholder: '请点击右边按钮选择',
        dicData: []
      },
      configurationWarehouse: {
        multipleChoices: false,
        multiple: false,
        collapseTags: false,
        placeholder: "请点击右边按钮选择",
        dicData: [],
        clearable: true,
      },
      form: {},
      data: [],
      loadingCost: false,
      choiceData: false,
      commodityData: false,
      dataCost: [],
      treeDataGoods: [],
      treeData: [],
      choiceIndex: '',
      dialogCost: false,
      treeDeptId: '',
      treeDeptIdCost: '',
      pageCost: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      loading: false,
      contactsForm: {},
      optionTwo: commodity,
      optionTwoCost: optionTwoCost,
      treeOptionCost: {
        nodeKey: 'id',
        lazy: true,
        treeLoad: function (node, resolve) {
          const parentId = (node.level === 0) ? 0 : node.data.id;
          getDeptLazyTree(parentId).then(res => {
            resolve(res.data.data.map(item => {
              return {
                ...item,
                leaf: !item.hasChildren
              }
            }))
          });
        },
        addBtn: false,
        menu: false,
        size: 'small',
        props: {
          labelText: '标题',
          label: 'title',
          value: 'value',
          children: 'children'
        }
      },
      treeOption: {
        nodeKey: 'id',
        lazy: true,
        treeLoad: function (node, resolve) {
          const parentId = (node.level === 0) ? 0 : node.data.id;
          getDeptLazyTreeTwo(parentId).then(res => {
            resolve(res.data.data.map(item => {
              return {
                ...item,
                leaf: !item.hasChildren
              }
            }))
          });
        },
        addBtn: false,
        menu: false,
        size: 'small',
        props: {
          labelText: '标题',
          label: 'title',
          value: 'value',
          children: 'children'
        }
      },
      dialogVisible: false,
      advantageProjectForm: {},
      bankOfDepositForm: {},
      contactsData: [],
      advantageProjectData: [],
      disabled: false,
      saveLoading: false,
      bankOfDepositData: [],
      tableDataCost: [],
      dic: [],
      tableData: [],
      customerContact: {},
      advantageProject: {},
      bankOfDeposit: bankOfDeposit,
      basicData: {
        column: [
          {
            label: '系统编号',//发货通知(点击)
            prop: 'sysNo',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '客户名称',
            prop: 'corpId',
            span: 16,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '单据状态',
            prop: 'deliveryStatus',
            disabled: true,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '所属公司',
            prop: 'salesCompany', //salesCompany
            span: 16,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '仓库类型',
            prop: 'warehouseType',//字典表
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '仓库名称',
            prop: 'storageId',
            span: 16,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },{
            label: '匹配订单号',
            prop: 'srcOrderNo',
            disabled:true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '出库金额',
            prop: 'deliveryAmount',
            disabled: false,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '出库数量',
            prop: 'totalQuantity',
            disabled: false,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '出库日期',
            prop: 'businessDate',
            type: 'datetime',
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '制单时间',
            type: 'datetime',
            prop: 'createTime',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '费用合计',
            prop: 'totalCost',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },{
            label: '收货地址',
            prop: 'arrivalAddress',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '收货人',
            prop: 'arrivalContact',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '收货电话',
            prop: 'arrivalTel',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '包装要求',
            prop: 'packageRemarks',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },{
            label: '赠送积分',
            prop: 'presenterIntegral',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },{
            label: '兑换积分',
            prop: 'convertIntegral',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '产生返利',
            prop: 'createProfit',
            disabled: false,
            type: 'number',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },{
            label: '业务员',
            prop: 'chargeMember',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'change'
              }
            ]
          },{
            label: "备注",
            span: 24,
            type: 'textarea',
            prop: "otherRemarks",
            mock: {
              type: 'county'
            }
          }
        ]
      },
      statusOption: [],
      warehouseTypeOption: [],
      // 仓库类型
      warehouseType: [],
      // 仓库名称
      warehouseName: [],
      maxFeeNum: 0,
      maxGoodsNum: 0,
      oldForm: {
        orderStatus: "录入"
      },
      oldGoodsList: [],
      oldGiftList: [],
      oldFeesList: [],
      oldUploadList: [],
      // 导入销售订单明细
      marketDialog: false,
      // 弹窗高度
      rowHeight: '',
      // 查询时loading页面
      pageLoading: false,
      goodsActives: 'goods',
      // 用于判断 tab是否是当前
      saveActives: '',
      goodsDisabled: false,
      // 赠品信息数据
      giftData: [],
      // 商品信息展示数据
      goodsShowData: [],
      // 确认收货禁用
      deliverDisabled: false,
      // 确认到货禁用
      arrivalDisabled: false,
      switchDialog: false,
      userList: [],
    }
  },
  mounted() {
    this.$nextTick(() => {
      // 监听浏览器高度变化，改变表格高度
      window.onresize = () => {
        this.rowHeight = (window.innerHeight - 130) + 'px'
      }
    })
  },
  filters: {
    IntegerFormat(num) {
      return IntegerFormat(num);
    },
    decimalFormat(num) {
      return num ? Number(num).toFixed(2) : "0.00";
    },
  },
  //初始化查询
  async created() {
    this.rowHeight = (window.innerHeight - 130) + 'px'
    this.customerContact = await this.getColumnData(this.getColumnName(21), customerContact);
    this.advantageProject = await this.getColumnData(this.getColumnName(22), advantageProject);
    this.getWorkDicts("order_status").then(res => {
      this.statusOption = res.data.data
    })
    this.getWorkDicts("warehouseType").then(res => {
      this.warehouseTypeOption = res.data.data
    })
    this.$set(this.form,'deliveryStatus','录入')
    this.$set(this.form, 'presenterIntegral' , 0)
    this.$set(this.form, 'convertIntegral' , 0)
    this.$set(this.form, 'createProfit' , 0)
    wareHouseType().then(res => {
      this.warehouseType = res.data.data.records
      this.warehouseType.forEach(item => {
        this.$set(item, 'label', item.cname)
        this.$set(item, 'value', item.id)
        if (item.hasChildren) {
          this.$set(item, 'children', [])
        }
      })
      let result = [], temp = {}
      for(let i = 0; i < this.warehouseType.length;i++) {
        temp[this.warehouseType[i].id] = this.warehouseType[i]
      }
      for (let j = 0;j < this.warehouseType.length;j++) {
        let current = this.warehouseType[j]
        let tempCurrentParent = temp[current.parentId]
        if (tempCurrentParent) {
          if (!tempCurrentParent["children"]) {
            tempCurrentParent["children"] = []
          }
          tempCurrentParent["children"].push(current)
        } else {
          result.push(current)
        }
      }
      this.warehouseType = result
    });
    selectWareHouse().then(res => {
      this.warehouseName = res.data.data.records
    })
    gainUser().then(res => {
      this.userList = res.data.data;
    });
    if (this.detailData.id) {
      let id = this.detailData.id
      this.queryData(id)
    }else if (this.detailData.form){
      this.form = JSON.parse(this.detailData.form);
      delete this.form.createTime
      delete this.form.id
      delete this.form.sysNo
      this.$set(this.form, 'deliveryStatus', '录入')
      this.$set(this.form, 'srcOrderNo', this.form.orgOrderNo)
      this.$set(this.form, 'arrivalContact', this.form.corpAttn)
      this.$set(this.form, 'arrivalTel', this.form.corpTel)
      this.form.orderItemsList.forEach(item => {
        this.$set(item, 'contractNumber', this.form.orgOrderNo)
      })
      this.contactsData = this.form.orderItemsList.filter(item => {
        return item.goodType == 0
      })
      this.giftData = this.form.orderItemsList.filter(item => {
        return item.goodType == 1
      })
      this.giftData.forEach(item => {
        this.$set(item, 'deliveryAmount', item.amount)
        this.$set(item, 'specificationAndModel', item.itemType)
        this.$set(item, 'orgOrderNo', this.form.orgOrderNo)
        this.$set(item, 'srcOrderNo', this.form.srcOrderNo)
        this.$set(item, "srcId", item.id)
        this.$set(item, 'actualQuantity', item.orderQuantity)
        delete item.id
        delete item.pid
        delete item.createTime
        delete item.createUser
        delete item.status
        delete item.updateTime
        delete item.updateUser
      })
      this.goodsShowData = this.giftData;
      this.goodsActives = 'goods';
      this.handleClick({name: this.goodsActives})
      // this.contactsData = this.form.orderItemsList
      delete this.form.orderItemsList
      this.configuration.dicData = this.form.corpName
      delete this.form.corpName
      this.$set(this.form, 'salesCompany', this.form.belongToCorpId)
      delete this.form.belongToCorpList
      this.$set(this.form, 'deliveryAmount', 0)
      this.$set(this.form, 'totalQuantity', 0)
      this.$set(this.form, 'totalCost', 0)
      this.advantageProjectData = this.form.orderFeesList;
      delete this.form.orderFeesList
      this.advantageProjectData.forEach(item => {
        delete item.createDept
        delete item.createTime
        delete item.createUser
        delete item.id
        delete item.isDeleted
        delete item.pid
        delete item.status
        delete item.tenantId
        delete item.updateTime
        delete item.updateUser
      })
      this.contactsData.forEach(item => {
        this.$set(item, 'specificationAndModel', item.itemType)
        this.$set(item, 'orgOrderNo', this.form.orgOrderNo)
        this.$set(item, 'srcOrderNo', this.form.srcOrderNo)
        this.$set(item, "srcId", item.id)
        this.$set(item, "actualQuantity", (Number(item.orderQuantity) - Number(item.actualQuantity)))
        this.$set(item, "arrivalQuantity", item.actualQuantity)
        this.$set(item, "deliveryAmount", item.amount)
        this.$set(item, "purchaseTotalAmount", (Number(item.purchaseAmount) * Number(item.actualQuantity)))
        item.purchaseTotalAmount = item.purchaseTotalAmount.toFixed(2)
        this.$set(item, "inventoryNumber", item.storageQuantity)
        this.form.deliveryAmount += Number(item.deliveryAmount)
        this.form.totalQuantity += Number(item.actualQuantity)
        this.form.totalCost += Number(item.deliveryAmount)
        // 出库数量和出库金额的比例
        this.$set(item, 'scale', (item.deliveryAmount / item.actualQuantity))
        delete item.id
        delete item.pid
        delete item.createTime
        delete item.createUser
        delete item.status
        delete item.updateTime
        delete item.updateUser
      })
    } else if (this.detailData.copyId) {
      let id = this.detailData.copyId
      this.queryData(id, true)
    }
    this.oldForm = Object.assign({}, this.form)
  },
  watch: {
  },
  methods: {
    queryData(id, isCopy = false, type) {
      this.pageLoading = true
      detail(id).then(res => {
        this.form = res.data.data;
        if (this.form.deliveryStatus == '已发货') {
          this.deliverDisabled = true;
          this.arrivalDisabled = false;
        } else if (this.form.deliveryStatus == '已到货') {
          this.arrivalDisabled = true;
          this.deliverDisabled = false;
        } else {
          this.arrivalDisabled = false;
          this.deliverDisabled = false;
        }
        if (this.deliverDisabled) {
          this.customerContact.column.forEach(item => {
            if (item.prop == 'arrivalQuantity') {
              item.disabled = false
            } else {
              item.disabled = true
            }
          })
        } else {
          this.customerContact.column.forEach(item => {
            item.disabled = false
          })
        }

        // this.contactsData = this.form.deliveryItemsList
        this.contactsData = this.form.deliveryItemsList.filter(item => {
          return item.goodType == 0
        })
        this.giftData = this.form.deliveryItemsList.filter(item => {
          return item.goodType == 1
        })
        this.giftData.forEach(item => {
          this.$set(item, 'deliveryAmount', item.amount)
        })
        this.goodsShowData = this.giftData;
        this.goodsActives = 'goods';
        this.handleClick({name: this.goodsActives})
        this.advantageProjectData = this.form.deliveryFeesList
        this.bankOfDepositData = this.form.deliveryFilesList
        this.configuration.dicData = this.form.corpName
        this.form.deliveryAmount = 0
        this.form.totalQuantity = 0
        this.contactsData.forEach(item => {
          this.form.deliveryAmount += Number(item.deliveryAmount)
          this.form.totalQuantity += Number(item.actualQuantity)
          // 出库金额和出库数量的比例
          this.$set(item, 'scale', (item.deliveryAmount / item.actualQuantity))
        })
        if (this.form.companyName) {
          this.companyConfiguration.dicData = this.companyConfiguration.dicData.concat(this.form.companyName)
        }
        if (this.form.storageMap) {
          this.configurationWarehouse.dicData = this.form.storageMap
        }
        let feesData = []
        this.form.deliveryFeesList.forEach(item => {
          let a = {
            cname: item.corpName,
            id: item.corpId
          }
          feesData.push(a)
        })
        this.configuration.dicData = this.configuration.dicData.concat(feesData)
        // 去重
        this.removeRepeat()
        delete this.form.deliveryItemsList
        delete this.form.deliveryFeesList
        delete this.form.deliveryFilesList
        delete this.form.corpName
        delete this.form.companyName
        // 获取最大值
        let num = []
        this.advantageProjectData.forEach(item => {
          num.push(item.sort)
        })
        if (num.length == 0) {
          this.maxFeeNum = 0;
        } else {
          this.maxFeeNum = num.reduce((a, b) => {
            return b > a? b: a;
          })
        }
        let goodsNum = []
        this.contactsData.forEach(item => {
          goodsNum.push(item.sort)
        })
        if (goodsNum.length == 0) {
          this.maxGoodsNum = 0;
        } else {
          this.maxGoodsNum = goodsNum.reduce((a, b) => {
            return b > a? b: a;
          })
        }
        this.oldGoodsList = []
        this.oldGiftList = []
        this.oldFeesList = []
        this.oldUploadList = []
        this.oldForm = Object.assign({}, this.form)
        this.oldGoodsList = this.deepClone(this.contactsData)
        this.oldGiftList = this.deepClone(this.giftData)
        this.oldFeesList = this.deepClone(this.advantageProjectData)
        this.oldUploadList = this.deepClone(this.bankOfDepositData)
        if (isCopy) {
          delete this.form.sysNo
          delete this.form.id
          this.contactsData.forEach(item => {
            delete item.id
            delete item.pid
            delete item.itemId
          })
          this.goodsShowData.forEach(item => {
            delete item.id
            delete item.pid
            delete item.itemId
          })
          this.giftData.forEach(item => {
            delete item.id
            delete item.pid
            delete item.itemId
          })
          this.advantageProjectData.forEach(item => {
            delete item.id
            delete item.pid
          })
          this.bankOfDepositData.forEach(item => {
            delete item.id
            delete item.pid
          })
          this.form.deliveryStatus = '录入'
        }
        if (type == '发货') {
          this.$nextTick(() => {
            this.form.deliveryItemsList = this.contactsData.concat(this.giftData)
            this.form.deliveryFeesList = this.$refs.feeInfo.submitData()
            this.form.deliveryFilesList = this.bankOfDepositData
            if (typeof this.form.corpsTypeId == 'object') {
              this.form.corpsTypeId = this.form.corpsTypeId.join(",")
            }
            this.pageLoading = true
            this.saveActives = ''
            sendOutGoods(this.form).then(res => {
              this.$message.success('发货成功')
              this.queryData(res.data.data.id)
            }).finally(() => {
              this.pageLoading = false
            })
          })
        } else if (type == '到货') {
          if (this.goodsActives == 'gift') {
            this.form.deliveryItemsList = this.goodsShowData.concat(this.contactsData)
          } else {
            this.form.deliveryItemsList = this.goodsShowData.concat(this.giftData)
          }
          this.pageLoading = true
          this.saveActives = ''
          confirmArrival(this.form).then(res => {
            this.$message.success('已确认到货')
            this.queryData(this.form.id)
          }).catch(() => {
            this.pageLoading = false
          })
        }
      }).finally(() => {
        this.saveLoading = false
        this.pageLoading = false
      });
    },
    getcorpId(row) {
      this.contactsData[row.index].corpId = row.id;
      this.contactsData[row.index].corpName = row.cname;
    },
    // 出库数量变化时调用
    actualQuantityChange(row) {
      // if (row.scale) {
      //   row.deliveryAmount = Number(row.actualQuantity) * Number(row.scale)
      // }
      if (this.goodsActives == 'goods') {
        if (Number(row.actualQuantity) < Number(row.arrivalQuantity)) {
          row.arrivalQuantity = row.actualQuantity
          row.purchaseTotalAmount = (Number(row.arrivalQuantity) * Number(row.purchaseAmount)).toFixed(2)
          row.deliveryAmount = (Number(row.arrivalQuantity) * Number(row.price)).toFixed(2)
        }
        this.form.deliveryAmount = 0
        this.form.totalQuantity = 0
        this.contactsData.forEach(item => {
          this.form.deliveryAmount += Number(item.deliveryAmount)
          this.form.totalQuantity += Number(item.actualQuantity)
        })
      } else {
        row.integral = Number(row.integralMultiples) * Number(row.actualQuantity)
        this.$set(this.form, 'convertIntegral' , 0)
        this.goodsShowData.forEach(item => {
          this.form.convertIntegral = (Number(this.form.convertIntegral) + Number(item.integral)).toFixed(2)
        })
      }
    },
    // 到货数量变化计算
    arrivalQuantityChange(row) {
      if (this.goodsActives == 'goods') {
        if (Number(row.arrivalQuantity) > Number(row.actualQuantity)) {
          this.$message.error('到货数量不能超过出库数量')
          row.arrivalQuantity = 0
        }
        row.purchaseTotalAmount = (Number(row.arrivalQuantity) * Number(row.purchaseAmount)).toFixed(2)
        row.deliveryAmount = (Number(row.arrivalQuantity) * Number(row.price)).toFixed(2)
        row.integral = Number(row.integralMultiples) * Number(row.arrivalQuantity)
        this.$set(this.form, 'presenterIntegral' , 0)
        this.goodsShowData.forEach(item => {
          this.form.presenterIntegral = (Number(this.form.presenterIntegral) + Number(item.integral)).toFixed(2)
        })
      } else {
      }
    },
    // 类别变换时触发
    warehouseTreeChange(id) {
      this.warehouseName = []
      if (this.firstComing) {
        if (!this.form.storageId) {
          this.$set(this.form, 'storageId', null)
        } else {
          this.form.storageId = null
        }
      }
      let data =  {
        storageTypeId: id
      }
      selectWareHouse(data).then(res => {
        this.warehouseName = res.data.data.records
      })
      this.firstComing = true
    },
    //点击行可编辑
    handleRowClick(row, event, column) {
    },
    //商品编辑
    rowCell(row, index) {
      this.$refs.crudContact.rowCell(row, row.$index)
    },
    //费用编辑
    rowCellTwo(row, index) {
      this.$refs.crudProject.rowCell(row, row.$index)
    },
    //费用新增触发
    costIncrease() {
      this.dialogCost = !this.dialogCost
      this.choiceData = false
    },
    //商品新增触发
    commoditySelection() {
      this.dialogVisible = !this.dialogVisible
      this.tableData = []
      this.commodityData = false
    },
    //点击费用明细选择触发
    choice(row) {
      this.dialogCost = !this.dialogCost
      this.choiceData = true
      this.choiceIndex = row.$index
    },
    //点击商品明细选择触发
    commodityChoice(row) {
      this.dialogVisible = !this.dialogVisible
      this.commodityData = true
      this.choiceIndexT = row.$index
    },
    //导入商品触发
    importChoice() {
      if (this.tableData.length === 1) {
        this.contactsData[this.choiceIndexT].cname = this.tableData[0].cname
        this.contactsData[this.choiceIndexT].code = this.tableData[0].code
        this.contactsData[this.choiceIndexT].typeno = this.tableData[0].typeno
        this.contactsData[this.choiceIndexT].specificationAndModel = this.tableData[0].typeno
        this.contactsData[this.choiceIndexT].itemId = this.tableData[0].id
        this.contactsData[this.choiceIndexT].priceCategory = this.tableData[0].goodsTypeName
        selectGoodsNum({
          goodsId: this.tableData[0].id,
          itemType: this.tableData[0].typeno,
          tradeType: 'GN'
        }).then(res => {
          this.contactsData[this.choiceIndexT].storageQuantity =  res.data.data
        })
      }
      this.dialogVisible = !this.dialogVisible
      this.commodityData = false
    },
    //费用编辑导入触发
    choiceCost() {
      if (this.tableDataCost.length === 1) {
        this.advantageProjectData[this.choiceIndex].feeName = this.tableDataCost[0].cname
        this.advantageProjectData[this.choiceIndex].itemId = this.tableDataCost[0].id
        this.advantageProjectData[this.choiceIndex].code = this.tableDataCost[0].code
      }
      this.dialogCost = !this.dialogCost
      this.choiceData = false
    },
    //费用导入触发
    importCost() {
      // this.advantageProjectForm = this.advantageProjectForm.concat(this.tableDataCost)
      if (this.tableDataCost.length > 0) {
        for (let item in this.tableDataCost) {
          this.tableDataCost[item].itemId = this.tableDataCost[item].id
          this.tableDataCost[item].feeName = this.tableDataCost[item].cname
          this.tableDataCost[item].sort = this.maxFeeNum + 1
          this.maxFeeNum++
          delete this.tableDataCost[item].id
          this.$refs.crudProject.rowCellAdd(this.tableDataCost[item]);
          this.$refs.crudProject.rowCell(this.tableDataCost[item], this.advantageProjectForm.length - 1)
        }
      }
      this.tableDataCost = []
      this.dialogCost = false
    },
    //确认导入触发
    importGoods() {
      // this.contactsData = this.contactsData.concat(this.tableData)
      if (this.tableData.length > 0) {
        for (let item in this.tableData) {
          selectGoodsNum({
            goodsId: this.tableData[item].id,
            itemType: this.tableData[item].typeno,
            tradeType: 'GN'
          }).then(res =>{
            this.tableData[item].storageQuantity =  res.data.data
            this.$set(this.tableData[item], 'specificationAndModel', this.tableData[item].typeno)
            this.tableData[item].itemId = this.tableData[item].id
            this.tableData[item].priceCategory = this.tableData[item].goodsTypeName
            delete this.tableData[item].goodsTypeName
            delete this.tableData[item].id
            delete this.tableData[item].status
            delete this.tableData[item].isDeleted
            this.$set(this.tableData[item], 'inventoryNumber', 0)
            this.$set(this.tableData[item], 'actualQuantity', 0)
            this.$set(this.tableData[item], 'inventoryAmount', 0)
            this.$set(this.tableData[item], 'deliveryAmount', 0)
            this.tableData[item].price = 0
            this.tableData[item].amount = 0
            if (this.goodsActives == "goods") {
              this.$set(this.tableData[item], 'goodType', 0)
              this.arrivalQuantityChange(this.tableData[item])
            } else {
              this.$set(this.tableData[item], 'goodType', 1)
              this.$set(this.tableData[item], 'integralMultiples', this.tableData[item].integral)
              this.actualQuantityChange(this.tableData[item])
            }
            this.$set(this.tableData[item], 'integral', '0')
            this.tableData[item].sort = this.maxGoodsNum + 1
            this.maxGoodsNum++
            this.$refs.crudContact.rowCellAdd(this.tableData[item]);
            this.$refs.crudContact.rowCell(this.tableData[item], this.contactsData.length - 1)
            if (this.goodsActives == "goods") {
              this.arrivalQuantityChange(this.tableData[item])
            } else {
              this.actualQuantityChange(this.tableData[item])
            }
          })
        }
      }
      this.dialogVisible = false
    },
    closeGoods() {
      this.treeDataGoods = [];
      this.treeDeptId = "";
    },
    closeFees() {
      this.treeDeptIdCost = "";
      this.treeData = [];
    },
    //选中触发
    selectionChange(list) {
      this.tableData = list
    },
    //费用选中触发
    selectionChangeCost(list) {
      this.tableDataCost = list
    },
    //导入页左商品类型查询
    nodeClick(data) {
      this.treeDeptId = data.id;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    //导入页左费用类型查询
    nodeClickCost(data) {
      this.treeDeptIdCost = data.id;
      this.pageCost.currentPage = 1;
      this.onLoadCost(this.pageCost);
    },
    //刷新触发
    refreshChange() {
      this.treeDeptId = '';
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    //费用刷新触发
    refreshChangeCost() {
      this.treeDeptIdCost = '';
      this.pageCost.currentPage = 1;
      this.onLoadCost(this.pageCost);
    },
    //新增商品信息保存触发
    rowSave(row, done, loading) {
      // this.contactsData.push(row)
      done()
    },
    //修改商品信息触发
    rowUpdate(row, index, done, loading) {
      done(row);
    },
    //删除商品信息触发
    rowDel(row, index, donerowDel) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        //商品判断是否需要调用删除接口
        if (row.id) {
          corpsattn(row.id).then(res => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.goodsShowData.splice(row.$index, 1);
            // 删除时主表积分跟着改变
            if (this.goodsActives == 'goods') {
              this.form.presenterIntegral = 0;
              this.goodsShowData.forEach(item => {
                this.form.presenterIntegral = (Number(this.form.presenterIntegral) + Number(item.integral)).toFixed(2)
              })
            } else {
              this.form.convertIntegral = 0;
              this.goodsShowData.forEach(item => {
                this.form.convertIntegral = (Number(this.form.convertIntegral) + Number(item.integral)).toFixed(2)
              })
            }
          })
        } else {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.goodsShowData.splice(row.$index, 1);
          // 删除时主表积分跟着改变
          if (this.goodsActives == 'goods') {
            this.form.presenterIntegral = 0;
            this.goodsShowData.forEach(item => {
              this.form.presenterIntegral = (Number(this.form.presenterIntegral) + Number(item.integral)).toFixed(2)
            })
          } else {
            this.form.convertIntegral = 0;
            this.goodsShowData.forEach(item => {
              this.form.convertIntegral = (Number(this.form.convertIntegral) + Number(item.integral)).toFixed(2)
            })
          }
        }
      })
    },
    //新增费用明细保存触发
    rowSaveProject(row, done, loading) {
      // this.advantageProjectData.push(row)
      done()
    },
    //修改费用明细触发
    rowUpdateProject(row, index, done, loading) {
      done(row);
    },
    goodsSearch(params, done) {
      this.treeDeptId = '';
      this.onLoad(this.page, params);
      done()
    },
    //商品列表查询
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query), this.treeDeptId).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    },
    // 费用查询按钮
    feesSearch(params, done) {
      this.treeDeptIdCost = '';
      this.onLoadCost(this.pageCost, params)
      done()
    },
    //费用查询
    onLoadCost(page, params = {}) {
      this.loadingCost = true;
      let queryParams = Object.assign({}, params, {
        pageSize: page.pageSize,
        pageNum: page.currentPage,
        parentId: 0,
        feesTypeId: this.treeDeptIdCost
      })
      customerList(queryParams).then(res => {
        const data = res.data.data;
        this.pageCost.total = data.total;
        this.dataCost = data.records;
        this.loadingCost = false;
      });
    },
    //删除费用明细触发
    rowDelProject(row, index, donerowDel) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        //费用判断是否需要调用删除接口
        if (row.id) {
          corpsitem(row.id).then(res => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.advantageProjectData.splice(row.$index, 1);
          })
        } else {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.advantageProjectData.splice(row.$index, 1);
        }
      })
    },
    // 去重
    removeRepeat() {
      let obj = []
      this.configuration.dicData = this.configuration.dicData.reduce((current,next) => {
        obj[next.id] ? '': obj[next.id] = true && current.push(next)
        return current
      }, [])
    },
    //
    receiveList(data){
      this.configuration.dicData = this.configuration.dicData.concat(data)
      this.removeRepeat()
    },
    //修改提交触发
    editCustomer(isBack = false, type) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          //商品信息
          this.contactsData.forEach(item => {
            this.$set(item, 'contractAmount', item.deliveryAmount)
          })
          if (this.goodsActives == 'gift') {
            this.form.deliveryItemsList = this.goodsShowData.concat(this.contactsData)
          } else {
            this.form.deliveryItemsList = this.goodsShowData.concat(this.giftData)
          }
          this.form.deliveryItemsList.forEach(item => {
            if (item.orderNo) {
              this.$set(item, 'contractNumber', item.orderNo)
              this.$set(item, 'srcOrderNo', item.orderNo)
            }
            this.$set(item, 'contractAmount', item.deliveryAmount)
          })
          this.form.deliveryItemsList = this.contactsData.concat(this.giftData)
          // this.form.deliveryFeesList = this.advantageProjectData
          this.form.deliveryFeesList = this.$refs.feeInfo.submitData()
          this.form.deliveryFilesList = this.bankOfDepositData
          if (typeof this.form.corpsTypeId == 'object') {
            this.form.corpsTypeId = this.form.corpsTypeId.join(",")
          }
          this.saveLoading = true
          this.form.billType = 'FH'
          // 如果有id解锁，没有跳过
          // !this.detailData.seeDisabled && this.form.id && this.unLock({moduleName: 'fh',tableName: 'business_delivery', billId: this.form.id})
          typeSave(this.form).then(res => {
            this.$message({type: "success", message: this.form.id ? "修改成功!" : "新增成功!"});
            // this.$set(this.detailData, 'seeDisabled', true);
            if (isBack) {
              //成功关闭此页面回到列表页
              this.$emit("goBack");
              this.leaveDetailsKey(this.$route.name)
            } else {
              this.saveActives = ''
              this.queryData(res.data.data.id, false, type)
            }
          }).catch(() => {
            this.pageLoading = false
            this.saveLoading = false
          })
        } else {
          return false;
        }
      });
    },
    //复制新单
    copyOrder() {
      this.queryData(this.form.id, true)
    },
    //返回列表
    backToList() {
      let getGoodsList = []
      let getGiftList = []
      let getFeeList = this.$refs.feeInfo.submitData()
      if (this.goodsActives == 'gift') {
        getGiftList = this.goodsShowData
        getGoodsList = this.contactsData
      } else {
        getGoodsList = this.goodsShowData
        getGiftList = this.giftData
      }
      if (contrastObj(this.form, this.oldForm) ||
        contrastList(getGoodsList, this.oldGoodsList) ||
        contrastList(getGiftList, this.oldGiftList) ||
        contrastList(getFeeList, this.oldFeesList) ||
        contrastList(this.bankOfDepositData, this.oldUploadList)
      ) {
        this.$confirm("数据发生变化未有提交记录, 是否提交?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.editCustomer(true)
        }).catch(() => {
          !this.detailData.seeDisabled && this.form.id && this.unLock({moduleName: 'fh',tableName: 'business_delivery', billId: this.form.id})
          this.$emit("goBack");
          this.leaveDetailsKey(this.$route.name)
        })
      } else {
        !this.detailData.seeDisabled && this.form.id && this.unLock({moduleName: 'fh',tableName: 'business_delivery', billId: this.form.id})
        this.$emit("goBack");
        this.leaveDetailsKey(this.$route.name)
      }
    },
    // 确认发货
    sendOutGoods() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.contactsData.length == 0) {
            return this.$message.error('商品信息为空')
          }
          let getGoodsList = []
          let getGiftList = []
          let getFeeList = this.$refs.feeInfo.submitData()
          if (this.goodsActives == 'gift') {
            getGiftList = this.goodsShowData
            getGoodsList = this.contactsData
          } else {
            getGoodsList = this.goodsShowData
            getGiftList = this.giftData
          }
          if (contrastObj(this.form, this.oldForm) ||
            contrastList(getGoodsList, this.oldGoodsList) ||
            contrastList(getGiftList, this.oldGiftList) ||
            contrastList(getFeeList, this.oldFeesList) ||
            contrastList(this.bankOfDepositData, this.oldUploadList)
          ) {
            this.$confirm("数据发生变化未有提交记录, 是否保存?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(async () => {
              await this.editCustomer(false, '发货')
            }).catch(() => {
              this.$message.info('已取消')
            })
          } else {
            //商品信息
            if (this.goodsActives == 'gift') {
              this.form.deliveryItemsList = this.goodsShowData.concat(this.contactsData)
            } else {
              this.form.deliveryItemsList = this.goodsShowData.concat(this.giftData)
            }
            this.form.deliveryFeesList = this.$refs.feeInfo.submitData()
            this.form.deliveryFilesList = this.bankOfDepositData
            if (typeof this.form.corpsTypeId == 'object') {
              this.form.corpsTypeId = this.form.corpsTypeId.join(",")
            }
            this.pageLoading = true
            this.saveActives = ''
            this.saveLoading = true
            sendOutGoods(this.form).then(res => {
              this.$message.success('发货成功')
              this.queryData(res.data.data.id)
            }).finally(() => {
              this.pageLoading = false
              this.saveLoading = false
            })
          }
        } else {
          return false;
        }
      });
    },
    // 撤销发货
    revokeOutGoods() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          //商品信息
          if (this.goodsActives == 'gift') {
            this.form.deliveryItemsList = this.goodsShowData.concat(this.contactsData)
          } else {
            this.form.deliveryItemsList = this.goodsShowData.concat(this.giftData)
          }
          this.form.deliveryFeesList = this.$refs.feeInfo.submitData()
          this.form.deliveryFilesList = this.bankOfDepositData
          if (typeof this.form.corpsTypeId == 'object') {
            this.form.corpsTypeId = this.form.corpsTypeId.join(",")
          }
          this.pageLoading = true
          this.saveLoading = true
          this.saveActives = ''
          revokeOutGoods(this.form).then(res => {
            this.$message.success('撤销成功')
            this.queryData(res.data.data.id)
          }).finally(() => {
            this.pageLoading = false
            this.saveLoading = false
          })
        } else {
          return false;
        }
      });
    },
    // 确认到货
    confirmArrival() {
      let getGoodsList = []
      let getGiftList = []
      let getFeeList = this.$refs.feeInfo.submitData()
      if (this.goodsActives == 'gift') {
        getGiftList = this.goodsShowData
        getGoodsList = this.contactsData
      } else {
        getGoodsList = this.goodsShowData
        getGiftList = this.giftData
      }
      if (contrastObj(this.form, this.oldForm) ||
        contrastList(getGoodsList, this.oldGoodsList) ||
        contrastList(getGiftList, this.oldGiftList) ||
        contrastList(getFeeList, this.oldFeesList) ||
        contrastList(this.bankOfDepositData, this.oldUploadList)
      ) {
        this.$confirm("数据发生变化未有提交记录, 是否保存?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.editCustomer(false, '到货')
        }).catch(() => {
          this.$message.info('已取消')
        })
      } else {
        if (this.goodsActives == 'gift') {
          this.form.deliveryItemsList = this.goodsShowData.concat(this.contactsData)
        } else {
          this.form.deliveryItemsList = this.goodsShowData.concat(this.giftData)
        }
        this.pageLoading = true
        this.saveLoading = true
        this.saveActives = ''
        confirmArrival(this.form).then(res => {
          this.$message.success('已确认到货')
          this.queryData(this.form.id)
        }).catch(() => {
          this.pageLoading = false
          this.saveLoading = false
        })
      }
    },
    // 撤销到货
    cancelArrival() {
      if (this.goodsActives == 'gift') {
        this.form.deliveryItemsList = this.goodsShowData.concat(this.contactsData)
      } else {
        this.form.deliveryItemsList = this.goodsShowData.concat(this.giftData)
      }
      this.pageLoading = true
      this.saveActives = ''
      cancelArrival(this.form).then(res => {
        this.$message.success('撤销到货成功')
        this.queryData(this.form.id)
      }).catch(() => {
        this.pageLoading = false
      })
    },
    // 导入销售明细
    importMarket(list) {
      list.forEach(item => {
        item.cname = item.cname
        this.$set(item, 'specificationAndModel', item.itemType)
        if (this.goodsActives == 'goods') {
          this.$set(item, 'deliveryAmount', item.amount)
        } else {
          this.$set(item, 'deliveryAmount', 0)
        }
        this.$set(item, 'actualQuantity', item.orderQuantity)
        this.$set(item, 'inventoryNumber', item.storageQuantity)
        this.$set(item, 'integral', 0)
        this.$set(item, 'orgOrderNo', this.form.orgOrderNo)
        this.$set(item, 'srcOrderNo', this.form.srcOrderNo)
        this.$set(item, 'arrivalQuantity', item.actualQuantity)
        this.$set(item, "srcId", item.id)
        this.$set(item, "purchaseTotalAmount", (Number(item.purchaseAmount) * Number(item.actualQuantity)))
        item.purchaseTotalAmount = item.purchaseTotalAmount.toFixed(2)
        if (this.goodsActives == "goods") {
          this.$set(item, 'goodType', 0)
        } else {
          this.$set(item, 'goodType', 1)
        }
        delete item.id
        delete item.createTime
        delete item.createUser
        delete item.pid
        this.arrivalQuantityChange(item)
        this.$refs.crudContact.rowCellAdd(item);
        this.arrivalQuantityChange(item)
      })
      this.marketDialog = false;
    },
    // 关闭销售弹窗
    closeMarkeDialog() {
      this.marketDialog = false;
    },
    // 保存列设置
    async saveColumn(name) {
      if (name == 'goods') {
        const inSave = await this.saveColumnData(
          this.getColumnName(21),
          this.customerContact
        );
        if (inSave) {
          this.$message.success("保存成功");
          //关闭窗口
          this.$refs.crudContact.$refs.dialogColumn.columnBox = false;
        }
      } else if (name === 'fees') {
        const inSave = await this.saveColumnData(
          this.getColumnName(22),
          this.advantageProject
        );
        if (inSave) {
          this.$message.success("保存成功");
          //关闭窗口
          this.$refs.crudProject.$refs.dialogColumn.columnBox = false;
        }
      }
    },
    async resetColumn() {
      this.customerContact = customerContact
      const inSave = await this.delColumnData(
        this.getColumnName(21),
        customerContact
      );
      if (inSave) {
        this.$message.success("重置成功");
        //关闭窗口
        this.$refs.crudContact.$refs.dialogColumn.columnBox = false;
      }
    },
    // 商品表格加色
    goodsRowClassName({row, column, rowIndex, columnIndex}) {
      if (Number(row.actualQuantity) > Number(row.inventoryNumber) && column.property == 'inventoryNumber') {
        return "color: #fff;background:#a4cf57"
      }
      return '';
    },
    // 库存刷新
    resetStock() {
      this.contactsData.forEach(item => {
        selectGoodsNum({
          goodsId: item.itemId,
          itemType: item.itemType? item.itemType: item.typeno,
          tradeType: 'GN',
          storageId: this.form.storageId
        }).then(res => {
          item.inventoryNumber = res.data.data
        })
      })
      this.$message.success('刷新成功')
    },
    // 商品信息标签页切换
    handleClick(data) {
      if (this.saveActives == data.name) return
      this.saveActives = data.name
      this.goodsDisabled = true
      if (data.name == 'goods') {
        this.giftData = this.goodsShowData
        // 显示
        this.customerContact.column.forEach(item => {
          if (item.prop == 'integralMultiples') item.label = '积分倍数'
          if (item.prop == 'integral') item.label = '赠送积分'
          if (item.prop == 'actualQuantity') item.label = '出库数量'
          if (item.prop == 'priceType' || item.prop == 'code' || item.prop == 'typeno' || item.prop == 'corpId'
            || item.prop == 'packageRemarks' || item.prop == 'invoiceWeight'
            || item.prop == 'inventoryNumber' || item.prop == 'inventoryAmount'
            || item.prop == 'arrivalQuantity'
          ) {
            item.hide = false;
            item.showColumn = true;
          }
        })
        this.goodsShowData = this.contactsData;
        setTimeout(() => {
          this.goodsDisabled = false
        },500)
      } else {
        // 隐藏字段
        this.contactsData = this.goodsShowData
        this.customerContact.column.forEach(item => {
          if (item.prop == 'integralMultiples') item.label = '积分单价'
          if (item.prop == 'integral') item.label = '兑换积分'
          if (item.prop == 'actualQuantity') item.label = '数量'
          if (item.prop == 'priceType' || item.prop == 'code' || item.prop == 'typeno' || item.prop == 'corpId'
            || item.prop == 'packageRemarks' || item.prop == 'invoiceWeight' || item.prop == 'inventoryNumber'
            || item.prop == 'inventoryAmount' || item.prop == 'arrivalQuantity'
          ) {
            item.hide = true;
            item.showColumn = false;
          }
        })
        this.goodsShowData = this.giftData;
        setTimeout(() => {
          this.goodsDisabled = false
        },500)
      }
    },
    // 报表
    openReport() {
      this.switchDialog =! this.switchDialog;
    },
    onClose(val) {
      this.switchDialog = val;
    },
    //费用明细回调
    beforeFinance(feesData,callback){
      this.advantageProjectData = feesData;
      let params = {}
      //暂时默认通过  之后优化
      params.valid = true
      params.parentId = this.form.id
      params.srcOrderno = this.form.orderNo
      callback(params)
    },
    // 编辑
    editHandle() {
      const data = {
        moduleName: 'fh',
        tableName: 'business_delivery',
        billId: this.form.id,
        no: localStorage.getItem('browserID'),
        billNo: this.form.sysNo
      }
      this.saveLoading = true
      this.checkLock(data).then(res => {
        if (res.data.code == 200) {
          this.onLock(data).then(response => {
            this.saveActives = ''
            this.queryData(this.form.id)
            this.inDetailsKey(this.$route.name, {
              moduleName: 'fh',
              tableName: 'business_delivery',
              billId: this.form.id,
            })
            this.detailData.seeDisabled = false;
          })
        }
      }).catch(error => {
      }).finally(() => {
        this.saveLoading = false
      })
    },
    returnBack(data) {
      if (data.belongtocompany) {
        // this.form.salesCompany = data.belongtocompany
      }
    },
    getGSName(row) {
      this.form.belongCompany = row.cname
    },
  }
}
</script>

<style lang="scss" scoped>
//.customer-head {
//  position: fixed;
//  top: 105px;
//  width: 100%;
//  margin-left: -10px;
//  height: 62px;
//  background: #ffffff;
//  box-shadow: 0 4px 12px 0px rgba(232, 232, 235, 1);
//  z-index: 999;
//}
//
//.customer-back {
//  cursor: pointer;
//  line-height: 62px;
//  font-size: 16px;
//  color: #323233;
//  font-weight: 400;
//}

.back-icon {
  line-height: 64px;
  font-size: 20px;
  margin-right: 8px;
}

//.add-customer-btn {
//  position: fixed;
//  right: 36px;
//  top: 115px;
//}

::v-deep .el-form-item {
  margin-bottom: 0;
}

.el-dialogDeep {
  ::v-deep .el-dialog {
    margin: 1vh auto 0 !important;
    padding-bottom: 10px !important;

    .el-dialog__body, .el-dialog__footer {
      padding-bottom: 0 !important;
      padding-top: 0 !important;
    }
  }
}

.print-div {
  color: #000;
}

.print_table {
  table {
    border-right: 1px solid #000;
    border-bottom: 1px solid #000;
    font-size: 12px;
    margin-bottom: 5px;
  }

  table td {
    border-left: 1px solid #000;
    border-top: 1px solid #000;
    vertical-align: middle;
    padding: 2px;
    text-align: center;
  }
}

.table {
  border-collapse: collapse;
  border-spacing: 0;
  background-color: transparent;
  display: table;
  width: 99%;
  max-width: 100%;
  margin: 0 auto;
}

.table td {
  text-align: left;
  vertical-align: middle;
  font-size: 14px;
  color: #000000;
  padding: 10.5px 0 10.5px 30px;
  //border: 1px solid #000;
}
::v-deep .el-form-item {
  margin-bottom: 0;
}

::v-deep .el-form-item__content{
  line-height: 32px;
}
</style>
