<template>
  <div class="borderless" v-loading="pageLoading">
    <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"
          :loading="btnLoading"
        >返回列表</el-button>
      </div>
      <div class="add-customer-btn">
        <el-button
          type="primary"
          size="small"
          class="el-button--small-yh"
          @click.stop="openEdit"
          v-if="form.id && disabled"
        >编 辑</el-button>
        <el-button
          type="primary"
          size="small"
          class="el-button--small-yh"
          style="margin-right: 8px;"
          @click="dealerSubmit"
          :disabled="disabled"
          :loading="btnLoading"
          v-if="form.id"
        >
          {{ form.status == 0? '确认订单': form.status == 3? '撤销订单': '' }}
        </el-button>
        <el-dropdown style="margin-right: 8px;">
          <el-button type="warning" size="small">账单处理<i class="el-icon-arrow-down el-icon--right"></i></el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              @click.native="applySettlement('申请')"
              :disabled="disabled">申请货款
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button
          type="success"
          :disabled="!form.id"
          size="small"
          @click="copyDoc"
          :loading="btnLoading"
        >
          复制单据
        </el-button>
        <el-button
          type="primary"
          @click="editCustomer"
          size="small"
          :loading="btnLoading"
          :disabled="disabled"
        >保存数据
        </el-button>
      </div>
    </div>
    <div class="customer-main">
      <containerTitle title="基础信息"/>
      <basic-container :showBtn="true">
        <avue-form
          ref="form"
          class="trading-form"
          v-model="form"
          :option="option"
        >
          <template slot="corpId">
            <crop-select
              v-model="form.corpId"
              @getCorpData="getCorpData"
              corpType="GYS"
              :disabled="disabled || confirmDisabled"
            ></crop-select>
          </template>
          <template slot="storageId">
            <warehouse-select
              v-model="form.storageId"
              :configuration="configurationWarehouse"
              :disabled="disabled || confirmDisabled"/>
          </template>
        </avue-form>
      </basic-container>
      <containerTitle title="商品信息"/>
      <basic-container>
        <avue-crud
          ref="crud"
          :data="dataList"
          :option="tableOption"
          :page.sync="goodPage"
          :table-loading="goodLoading"
          @current-change="currentChange"
          @size-change="sizeChange"
          :cell-style="cellStyle"
          @saveColumn="saveColumn"
          @resetColumn="resetColumn"
        >
          <template slot="headerSerial" slot-scope="{column}">
            <el-button
              type="primary"
              icon="el-icon-circle-plus-outline"
              circle
              size="mini"
              :disabled="disabled || confirmDisabled"
              @click="$refs.crud.rowCellAdd()"></el-button>
          </template>
          <template slot="menuLeft">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click.stop="newDetails"
              :disabled="disabled || confirmDisabled"
            >录入明细</el-button>
            <el-button
              type="info"
              icon="el-icon-printer"
              size="small"
              @click.stop="openReport()"
            >报表打印</el-button>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-download"
              @click="downloadHandle"
            >下载模板</el-button>
            <el-upload
              :action="baseURL"
              :headers="headers"
              :disabled="disabled || confirmDisabled"
              :on-progress="uploading"
              :show-file-list=false
              accept=".xls,.xlsx"
              multiple
              :on-success="importTemplate"
              :on-error="uploadError"
              style="float: right"
            >
              <el-button
                type="primary"
                size="small"
                icon="el-icon-upload"
              >导 入</el-button>
            </el-upload>
          </template>
          <template slot="menu" slot-scope="{ row, index }">
            <el-button
              size="small"
              icon="el-icon-edit"
              type="text"
              @click="rowCell(row, index)"
              :disabled="disabled || confirmDisabled"
            >{{ row.$cellEdit ? "保存" : "修改" }}</el-button
            >
            <el-button
              size="small"
              icon="el-icon-delete"
              type="text"
              @click="rowDel(row, index)"
              :disabled="disabled || confirmDisabled"
            >删除</el-button
            >
          </template>
          <template slot="code" slot-scope="{ row, index }">
            <span v-if="row.$cellEdit" style="display:flex">
              <el-select
                v-model="row.code"
                placeholder="请选择"
                filterable
                size="small"
                style="width:60%"
                @change="codeChange(row, index)"
                :disabled="!form.storageId"
              >
                <el-option
                  v-for="item in goodsoptions"
                  :key="item.id"
                  :label="item.code"
                  :value="item.code"
                >
                </el-option>
              </el-select>
              <el-button
                icon="el-icon-search"
                size="small"
                @click="rePick(row, index)"
              ></el-button>
            </span>
            <span v-else> {{ row.code }}</span>
          </template>
          <template slot="cname" slot-scope="{ row, index }">
            <span v-if="row.$cellEdit" style="display:flex">
              <el-select
                v-model="row.itemId"
                placeholder="请选择"
                size="small"
                style="width:60%"
                filterable
                @change="cnameChange(row, index)"
                :disabled="!form.lotNo"
              >
                <el-option
                  v-for="item in goodsoptions"
                  :key="item.id"
                  :label="item.cname"
                  :value="item.id"
                >
                </el-option>
              </el-select>
              <el-button
                icon="el-icon-search"
                size="small"
                @click="rePick(row, index)"
              ></el-button>
            </span>
            <span v-else> {{ row.cname }}</span>
          </template>
          <template slot="batch" slot-scope="{row, index}">
            <span>{{ row.batch == 0? '否': '是' }}</span>
          </template>
          <template slot="orderQuantity" slot-scope="{ row, index }">
            <el-input-number
              v-if="row.$cellEdit"
              v-model="row.orderQuantity"
              size="small"
              :controls="false"
              :precision="0"
              @input="amountChange(row)"
              style="width: 100%"
              :disabled="!form.lotNo"
            />
            <span v-else>{{ row.orderQuantity | IntegerFormat }}</span>
          </template>
          <template slot="price" slot-scope="{ row, index }">
            <el-input-number
              v-if="row.$cellEdit"
              v-model="row.price"
              size="small"
              :controls="false"
              :precision="2"
              @input="amountChange(row)"
              style="width: 100%"
              :disabled="!form.lotNo"
            ></el-input-number>
            <span v-else>{{ row.price }}</span>
          </template>
          <!--          单位-->
          <template slot="unit" slot-scope="{ row, index }">
            <el-select
              v-if="row.$cellEdit"
              v-model="row.unit"
              size="small"
              :disabled="!form.lotNo"
              clearable
              filterable
            >
              <el-option
                v-for="(item, index) in unitOption"
                :key="index"
                :label="item.dictValue"
                :value="item.dictValue"
              />
            </el-select>
            <span v-else>{{ row.unit }}</span>
          </template>
          <template slot="amount" slot-scope="{ row, index }">
            <span>{{ row.amount | decimalFormat }}</span>
          </template>
          <template slot="storageQuantity" slot-scope="{ row, index }">
            <span>{{ row.storageQuantity | IntegerFormat }}</span>
          </template>
          <template slot="newJob" slot-scope="{ row, index }">
            <span style="color: #1e9fff;cursor: pointer" @click="openHistory(row)">{{ row.newJob }}</span>
          </template>
          <template slot="remarks" slot-scope="{ row, index }">
            <el-input
              v-if="row.$cellEdit"
              v-model="row.remarks"
              size="small"
              :disabled="!form.storageId"
            />
            <span v-else>{{ row.remarks }}</span>
          </template>
        </avue-crud>
      </basic-container>
      <containerTitle title="详细信息"/>
      <basic-container :showBtn="true">
        <avue-form
          ref="form1"
          class="trading-form"
          v-model="form"
          :option="detailOption"
        ></avue-form>
      </basic-container>
      <containerTitle title="附件管理"></containerTitle>
      <c-upload
        :data="uploadData"
        deleteUrl="/api/blade-client/corpsbank/update"
        :enumerationValue="84"
        :disabled="disabled || confirmDisabled"
      />
    </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"
      top="5vh"
      v-dialog-drag
    >
      <span>
        <el-row>
          <el-col :span="4">
            <div>
              <el-scrollbar>
                <basic-container>
                  <avue-tree
                    :option="treeOption"
                    @node-click="nodeClick"
                    :style="treeStyle"
                  />
                </basic-container>
              </el-scrollbar>
            </div>
          </el-col>
          <el-col :span="20">
            <avue-crud
              :option="goodsOption"
              :table-loading="loading"
              :data="goodsList"
              ref="goodsCrud"
              :search.sync="search"
              @search-change="searchChange"
              @selection-change="selectionChange"
              @row-click="rowClick"
              :page.sync="page"
              @on-load="onLoad"
              @saveColumn="saveGoodsColumn"
              @resetColumn="resetGoodsColumn"
              :cell-style="cellStyle"
            >
              <template slot="menuLeft">
                <el-tabs v-model="activeName" @tab-click="tabHandle">
                  <el-tab-pane label="查询结果" name="searchList"></el-tab-pane>
                  <el-tab-pane label="已选定数据" name="importStaging"></el-tab-pane>
                </el-tabs>
              </template>
              <template slot-scope="scope" slot="menu">
                <el-button
                  type="text"
                  icon="el-icon-edit"
                  size="small"
                  @click.stop="importStagList(scope.row,scope.index)"
                  v-if="activeName=='searchList'"
                  :disabled="goodsListSave.findIndex(item => item.id == scope.row.id) !== -1"
                >选择
                </el-button>
                <el-button
                  type="text"
                  icon="el-icon-delete"
                  size="small"
                  @click.stop="removeStagList(scope.row,scope.index)"
                  v-else
                >移除
                </el-button>
              </template>
            </avue-crud>
          </el-col>
        </el-row>
      </span>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="importGoods"
          :disabled="selectionList.length == 0 && goodsListSave.length == 0"
        >导入</el-button
        >
      </span>
    </el-dialog>
    <!--    账单-->
    <el-dialog
      append-to-body
      title="账单"
      class="el-dialogDeep"
      :visible.sync="financialAccountDialog"
      width="70%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :close-on-press-escape="false"
      v-dialog-drag
    >
      <financial-account
        :billType="billType"
        :billData="{}"
        :arrList="applyPaymentList"
        :belongCompany="form.belongToCorpId"
        :checkData="checkData"
        @choceFun="choceFun"
        @submit="feeSubmit"
      />
    </el-dialog>
<!--    历史记录-->
    <view-history
      v-if="historyVisible"
      ref="history"
      :params="historyParams"
      @closeDialog="closeDialog"
    />
  </div>
</template>

<script>
import tableOption from "./config/customerContact.json";
import goodsOption from "./config/commodity.json";
import {getDeptLazyTree,
  getGoods,} from "@/api/basicData/customerInquiry";
import {selectGoodsNum} from "@/api/basicData/inventoryAccount"; // 库存查询
import {getUserInfo} from "@/api/system/user"; //登录用户信息
import {dataDetail, removeGoods, typeSave, dealerSubmit, historyPrice, itemDetail} from "@/api/dealer/purchase";
import {
  isDiscount,
  isPercentage,
  micrometerFormat,
  IntegerFormat
} from "@/util/validate";
import reportDialog from "@/components/report-dialog/main";
import financialAccount from "../../../components/finance/financialAccount";
import checkSchedule from "@/components/check/checkSchedule";
import  billApplication from "@/components/bill/billApplication";
import { customerList as feeList } from "@/api/basicData/basicFeesDesc";
import {getDetail} from "@/api/basicData/inventoryAccount";
import { getToken } from "@/util/auth";
import { getCurrentDate } from "@/util/date";
import viewHistory from '../componet/history';
import { contrastObj, contrastList } from "@/util/contrastData";

export default {
  name: "detail",
  props: {
    detailData: {
      type: Object
    }
  },
  components: {
    reportDialog,
    billApplication,
    financialAccount,
    checkSchedule,
    viewHistory,
  },
  data() {
    return {
      pageLoading: false,
      btnLoading: false,
      disabled: false,
      confirmDisabled: false, // 确认禁用
      form: {},
      option: {
        menuBtn: false,
        labelWidth: 100,
        column: [
          {
            label: "供应商",
            prop: "corpId",
            rules: [
              {
                required: true,
                message: " ",
                trigger: "change"
              }
            ],
            span: 16,
            slot: true,
          },
          {
            label: "业务时间",
            prop: "businesDate",
            span: 8,
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd 00:00:00",
            rules: [
              {
                required: true,
                message: "",
                trigger: "blur"
              }
            ]
          },
          {
            label: "批次号",
            prop: "lotNo",
            rules: [
              {
                required: true,
                message: " ",
                trigger: "blur"
              }
            ],
            span: 8,
            slot: true
          },
          {
            label: "收货仓库",
            prop: "storageId",
            span: 8,
            rules: [
              {
                required: true,
                message: " ",
                trigger: "change"
              }
            ],
          },
          {
            label: "电话",
            prop: "corpTel",
            span: 8
          },
          {
            label: "地址",
            prop: "arrivalAddress",
            span: 8
          },
          {
            label: "备注",
            prop: "orderRemark",
            type: "textarea",
            minRows: 2,
            span: 24
          },
        ],
      },
      detailOption: {
        menuBtn: false,
        labelWidth: 100,
        column: [
          {
            label: "系统号",
            prop: "sysNo",
            span: 8,
            disabled: true
          },
          {
            label: "打印时间",
            prop: "printTime",
            span: 8,
            disabled: true
          },
          {
            label: "打印次数",
            prop: "printNumber",
            span: 8,
            disabled: true
          },
          {
            label: "客户欠款",
            prop: "corpDebt",
            span: 8,
            disabled: true
          },
          {
            label: "总数量",
            prop: "orderQuantity",
            span: 8,
            disabled: true
          },
          {
            label: "应付金额",
            prop: "debitAmount",
            span: 8,
            disabled: true
          },
          {
            label: "总金额",
            prop: "amount",
            span: 8,
            disabled: true
          },
          {
            label: "制单人",
            prop: "createUserName",
            span: 8,
            disabled: true,
          },
        ]
      },
      // 仓库配置
      configurationWarehouse: {
        multipleChoices: false,
        multiple: false,
        collapseTags: false,
        placeholder: "请点击右边按钮选择",
        dicData: [],
      },
      dataList: [],
      tableOption: {},
      dialogVisible: false,
      selectionList: [],
      treeDeptId: null,
      reData: null,
      treeOption: {
        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: {
          label: "title",
          value: "value",
          children: "children"
        }
      },
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      search: {},
      goodsList: [],
      loading: false,
      goodsOption: {},
      treeStyle: "height:" + (window.innerHeight - 315) + "px",
      goodsoptions: [],
      uploadData: [],
      goodData: [], // 存储所有商品信息
      activeName: 'searchList',
      // 商品列表数据合计
      goodsListShow: [],
      // 商品列表暂存
      goodsListSave: [],
      pageList: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      applyPaymentList: [],
      billType:"收费",  //账单类型
      billData:{},     //账单需要数据
      checkData:{
        url:"/financialManagement/paymentRequest/index",
        pageStatus:"this.$store.getters.pqStatus",
        pageLabel:"付费申请",
        checkType: 'ffsq'
      },
      applySettlementDialog:false,//生成账单组件
      financialAccountDialog:false,
      feesOption: [],
      unitOption: [],
      baseURL: '/api/blade-purchase-sales/orderitems/importDealerOrder',
      headers: { "Blade-Auth": 'Bearer ' + getToken()},
      historyVisible: false,
      historyParams: {},
      goodPage: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      goodLoading: false,
      oldForm: {},
      oldDataList: [],
      oldUploadData: [],
    }
  },
  async created() {
    this.tableOption = await this.getColumnData(
      this.getColumnName(82),
      tableOption
    );
    this.goodsOption = await this.getColumnData(
      this.getColumnName(83),
      goodsOption
    );
    this.getWorkDicts('unit').then(res => {
      this.unitOption = res.data.data;
    })
    getGoods(1, 10).then(res => {
      if (res.data.data.total > 0) {
        this.goodsoptions = res.data.data.records;
        if (Math.ceil(res.data.data.total / 10) > 1) {
          for (let i = 2; i <= Math.ceil(res.data.data.total / 10); i++) {
            getGoods(i, 10).then(e => {
              this.goodsoptions = this.goodsoptions.concat(e.data.data.records);
            });
          }
        }
      }
    });
    getUserInfo().then(res => {
      this.$set(this.form, 'createUserName', res.data.data.realName)
      this.$set(this.form, 'createUser', res.data.data.id)
    })
    feeList().then(res => {
      this.feesOption = res.data.data.records
    });
    this.$set(this.form, 'businesDate', getCurrentDate());
    this.$set(this.form, 'status', 0);
    if (this.detailData.query) {
      this.disabled = true;
      this.option.column.map(e => {
        this.$set(e, 'disabled', true)
      })
      this.queryData(this.detailData.id);
    } else {
      this.dataList = [
        {
          code: null,
          cname: null,
          typeno: null,
          brandItem: null,
          specsOne: null,
          specsTwo: null,
          unit: null,
          storageQuantity: 0,
          orderQuantity: 0,
          size: null,
          price: 0,
          amount: 0,
          $cellEdit: true
        }
      ]
    }
  },
  filters: {
    IntegerFormat(num) {
      return IntegerFormat(num);
    },
    decimalFormat(num) {
      return num ? Number(num).toFixed(2) : "0.00";
    }
  },
  methods: {
    // 查询
    queryData(id) {
      this.pageLoading = true;
      dataDetail(id).then(res => {
        this.form = res.data.data;
        this.getItemDetail();
        this.form.amount = Number(this.form.amount).toFixed(2);
        this.confirmDisabled = this.form.status == 3? true: false;
        if (this.confirmDisabled) {
          // this.option.column.map(e => {
          //   this.$set(e, 'disabled', true)
          // })
        }
        this.goodData = this.form.orderItemsList? this.form.orderItemsList: [];
        this.uploadData = this.form.orderFilesList? this.form.orderFilesList: [];
        delete this.form.orderItemsList;
        delete this.form.orderFilesList;
        this.oldForm = {...this.form};
        // this.oldDataList = [...this.dataList];
        this.oldUploadData = [...this.uploadData];
      }).finally(() => {
        this.pageLoading = false;
      })
    },
    cellStyle() {
      return "padding:0;height:40px;";
    },
    openEdit() {
      this.disabled = false;
      this.option.column.map(e => {
        if (this.confirmDisabled) {
          if (e.prop == 'businesDate' || e.prop == 'lotNo') {
            this.$set(e, 'disabled', true)
          } else {
            this.$set(e, 'disabled', false)
          }
        } else {
          this.$set(e, 'disabled', false)
        }
      })
    },
    copyDoc() {
      this.$emit("copyOrder", this.form.id);
    },
    getCorpData(row) {},
    //修改提交触发
    editCustomer(status) {
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          // 总金额计算
          let amount = 0;
          this.dataList.forEach(item => {
            amount = Number(amount) + Number(item.amount)
          })
          this.$set(this.form, 'debitAmount', amount.toFixed(2));
          this.$set(this.form, 'amount', amount.toFixed(2));
          this.form.billType = 'CG';
          this.$set(this.form, 'itemsVOList', this.dataList);
          this.$set(this.form, 'orderFilesList', this.uploadData);
          this.btnLoading = true;
          typeSave(this.form).then(res => {
            this.$message({type: "success", message: this.form.id ? "修改成功!" : "新增成功!"});
            this.queryData(res.data.data);
          }).finally(() => {
            this.btnLoading = false;
          })
        }
      })
    },
    //返回列表
    backToList() {
      this.$emit("goBack");
    },
    async saveColumn() {
      const inSave = await this.saveColumnData(
        this.getColumnName(82),
        this.tableOption
      );
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
        this.$nextTick(() => {
          this.$refs.crud.doLayout()
        })
      }
    },
    async resetColumn() {
      this.tableOption = tableOption;
      const inSave = await this.delColumnData(
        this.getColumnName(82),
        tableOption
      );
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout()
        })
        this.$message.success("重置成功");
        //关闭窗口
        setTimeout(() => {
          this.$refs.crud.$refs.dialogColumn.columnBox = false;
        }, 1000);
      }
    },
    //商品明细导入
    newDetails() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.dialogVisible = !this.dialogVisible;
        }
      })
      // if (!this.form.corpId) {
      //   return this.$message.error("请选择客户名称");
      // }
    },
    importGoods() {
      let form = {};
      if (this.reData) {
        if (this.selectionList.length != 1) {
          return this.$message.error("重新选择的时候只能选择一条数据");
        } else {
          this.selectionList.forEach(e => {
            this.dataList.forEach(async (item, index) => {
              if (index == this.reData.index) {
                let historyData = await this.getHistoryData(e, 1); // 获得最新数据
                if (historyData.length > 0) {
                  e.newJob = historyData[0].price;
                  e.newDate = historyData[0].businesDate;
                } else {
                  e.newJob = null;
                  e.newDate = null;
                }
                form = await this.getStockInfo({
                  tradeType: 'JXS',
                  goodsId: e.id,
                  storageId: this.form.storageId,
                  lotNo: e.batch == 1? this.form.lotNo: null
                })
                item.storageQuantity = form.stock;
                item.purchaseAmount = form.purchaseAmount;
                item.itemId = e.id;
                item.code = e.code;
                item.cname = e.cname;
                item.corpId = e.corpId;
                item.corpName = e.corpName;
                item.brandItem = e.brandItem;
                item.specsOne = e.specsOne;
                item.specsTwo = e.specsTwo;
                item.typeno = e.typeno;
                item.unit = e.unit;
                item.size = e.size;
                item.lotNo = e.batch == 1? this.form.lotNo: null;
                item.priceCategory = e.goodsTypeName;
                item.newJob = e.newJob;
                item.newDate = e.newDate;
                item.$cellEdit = true;
              }
            });
          });
        }
      } else {
        if (this.goodsListSave.length > 0) { // 暂存的有数据
          this.goodsListSave.forEach(async e => {
            let historyData = await this.getHistoryData(e, 1); // 获得最新数据
            if (historyData.length > 0) {
              e.newJob = historyData[0].price;
              e.newDate = historyData[0].businesDate;
            } else {
              e.newJob = null;
              e.newDate = null;
            }
            form = await this.getStockInfo({
              tradeType: 'JXS',
              goodsId: e.id,
              storageId: this.form.storageId,
              lotNo: e.batch == 1? this.form.lotNo: null
            })
            e.storageQuantity = form.stock;
            e.purchaseAmount = form.purchaseAmount;
            this.dataList.push({
              itemId: e.id,
              code: e.code,
              cname: e.cname,
              brandItem: e.brandItem,
              specsOne: e.specsOne,
              specsTwo: e.specsTwo,
              typeno: e.typeno,
              corpId: e.corpId,
              corpName: e.corpName,
              unit: e.unit,
              size: e.size,
              price: 0,
              amount: 0,
              orderQuantity: 0,
              storageQuantity: e.storageQuantity,
              purchaseAmount: e.purchaseAmount,
              newJob: e.newJob,
              newDate: e.newDate,
              lotNo: e.batch == 1? this.form.lotNo: null,
              $cellEdit: true
            });
          });
        } else {
          this.selectionList.forEach(async e => {
            let historyData = await this.getHistoryData(e, 1); // 获得最新数据
            if (historyData.length > 0) {
              e.newJob = historyData[0].price;
              e.newDate = historyData[0].businesDate;
            } else {
              e.newJob = null;
              e.newDate = null;
            }
            form = await this.getStockInfo({
              tradeType: 'JXS',
              goodsId: e.id,
              storageId: this.form.storageId,
              lotNo: e.batch == 1? this.form.lotNo: null
            })
            e.storageQuantity = form.stock;
            e.purchaseAmount = form.purchaseAmount;
            this.dataList.push({
              itemId: e.id,
              code: e.code,
              cname: e.cname,
              brandItem: e.brandItem,
              specsOne: e.specsOne,
              specsTwo: e.specsTwo,
              typeno: e.typeno,
              corpId: e.corpId,
              corpName: e.corpName,
              unit: e.unit,
              size: e.size,
              price: 0,
              amount: 0,
              orderQuantity: 0,
              storageQuantity: e.storageQuantity,
              purchaseAmount: e.purchaseAmount,
              newJob: e.newJob,
              newDate: e.newDate,
              lotNo: e.batch == 1? this.form.lotNo: null,
              $cellEdit: true
            });
          });
        }
      }
      this.dialogVisible = false;
    },
    closeGoods() {
      this.selectionList = [];
      this.treeDeptId = "";
      this.reData = null;
      this.activeName = 'searchList';
      this.goodsListSave = [];
    },
    nodeClick(data) {
      this.treeDeptId = data.id;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    //费用查询
    onLoad(page, params = {}) {
      let obj = this.deepClone(Object.assign(params, this.search));
      this.loading = true;
      getGoods(page.currentPage, page.pageSize, this.treeDeptId, obj)
        .then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.goodsList = data.records;
          if (this.page.total) {
            this.goodsOption.height = window.innerHeight - 350;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    searchChange(params, done) {
      this.search = this.deepClone(params);
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    rowClick(row) {
      this.$refs.goodsCrud.toggleSelection([this.goodsList[row.$index]]);
    },
    async saveGoodsColumn() {
      const inSave = await this.saveColumnData(
        this.getColumnName(83),
        this.goodsOption
      );
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs.goodsCrud.$refs.dialogColumn.columnBox = false;
        this.$nextTick(() => {
          this.$refs.goodsCrud.doLayout()
        })
      }
    },
    async resetGoodsColumn() {
      this.goodsOption = goodsOption;
      const inSave = await this.delColumnData(
        this.getColumnName(83),
        goodsOption
      );
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.goodsCrud.doLayout()
        })
        this.$message.success("重置成功");
        //关闭窗口
        setTimeout(() => {
          this.$refs.goodsCrud.$refs.dialogColumn.columnBox = false;
        }, 1000);
      }
    },
    openReport() {},
    rowCell(row, index) {
      if (row.$cellEdit == true) {
        this.$set(row, "$cellEdit", false);
      } else {
        this.$set(row, "$cellEdit", true);
      }
    },
    rowDel(row, index) {
      this.$confirm("确定删除数据?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (row.id) {
          removeGoods(row.id).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
            this.dataList.splice(row.$index, 1);
          })
        } else {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.dataList.splice(row.$index, 1);
        }
      });
    },
    codeChange(row) {
      let form = {};
      this.goodsoptions.forEach(async e => {
        if (e.code == row.code) {
          let historyData = await this.getHistoryData(e, 1); // 获得最新数据
          if (historyData.length > 0) {
            e.newJob = historyData[0].price;
            e.newDate = historyData[0].businesDate;
          } else {
            e.newJob = null;
            e.newDate = null;
          }
          form = await this.getStockInfo({
            tradeType: 'JXS',
            goodsId: e.id,
            storageId: this.form.storageId,
            lotNo: e.batch == 1? this.form.lotNo: null
          })
          e.storageQuantity = form.stock;
          e.purchaseAmount = form.purchaseAmount;
          row.itemId = e.id;
          row.cname = e.cname;
          row.code = e.code;
          row.corpId = e.corpId;
          row.corpName = e.corpName;
          row.brandItem = e.brandItem;
          row.specsOne = e.specsOne;
          row.specsTwo = e.specsTwo;
          row.typeno = e.typeno;
          row.unit = e.unit;
          row.size = e.size;
          row.priceCategory = e.goodsTypeName;
          row.storageQuantity = e.storageQuantity;
          row.purchaseAmount = e.purchaseAmount;
          row.lotNo = e.batch == 1? this.form.lotNo: null;
          row.newJob = e.newJob;
          row.newDate = e.newDate;
          // row.amount = 0;
        }
      });
    },
    cnameChange(row) {
      let form = {};
      this.goodsoptions.forEach(async e => {
        if (e.id == row.itemId) {
          let historyData = await this.getHistoryData(e, 1); // 获得最新数据
          if (historyData.length > 0) {
            e.newJob = historyData[0].price;
            e.newDate = historyData[0].businesDate;
          } else {
            e.newJob = null;
            e.newDate = null;
          }
          form = await this.getStockInfo({
            tradeType: 'JXS',
            goodsId: e.id,
            storageId: this.form.storageId,
            lotNo: e.batch == 1? this.form.lotNo: null
          })
          e.storageQuantity = form.stock;
          e.purchaseAmount = form.purchaseAmount;
          row.cname = e.cname;
          row.code = e.code;
          row.corpId = e.corpId;
          row.corpName = e.corpName;
          row.brandItem = e.brandItem;
          row.specsOne = e.specsOne;
          row.specsTwo = e.specsTwo;
          row.typeno = e.typeno;
          row.unit = e.unit;
          row.size = e.size;
          row.priceCategory = e.goodsTypeName;
          row.storageQuantity = e.storageQuantity;
          row.purchaseAmount = e.purchaseAmount;
          row.lotNo = e.batch == 1? this.form.lotNo: null;
          row.newJob = e.newJob;
          row.newDate = e.newDate;
          // row.amount = 0;
        }
      });
    },
    rePick(row, index) {
      this.reData = {
        ...row,
        index: index
      };
      this.newDetails();
    },
    // 商品信息价格计算
    amountChange(row) {
      if (!row.orderQuantity) {
        row.orderQuantity = 0;
      }
      if (!row.price) {
        row.price = 0;
      }
      row.amount = Number(row.price) * Number(row.orderQuantity)
    },
    // 标签页切换
    tabHandle(data) {
      if (data.name == 'searchList') {
        this.goodsListShow = this.goodsList;
        this.page.total = this.pageList.total
      } else if (data.name == 'importStaging') {
        this.goodsListShow = this.goodsListSave;
        this.page.total = 0
      }
    },
    removeStagList(row, index) {
      this.goodsListSave.splice(row.$index, 1)
    },
    importStagList(row, index) {
      this.goodsListSave.push(row);
    },
    // 生成结算
    applySettlement(type) {
      this.beforeBillData(true,type)
      this.financialAccountDialog = true;
    },
    //生成账单 拿到主表信息
    beforeBillData(bool,type) {
      this.billType = type;
      this.applyPaymentList = [];
      this.goodData.map(e => {
        if (e.submitPay != 1) {
          const form = {
            srcOrderno:this.form.orderNo,
            srcParentId: this.form.id,
            itemType:"采购",
            corpsName:this.form.corpsName,
            corpId:this.form.corpId,
            currency: 'CNY',
            exchangeRate: '1',
            taxRate: '0',
            accDate: this.form.businesDate,
            srcType: 1,
            // chargeMember: this.form.chargeMember,
            parentId: this.form.id,
            tradeType: 'JXS',
            optionType: 'JXS',
            amount: e.amount,
            costType: this.feesOption.find(item => item.cname == '货款')? this.feesOption.find(item => item.cname == '货款').id: null,
            srcFeesId: e.id,
            goodName: e.cname,
            price: e.price,
            quantity: e.orderQuantity,
            unit:e.unit,
          }
          this.applyPaymentList.push(form);
        }
      })
    },
    //关闭账单
    choceFun(){
      this.financialAccountDialog  = false
    },
    feeSubmit() {
      this.queryData(this.form.id);
    },
    // 获得库存信息
    async getStockInfo(data) {
      //tradeType JXS
      //goodsId
      //storageId
      //lotNo 批次号
      let form = {};
      await getDetail(data).then(res => {
        const a = res.data.data? res.data.data: {
          stock: 0,
          balanceAmount: 0,
          balanceQuantity: 0,
        };
        this.$set(form, 'purchaseAmount', a.balanceQuantity == 0? 0: (Number(a.balanceAmount) / Number(a.balanceQuantity)).toFixed(2));
        this.$set(form, 'stock', a.balanceQuantity);
      })
      return form;
    },
    // 确认或者取消订单
    dealerSubmit() {
      if (this.verification()) {
        let dealer;
        if (this.form.status == 0) {
          dealer = 1;
        } else if (this.form.status == 3) {
          dealer = 2;
        }
        this.btnLoading = true;
        dealerSubmit({
          id: this.form.id,
          dealer
        }).then(res => {
          if (res.data.code == 200) {
            this.$message.success('操作成功')
            this.queryData(this.form.id)
          } else {
            this.$message.error(res.data.msg)
          }
        }).finally(() => {
          this.btnLoading = false;
        })
      }
    },
    // 下载模板
    downloadHandle() {
      this.$confirm('是否下载模板文件？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.open(
          `/api/blade-purchase-sales/orderitems/exportDealerOrder?${
            this.website.tokenHeader
          }=${getToken()}`
        );
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      })
    },
    //文件上传时
    uploading(event, file, fileList) {
      this.openFullScreen(false, '文件正在解析中');
    },
    importTemplate(res, file) {
      this.openFullScreen(true)
      res.data.forEach(item => {
      })
      this.dataList = this.dataList.concat(res.data)
    },
    uploadError(err, file, fileList) {
      this.openFullScreen(true)
      this.$message.error(JSON.parse(err.message).msg)
    },
    //遮罩层
    openFullScreen(res, text) {
      const loading = this.$loading({
        lock: true,
        text: text,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      if (res === true) loading.close();
    },
    // 获得历史数据
    async getHistoryData(row, typeId = null) {
      let data;
      const params = {
        typeId,
        tradeType: 'JXS',
        billType: 'CG',
        itemId: row.id
      }
      await historyPrice(params).then(res => {
        data = res.data.data? res.data.data: [];
      })
      return data;
    },
    openHistory(row) {
      this.historyParams = {
        tradeType: 'JXS',
        billType: 'CG',
        itemId: row.itemId
      }
      this.historyVisible = true;
      this.$nextTick(() => {
        this.$refs.history.init();
      })
    },
    closeDialog() {
      this.historyVisible = false;
    },
    // 商品明细分页处理
    currentChange(val) {
      this.goodPage.currentPage = val;
      this.getItemDetail();
    },
    sizeChange(val) {
      this.goodPage.currentPage = 1;
      this.goodPage.pageSize = val;
      this.getItemDetail();
    },
    getItemDetail() {
      const data = {
        pid: this.form.id,
      };
      this.goodLoading = true;
      itemDetail(this.goodPage.currentPage, this.goodPage.pageSize, data).then(res => {
        this.dataList = res.data.data.records;
        this.goodPage.total = res.data.data.total;
        this.oldDataList = [...this.dataList];
      }).finally(() => {
        this.goodLoading = false;
      })
    },
    // 验证新旧值对比
    verification() {
      console.log(contrastList(this.dataList, this.oldDataList))
      if (contrastObj(this.form, this.oldForm) ||
        contrastList(this.dataList, this.oldDataList) ||
        contrastList(this.uploadData, this.oldUploadData)) {
        this.$confirm("数据发生变化未有提交记录, 是否提交?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.editCustomer();
        }).catch(() => {
          return false;   //取消改动数据
        })
      } else {
        return true;
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.trading-form ::v-deep .el-form-item {
  margin-bottom: 8px !important;
}
::v-deep .el-form-item__error {
  display: none !important;
}
::v-deep .select-component {
  display: flex !important;
}
</style>
