<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="100px" 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="date">
            <el-date-picker
              v-model="mainForm.date"
              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="salesMan">
            <el-select v-model="mainForm.salesMan" placeholder="选择业务员" size="small" filterable clearable style="width: 100%">
              <el-option
                v-for="item in salesmanList"
                :key="item.adminUserId"
                :label="item.nickName"
                :value="item.adminUserId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <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="fileNum">
            <el-input v-model="mainForm.fileNum" placeholder="请输入文件编号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="16">
          <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>
        <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">
      <el-table :data="goodsList" element-loading-text="Loading" border fit highlight-current-row stripe max-height="400"
        show-summary
        :summary-method="$getSummaries">
        <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
        <el-table-column align="center" label="销售类型" prop="saleTypeName" min-width="140" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-select v-model="scope.row.saleTypeId" placeholder="选择销售类型" size="mini" clearable style="width: 100%" @change="changeSaleType(scope.$index)" v-if="listItem">
              <el-option v-for="item in salesTypeList" :key="item.id" :label="item.saleName" :value="item.id"></el-option>
            </el-select>
            <div v-else>{{scope.row.saleTypeName}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="物料编码" prop="materialCode" min-width="120" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="产品编码" prop="materialOldNumber" min-width="120" 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>
          <template slot-scope="scope">
            <el-input v-model="scope.row.specification" size="small" v-if="listItem"></el-input>
            <div v-else>{{scope.row.specification}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="单位" prop="unit" min-width="100" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column align="left" label="文件编号" prop="fileNo" min-width="200" show-overflow-tooltip>
          <template slot-scope="scope">
               <el-input v-model="scope.row.fileNo" size="small" ></el-input>
          </template>
           </el-table-column> -->
        <el-table-column align="right" label="单价" prop="price" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.price" size="small" type="number" @mousewheel.native.prevent v-if="listItem && !isDealer"></el-input>
            <div v-else>{{scope.row.price | numToFixed}}</div>
          </template>
        </el-table-column>
        <el-table-column align="right" label="数量" prop="qty" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.qty" size="small" type="number" @mousewheel.native.prevent></el-input>
          </template>
        </el-table-column>
        <el-table-column align="right" label="订单金额" prop="compute_amount" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{(scope.row.price * scope.row.qty) | numToFixed}}
          </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 scope.row.rebateWallets"
                :key="item.customerWalletId"
                :label="item.customerWalletName"
                :value="item.customerWalletId">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="right" label="可用返利" prop="rebateAmount" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{scope.row.rebateAmount | numToFixed}}
          </template>
        </el-table-column>
        <el-table-column align="right" label="使用返利金额" prop="compute_flAmount" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            {{(((scope.row.price - scope.row.discAmount) * scope.row.qty * (scope.row.rebateRate * 100)) / 100) | numToFixed}}
          </template>
        </el-table-column>
        <el-table-column align="right" label="格力折扣" prop="compute_zkAmount" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{(scope.row.qty * scope.row.discAmount) | numToFixed}}
          </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 scope.row.wallets"
                :key="item.customerWalletId"
                :label="item.customerWalletName"
                :value="item.customerWalletId">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="right" label="实付金额" prop="compute_sfAmount" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{(((scope.row.price * scope.row.qty) * 100 - (((scope.row.price - scope.row.discAmount) * scope.row.qty * (scope.row.rebateRate * 100)) / 100) * 100 - ((scope.row.qty * (scope.row.discAmount * 100)) / 100) * 100) / 100) | numToFixed}}
          </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="right" label="直调数量" prop="directTransferQty" min-width="100"></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 >
          <template slot-scope="scope">
            <div>{{ status2Filter(scope.row) }}</div>
          </template>
        </el-table-column>

        <!-- <el-table-column align="center" label="业务员" prop="serviceId" min-width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-select v-model="scope.row.serviceId" placeholder="选择业务员" size="small" clearable disabled>
              <el-option
                v-for="item in salesmanList"
                :key="item.adminUserId"
                :label="item.nickName"
                :value="item.adminUserId">
              </el-option>
            </el-select>
          </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">保 存</el-button>
        <el-popconfirm title="确定关闭吗？" @onConfirm="goBack" style="margin-left: 10px;">
          <el-button slot="reference">返回列表</el-button>
        </el-popconfirm>
      </div>
    </div>

    <el-dialog v-drag title="添加产品"  :visible.sync="isShowDialog" width="80%" :modal="false"   >
      <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="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="18" 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="materialNumber" min-width="120" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" label="产品编码" prop="materialOldNumber" min-width="120" 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-column align="center" label="销售类型" prop="saleName" 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="saleName" min-width="80" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" label="物料编码" prop="materialNumber" min-width="120" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" label="产品编码" prop="materialOldNumber" min-width="120" 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 {
  addData,
  checkStock,
  editData,
  getDetail,
  getGoodsList,
  getSalesTypeList,
  getWarehouseList
} from '@/api/supply/retail'
import { getDictList, getSalesmanList } from '@/api/common'
import { findElem } from '@/utils/util'

let that
export default {
  name: 'RetailForm',
  componentName: 'RetailForm',
  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 '充足';
    },
  },
  directives:{
    drag:{
      bing: function (el) {
        console.log(el);
          let oDiv = el
          oDiv.onmousedown = e =>{
            console.log('onmousedown');
            let disX = e.clientX - oDiv.offsetLeft
            let disY = e.clientY - oDiv.offSetTop

          document.onmousemove = e =>{
            let left = e.clientX - disX
            let top = e.clientY - disY
            oDiv.style.left = left + 'px'
            oDiv.style.top = top + 'px'
          }

          document.onmouseup = e =>{
            document.onmousemove = null
            document.onmouseup = null
          }

        }
      }
    }
  },
  data() {
    return {
      mainForm: {
        orderNum: '',
        date: '',
        // type: '',
        jxsNum: '',
        jxsName: '',
        fileNum: '',
        remark: '',
        salesMan: '',
      },
      mainFormRules: {
        // date: [
        //   { required: true, message: '请选择单据日期', trigger: 'change' }
        // ],
        // type: [
        //   { required: true, message: '请选择品类', trigger: 'change' }
        // ],
      },
      goodsList: [],

      warehouseList: [],
      warehouseValue: '',
      isShowDialog: false,
      screenForm: {
        type: '',
        salesType: '',
        proNum: '',
        proName: '',
        proModel: '',
        price1: '',
        price2: '',
        fileNum:''
      },
      currentPage: 1,
      listTotal: 0,
      salesTypeList: [],
      typeList: [],
      stockList: [],

      leftGoodsList: [],
      rightGoodsList: [],

      leftSelection: [],
      rightSelection: [],

      isFirst: false,
      salesmanList: [],
    }
  },

  computed: {
    isDealer() {
      return JSON.parse(localStorage.getItem("supply_user")).isCustomer;
    },

    outSalesmanList() {
      let list = [];
      if(this.goodsList && this.goodsList.length) {
        this.goodsList.forEach(item => {
          if(item.serviceId) {
            let hasItem = findElem(list, 'adminUserId', item.serviceId);
            if(hasItem < 0) {
              let obj = this.salesmanList.find(o => o.adminUserId == item.serviceId);
              if(obj) {
                list.push(obj);
              }
            }
          }
        })
        if(this.isFirst) {
          this.isFirst = false;
        }else {
          this.mainForm.salesMan = this.goodsList[0].serviceId;
        }
      }
      return list
    }
  },

  watch: {
    goodsList: {
      handler(newValue, oldValue) {
        if(this.goodsList && this.goodsList.length) {
          if(this.isFirst) {
            this.isFirst = false;
          }else {
            // this.mainForm.salesMan = this.goodsList[0].serviceId;
          }
        }else {
          this.mainForm.salesMan = '';
        }

        if(newValue && newValue.length) {
          newValue.forEach((item, index) => {
            this.goodsList[index].compute_amount = item.price * item.qty;
            this.goodsList[index].compute_flAmount = ((item.price - item.discAmount) * item.qty * (item.rebateRate * 100)) / 100;
            this.goodsList[index].compute_zkAmount = item.qty * item.discAmount;
            this.goodsList[index].compute_sfAmount = ((item.price * item.qty) * 100 - (((item.price - item.discAmount) * item.qty * (item.rebateRate * 100)) / 100) * 100 - ((item.qty * (item.discAmount * 100)) / 100) * 100) / 100;
          })
        }
      },
      immediate: true,
      deep: true
    }
  },

  beforeCreate() {
    that = this;
  },

  async created() {
    await this.getSalesmanList();
    this.getDictList();
    this.getWarehouseList();
    this.getSalesTypeList();
    if(this.listItem) {
      this.isFirst = true;
      this.getDetail();
    }else {
      this.mainForm.jxsNum = JSON.parse(localStorage.getItem("supply_user")).customerNumber;
      this.mainForm.jxsName = JSON.parse(localStorage.getItem("supply_user")).customerName;
    }
  },

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

    // 获取详情
    getDetail() {
      getDetail({id: this.listItem.id}).then(res => {
        let data = res.data;
        this.mainForm.orderNum = data.id;
        this.mainForm.date = data.theTime.slice(0, 10);
        this.mainForm.salesMan = data.k3ServiceId;
        this.mainForm.jxsNum = data.customerNumber;
        this.mainForm.jxsName = data.customerName;
        this.mainForm.fileNum = data.fileNo;
        this.mainForm.remark = data.remark;

        data.retailOrderItemList.forEach(item => {
          item.status1 = '';
          item.status2 = '';
          item.rebateAmount = item.curRebateAmount;

          item.sums1 = ['qty', 'directTransferQty'];
          item.sums2 = ['price', 'rebateAmount', 'compute_amount', 'compute_flAmount', 'compute_zkAmount', 'compute_sfAmount'];
        })
        this.goodsList = data.retailOrderItemList;
      })
    },

    // 获取仓库列表
    getWarehouseList() {
      getWarehouseList({
        pageNum: 1,
        pageSize: -1
      }).then((res) => {
        this.warehouseList = res.data.records;
      })
    },

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

    getDictList() {
      // getDictList({sysDictEnum: 'PRODUCT_TYPE'}).then(res => {
      //   this.typeList = res.data;
      // })
      getDictList({sysDictEnum: 'STOCK_ORDER'}).then(res => {
        this.stockList = res.data;
      })
    },

    async getSalesmanList() {
      const res = await getSalesmanList({
        pageNum: 1,
        pageSize: -1,
        isCustomer: 0,
        status: true,
      });
      this.salesmanList = res.data.records;
    },

    // 获取商品列表
    getGoodsList() {
      getGoodsList({
        pageNum: this.currentPage,
        pageSize: 10,
        // mainId: this.mainForm.type,
        saleId: this.screenForm.salesType,
        materialCode: this.screenForm.proNum,
        materialName: this.screenForm.proName,
        specification: this.screenForm.proModel,
        price1: this.screenForm.price1,
        price2: this.screenForm.price2,
            customerId:this.listItem ?this.listItem.customerId :'' ,
      }).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.id === oldItem.id){
              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;
          item.customerWalletId = (item.wallets && item.wallets.length) ? item.wallets[0].customerWalletId : '';
          item.serviceId = (item.wallets && item.wallets.length) ? item.wallets[0].serviceId : '';
          item.serviceName = (item.wallets && item.wallets.length) ? item.wallets[0].serviceName : '';
          item.needDeleteId = true;

          item.sums1 = ['qty', 'directTransferQty'];
          item.sums2 = ['price', 'rebateAmount', 'compute_amount', 'compute_flAmount', 'compute_zkAmount', 'compute_sfAmount'];
        });
        this.leftGoodsList = res.data.records;
        this.listTotal = res.data.total;
      })
    },

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

    // 点击 选择商品
    openDialog() {
      this.isShowDialog = true;
      // if(this.mainForm.type) {
        this.getGoodsList();
      // }
    },

    // 提交筛选表单
    submitScreenForm() {
      // if(!this.mainForm.type) {
      //   return this.$errorMsg('请选择产品大类');
      // }
      this.currentPage = 1;
      this.getGoodsList();
    },

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

    // 更改列表当前页
    handleTableCurrentChange(val) {
      this.currentPage = val;
      this.getGoodsList();
    },

    // 关闭 弹窗
    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].id == newArr[j].id){ // 让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 = [];
    },

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

    // 修改返利钱包
    changeWallet(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].rebateAmount = obj.amount;
      }else {
        this.goodsList[index].rebateRate = '';
        this.goodsList[index].rebateAmount = '';
      }
    },

    changeSaleType(index) {
      if(this.goodsList[index].saleTypeId) {
        let obj = this.salesTypeList.find(o => o.id == this.goodsList[index].saleTypeId);
        this.goodsList[index].saleTypeName = obj.saleName;
        this.goodsList[index].saleTypeCode = obj.saleCode;
      }else {
        this.goodsList[index].saleTypeName = '';
        this.goodsList[index].saleTypeCode = '';
      }
    },

    // 检查库存
    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) {
      console.log(item.refundableQty,'uiui' ,item.status2 );
      if (item.status2 === '' || item.status2 === null || item.status2 === undefined) return '未检查';

        if ( item.status2 <= 0 ) {
          return '无货'
        }else if(item.status2 >= 1 &&  item.status2 <= 30){
          return item.status2
        }else if(item.status2 >=31 && item.status2 <= 1000 ){
          return '有货'
        }else{
          return '充足'
        }

      // else if (item.status2 <= 0) return '无货';
      // else if (item.status2 >= item.qty) return '可用';
      // else return '短缺';
    },

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

          let goodsList = JSON.parse(JSON.stringify(this.goodsList));
          goodsList.forEach(item => {
            delete item.rebateWallets;
            delete item.wallets;
            if(item.needDeleteId) {
              delete item.id;
            }
          })

          let saleManItem = this.mainForm.salesMan ? this.salesmanList.find(o => o.adminUserId == this.mainForm.salesMan) : '';
          let params = {
            // theTime: this.mainForm.date + ' 00:00:00',
            // mainId: this.mainForm.type,
            // mainName,
            k3ServiceId: this.mainForm.salesMan,
            k3ServiceName: saleManItem.nickName || '',
            fileNo: this.mainForm.fileNum,
            remark: this.mainForm.remark,
            type: 1, // 1:普通零售单，2:政策零售单
            retailOrderItemList: goodsList
          }
          if(this.listItem) {
            params.id = this.listItem.id;
            editData(params).then(res => {
              this.$successMsg('编辑成功');
              this.goBack();
              this.$parent.getList();
            })
          }else {
            addData(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;
    }
  }
  .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;
      }
    }
  }
</style>
