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

    <div class="main-title">
      <div class="title">置换订单信息</div>
    </div>

    <el-form ref="mainForm" :model="mainForm" label-width="100px" size="small" label-position="left">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="订单号" prop="orderNo">
            <div  >
              <el-input v-model="mainForm.orderNo" placeholder="请输入订单号" disabled>
                <el-button slot="append" icon="el-icon-search" @click="openShareDetail" class="choose-order">选择</el-button>
              </el-input>
            </div>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8" style="height: 51px;">
          <el-form-item label="单据日期" prop="orderDate" :rules="{ required: true, message: '单据日期不能为空', trigger: 'blur' }">
            <el-date-picker
              v-model="mainForm.orderDate"
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 100%;"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="品类" prop="mainName">
            <el-input :value="mainForm.mainName" placeholder="品类" disabled></el-input>
          </el-form-item>
        </el-col>
        <template v-if="mainForm.policyCode">
          <el-col :xs="24" :sm="12" :lg="8">
            <el-form-item label="销售政策编号" prop="policyCode">
              <el-input :value="mainForm.policyCode" placeholder="销售政策编号" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="8">
            <el-form-item label="销售政策" prop="policyTitle">
              <el-input :value="mainForm.policyTitle" placeholder="销售政策" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="8">
            <el-form-item label="销售政策说明" prop="policyRemark">
              <el-input :value="mainForm.policyRemark" placeholder="销售政策说明" disabled></el-input>
            </el-form-item>
          </el-col>
        </template>
        <template v-if="mainForm.enginRecordNo">
          <el-col :xs="24" :sm="12" :lg="8">
            <el-form-item label="工程登录编号" prop="enginRecordNo">
              <el-input :value="mainForm.enginRecordNo" placeholder="工程登录编号" disabled></el-input>
            </el-form-item>
          </el-col>
        </template>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="订单类型" prop="orderType">
            <el-input :value="$parent.findOrderType(mainForm.orderType)"  placeholder="订单类型" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="业务员" prop="serviceName">
            <el-input :value="mainForm.serviceName" placeholder="业务员" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="mainForm.remark" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="main-title">
      <div class="title">原订单货品信息</div>
    </div>

    <div class="table" style="margin-top: 20px">
      <el-table :data="originGoodsList" element-loading-text="Loading" border fit highlight-current-row stripe max-height="400">
        <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
        <el-table-column align="center" label="销售类型" prop="saleTypeName" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="产品编码" prop="materialNumber" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="产品旧编码" prop="materialOldNumber" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="产品名称" prop="materialName" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="规格型号" prop="specification" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="单位" prop="unit" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="单价" prop="price" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="数量" prop="qty" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="订单金额" prop="totalAmount" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="返利类型" prop="customerWalletName2" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="返利金额" prop="rebateAmount" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="格力折扣" prop="discAmount" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="现金钱包" prop="customerWalletName" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="实付金额" prop="payAmount" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="原数量" prop="refundableQty" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="置换数量" prop="displaceQty" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="备注" prop="remark" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="税率" prop="tax" min-width="100" show-overflow-tooltip></el-table-column>
      </el-table>
    </div>

    <div class="main-title" v-if="mainForm.orderNo">
      <div class="title">置换货品信息</div>
      <div v-if="!listItem">
        <el-select v-model="warehouseValue" placeholder="请选择发货仓库" size="small" style="margin-right: 10px">
          <el-option :label="item.name" :value="item.id" v-for="(item, index) in warehouseList" :key="index"></el-option>
        </el-select>
        <el-button type="primary" size="small" icon="el-icon-search" @click="checkStock">检查库存</el-button>
        <el-divider direction="vertical"></el-divider>
        <el-button type="primary" size="small" icon="el-icon-plus" @click="openDialog">添加货品</el-button>
      </div>
    </div>
    <div class="table" style="margin-top: 20px" v-if="mainForm.orderNo">
      <el-table :data="goodsList" element-loading-text="Loading" border fit highlight-current-row stripe max-height="400">
        <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
        <el-table-column align="center" label="销售类型" prop="saleTypeName" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="产品编码" prop="materialNumber" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="产品旧编码" prop="materialOldNumber" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="产品名称" prop="materialName" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="规格型号" prop="specification" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="单位" prop="unit" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="单价" prop="price" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="数量" prop="qty" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.qty" size="small"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单金额" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{scope.row.price * scope.row.qty}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="返利类型" prop="customerWalletId2" min-width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-select v-model="scope.row.customerWalletId2" placeholder="选择返利类型" size="small" clearable @change="changeWallet(scope.$index)">
              <el-option
                v-for="item in flWalletList"
                :key="item.customerWalletId"
                :label="item.name"
                :value="item.customerWalletId">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="使用返利金额" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            {{(scope.row.price * scope.row.qty * (scope.row.rebateRate * 100)) / 100}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="格力折扣" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{scope.row.qty * scope.row.discAmount}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="现金钱包" prop="customerWalletId" min-width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-select v-model="scope.row.customerWalletId" placeholder="选择现金钱包" size="small" clearable>
              <el-option
                v-for="item in xjWalletList"
                :key="item.customerWalletId"
                :label="item.name"
                :value="item.customerWalletId">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="实付金额" prop="payAmount" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{((scope.row.price * scope.row.qty) * 100 - ((scope.row.price * scope.row.qty * (scope.row.rebateRate * 100)) / 100) * 100 - ((scope.row.qty * (scope.row.discAmount * 100)) / 100) * 100) / 100}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注" prop="remark" min-width="160">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" size="small"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="税率" prop="tax" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="总仓库" prop="status1" min-width="100" show-overflow-tooltip v-if="!listItem">
          <template slot-scope="scope">
            <div>{{ scope.row.status1 | status1Filter }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="仓库状态" prop="status2" min-width="100" show-overflow-tooltip v-if="!listItem">
          <template slot-scope="scope">
            <div>{{ status2Filter(scope.row) }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="deleteItem(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-footer">
      <div class="footer" :class="classObj">
        <el-button type="primary" @click="clickSubmitForm">保 存</el-button>
        <el-popconfirm title="确定关闭吗？" @onConfirm="goBack" style="margin-left: 10px;">
          <el-button slot="reference">关 闭</el-button>
        </el-popconfirm>
      </div>
    </div>


    <!-- 订单列表 -->
    <el-dialog title="订单列表" :visible.sync="isShowOriginDialog" width="70%" :close-on-click-modal="false">
      <el-form v-if="mainForm.examineStatus === ''" ref="screenOriginForm" :model="screenOriginForm" label-width="80px" size="small">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="8">
            <el-form-item label="原订单号"
                          prop="orderNo"
                          :rules="{ required: true, message: '原订单号不能为空', trigger: 'blur' }"
            >
              <el-input v-model="screenOriginForm.orderNo" placeholder="原订单号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6" class="tr">
            <el-form-item label="">
              <el-button size="small" type="primary" @click="submitScreenOriginForm">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="table" style="margin: 10px 0 20px;">
        <el-table
          ref="originOrderTable"
          v-loading="dialogTable_listLoading"
          :data="dialogTable_dataList"
          element-loading-text="Loading"
          tooltip-effect="dark"
          style="width: 100%"
          border
          max-height="270">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column align="center" prop="orderType" label="订单类型" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ $parent.findOrderType(dialogTable_data.orderType) }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="saleTypeName" label="销售类型" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="materialName" label="产品名称" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="specification" label="规格型号" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="unit" label="单位" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="qty" label="数量" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="refundableQty" label="可退单置换数" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="displaceQty" label="退订置换数" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input v-model="scope.row.displaceQty" size="small"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowOriginDialog = false">关 闭</el-button>
        <el-button @click="chooseDetail">提 交</el-button>
      </div>
    </el-dialog>


    <el-dialog title="添加产品" :visible.sync="isShowDialog" width="80%">
      <el-form ref="screenForm" :model="screenForm" size="small" label-position="left">
        <el-row :gutter="20">
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="type">
              <el-select v-model="mainForm.mainId" placeholder="选择品类" style="width: 100%" disabled>
                <el-option v-for="item in typeList" :key="item.dictCode" :label="item.dictValue" :value="item.dictCode"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="salesType">
              <el-select v-model="screenForm.salesType" placeholder="选择销售类型" style="width: 100%" clearable>
                <el-option v-for="item in salesTypeList" :key="item.id" :label="item.saleName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="proNum">
              <el-input v-model="screenForm.proNum" placeholder="请输入产品编码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="proName">
              <el-input v-model="screenForm.proName" placeholder="请输入产品名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="proModel">
              <el-input v-model="screenForm.proModel" placeholder="请输入产品型号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="price1"  style="display: flex">
              <el-input v-model="screenForm.price1" placeholder="请输入价格" style="width: 46%"></el-input>
              <span> - </span>
              <el-input v-model="screenForm.price2" placeholder="请输入价格" style="width: 46%"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :lg="12" class="tr">
            <el-form-item label="">
              <el-button size="small" @click="resetScreenForm">清空</el-button>
              <el-button size="small" type="primary" @click="submitScreenForm">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

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


      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitAddGoods">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getDetail, queryRefDetail, addData, editData} from "@/api/supply/displace";
import {checkStock, getWalletList, getWarehouseList} from "@/api/supply/engin";
import {getDictList, getTypeList} from "@/api/common";
import {getGoodsList} from "@/api/supply/retail";

export default {
  name: 'DisplaceForm',
  componentName: 'DisplaceForm',
  props: ['listItem'],
  filters: {
    status1Filter(val) {
      if (val === '' || val === null || val === undefined) return '未检查';
      else if (val === 0) return '无货';
      else if (val > 0 && val <= 30) return val;
      else if (val > 30 && val <= 1000) return '有货';
      else if (val > 1000) return '充足';
    },
  },
  data() {
    return {
      editId: '',
      detailData: {},
      mainForm: {
        displaceOrderId: '',
        orderType: '',
        orderNo: '',
        orderDate: '',
        mainId: '',
        mainName: '',
        enginRecordNo: '',
        projectNo: '',
        projectName: '',
        useUnit: '',
        installAddress: '',
        policyId: '',
        policyCode: '',
        policyTitle: '',
        policyRemark: '',
        serviceId: '',
        serviceName: '',
        takeDeposit: '',
        remark: '',
        examineStatus: ''
      },
      isShowOriginDialog: false,
      isShowDialog: false,
      dialogTable_data: null, // 列表订单数据
      dialogTable_dataList: [],
      dialogTable_listLoading: false, // 列表加载loading
      screenOriginForm: {
        orderNo: ''
      },
      screenForm: {
        type: '',
        salesType: '',
        proNum: '',
        proName: '',
        proModel: '',
        price1: '',
        price2: '',
      },
      currentPage: 1,
      listTotal: 0,

      salesTypeList: [],
      typeList: [],
      goodsList: [],
      originGoodsList: [],
      warehouseList: [],
      warehouseValue: '',

      leftGoodsList: [],
      rightGoodsList: [],

      leftSelection: [],
      rightSelection: [],

      xjWalletList: [],
      flWalletList: []
    }
  },

  computed: {
    sidebar() {
      return this.$store.state.app.sidebar
    },
    classObj() {
      return {
        hideSidebar: !this.sidebar.opened,
        openSidebar: this.sidebar.opened
      }
    },
  },

  created() {
    this.getDictList();
    this.getWalletList();
    this.getSalesTypeList();
    this.getWarehouseList();

    if(this.listItem) {
      this.editId = this.listItem.displaceOrderId;
      this.getDetail();
    } else {
      this.mainForm.jxsNum = JSON.parse(localStorage.getItem("supply_user")).customerNumber;
      this.mainForm.jxsName = JSON.parse(localStorage.getItem("supply_user")).customerName;
      this.mainForm.createMan = JSON.parse(localStorage.getItem("supply_user")).nickName;
      this.mainForm.createDate = this.getDate();
    }
  },

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

    // 获取详情
    getDetail() {
      getDetail({id: this.editId}).then(res => {
        const data = res.data;
        this.mainForm.displaceOrderId = data.displaceOrderId
        this.mainForm.orderType = data.orderType
        this.mainForm.orderNo = data.orderNo
        this.mainForm.orderDate = data.orderDate
        this.mainForm.mainId = data.mainId
        this.mainForm.mainName = data.mainName
        this.mainForm.enginRecordNo = data.enginRecordNo
        this.mainForm.projectNo = data.projectNo
        this.mainForm.projectName = data.projectName
        this.mainForm.useUnit = data.useUnit
        this.mainForm.installAddress = data.installAddress
        this.mainForm.policyId = data.policyId
        this.mainForm.policyCode = data.policyCode
        this.mainForm.policyTitle = data.policyTitle
        this.mainForm.policyRemark = data.policyRemark
        this.mainForm.serviceId = data.serviceId
        this.mainForm.serviceName = data.serviceName
        this.mainForm.takeDeposit = data.takeDeposit
        this.mainForm.examineStatus = data.examineStatus

        this.originGoodsList = data.originItems
        this.goodsList = data.items
      })
    },
    // 原订单列表 - 打开弹窗
    openShareDetail() {
      this.isShowOriginDialog = true;
      if (this.mainForm.examineStatus && this.originGoodsList.length > 0) {
        this.screenOriginForm.orderNo = this.mainForm.orderNo
        this.queryRefDetail()
      }
    },
    submitScreenOriginForm() {
      this.$refs['screenOriginForm'].validate((valid) => {
        if (valid) {
          this.queryRefDetail()
        }
      })
    },
    queryRefDetail() {
      this.dialogTable_listLoading = true
      queryRefDetail({
        originOrderNo: this.screenOriginForm.orderNo
      }).then(res => {
        this.dialogTable_data = res.data;
        this.dialogTable_dataList = this.dialogTable_data.originItems
        if (this.mainForm.displaceOrderId) {
          this.originAfterHandle(this.dialogTable_dataList)
        }
        this.dialogTable_listLoading = false;
      }).catch(() => {
        this.dialogTable_listLoading = false;
      })
    },
    originAfterHandle() {
      const data = this.dialogTable_dataList
      // 历史选中的置换数回显
      this.$nextTick(() => {
        for (let i = 0; i < data.length; i++) {
          this.originGoodsList.forEach(goods => {
            if (goods.materialId === data[i].materialId) {
              data[i].displaceQty = goods.displaceQty
              this.$refs['originOrderTable'].toggleRowSelection(data[i], true)
            }
          })
        }
      })
    },
    chooseDetail() {
      const tableData = this.$refs['originOrderTable'].selection
      if (!tableData || tableData.length === 0) {
        return this.$errorMsg('请选择订单明细')
      }
      for (let i = 0; i < tableData.length; i++) {
        if (!tableData[i].displaceQty || tableData[i].displaceQty <= 0) {
          return this.$errorMsg(tableData[i].materialName + '：置换数量不能少于0')
        }
        if (tableData[i].displaceQty > tableData[i].refundableQty) {
          return this.$errorMsg(tableData[i].materialName + '：置换数量不能大于可退单置换数 ')
        }
      }
      this.originGoodsList = tableData

      this.mainForm.orderType = this.dialogTable_data.orderType
      this.mainForm.orderNo = this.dialogTable_data.orderNo
      this.mainForm.mainId = this.dialogTable_data.mainId
      this.mainForm.mainName = this.dialogTable_data.mainName
      this.mainForm.enginRecordNo = this.dialogTable_data.enginRecordNo
      this.mainForm.projectNo = this.dialogTable_data.projectNo
      this.mainForm.projectName = this.dialogTable_data.projectName
      this.mainForm.useUnit = this.dialogTable_data.useUnit
      this.mainForm.installAddress = this.dialogTable_data.installAddress
      this.mainForm.policyId = this.dialogTable_data.policyId
      this.mainForm.policyCode = this.dialogTable_data.policyCode
      this.mainForm.policyTitle = this.dialogTable_data.policyTitle
      this.mainForm.policyRemark = this.dialogTable_data.policyRemark
      this.mainForm.serviceId = this.dialogTable_data.serviceId
      this.mainForm.serviceName = this.dialogTable_data.serviceName
      this.mainForm.takeDeposit = this.dialogTable_data.takeDeposit
      this.isShowOriginDialog = false
    },
    clickSubmitForm() {
      this.$refs.mainForm.validate((valid) => {
        if (valid) {
          for(let i=0; i<this.goodsList.length; i++) {
            if (!this.goodsList[i].qty || this.goodsList[i].qty <= 0) {
              this.$errorMsg(this.goodsList[i].materialName + '数量不能小于0');
              return;
            }
            if(!this.goodsList[i].customerWalletId) {
              this.$errorMsg('请选择现金钱包');
              return;
            }
          }
          let params = {
            orderDate: this.mainForm.orderDate + ' 00:00:00',
            orderNo: this.mainForm.orderNo,
            remark: this.mainForm.remark,
            originItems: this.originGoodsList,
            items: this.goodsList
          }
          if(this.listItem) {
            params.displaceOrderId = this.editId;
            editData(params).then(res => {
              this.$successMsg('编辑成功');
              this.goBack();
              this.$parent.getList();
            })
          }else {
            addData(params).then(res => {
              this.$successMsg('添加成功');
              this.goBack();
              this.$parent.getList();
            })
          }
        }
      })
    },
    // 获取钱包列表
    getWalletList() {
      getWalletList({
        customerId: JSON.parse(localStorage.getItem("supply_user")).customerId,
        type: 'COMMONLY'
      }).then(res => {
        this.xjWalletList = res.data;
      })
      getWalletList({
        customerId: JSON.parse(localStorage.getItem("supply_user")).customerId,
        type: 'REBATE'
      }).then(res => {
        this.flWalletList = res.data;
      })
    },

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

    // 获取销售类型列表
    getSalesTypeList() {
      getTypeList({
        pageNum: 1,
        pageSize: -1
      }).then((res) => {
        this.salesTypeList = res.data.records;
      })
    },

    // 获取仓库列表
    getWarehouseList() {
      getWarehouseList({
        pageNum: 1,
        pageSize: -1
      }).then((res) => {
        this.warehouseList = res.data.records;
      })
    },
    getDate() {
      var date = new Date();
      var seperator1 = "-";
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      return year + seperator1 + month + seperator1 + strDate;
    },
    // 检查库存
    checkStock() {
      if(!this.warehouseValue) {
        return this.$errorMsg('请选择仓库');
      }
      if(!this.goodsList) {
        return this.$errorMsg('请添加货品');
      }
      let ids = [];
      this.goodsList.forEach(item => {
        ids.push(item.materialId);
      })
      checkStock({
        correspondId: this.warehouseValue,
        materialId: ids.join(',')
      }).then(res => {
        if(res.data) {
          this.goodsList.forEach((item, index) => {
            item.status1 = res.data[index].allStockNum;
            item.status2 = res.data[index].stockNum;
          })
        }
      })
    },
    // 点击 选择商品
    openDialog() {
      this.getSalesTypeList();
      this.getGoodsList();
      this.isShowDialog = true;
    },
    // 关闭 弹窗
    closeDialog() {
      this.isShowDialog = false;
    },

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

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

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

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

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

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

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

    // 确定 添加产品
    submitAddGoods() {
      this.goodsList = this.delRepeat(this.rightGoodsList, this.goodsList);
      this.isShowDialog = false;
      this.leftGoodsList = [];
      this.rightGoodsList = [];
    },

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

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

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

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

    // 更改列表当前页
    handleTableCurrentChange(val) {
      this.currentPage = val;
      this.getGoodsList();
    },
    // 修改返利钱包
    changeWallet(index) {
      if(this.goodsList[index].customerWalletId2) {
        let obj = this.flWalletList.find(o => o.customerWalletId == this.goodsList[index].customerWalletId2);
        this.goodsList[index].rebateRate = obj.rebateRate;
      }else {
        this.goodsList[index].rebateRate = '';
      }
    },
    status2Filter(item) {
      if (item.status2 === '' || item.status2 === null || item.status2 === undefined) return '未检查';
     if ( item.status2 <= 0 ) {
          return '无货'
        }else if(item.status2 >= 1 &&  item.status2 <= 30){
          return '紧缺'
        }else if(item.status2 >=31 && item.status2 <= 1000 ){
          return '有货'
        }else{
          return '充足'
        }
    },
    // 获取商品列表
    getGoodsList() {
      getGoodsList({
        pageNum: this.currentPage,
        pageSize: 10,
        mainId: this.mainForm.mainId,
        saleId: this.screenForm.salesType,
        materialCode: this.screenForm.proNum,
        materialName: this.screenForm.proName,
        specification: this.screenForm.proModel,
        price1: this.screenForm.price1,
        price2: this.screenForm.price2,
      }).then(res => {
        let oldGoodsList = this.goodsList;
        let newGoodsList = res.data.records;
        for(let i = 0; i < oldGoodsList.length; i++) {
          let oldItem = oldGoodsList[i]
          for(let j = 0; j < newGoodsList.length; j++) {
            let newItem = newGoodsList[j]
            if(newItem.materialId === oldItem.materialId){
              newGoodsList[j].selected = true;
              break;
            }
          }
        }
        res.data.records.forEach(item => {
          item.materialName = item.name;
          item.materialCode = item.number;
          item.saleTypeName = item.saleName;
          item.unit = item.baseUnit;
          item.price = item.batchPrice;
          item.tax = item.taxRate;
          item.isDirectTransfer = false;
          item.directTransferQty = '';
          item.status1 = '';
          item.status2 = '';
          item.rebateAmount = '';
          item.rebateRate = '';
          item.productPriceId = item.id;
        });
        this.leftGoodsList = res.data.records;
        this.listTotal = res.data.total;
      })
    },
  }
}
</script>

<style scoped lang="scss">
  .detail-container {
    width: 100%;
    height: 100%;
  }
  .main-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    height: 60px;
    border-bottom: 1px solid #DCDFE6;
    margin-bottom: 20px;
    .title {
      font-size: 16px;
      font-weight: 600;
      padding-left: 10px;
    }
  }
  .tables {
    display: flex;
    margin-top: 10px;
    .table {
      width: 45%;
    }
    .buttons {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding: 0 10px;
      button {
        margin: 0;
        margin-top: 10px;
      }
    }
  }
  .choose-order {

  }
</style>
