<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" :rules="mainFormRules" label-width="110px" size="small" label-position="right">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="工程订单" prop="orderNum">
            <el-input v-model="mainForm.orderNum" placeholder="系统自动生成" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8" style="height: 51px;">
          <el-form-item label="单据日期" prop="orderDate">
            <el-date-picker
              v-model="mainForm.orderDate"
              disabled
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 100%;"
              placeholder="系统自动生成">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <!-- <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="产品大类" prop="type">
            <el-input v-model="mainForm.type" disabled v-if="listItem"></el-input>
            <el-select v-model="mainForm.type" placeholder="选择产品大类" style="width: 100%" disabled v-else>
              <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="24" :sm="12" :lg="8">
          <el-form-item label="销售类型" prop="saleType">
            <el-select v-model="mainForm.saleType" placeholder="选择销售类型" style="width: 100%" clearable @change="changeSaleType">
              <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="24" :sm="12" :lg="8">
          <el-form-item label="经销商编码" prop="jxsNum">
            <el-input v-model="mainForm.jxsNum" placeholder="请输入经销商编码" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="16">
          <el-form-item label="经销商名称" prop="jxsName">
            <el-input v-model="mainForm.jxsName" placeholder="请输入经销商名称" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="工程登录编号" prop="loginNum">
            <div style="display: flex;">
              <el-input v-model="mainForm.loginNum" placeholder="请引用工程登录" disabled></el-input>
              <el-button style="margin-left: 10px;" @click="openShareDetail">引用</el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="工程项目名称" prop="enginName">
            <el-input v-model="mainForm.enginName" placeholder="请输入工程项目名称" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="工程登录类型" prop="loginType">
            <el-input v-model="mainForm.loginType" placeholder="请输入工程登录类型" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="厂工程编码" prop="factoryNum">
            <el-input v-model="mainForm.factoryNum" placeholder="请输入厂工程编码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="使用单位" prop="company">
            <el-input v-model="mainForm.company" placeholder="请输入使用单位" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="联系人" prop="contactMan">
            <el-input v-model="mainForm.contactMan" placeholder="请输入联系人" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="固定电话" prop="tel">
            <el-input v-model="mainForm.tel" placeholder="请输入固定电话" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="移动电话" prop="phone">
            <el-input v-model="mainForm.phone" placeholder="请输入移动电话" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="安装地址" prop="address">
            <el-input v-model="mainForm.address" placeholder="请输入安装地址" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="格力内部备注" prop="greeRemark">
            <el-input v-model="mainForm.greeRemark" placeholder="请输入格力内部备注"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="格力回复" prop="greeReply">
            <el-input v-model="mainForm.greeReply" placeholder="请输入格力回复"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="mainForm.remark" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="制单人" prop="createMan">
            <el-input v-model="mainForm.createMan" placeholder="请输入制单人" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8" style="height: 51px;">
          <el-form-item label="制单日期" prop="createDate">
            <el-date-picker
              v-model="mainForm.createDate"
              disabled
              type="date"
              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="fileNum">
            <el-input v-model="mainForm.fileNum" placeholder="请输入文件编号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="main-title">
      <div class="title">货品信息</div>
      <div>
        <el-select v-model="warehouseValue" placeholder="请选择发货仓库" size="small" style="margin-right: 10px">
          <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>
      </div>
    </div>

    <div class="table" style="margin-top: 20px">
      <el-table :data="goodsList" element-loading-text="Loading" border fit highlight-current-row stripe max-height="400">
        <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
        <el-table-column align="center" label="引用记录" prop="useRefCount" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="销售类型" prop="saleTypeName" min-width="120" show-overflow-tooltip></el-table-column>
        <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="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="单价" prop="price" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="工程登录数量" prop="enginNum" min-width="120" 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="changeFlWallet(scope.$index)">
              <el-option
                v-for="item in scope.row.rebateWallets"
                :key="item.customerWalletId"
                :label="item.customerWalletName"
                :value="item.customerWalletId">
              </el-option>
            </el-select>
          </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 * (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 @change="changeXjWallet(scope.$index)">
              <el-option
                v-for="item in scope.row.wallets"
                :key="item.customerWalletId"
                :label="item.customerWalletName"
                :value="item.customerWalletId">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="实付金额" prop="qty" 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="isDirectTransfer" min-width="100">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.isDirectTransfer"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column align="center" label="直调数量" prop="directTransferQty" min-width="100"></el-table-column>
        <el-table-column align="center" label="已发货数量" prop="hasSendQty" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="已退数量" prop="retiredQty" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="备注" prop="remark" min-width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" size="small"></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>
          <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>
          <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">
        <el-button type="primary" @click="clickSubmitForm(1)">保 存</el-button>
        <el-button type="primary" @click="clickSubmitForm(2)">提交审核</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="isShowDialog" width="70%" :close-on-click-modal="false">
      <el-form ref="screenForm" :model="screenForm" label-width="0" size="small" label-position="left">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item prop="loginNum">
              <el-input v-model="screenForm.loginNum" placeholder="工程登录编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item prop="enginName">
              <el-input v-model="screenForm.enginName" placeholder="工程项目"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item prop="company">
              <el-input v-model="screenForm.company" placeholder="使用单位"></el-input>
            </el-form-item>
          </el-col>

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

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

  </div>
</template>

<script>
import { getOrderDetail, getHomeLoginList, getHomeLoginDetail, getWarehouseList, addHome, editHome, submitHome, checkStock, getWalletList } from "@/api/supply/engin";
import { getDictList, getTypeList } from '@/api/common'

let that
export default {
  name: 'HomeForm',
  componentName: 'HomeForm',
  props: ['listItem'],
  filters: {
    status1Filter(val) {
      let STOCK_ORDER_START = that.stockList.find(o => o.dictCode == 'STOCK_ORDER_START').dictValue;
      let STOCK_ORDER_END = that.stockList.find(o => o.dictCode == 'STOCK_ORDER_END').dictValue;
      let STOCK_ORDER_HAVE_START = that.stockList.find(o => o.dictCode == 'STOCK_ORDER_HAVE_START').dictValue;
      let STOCK_ORDER_HAVE_END = that.stockList.find(o => o.dictCode == 'STOCK_ORDER_HAVE_END').dictValue;
      let STOCK_ORDER_ALL_NUM = that.stockList.find(o => o.dictCode == 'STOCK_ORDER_ALL_NUM').dictValue;
      if (val === '' || val === null || val === undefined) return '未检查';
      else if (val === 0) return '无货';
      else if (val > STOCK_ORDER_START && val <= STOCK_ORDER_END) return val;
      else if (val >= STOCK_ORDER_HAVE_START && val <= STOCK_ORDER_HAVE_END) return '有货';
      else if (val > STOCK_ORDER_ALL_NUM) return '充足';
    },
  },
  data() {
    return {
      editId: '',
      mainForm: {
        orderNum: '',
        orderDate: '',
        type: '',
        jxsNum: '',
        jxsName: '',
        loginNum: '',
        enginName: '',
        loginType: '',
        factoryNum: '',
        company: '',
        saleType: '',
        contactMan: '',
        tel: '',
        phone: '',
        address: '',
        greeRemark: '',
        greeReply: '',
        remark: '',
        createMan: '',
        createDate: '',
        fileNum: '',
        loginUserId: ''
      },
      mainFormRules: {
        // orderDate: [{ required: true, message: '请选择单据日期', trigger: 'change' }],
        jxsNum: [{ required: true, message: '请输入经销商编码', trigger: 'blur' }],
        jxsName: [{ required: true, message: '请输入经销商名称', trigger: 'blur' }],
        loginNum: [{ required: true, message: '请输入工程登录编号', trigger: 'blur' }],
        enginName: [{ required: true, message: '请输入工程项目名称', trigger: 'blur' }],
        loginType: [{ required: true, message: '请输入工程登录类型', trigger: 'blur' }],
        company: [{ required: true, message: '请输入使用单位', trigger: 'blur' }],
        saleType: [{ required: true, message: '请选择销售类型', trigger: 'change' }],
        // contactMan: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
        // tel: [{ required: true, message: '请输入固定电话', trigger: 'blur' }],
        // phone: [{ required: true, message: '请输入移动电话', trigger: 'blur' }],
        address: [{ required: true, message: '请输入安装地址', trigger: 'blur' }],
      },
      salesTypeList: [],
      // typeList: [],
      stockList: [],
      goodsList: [],

      isShowDialog: false, // 工程登录列表 - 弹窗
      screenForm: {
        loginNum: '',
        enginName: '',
        company: '',
      },
      dialogTable_dataList: null, // 工程登录列表 - 列表数据
      dialogTable_listLoading: true, // 工程登录列表 - 列表加载loading
      dialogTable_currentPage: 1, // 工程登录列表 - 当前页码
      dialogTable_pageSize: 10, // 工程登录列表 - 每页数量
      dialogTable_listTotal: 0, // 工程登录列表 - 列表总数

      warehouseList: [],
      warehouseValue: '',
    }
  },

  beforeCreate() {
    that = this;
  },

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

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

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

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

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

    // 获取销售类型列表
    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;
      })
    },

    // 获取详情
    getDetail() {
      getOrderDetail({id: this.editId}).then(res => {
        let data = res.data;
        this.mainForm.orderNum = data.enginOrderId;
        this.mainForm.orderDate = data.orderDate;
        this.mainForm.type = data.mainId;
        this.mainForm.jxsNum = data.customerId;
        this.mainForm.jxsName = data.customerName;
        this.mainForm.loginNum = data.refEnginRecordNo;
        this.mainForm.enginName = data.refProjectName;
        this.mainForm.loginType = data.refPromiseStatus;
        this.mainForm.factoryNum = data.refFactoryNo;
        this.mainForm.company = data.refUseUnit;
        this.mainForm.saleType = data.saleTypeId;
        this.mainForm.contactMan = data.refLinkman;
        this.mainForm.tel = data.refTel;
        this.mainForm.phone = data.refPhone;
        this.mainForm.address = data.refInstallAddress;
        this.mainForm.greeRemark = data.note2;
        this.mainForm.greeReply = data.note1;
        this.mainForm.remark = data.remark;
        this.mainForm.createMan = data.createName;
        this.mainForm.createDate = data.createTime;
        this.mainForm.fileNum = data.fileNo;

        data.items.forEach(item => {
          item.status1 = '';
          item.status2 = '';
          item.rebateWallets = item.customerWalletList.filter(item => {
            return item.type === 'REBATE';
          });
          item.wallets = item.customerWalletList.filter(item => {
            return item.type === 'COMMONLY';
          });
        })
        this.goodsList = data.items;
      })
    },

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

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

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

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

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

    // 选择工程登录
    chooseItem(id) {
      getHomeLoginDetail({
        recordNo: id,
        saleTypeId: this.mainForm.saleType,
      }).then(res => {
        this.isShowDialog = false;
        let data = res.data;
        this.mainForm.type = data.productCategory;
        this.mainForm.loginUserId = data.userid;
        // this.mainForm.saleType = '';
        this.mainForm.loginNum = data.recordNo;
        this.mainForm.enginName = data.projectName;
        this.mainForm.loginType = data.promiseStatus;
        this.mainForm.company = data.useUnit;
        this.mainForm.contactMan = data.buyUnitCallMen;
        this.mainForm.tel = data.buyUnitTel;
        this.mainForm.phone = data.buyUnitPhone;
        this.mainForm.address = data.installAddress;

        let saleTypeItem = this.salesTypeList.find(o => o.id == this.mainForm.saleType);

        this.goodsList = data.items.map(item => {
          return {
            useRefCount: '',
            saleTypeId: saleTypeItem.id,
            saleTypeCode: saleTypeItem.saleCode,
            saleTypeName: saleTypeItem.saleName,
            materialId: item.materialId,
            materialNumber: item.materialNumber,
            materialOldNumber: item.materialOldNumber,
            materialName: item.materialName,
            specification: item.machine,
            unit: item.unit,
            price: item.price,
            enginNum: '',
            qty: item.num,
            customerWalletId2: '',
            rebateRate: '',
            discAmount: '',
            customerWalletId: '',
            isDirectTransfer: false,
            directTransferQty: '',
            hasSendQty: '',
            remark: item.discri,
            tax: '',
            status1: '',
            status2: '',
            rebateWallets: item.customerWalletList.filter(item => {
              return item.type === 'REBATE';
            }),
            wallets: item.customerWalletList.filter(item => {
              return item.type === 'COMMONLY';
            }),
          }
        })
      })
    },

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

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

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

    // 修改现金钱包
    changeXjWallet(index) {
      if(this.goodsList[index].customerWalletId) {
        let obj = this.goodsList[index].wallets.find(o => o.customerWalletId == this.goodsList[index].customerWalletId);
        this.goodsList[index].customerWalletName = obj.customerWalletName;
      }else {
        this.goodsList[index].customerWalletName = '';
      }
    },

    // 检查库存
    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;
          })
        }
      })
    },

    status2Filter(item) {
      if (item.status2 === '' || item.status2 === null || item.status2 === undefined) return '未检查';
      else if (item.status2 >= item.qty) return '可用';
      else return '短缺';
    },

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

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

          let saleTypeItem = this.salesTypeList.find(o => o.id == this.mainForm.saleType);
          let params = {
            enginOrderId: this.mainForm.orderNum,
            // orderDate: this.mainForm.orderDate,
            // mainId: this.mainForm.type || '',
            loginUserId: this.mainForm.loginUserId,
            refEnginRecordNo: this.mainForm.loginNum || '',
            refProjectName: this.mainForm.enginName || '',
            refPromiseStatus: this.mainForm.loginType || '',
            refFactoryNo: this.mainForm.factoryNum || '',
            refUseUnit: this.mainForm.company || '',
            refLinkman: this.mainForm.contactMan || '',
            refTel: this.mainForm.tel || '',
            refPhone: this.mainForm.phone || '',
            refInstallAddress: this.mainForm.address || '',
            saleTypeId: this.mainForm.saleType,
            saleTypeCode: saleTypeItem.saleCode,
            saleTypeName: saleTypeItem.saleName,
            note2: this.mainForm.greeRemark || '',
            note1: this.mainForm.greeReply || '',
            remark: this.mainForm.remark || '',
            fileNo: this.mainForm.fileNum || '',
            items: this.goodsList,
          }
          if(type === 1) {
            if(this.listItem) {
              editHome(params).then(res => {
                this.$successMsg('编辑成功');
                this.goBack();
                this.$parent.getList();
              })
            }else {
              addHome(params).then(res => {
                this.$successMsg('新增成功');
                this.goBack();
                this.$parent.getList();
              })
            }
          }else if(type === 2) {
            submitHome(params).then(res => {
              this.$successMsg('提交审核成功');
              this.goBack();
              this.$parent.getList();
            })
          }
        }
      })
    },
  }
}
</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;
    }
  }

  ::v-deep input::-webkit-outer-spin-button,
  ::v-deep input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  ::v-deep input[type='number'] {
    -moz-appearance: textfield;
  }
</style>
