<template>
  <div>
    <div class="customer-head">
      <div class="customer-back">
        <el-button type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left" @click="backToList(0)"
          >返回列表
        </el-button>
      </div>
      <div class="add-customer-btn">
        <el-button class="el-button&#45;&#45;small-yh" type="primary" size="small" v-if="editButton" @click="confirmEditing">编辑 </el-button>
        <el-button class="el-button--small-yh" type="primary" size="small" :disabled="isSave" @click="editCustomer">保存数据 </el-button>
        <el-button
          class="el-button--small-yh"
          type="warning"
          size="small"
          v-if="form.statusName == '确认调拨'"
          @click="revoke"
          :disabled="isSave || form.status == '是'"
          >撤销调拨
        </el-button>
        <el-button class="el-button--small-yh" type="success" size="small" style="margin-left: 6px;" v-else @click="complete" :disabled="isSave"
          >确认调拨
        </el-button>
        <el-button
          v-if="form.statusName == '确认调拨' && form.status == '否'"
          class="el-button--small-yh"
          type="info"
          size="small"
          style="margin-left: 6px;"
          @click="confirmComplete"
          :disabled="isSave"
          >已出仓
        </el-button>
      </div>
    </div>
    <div style="margin-top: 50px">
      <trade-card title="基础信息">
        <avue-form :option="optionForm" v-model="form" ref="form">
          <template slot="storageName">
            <dic-select
              v-model="form.storageName"
              placeholder="调出仓库"
              label="cname"
              res="records"
              :disabled="isSave || isAddDisabled || form.shipItemsList.length"
              url="/blade-sales-part/storageDesc/list?current=1&size=5"
              :filterable="true"
              :remote="true"
              dataName="cname"
              @selectChange="dicChange('storageName', $event)"
            ></dic-select>
          </template>
          <template slot="callInStorageName">
            <dic-select
              v-model="form.callInStorageName"
              placeholder="调入仓库"
              label="cname"
              res="records"
              :disabled="isSave || isAddDisabled || form.shipItemsList.length"
              url="/blade-sales-part/storageDesc/list?current=1&size=5"
              :filterable="true"
              :remote="true"
              dataName="cname"
              @selectChange="dicChange('callInStorageName', $event)"
            ></dic-select>
          </template>
        </avue-form>
      </trade-card>
      <trade-card title="明细信息">
        <avue-crud
          :option="optionContacts"
          v-model="formContacts"
          ref="formContacts"
          :data="form.shipItemsList"
          :key="key"
          @row-save="rowSave"
          @row-update="rowUpdate"
          @selection-change="selectionContacts"
          @resetColumn="resetColumnTwo('formContacts', 'optionContacts', 'optionContactsBack', 430)"
          @saveColumn="saveColumnTwo('formContacts', 'optionContacts', 'optionContactsBack', 430)"
        >
          <template slot-scope="{ scope, row }" slot="menuLeft">
            <el-button type="primary" icon="el-icon-printer" size="small" @click="adddiailsfun">录入明细</el-button>
            <el-button type="primary" icon="el-icon-printer" size="small" @click="handlePrint">打印</el-button>
            <el-popover width="800" trigger="click" placement="right">
              <avue-crud :data="inventoryData" :option="inventoryOption">
                <template slot-scope="{ row }" slot="menu">
                  <el-button
                    type="text"
                    icon="el-icon-refresh"
                    size="small"
                    :disabled="row.storageId != form.storageId"
                    @click.stop="synchronous(row)"
                    >更新库存
                  </el-button>
                </template>
              </avue-crud>
              <el-button type="primary" plain size="small" slot="reference" @click="viewInventory" :disabled="selectionMultilist.length != 1"
                >同步库存</el-button
              >
            </el-popover>
          </template>
          <template slot-scope="{ type, size, row, index, disabled }" slot="menu">
            <el-button
              v-if="reservoirArea == 1 && row.historyList.length"
              :size="size"
              :disabled="!row.id || disabled || isAddDisabled"
              type="text"
              @click="rowDelArea(row, index)"
            >
              清空库区
            </el-button>
            <el-button v-if="reservoirArea == 1 && row.historyList.length" :size="size" :disabled="!row.id" type="text" @click="rowArea(row, index)">
              查看库区
            </el-button>
            <el-button
              v-if="reservoirArea == 1 && row.historyList.length == 0"
              :size="size"
              :disabled="!row.id || disabled || isAddDisabled"
              type="text"
              @click="rowArea(row, index)"
            >
              选择库区
            </el-button>
            <el-button
              v-if="reservoirArea != 1"
              :size="size"
              :disabled="disabled || isAddDisabled"
              :type="type"
              :icon="row.$cellEdit ? 'el-icon-plus' : 'el-icon-edit'"
              @click="rowEdit(row, index)"
            >
              {{ row.$cellEdit ? "保存" : "编辑" }}
            </el-button>
            <el-button icon="el-icon-delete" :size="size" :disabled="disabled || isDisabled" :type="type" @click="rowDelBox(row, index)"
              >删除
            </el-button>
          </template>
          <template slot="goodsNum" slot-scope="{ row }">
            <el-input-number
              v-if="row.$cellEdit && whetherFinancing != 1"
              v-model="row.goodsNum"
              size="small"
              :controls="false"
              :precision="0"
              style="width: 100%"
              @change="calculator2(row)"
            />
            <span v-else>{{ row.goodsNum }}</span>
          </template>
          <template slot="sendNumFinancing" slot-scope="{ row }">
            <el-input-number
              v-if="row.$cellEdit"
              v-model="row.sendNumFinancing"
              size="small"
              :controls="false"
              :precision="0"
              style="width: 100%"
              @change="calculator(row)"
            />
            <span v-else>{{ row.sendNumFinancing }}</span>
          </template>
          <template slot="sendNumHave" slot-scope="{ row }">
            <el-input-number
              v-if="row.$cellEdit"
              v-model="row.sendNumHave"
              size="small"
              :controls="false"
              :precision="0"
              style="width: 100%"
              @change="calculator(row)"
            />
            <span v-else>{{ row.sendNumHave }}</span>
          </template>
          <template slot="dot" slot-scope="{ row }">
            <!--使用allow-create属性即可通过在输入框中输入文字来创建新的条目。注意此时filterable必须为真。-->
            <!--本例还使用了default-first-option属性， 在该属性打开的情况下，按下回车就可以选中当前选项列表中的第一个选项，-->
            <!--无需使用鼠标或键盘方向键进行定位。-->
            <!--allow-create filterable default-first-option-->
            <el-select
              v-if="row.$cellEdit"
              v-model="row.dot"
              size="small"
              filterable
              default-first-option
              @focus="picihaolistfun(row.goodsId)"
              @change="picihaolistChangefun($event, row)"
            >
              <el-option v-for="(item, index) in picihaolist" :key="index" :label="item.dot" :value="item.dot"></el-option>
            </el-select>
            <span v-else>{{ row.dot }}</span>
          </template>
          <template slot="price" slot-scope="{ row }">
            <el-input-number v-if="row.$cellEdit" v-model="row.price" size="small" :controls="false" style="width: 100%" @change="calculator2(row)" />
            <span v-else>{{ row.price }}</span>
          </template>
        </avue-crud>
      </trade-card>
      <view-area ref="viewArea" @areaData="areaData" :disabled="disabled || isAddDisabled"></view-area>
      <containerTitle title="上传附件"></containerTitle>
      <c-upload
        v-loading="loadingBtn"
        typeUpload="LT"
        :disabled="isAddDisabled"
        deleteUrl="/api/trade-purchase/woodHarvestingCloud/removeByFileId"
        :data="filesList"
        display
        :enumerationValue="35.1"
      ></c-upload>
      <report-dialog :switchDialog="switchDialog" :reportId="form.id" @onClose="onClose()"></report-dialog>
      <dialogAssembly ref="dialogAssemblyRef" :form="form" @tableDataHandle="tableDataHandle"> </dialogAssembly>
    </div>
  </div>
</template>

<script>
import {
  getDetails,
  tradingBox,
  transferAllocateSubmit,
  confirmTransferAllocate,
  revokeTransferAllocate,
  itemRemove,
  confirmComplete
} from "@/api/tirePartsMall/salesManagement/outboundWorkOrder";
import { dateFormat } from "@/util/date";
import reportDialog from "@/components/report-dialog/main";
import { dotList } from "@/api/tirePartsMall/purchasingManagement/warehouseEntryOrder";
import { isProcurement } from "@/api/basicData/configuration";
import dialogAssembly from "@/views/tirePartsMall/salesManagement/outboundWorkOrderL/dialogAssembly.vue";
import { getKh } from "@/api/tirePartsMall/salesManagement/saleOrder";
import { getList as inventoryList } from "@/api/tirePartsMall/inventory";
import viewArea from "./components/viewArea.vue";
import dicSelect from "@/components/dicSelect/main";

export default {
  name: "detailsPage",
  data() {
    return {
      reservoirArea: 0,
      selectionMultilist: [],
      inventoryData: [],
      inventoryOption: {
        header: false,
        menu: true,
        menuWidth: 90,
        editBtn: false,
        delBtn: false,
        column: [
          {
            label: "商品名称",
            prop: "cname",
            overHidden: true
          },
          {
            label: "仓库",
            prop: "storageName",
            overHidden: true
          },
          {
            label: "结余数量",
            prop: "balanceQuantity",
            overHidden: true
          },
          {
            label: "结余数量（融资）",
            prop: "balanceQuantityFinancing",
            overHidden: true
          },
          {
            label: "结余数量（自有）",
            prop: "balanceQuantityHave",
            overHidden: true
          },
          {
            label: "批次号",
            prop: "dot",
            overHidden: true
          }
        ]
      },
      whetherFinancing: 0,
      picihaolist: [], // 批次号数据
      tableData: [],
      // 上传附件的需要参数
      loadingBtn: false,
      filesList: [],

      switchDialog: false,
      activeName: "sale_detail",
      editButton: true,
      isSave: true,
      disabled: false,
      isDisabled: false,
      isAddDisabled: false,
      form: {
        shipItemsList: [],
        shipVOList: [],
        historyList: []
      },
      key: 0,
      optionForm: {
        disabled: false,
        menuBtn: false,
        span: 8,
        column: [
          //     {
          //   label: '业务对象',
          //   disabled: false,
          //   prop: "customerId",
          //   type: 'select',
          //   props: {
          //     label: 'cname',
          //     value: 'id'
          //   },
          //   dicUrl: '/api/blade-sales-part/corpsDesc/listAll?corpType=KH&enableOrNot=1',
          //     dicData:[],
          //   rules: [{
          //     required: true,
          //     message: " ",
          //     trigger: "blur"
          //   }]
          // },
          {
            label: "调出仓库",
            prop: "storageName",
            disabled: true,
            // type: "select",
            // props: {
            //   label: "cname",
            //   value: "id"
            // },
            // dicUrl: "/api/blade-sales-part/storageDesc/listAll",
            rules: [
              {
                required: true,
                message: " ",
                trigger: "blur"
              }
            ]
          },
          {
            label: "调入仓库",
            prop: "callInStorageName",
            disabled: true,
            // type: "select",
            // props: {
            //   label: "cname",
            //   value: "id"
            // },
            // dicUrl: "/api/blade-sales-part/storageDesc/listAll",
            rules: [
              {
                required: true,
                message: " ",
                trigger: "blur"
              }
            ]
          },
          {
            label: "库管",
            prop: "stockClerkId",
            type: "select",
            disabled: true,
            props: {
              label: "realName",
              value: "id"
            },
            dicUrl: "/api/blade-user/stockClerkList",
            rules: [
              {
                required: true,
                message: " ",
                trigger: "blur"
              }
            ]
          },
          {
            label: "业务日期",
            prop: "businesDate",
            searchProp: "businesDateList",
            disabled: true,
            type: "datetime",
            value: dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss"),
            format: "yyyy-MM-dd HH:mm",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            rules: [
              {
                required: true,
                message: "",
                trigger: "blur"
              }
            ]
          },
          {
            label: "调拨单号",
            prop: "billno",
            disabled: true
          },
          {
            label: "调拨数量",
            prop: "goodsTotalNum",
            disabled: true
          },
          {
            label: "备注",
            prop: "remarks",
            type: "textarea",
            disabled: false,
            span: 24,
            minRows: 1
          }
        ]
      },
      formContacts: {},
      optionContacts: {},
      optionContactsBack: {
        align: "center",
        index: true,
        addBtnText: "录入明细",
        updateBtnText: "保存",
        refreshBtn: false,
        dialogDrag: true,
        addBtn: false,
        span: 8,
        height: 300,
        addRowBtn: false,
        editBtn: false,
        delBtn: false,
        menuWidth: 250,
        dialogTop: 25,
        dialogWidth: "80%",
        showSummary: true,
        tip: false,
        selection: true,
        sumColumnList: [
          {
            name: "goodsNum",
            type: "sum"
          },
          {
            name: "sendNum",
            type: "sum"
          }
        ],
        column: [
          {
            label: "商品名称",
            prop: "goodsName",
            width: 200,
            overHidden: true,
            hide: false
          },
          {
            label: "商品编码",
            disabled: true,
            prop: "goodsNo",
            overHidden: true,
            width: 100
          },
          {
            label: "批次号",
            prop: "dot",
            overHidden: true,
            width: 160,
            type: "select",
            // disabled: true,
            dicData: [],
            props: {
              label: "dot",
              value: "dot"
            },
            dicUrl: "/api/blade-sales-part/stockDesc/dotList"
          },
          {
            label: "库存数量",
            prop: "inventory",
            overHidden: true,
            disabled: true
          },
          {
            label: "参考库存融资",
            prop: "inventoryFinancing",
            overHidden: true,
            width: 120,
            disabled: true,
            hide: true,
            showColumn: false
          },
          {
            label: "参考库存自有",
            prop: "inventoryHave",
            overHidden: true,
            width: 120,
            disabled: true,
            hide: true,
            showColumn: false
          },
          {
            label: "调拨数量",
            prop: "goodsNum",
            overHidden: true,
            disabled: false
          },
          {
            label: "调拨融资",
            prop: "sendNumFinancing",
            overHidden: true,
            disabled: false,
            hide: true,
            showColumn: false
          },
          {
            label: "调拨自有",
            prop: "sendNumHave",
            overHidden: true,
            disabled: false,
            hide: true,
            showColumn: false
          },
          {
            label: "单价",
            prop: "price",
            overHidden: true,
            disabled: true
          },
          {
            label: "品牌",
            prop: "brandName",
            disabled: false,
            width: 100,
            overHidden: true
          },
          {
            label: "规格型号",
            prop: "propertyName",
            overHidden: true,
            disabled: true,
            width: 100
          },
          {
            label: "花纹",
            prop: "pattern",
            overHidden: true,
            disabled: true,
            width: 100
          },
          {
            label: "商品描述",
            prop: "goodsDescription",
            overHidden: true,
            disabled: true
          },
          {
            label: "单位",
            prop: "units",
            overHidden: true,
            type: "select",
            disabled: true,
            props: {
              label: "dictValue",
              value: "dictValue"
            },
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=unit"
          },
          {
            label: "备注",
            prop: "remarks",
            overHidden: true
          }
        ]
      },
      optionContactsBack2: {
        disabled: false,
        border: true,
        align: "center",
        index: true,
        addBtnText: "添加商品",
        updateBtnText: "保存",
        refreshBtn: false,
        dialogDrag: true,
        addBtn: false,
        span: 8,
        height: 500,
        // 添加
        addRowBtn: false,
        // 保存按钮
        editBtn: false,
        // 航编辑开启
        cellBtn: true,
        rowKey: "ids",
        delBtn: false,
        menuWidth: 140,
        dialogTop: 25,
        dialogWidth: "80%",
        summaryText: this.$t("land118n.total"),
        showSummary: true,
        selection: true,
        sumColumnList: [
          {
            name: "goodsNum",
            type: "sum"
          },
          {
            name: "price",
            type: "sum",
            decimals: 2
          },
          {
            name: "sendNum",
            type: "sum",
            decimals: 2
          },
          {
            name: "outGoodsTotalShipNum",
            type: "sum",
            decimals: 2
          },
          {
            name: "outGoodsTotalShipAmount",
            type: "sum",
            decimals: 2
          },
          {
            name: "subTotalMoney",
            type: "sum",
            decimals: 2
          },
          {
            name: "returnsNumber",
            type: "sum"
          },
          {
            name: "returnsAmount",
            type: "sum"
          },
          {
            name: "primaryGoodsTotalNum",
            type: "sum"
          },
          {
            name: "inventory",
            type: "sum"
          },
          {
            name: "rebatePrice",
            type: "sum",
            decimals: 2
          },
          {
            name: "rebateCostprie",
            type: "sum",
            decimals: 2
          },
          {
            name: "rebateProfit",
            type: "sum",
            decimals: 2
          },
          {
            name: "primaryGoodsTotalAmount",
            type: "sum",
            decimals: 2
          }
        ],
        column: [
          {
            label: "商品名称",
            prop: "goodsId",
            width: 200,
            disabled: false,
            remote: true,
            hide: true,
            overHidden: true,
            type: "select",
            // dicData: [],
            props: {
              label: "cname",
              value: "id"
            },
            // dicUrl: '/api/blade-sales-part/goodsDesc/goodsListAll?cname={{key}}'
            dicUrl: "/api/blade-sales-part/goodsDesc/list?current=1&size=10&cname={{key}}&enableOrNot=1"
            // dicUrl: "/api/blade-sales-part/goodsDesc/goodsListXs?cname={{key}}"
          },
          {
            label: "商品名称",
            prop: "goodsName",
            width: 200,
            disabled: false,
            remote: true,
            overHidden: true
          },
          {
            label: "数量",
            prop: "goodsNum",
            overHidden: true,
            disabled: false,
            cell: true,
            width: 100,
            rules: [
              {
                required: true,
                message: " ",
                trigger: "blur"
              },
              {
                validator: (rule, value, callback) => {
                  console.log(this.formContacts.inventory);
                  if (value < 0) {
                    callback(new Error("数量不能小于0"));
                  } else {
                    callback();
                  }
                },
                trigger: "blur"
              }
            ]
          },
          {
            label: "价格",
            prop: "price",
            overHidden: true,
            width: 100,
            disabled: false,
            cell: true,
            rules: [
              {
                required: true,
                message: " ",
                trigger: "blur"
              },
              {
                validator: (rule, value, callback) => {
                  if (value < 0) {
                    callback(new Error("价格不能小于0"));
                  } else {
                    callback();
                  }
                },
                trigger: "blur"
              }
            ]
          },
          {
            label: "库存",
            prop: "inventory",
            overHidden: true,
            width: 100
          },
          {
            label: "批次号",
            prop: "dot",
            cell: true,
            width: 120,
            type: "select",
            disabled: true,
            allowCreate: true,
            filterable: true,
            dicData: [],
            props: {
              label: "dot",
              value: "dot"
            },
            dicUrl: "/api/blade-sales-part/stockDesc/dotList",
            overHidden: true
          },
          {
            label: "小计",
            prop: "subTotalMoney",
            overHidden: true,
            width: 100,
            disabled: true,
            editDisplay: false,
            addDisplay: false
          },
          {
            label: "商品编码",
            prop: "goodsNo",
            overHidden: true,
            disabled: false,
            width: 100
          },
          {
            label: "品牌",
            prop: "brandName",
            disabled: false,
            width: 100,
            overHidden: true
          },
          {
            label: "规格型号",
            prop: "propertyName",
            overHidden: true,
            disabled: false,
            width: 100
          },
          {
            label: "花纹",
            prop: "pattern",
            overHidden: true,
            disabled: false,
            width: 100
          },
          {
            label: "商品描述",
            prop: "goodsDescription",
            disabled: false,
            overHidden: true,
            width: 100
          },
          {
            label: "单位",
            prop: "units",
            type: "select",
            disabled: false,
            props: {
              label: "dictValue",
              value: "dictValue"
            },
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=unit",
            overHidden: true,
            width: 100
          },
          {
            label: "订单数量",
            prop: "primaryGoodsTotalNum",
            overHidden: true,
            width: 100,
            disabled: true,
            editDisplay: false,
            addDisplay: false
          },
          {
            label: "订单金额",
            prop: "primaryGoodsTotalAmount",
            overHidden: true,
            width: 100,
            disabled: true,
            editDisplay: false,
            addDisplay: false
          },
          {
            label: "入库数量",
            prop: "sendNum",
            overHidden: true,
            width: 100,
            disabled: true,
            editDisplay: false,
            addDisplay: false
          },
          {
            label: "出库数量",
            prop: "outGoodsTotalShipNum",
            overHidden: true,
            width: 100,
            disabled: true,
            editDisplay: false,
            addDisplay: false
          },
          {
            label: "出库金额",
            prop: "outGoodsTotalShipAmount",
            overHidden: true,
            width: 100,
            disabled: true,
            editDisplay: false,
            addDisplay: false
          },
          {
            label: "原始数量",
            prop: "primaryGoodsTotalNum",
            overHidden: true,
            width: 100,
            disabled: true,
            editDisplay: false,
            addDisplay: false
          },
          {
            label: "原始金额",
            prop: "primaryGoodsTotalAmount",
            overHidden: true,
            width: 100,
            disabled: true,
            editDisplay: false,
            addDisplay: false
          },
          {
            label: "返利后单价",
            prop: "rebatePrice",
            overHidden: true,
            width: 100,
            cell: true
          },
          {
            label: "返利后成本价",
            prop: "rebateCostprie",
            overHidden: true,
            width: 100,
            disabled: true,
            editDisplay: false,
            addDisplay: false
          },
          {
            label: "返利后利润",
            prop: "rebateProfit",
            overHidden: true,
            width: 100,
            disabled: true,
            editDisplay: false,
            addDisplay: false
          },
          // {
          //     label: '退货数量',
          //     prop: "returnsNumber",
          //     overHidden: true,
          //     width: 100,
          //     disabled: true,
          // },
          // {
          //     label: '退货金额',
          //     prop: "returnsAmount",
          //     overHidden: true,
          //     width: 100,
          //     disabled: true,
          // },
          // {
          //     label: '利润',
          //     prop: 'profit',
          //     overHidden: true,
          //     width: 100
          // },

          // {
          //     label: '返利',
          //     prop: 'thisAmount',
          //     overHidden: true,
          //     width: 100
          // },
          // {
          //     label: '成本',
          //     prop: 'costprie',
          //     overHidden: true,
          //     width: 100,
          //     disabled: true,
          //     editDisplay: false,
          //     addDisplay: false

          // },
          // {
          //     label: '毛利',
          //     prop: 'grossProfit',
          //     overHidden: true,
          //     width: 100,
          //     disabled: true,
          //     editDisplay: false,
          //     addDisplay: false
          // },
          {
            label: "备注",
            prop: "remarks",
            overHidden: true,
            width: 100,
            disabled: false
          }
        ]
      }
    };
  },
  components: {
    reportDialog,
    dialogAssembly,
    viewArea,
    dicSelect
  },
  props: {
    onLoad: Object,
    detailData: Object
  },
  async created() {
    this.optionContacts = await this.getColumnData(this.getColumnName(430), this.optionContactsBack);
    isProcurement({ param: "whether.model" }).then(res => {
      if (res.data.data == 1) {
        this.findObject(this.optionContacts.column, "pattern").label = "规格型号1";
      }
    });
    isProcurement({ param: "whether.financing" }).then(res => {
      if (res.data.data == 1) {
        this.whetherFinancing = res.data.data;
        this.findObject(this.optionContacts.column, "inventoryFinancing").hide = false;
        this.findObject(this.optionContacts.column, "inventoryFinancing").showColumn = true;
        this.findObject(this.optionContacts.column, "inventoryHave").hide = false;
        this.findObject(this.optionContacts.column, "inventoryHave").showColumn = true;
        this.findObject(this.optionContacts.column, "sendNumFinancing").hide = false;
        this.findObject(this.optionContacts.column, "sendNumFinancing").showColumn = true;
        this.findObject(this.optionContacts.column, "sendNumHave").hide = false;
        this.findObject(this.optionContacts.column, "sendNumHave").showColumn = true;
      }
    });
    isProcurement({ param: "reservoir.area" }).then(res => {
      this.reservoirArea = res.data.data;
    });
    this.key++;
    if (this.detailData.id) {
      this.refresh();
    } else {
      this.optionForm.column.forEach(item => {
        if (item.prop == "remarks" || item.prop == "stockClerkId" || item.prop == "businesDate") {
          item.disabled = false;
        } else {
          item.disabled = true;
        }
      });
      this.editButton = false;
      this.isSave = false;
    }
    this.$store.commit("DOMIO_IN_ALLOCATW");
  },
  activated() {
    if (this.detailData.id) {
      this.refresh();
    }
    this.$store.commit("DOMIO_IN_ALLOCATW");
  },
  methods: {
    dicChange(name, row) {
      if (name == "storageName") {
        if (row) {
          this.form.storageId = row.id;
        } else {
          this.form.storageId = null;
          this.form.storageName = row.id;
        }
      }
      if (name == "callInStorageName") {
        if (row) {
          this.form.callInStorageId = row.id;
          this.form.remarks = row.remarks;
        } else {
          this.form.callInStorageId = null;
          this.form.callInStorageName = row.id;
        }
      }
    },
    rowDelArea(row, index) {
      if (row.historyList.filter(item => item.id).length) {
        this.$confirm("是否撤销库区?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          let ids = [];
          for (let item of row.historyList) {
            ids.push(item.id);
          }
          itemRemove({ ids: ids.join(",") }).then(res => {
            row.historyList = [];
            row.dot = null;
            row.sendNum = 0;
            row.sendNumFinancing = 0;
            row.sendNumHave = 0;
          });
        });
      } else {
        row.historyList = [];
        row.dot = null;
        row.sendNum = 0;
        row.sendNumFinancing = 0;
        row.sendNumHave = 0;
      }
    },
    rowArea(row, index) {
      this.$refs.viewArea.openDialog(this.form, row, index);
    },
    areaData(row, index) {
      console.log(row, index);
      this.form.shipItemsList[index].dot = row.dot;
      this.form.shipItemsList[index].goodsNum = row.sendNum;
      this.form.shipItemsList[index].sendNumFinancing = row.sendNumFinancing;
      this.form.shipItemsList[index].sendNumHave = row.sendNumHave;
      this.form.shipItemsList[index].historyList = row.historyList;
    },
    viewInventory() {
      inventoryList({
        cname: this.selectionMultilist[0].goodsName,
        dot: this.selectionMultilist[0].dot,
        storageId: this.form.storageId
      }).then(res => [(this.inventoryData = res.data.data.records)]);
    },
    synchronous(row) {
      this.form.shipItemsList.forEach(e => {
        if (e.goodsName == this.selectionMultilist[0].goodsName) {
          e.inventory = row.balanceQuantity;
          e.inventoryFinancing = row.balanceQuantityFinancing;
          e.inventoryHave = row.balanceQuantityHave;
        }
      });
    },
    selectionContacts(list) {
      this.selectionMultilist = list;
    },
    // 撤销调拨
    revoke() {
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "加载中",
            spinner: "el-icon-loading",
            background: "rgba(255,255,255,0.7)"
          });
          revokeTransferAllocate({
            ...this.form,
            bizTypeName: "DBGD"
          })
            .then(res => {
              this.$message.success("撤销成功");
              this.refresh(res.data.data.id);
              loading.close();
            })
            .finally(() => {
              loading.close();
            });
        }
      });
    },
    confirmComplete() {
      this.$confirm("调拨单是否确认完成?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: "加载中",
          spinner: "el-icon-loading",
          background: "rgba(255,255,255,0.7)"
        });
        confirmComplete({
          ...this.form,
          bizTypeName: "DBGD"
        })
          .then(res => {
            this.$message.success("撤销成功");
            this.refresh(this.form.id);
          })
          .finally(() => {
            loading.close();
          });
      });
    },
    rowEdit(row, index) {
      this.$set(row, "$cellEdit", !row.$cellEdit);
      // if (this.form.statusName == '录入') {
      //   this.optionContactsBack.column.forEach(its => {
      //     if (its.prop == 'dot') {
      //       this.$set(its, 'disabled', false)
      //     }
      //   })
      // }
      // console.log('this.formContacts.goodsId', this.formContacts.goodsId);
      // dotList({
      //   storageId: this.form.storageId,
      //   goodsId: row.goodsId
      // }).then(res => {
      //   this.findObject(this.optionContactsBack.column, "dot").dicData = res.data.data
      // })
      // this.$refs.formContacts.rowEdit(row, index)
    },
    // 批次号获取数据
    picihaolistfun(goodsId) {
      dotList({
        storageId: this.form.storageId,
        goodsId: goodsId
      }).then(res => {
        this.picihaolist = res.data.data;
      });
    },
    // 批次号
    picihaolistChangefun(value, row) {
      for (let item of this.picihaolist) {
        if (item.dot == value) {
          this.$set(row, "inventory", item.balanceQuantity);
        }
      }
    },
    // 确认调拨
    complete() {
      if (!this.form.id) {
        this.$message.warning("请先保存数据");
        return;
      }
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          if (this.whetherFinancing == 1) {
            for (let item of this.form.shipItemsList) {
              if (item.historyList.length == 0) {
                return this.$message.error("请维护出库明细的库区");
              }
              if (!item.dot) {
                return this.$message.error("请维护明细信息的批次号");
              }
            }
          }
          const loading = this.$loading({
            lock: true,
            text: "加载中",
            spinner: "el-icon-loading",
            background: "rgba(255,255,255,0.7)"
          });
          this.form.shipItemsList.forEach(item => {
            item.goodsName = item.$goodsId;
          });
          transferAllocateSubmit({
            ...this.form,
            bizTypeName: "DBGD"
          })
            .then(res => {
              confirmTransferAllocate({
                ...this.form,
                bizTypeName: "DBGD"
              })
                .then(res => {
                  this.$message.success("调拨完成");
                  this.refresh(res.data.data.id);
                  loading.close();
                })
                .finally(() => {
                  loading.close();
                });
            })
            .catch(() => {
              loading.close();
            });
        } else {
          this.$message.error("请选择库管");
        }
      });
    },
    //修改提交触发
    editCustomer() {
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "加载中",
            spinner: "el-icon-loading",
            background: "rgba(255,255,255,0.7)"
          });
          // this.goodsName;
          transferAllocateSubmit({
            ...this.form,
            bizTypeName: "DBGD",
            filesList: this.filesList
          })
            .then(res => {
              this.$message.success("保存成功");
              this.editButton = true;
              this.refresh(res.data.data.id);
              loading.close();
            })
            .finally(() => {
              loading.close();
            });
        } else {
          return false;
        }
      });
    },
    refresh(id, type) {
      this.$set(this.optionContactsBack, "addBtn", false);
      this.$set(this.optionContacts, "addBtn", false);
      this.isDisabled = true;
      const loading = this.$loading({
        lock: true,
        text: "加载中",
        spinner: "el-icon-loading",
        background: "rgba(255,255,255,0.7)"
      });
      if (!this.detailData.id) {
        getDetails({ id: id })
          .then(res => {
            if (res.data.data.statusName == "确认调拨") {
              this.$set(this.optionForm, "disabled", true);
              this.isAddDisabled = true;
              this.optionContacts.column.forEach(item => {
                if (item.prop == "sendNum") {
                  item.disabled = true;
                }
              });
            }
            this.isAddDisabled = true;
            if (res.data.data.statusName == "录入") {
              this.isAddDisabled = true;
              this.isDisabled = true;
            }
            this.form = res.data.data;
            this.filesList = res.data.data.filesList;
            this.$nextTick(() => {
              this.$refs.formContacts.refreshTable();
            });
            loading.close();
          })
          .catch(() => {
            loading.close();
          });
      } else {
        getDetails({ id: this.detailData.id })
          .then(res => {
            if (res.data.data.statusName == "已出库") {
              this.$set(this.optionForm, "disabled", true);
              this.isAddDisabled = true;
              this.optionContacts.column.forEach(item => {
                if (item.prop == "sendNum") {
                  item.disabled = true;
                }
              });
            }
            this.isAddDisabled = true;
            if (res.data.data.statusName == "待出库") {
              this.isAddDisabled = true;
              this.isDisabled = true;
            }
            this.form = res.data.data;
            this.filesList = res.data.data.filesList;
            this.$nextTick(() => {
              this.$refs.formContacts.refreshTable();
            });
            loading.close();
          })
          .catch(() => {
            loading.close();
          });
      }
    },
    rowDelBox(row, index) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (row.id) {
          tradingBox(row.id).then(res => {
            this.form.shipItemsList.splice(index, 1);
            this.$message.success("操作成功!");
          });
        } else {
          this.form.shipItemsList.splice(index, 1);
          this.$message.success("操作成功!");
        }
      });
    },
    rowSave(form, done, loading) {
      done(form);
    },
    rowUpdate(form, index, done, loading) {
      done(form);
    },
    //打印
    handlePrint() {
      this.switchDialog = !this.switchDialog;
    },
    onClose(val) {
      this.switchDialog = val;
    },
    // 新增出库明细
    adddiailsfun() {
      if (!this.form.storageId) {
        this.$message.warning("请先选择调出仓库!");
        return;
      }
      this.$refs.dialogAssemblyRef.dialogVisible = true;
      this.$refs.dialogAssemblyRef.getAllWorkDicts();
      // this.dialogVisible = true
    },
    //编辑
    confirmEditing() {
      if (this.form.statusName == "录入") {
        this.isDisabled = false;
        this.isSave = false;
        this.$set(this.optionForm, "disabled", false);
        this.optionForm.column.forEach(item => {
          if (item.prop == "remarks" || item.prop == "stockClerkId" || item.prop == "businesDate") {
            item.disabled = false;
          } else {
            item.disabled = true;
          }
        });
        // if (this.form.shipItemsList.length != 0) {
        //   this.findObject(this.optionForm.column, "storageId").disabled = true;
        // }

        this.isAddDisabled = false;
        this.optionContactsBack.column.forEach(its => {
          if (its.prop == "dot") {
            this.$set(its, "disabled", false);
          }
        });
      } else {
        this.$set(this.optionForm, "disabled", false);
        this.isAddDisabled = true;
        this.isSave = false;
        // this.optionForm.column.forEach(item => {
        //   if (item.prop == 'remarks') {
        //     item.disabled = false
        //   } else {
        //     item.disabled = true
        //   }
        // })
        this.optionForm.column.forEach(item => {
          item.disabled = true;
        });
        // this.isAddDisabled = false
      }
    },
    calculator(row) {
      if (row.sendNumFinancing > row.inventoryFinancing) {
        this.$set(row, "sendNumFinancing", null);
        this.$message.error("融资数量不能大于参考库存融资");
      }
      if (row.sendNumHave > row.inventoryHave) {
        this.$set(row, "sendNumHave", null);
        this.$message.error("自由数量不能大于参考库存自有");
      }
      row.goodsNum = Number(Number(row.sendNumFinancing) + Number(row.sendNumHave));
      row.subTotalMoney = row.goodsNum * row.price;
    },
    calculator2(row) {
      if (row.goodsNum > row.inventory) {
        this.$set(row, "goodsNum", null);
        this.$message.error("调拨数量不能大于库存");
      }
      row.subTotalMoney = row.goodsNum * row.price;
    },
    // 导入按钮事件
    tableDataHandle(arr) {
      this.tableData = arr;
      // 循环获取库存数量
      for (let item of this.tableData) {
        let obj = {
          goodsId: item.id,
          price: item.price, // 单价
          goodsName: item.cname,
          goodsNum: item.goodsNum,
          sendNumFinancing: this.whetherFinancing == 1 ? item.sendNumFinancing : 0,
          sendNumHave: this.whetherFinancing == 1 ? item.sendNumHave : 0,
          brandName: item.brandName,
          brandId: item.brandId,
          goodsNo: item.code,
          propertyName: item.specificationAndModel,
          inventory: item.inventory,
          inventoryHave: this.whetherFinancing == 1 ? item.inventoryHave : 0,
          inventoryFinancing: this.whetherFinancing == 1 ? item.inventoryFinancing : 0,
          pattern: item.brandItem,
          goodsDescription: item.goodsDescription,
          dot: item.dot,
          whether: item.whether,
          units: item.unit,
          // 小计
          subTotalMoney: item.goodsNum * item.price,
          // 备注
          remarks: item.remarks,
          // 批次号的状态
          dotedittype: false,
          // 价格数量
          goodsNumtype: false,
          // 价格
          pricetype: false,
          historyList: [],
          $cellEdit: this.reservoirArea == 1 ? false : true
        };
        this.form.shipItemsList.push(obj);
      }
      this.$refs.dialogAssemblyRef.dialogVisible = false;
      this.$nextTick(() => {
        this.$refs.formContacts.doLayout();
        this.$refs.formContacts.refreshTable();
      });
    },

    //自定义列保存
    async saveColumnTwo(ref, option, optionBack, code) {
      /**
       * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
       * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
       * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
       */
      const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
      isProcurement({ param: "whether.model" }).then(res => {
        if (res.data.data == 1) {
          this.findObject(this.optionContacts.column, "pattern").label = "规格型号1";
        }
      });
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
    //自定义列重置
    async resetColumnTwo(ref, option, optionBack, code) {
      this[option] = this[optionBack];
      isProcurement({ param: "whether.model" }).then(res => {
        if (res.data.data == 1) {
          this.findObject(this.optionContacts.column, "pattern").label = "规格型号1";
        }
      });
      const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
      if (inSave) {
        this.$message.success("重置成功");
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
    backToList(type) {
      this.$emit("backToList", type);
      // this.$store.commit("DOMIO_OUT_DETAIL");
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-bottom: 8px !important;
}
</style>
