<template>
  <div class="app-container">
    <div class="app-container-search main-bgcolor main-radius">
      <h1 class="">出库管理</h1>
      <br />

      <!-- 搜索工作栏 -->
      <Bound
        ref="searchForm"
        :searchFormParam="{ queryParams, dataSource }"
        :showSearch.sync="showSearch"
        @handleQuery="handleQuery"
        @resetQuery="resetQuery"
      ></Bound>
    </div>

    <div class="app-container-list main-bgcolor main-radius shopping">
      <!-- 操作工具栏 -->
      <div class="shopping-top">
        <div class="shopping-title">出库管理列表</div>
        <el-button class="shopping-add-btn" type="primary" plain @click="handleAdd"
              :loading="exportLoading"  v-hasPermi="['flow:outbound:create']">新建出库信息</el-button>
      </div>

      <!-- 列表 -->
      <el-table v-loading="loading" :data="list">
        <el-table-column label="编号" align="center" type="index" width="80" >
          <template v-slot="{ $index }">
            <span>{{($index+1)+ (queryParams.pageNo-1)*queryParams.pageSize }}</span>
          </template>
        </el-table-column>
        <el-table-column label="出库时间" align="center" prop="outBoundTime" width="170">
          <template slot-scope="{row}">
            <span>{{parseTime(row.outBoundTime)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="出库单号" align="center" prop="outBoundId" width="245">
          <template slot-scope="{ row }">
            <el-tooltip class="item" effect="dark" :content="row.outBoundId" placement="top">
              <div class="table-column">
                <span class="more-width-20">{{row.outBoundId}}</span>
                <el-button type="text" icon="el-icon-copy-document" @click.stop="copyContent(row.outBoundId)"></el-button>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="经销商名称" align="center" prop="vendorName" width="245">
          <template slot-scope="{ row }">
             <div class="table-column">
               <span class="more-width-20">{{ row.vendorName }}</span>
               <el-button type="text" icon="el-icon-copy-document" @click.stop="copyContent(row.vendorName)"></el-button>
             </div>
          </template>
        </el-table-column>
        <el-table-column
          label="所属商户"
          align="center"
          prop="belongBusinessName"
        >
          <template slot-scope="{ row }">
             <div class="table-column">
               <span class="more-width-20">{{ row.belongBusinessName }}</span>
               <el-button type="text" icon="el-icon-copy-document" @click.stop="copyContent(row.belongBusinessName)"></el-button>
             </div>
          </template>
        </el-table-column>
        <!-- 上链状态就是状态 -->
        <el-table-column label="状态" align="center" prop="blockState" width="150" >
          <template slot-scope="{row}">
            <div class="table-column">
              <el-tag
                :type="row.blockState==0?'info':row.blockState == 1?'success':'danger'">
                {{filterText(row.blockState)}}
              </el-tag>
            </div>
           </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template v-slot="scope">
            <el-button
              size="mini"
              type="text"
              v-hasPermi="['flow:outbound:update']"
              @click="handleUpdate(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleWatch(scope.row)"
            >查看</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleCopy(scope.row)"
            >复制</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleState(scope.row,'upChain')"
              v-if="scope.row.blockState == 0"
            >上传</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleState(scope.row,'freeze')"
              v-if="scope.row.blockState == 1"
            >冻结</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleState(scope.row,'active')"
              v-if="scope.row.blockState == 2"
            >激活</el-button>
          </template>
        </el-table-column>
        <div slot="empty">
          <EmptyBound />
        </div>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNo"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      v-dialogDrag
      append-to-body
      width="60%"
    >

    <el-dialog
      :width="isQrcode?'800px':'55%'"
      :title="isQrcode?'商品信息列表':'添加经销商'"
      :visible.sync="open2"
      :class="isQrcode?'line':''"
      append-to-body>

        <el-dialog
          width="700px"
          :title="titleArea"
          v-if="open4"
          :visible.sync="open4"
          append-to-body>
          <el-form ref="formArea" :model="formArea" :rules="rulesArea" label-position="top" label-width="100px">
            <el-form-item label="商品销售区域" prop="saleArea">
              <!-- <areaByld
              class="w100"
              v-if="open4"
              @transfer="formArea.saleArea = $event"
              @transferId="formArea.saleAreaId = $event"
              :isValue="String(formArea.saleAreaId)"
              :pca="areaOptions"></areaByld> -->
              <el-input v-model="formArea.saleArea" placeholder="请输入商品经销区域" style="width: 47%;"></el-input>
            </el-form-item>
            <Transfer
            ref="goodsTransfer"
            :data="goodsOptions"
            :vModel="inputCheckedIdList"
            :renderContent="renderTransferLabel"
            :titles="['可选', '已选']"
            @change="handleSelectChange"
            :leftCurrentPage="leftCurrentPage"
            :rightCurrentPage="rightCurrentPage"
            @handlePageChange="handlePageChange"
            :leftDefaultChecked="leftDefaultChecked"
            :rightDefaultChecked="rightDefaultChecked"
            ></Transfer>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="closeOpen4">取 消</el-button>
            <el-button type="primary" @click="submit4">确 定</el-button>
          </div>
        </el-dialog>

      <template v-if="!isQrcode">
          <el-form ref="formDealer" :model="formDealer" :rules="rulesDealer" label-width="130px">
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="经销商名称" prop="dealerName">
                  <el-input class="w100" v-model="formDealer.dealerName" placeholder="请输入经销商名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属商户" prop="belongBusinessName">
                  <el-select class="w100" ref="businessName" @change="handchangeBusiness" v-model="formDealer.belongBusinessId" placeholder="请选择所属商户">
                    <el-option v-for="item in businessNameList" :key="item.id" :label="item.businessName" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="负责人" prop="contactName">
                  <el-input class="w100" v-model="formDealer.contactName" placeholder="请输入负责人"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系方式" prop="contactPhone">
                  <el-input class="w100" v-model="formDealer.contactPhone" placeholder="请输入联系方式"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="销售区域" prop="commonSaleArea">
                  <!-- <areaByld
                  class="w100"
                  @transfer="formDealer.commonSaleArea = $event"
                  @transferId="formDealer.commonSaleAreaId = $event"
                  :isValue="String(formDealer.commonSaleAreaId)"
                  :pca="areaOptions"></areaByld> -->
                  <el-input v-model="formDealer.commonSaleArea"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="统一社会信用代码" prop="businessCode">
                  <el-input class="w100" v-model="formDealer.businessCode" placeholder="请输入"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注" prop="remarks">
                  <el-input type="textarea" class="w100" v-model="formDealer.remarks" placeholder="请输入"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <div class="content">
            <h2 style="float: left;">该经销商销售区域/商品</h2>
            <el-button style="float: right; margin-bottom: 10px" type="primary" @click="handleExport" :loading="exportLoading" v-hasPermi="['identity:diversion-stats:export']" >新增</el-button>
          </div>
          <el-table  :data="tableData">
            <!-- <el-table-column label="省级" align="center" prop="province" />
            <el-table-column label="市级" align="center" prop="city" />
            <el-table-column label="县级" align="center" prop="count" /> -->
            <el-table-column label="商品经销商区域" align="center" prop="saleArea" />
            <el-table-column label="绑定商品" align="center" prop="goodsName" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template v-slot="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="handeleChangeAreaGoods(scope.row,scope.$index)"
                >编辑</el-button>

                <el-popconfirm
                  title="确定删除吗？"
                  @confirm="handeleDelAreaGoods(scope.$index)"
                >
                  <el-button
                    slot="reference"
                    size="mini"
                    type="text"
                  >删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
            <div slot="empty">
              <EmptyBound />
            </div>
          </el-table>
      </template>

      <template v-if="isQrcode">
        <Transfer
        ref="goodsTransfer"
        :data="saleGoodsOptions"
        :vModel="inputCheckedIdList"
        :renderContent="renderTransferLabel"
        :titles="['可选', '已选']"
        @change="handleSelectChange"
        :leftCurrentPage="leftCurrentPage"
        :rightCurrentPage="rightCurrentPage"
        @handlePageChange="handlePageChange"
        :leftDefaultChecked="leftDefaultChecked"
        :rightDefaultChecked="rightDefaultChecked"
        ></Transfer>
      </template>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel2">取 消</el-button>
        <el-button type="primary" @click="isQrcode?submitFormQrcode():submitForm2()">确 定</el-button>
      </div>
    </el-dialog>

      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="经销商名称" prop="vendorId">
              <el-select
                class="w100"
                v-model="form.vendorId"
                placeholder="请选择经销商"
                ref="vendorRef"
                @change="changeVendorId"
                :disabled="disabled || disabledWatch"
              >
                <el-option
                  v-for="item in vendorList"
                  :key="item.dealerId"
                  :label="item.dealerName"
                  :value="item.dealerId"
                  :belongBusinessId="item.belongBusinessId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- disabledWatch-查看出库单- station:高度36px占位 -->
          <el-col :span="12">
            <el-form-item label=""  :class="[disabledWatch?'station':'']">
              <el-button v-if="!disabledWatch" type="primary" @click="showOpen2">新增</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库单号" prop="outBoundId">
              <el-input
                v-model="form.outBoundId"
                placeholder="请输入出库单号"
                disabled
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="出库时间" prop="outBoundTime">
              <el-date-picker
                :style="{ width: '100%' }"
                clearable
                v-model="form.outBoundTime"
                type="datetime"
                format="yyyy-MM-dd HH:mm"
                value-format="timestamp"
                placeholder="选择出库时间"
                :disabled="disabledWatch"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="承运车辆" prop="carrier">
              <el-input
                v-model="form.carrier"
                placeholder="请输入承运车辆"
                :disabled="disabledWatch"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="承运人" prop="carrierVehicles">
              <el-input
                v-model="form.carrierVehicles"
                placeholder="请输入承运人"
                :disabled="disabledWatch"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="carrierContact">
              <el-input
                v-model="form.carrierContact"
                placeholder="请输入联系方式"
                :disabled="disabledWatch"
              /> </el-form-item
          ></el-col>
        </el-row>
      </el-form>

      <el-button
        v-if="!disabledWatch"
        style="float: right; margin-bottom: 10px"
        type="primary"
        @click="storage"
        >选择商品</el-button
      >
      <el-table v-loading="outboundGoodsLoading" :data="form.outboundGoods">
        <el-table-column fixed type="selection" width="45" />
        <el-table-column
          label="序号"
          align="center"
          type="index"
          min-width="36px"
        />
        <el-table-column label="商品名称" align="center" prop="goodsName" width="100" />
        <el-table-column label="商品编码" align="center" prop="goodsId" width="100" >
          <template slot-scope="{ row }">
            <div>
              <el-tooltip class="item" effect="dark" :content="row.goodsId" placement="top">
                <span class="more-width-full">{{row.goodsId}}</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="入库批次" align="center" prop="harvestBatchId" width="180" >
          <template slot="header">
            <span class="warnDiv">*</span>
            <span>入库批次</span>
          </template>
          <template slot-scope="{ row,$index }">
            <span v-if="disabledWatch">{{row.harvestBatchId}}</span>
            <el-select  placeholder="请选择" v-if="!disabledWatch" v-model="row.harvestBatchId">
              <el-option
              v-for="item in row.harvestOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="goodsNum" width="100" >
          <template slot="header">
            <span class="warnDiv">*</span>
            <span>数量</span>
          </template>
          <template slot-scope="{ row }">
            <span v-if="disabledWatch">{{row.goodsNum}}</span>
            <el-input placeholder="请输入" v-if="!disabledWatch" v-model="row.goodsNum"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" prop="goodsUnit" width="80" />
        <el-table-column label="重量(KG)" align="center" prop="goodsWeight" width="100" >
          <template slot="header">
            <span class="warnDiv">*</span>
            <span>重量(KG)</span>
          </template>
          <template slot-scope="{ row }">
            <span v-if="disabledWatch">{{row.goodsWeight}}</span>
            <el-input placeholder="请输入" v-if="!disabledWatch" v-model="row.goodsWeight"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" prop="goodsUnitPrice" width="100" >
          <template slot="header">
            <span class="warnDiv">*</span>
            <span>单价</span>
          </template>
          <template slot-scope="{ row }">
            <span v-if="disabledWatch">{{row.goodsUnitPrice}}</span>
            <el-input placeholder="请输入"  v-if="!disabledWatch" v-model="row.goodsUnitPrice"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="总价" align="center" prop="totalPrice" min-width="120" >
          <template slot-scope="{ row,$index }">
            <span>{{getTotalPrice(row.goodsUnitPrice , row.goodsNum, $index) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          v-if="!disabledWatch"
          class-name="small-padding fixed-width">
          <template v-slot="scope" >
            <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="form.outboundGoods.push(scope.row)"
                v-hasPermi="['basic:goods-info:update']">复制</el-button> -->
            <el-popconfirm
              title="确定删除吗？"
              @confirm="delOutboundGoodsList(scope.$index)">
              <el-button slot="reference" size="mini" type="text" icon="el-icon-delete"
                v-hasPermi="['basic:goods-info:delete']">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
        <div slot="empty">
          <EmptyBound />
        </div>
      </el-table>
      <div slot="footer" class="dialog-footer" v-if="!disabledWatch">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import Bound from '@/components/Customer/SearchForm'
import EmptyBound from '@/components/EmptyTable'
import Transfer from '@/components/Customer/Transfer'
import areaByld from '@/components/Customer/Cascader/areaById'
import { GetRandomNum } from '@/utils/index'
import {
  createOutbound,
  updateOutbound,
  deleteOutbound,
  getOutbound,
  getOutboundPage,
  exportOutboundExcel,
  outboundUpChain,
  outboundFreeze,
  outboundActive
} from '@/api/flow/outbound'
import { deleteOutboundGoods } from '@/api/flow/outboundgoods'
import { getPullInfoList , createDealerInfo , createDealerAndAreaGoodsInfo } from '@/api/basic/dealerInfo'
import { getGoodsNameLists, getGoodsNameList , getGoodsListByBelongBusinessId , queryListMiniResult } from '@/api/basic/goodsInfo'
import { getBusinessNameList } from '@/api/basic/businessInfo';
import { getHarvestBatchIdsByGoodsId , getByGoodsId , getBatchIdsByGoodsId } from '@/api/product/harvestBatch'
import { getAreaTree } from '@/api/system/area'
import { cos } from 'mathjs'
export default {
  name: 'Outbound',
  components: {
    Bound,
    EmptyBound,
    Transfer,
    areaByld
  },
  data() {
    return {
      //状态切换
      checked: true,
      //展示
      foldBoole: false,
      // 遮罩层
      loading: true,
      outboundGoodsLoading: false,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出库单列表
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      //内层控制按钮
      open2: false,
      //扫码出库按钮
      open3: false,
      // 2层内容判断显示
      isQrcode:false,
      // 二维码  先放这
      textareaQrcode:'',
      // 导出按钮
      open4:false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        dealerId: null,
        dealerName: null,
        outBoundId: null,
        outBoundTime: [],
        carrierVehicles: null,
        carrier: null,
        carrierContact: null,
        blockState: null,
        blockChainId: null,
        blockChainBlockIdentity: null,
        belongBusinessId: null,
        belongBusinessName: null,
        createTime: [],
      },
      //表单对象
      dataSource: [
        {
          key: 'outBoundTime', //出库时间
          itemType: 'datePicker',
          label: '出库时间',
          onEnterKeyUp: this.handleQuery,
        },
        {
          key: 'outBoundId', //出库单号
          itemType: 'input',
          label: '出库单号',
          placeholder: '请输入',
          onEnterKeyUp: this.handleQuery,
        },
        {
          key: 'vendorName', //经销商名称
          itemType: 'input',
          label: '经销商名称',
          placeholder: '请输入',
          onEnterKeyUp: this.handleQuery,
        },
        {
          key: 'belongBusinessName', //所属商户
          itemType: 'input',
          label: '所属商户',
          placeholder: '请输入',
          onEnterKeyUp: this.handleQuery,
        },
        {
          key: 'blockState', //上链状态
          itemType: 'select',
          label: '上传状态',
          placeholder: '请选择',
          onEnterKeyUp: this.handleQuery,
          options:[
            {value: 0, label:'未上传'},{value: 1, label:'已上传'},{value: 2, label:'冻结'}
          ],
        },
      ],
      // 编辑时禁用
      disabled: false,
      // 操作-查看时禁用
      disabledWatch: false,
      // 表单参数
      form: {},
      formDealer: {},
      // 表单校验
      rules: {
        vendorId: [
          { required: true, message: '经销商不能为空', trigger: 'change' },
        ],
        vendorName: [
          { required: true, message: '经销商名称不能为空', trigger: 'change' },
        ],
        outBoundId: [
          { required: true, message: '出库单号不能为空', trigger: 'blur' },
        ],
        outBoundTime: [
          { required: true, message: '出库时间不能为空', trigger: 'blur' },
        ],
        blockState: [
          { required: true, message: '上传状态不能为空', trigger: 'blur',},
        ],
        belongBusinessId: [
          { required: true, message: '所属商户id不能为空', trigger: 'blur' },
        ],
        belongBusinessName: [
          { required: true, message: '所属商户名称不能为空', trigger: 'blur' },
        ],
        contactName: [
          { required: true, message: '负责人不能为空', trigger: 'blur' },
        ],
        carrierContact: [
          // { required: true, message: '联系方式不能为空', trigger: 'change' },
          {
            pattern:  /^1[3|4|5|7|8|9][0-9]{9}$/,
            message: '联系方式格式有误！',
            trigger: 'change',
          },
        ],
        contactPhone:[
          { required: true, message: '联系方式不能为空', trigger: 'change' },
        ],
        saleArea: [
          { required: true, message: '销售区域', trigger: 'blur' },
        ],
      },
      rulesDealer: {
        dealerId: [
          { required: true, message: '经销商不能为空', trigger: 'blur' },
        ],
        dealerName: [
          { required: true, message: '经销商名称不能为空', trigger: 'blur' },
        ],
        outBoundId: [
          { required: true, message: '出库单号不能为空', trigger: 'blur' },
        ],
        outBoundTime: [
          { required: true, message: '出库时间不能为空', trigger: 'blur' },
        ],
        blockState: [
          { required: true, message: '上传状态不能为空', trigger: 'blur',},
          //  0：未上链  1：已上链  2：冻结
        ],
        belongBusinessId: [
          { required: true, message: '所属商户id不能为空', trigger: 'blur' },
        ],
        belongBusinessName: [
          { required: true, message: '所属商户名称不能为空', trigger: 'blur' },
        ],
        contactName: [
          { required: true, message: '负责人不能为空', trigger: 'blur' },
        ],
        carrierContact: [
          { required: true, message: '联系方式不能为空', trigger: 'change' },
        ],
        contactPhone:[
          { required: true, message: '联系方式不能为空', trigger: 'change' },
          {
            pattern:  /^1[3|4|5|7|8|9][0-9]{9}$/,
            message: '联系方式格式有误！',
            trigger: 'change',
          },
        ],
        commonSaleArea: [
          { required: true, message: '销售区域不能为空', trigger: 'blur' },
        ],
      },
      // 出库码
      outCode: 'OUPJOE',
      // 经销商列表
      vendorList: [],
      //弹窗的列表
      tableData: [],
      // 地区选择列表
      areaOptions: [],
      // 临时 选项参数
      harvestOptions: [],
      // 所属商户列表
      businessNameList: [],

      /***********************  选择商品弹窗相关参数  ************************/
      // 商品可选列表
      goodsOptions: [],
      saleGoodsOptions: [],
      // 已选中的农资列表【临时】，只在弹窗时作为临时存放用
      inputCheckedIdList: [],
      // 这里定义俩个参数是为了每次重新打开组件时可以重置当前页码到1
      leftCurrentPage: 1,
      rightCurrentPage: 1,
      leftDefaultChecked: [],
      rightDefaultChecked: [],
      // 已选/已入数据库的农资信息列表
      inputInfoList: [],

      /***********************  新增区域商品弹窗相关参数  ************************/
      // 已选区域商品信息列表 临时
      checkGoods: [],
      titleArea: '',
      formArea: {},
      editIndex: undefined,
      rulesArea: {
        saleArea: [
          { required: true, message: '商品销售区域不能为空', trigger: 'change' },
        ],
      },


    }
  },
  created() {
    this.getList()
    this.getPullInfoList()
    this.getBusinessNameList();
    this.getAreaTree()
  },
  methods: {
    // 删除出库单
    async delOutboundGoodsList(index){
      if(this.form.outboundGoods[index].id){
        let res = await deleteOutboundGoods(this.form.outboundGoods[index].id);
        if(res.data && res.code == 0){
          this.form.outboundGoods.splice(index,1);
        }
      }else{
        this.form.outboundGoods.splice(index,1);
      }
    },
    // 编辑出库单-计算总价
    getTotalPrice(price,num,index){
      let a = !isNaN(parseFloat(price)) && isFinite(price);
      let b = !isNaN(parseFloat(num)) && isFinite(num);
      if( a && b ){
        let totalPrice = (price * num).toFixed(2);
        this.$set(this.form.outboundGoods[index],'totalPrice',totalPrice)
        return totalPrice;
      }else{
        return '--';
      }
    },
    filterText(blockState){
      switch(blockState){
        case 0:
          return '未上传'
        case 1:
          return '已上传'
        case 2:
          return '冻结'
        default :
          break;
      }
    },
    // 这个接口时获取经销商列表
    async getPullInfoList() {
      const res = await getPullInfoList()
      this.vendorList = res.data
    },
    // 获取三级地区选择数据
    async getAreaTree() {
      const res = await getAreaTree()
      this.areaOptions = res.data;
    },
    handleState(row,type){
      const id = row.id;
      let text;
      switch(type){
        case 'upChain':
          text = '上传';
          break;
        case 'freeze':
          text = '冻结';
          break;
        case 'active':
          text = '激活';
          break;
      }
      this.$modal.confirm(`是否确认${text}出库编号为${id}的数据项?`).then(function() {
          switch(type){
            case 'upChain':
              return outboundUpChain(id);
            case 'freeze':
              return outboundFreeze(id);
            case 'active':
              return outboundActive(id);
          }
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess(`${text}成功`);
        }).catch(() => {});
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      // 执行查询
      getOutboundPage(this.queryParams).then((response) => {
        this.list = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    showOpen2(){
      this.isQrcode = false
      this.open2 = true
    },
    // 取消内层
    cancel2() {
      this.open2 = false
    },
     // 取消扫码出库按钮
    cancel3() {
      this.open3 = false
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        dealerId: undefined,
        dealerName: undefined,
        outBoundId: undefined,
        outBoundTime: undefined,
        carrierVehicles: undefined,
        carrier: undefined,
        carrierContact: undefined,
        blockState: undefined,
        blockChainId: undefined,
        blockChainBlockIdentity: undefined,
        belongBusinessId: undefined,
        belongBusinessName: undefined,
      }
      this.resetForm('form')
    },
    resetDealer() {
      this.formDealer = {
        id: undefined,
        dealerId: undefined,
        dealerName: undefined,
        outBoundId: undefined,
        outBoundTime: undefined,
        carrierVehicles: undefined,
        carrier: undefined,
        carrierContact: undefined,
        blockState: undefined,
        blockChainId: undefined,
        blockChainBlockIdentity: undefined,
        belongBusinessId: undefined,
        belongBusinessName: undefined,
      }
      this.tableData = [];
      this.resetForm('formDealer')
    },
    /** 销售区域表单重置 */
    resetArea() {
      this.formArea = {
        id: undefined,
        saleAreaId: '',
        saleArea: undefined,
      }
      this.resetForm('formArea')
    },
    /** 搜索按钮操作 */
    handleQuery(search) {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm", "searchForm");
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新建出库信息'
      this.disabled = false;
      this.disabledWatch = false;
      this.$set(this.form, 'outBoundTime', +new Date())
      let date = this.$moment().format('YYYYMMDDHHmmssSS')
      let randomNumber = GetRandomNum()
      this.$set(
        this.form,
        'outBoundId',
        `${this.outCode}${date}${randomNumber}`
      )
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id
      getOutbound(id).then((response) => {
        this.form = response.data
        this.disabled = true
        this.disabledWatch = false
        this.open = true
        this.title = '修改出库单'
        this.getHarvestOptions();
        this.handleGoodsOptions(this.form.belongBusinessId);
      })
    },
    /** 查看按钮操作 */
    handleWatch(row){
      this.reset()
      const id = row.id
      getOutbound(id).then((response) => {
        this.form = response.data
        this.disabledWatch = true
        this.open = true
        this.title = '查看出库单'
      })
    },
    /** (上链、冻结)按钮操作 */
    handleChange(){

    },
    /** 复制按钮操作 */
    handleCopy(row){
      this.reset()
      const id = row.id;
      getOutbound(id).then((res) => {
        res.data.outboundGoods.length && res.data.outboundGoods.map(item=>{
          item.harvestBatchId = undefined;
        });
        this.form = {
          ...res.data,
          id: undefined,
        };
        this.disabled = true
        this.disabledWatch = false
        this.open = true
        this.title = '复制出库单'
        this.$set(this.form, 'outBoundTime', +new Date())
        let date = this.$moment().format('YYYYMMDDHHmmssSS')
        let randomNumber = GetRandomNum()
        this.$set(
          this.form,
          'outBoundId',
          `${this.outCode}${date}${randomNumber}`
        )
        this.getHarvestOptions();
        this.handleGoodsOptions(this.form.belongBusinessId);
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return
        }
        if( !this.form.outboundGoods || this.form.outboundGoods.length == 0 ){
          this.$message.error('出库商品不能为空');
          return;
        }
        let showError = false;
        this.form.outboundGoods.map(item=>{
          if(!item.harvestBatchId || !item.goodsNum || !item.goodsWeight || !item.goodsUnitPrice) showError = true;
        })
        if( showError ){
          this.$message.error('出库商品的必填项不能为空');
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateOutbound(this.form).then((response) => {
            this.$modal.msgSuccess('修改成功')
            this.open = false
            this.getList()
          })
          return
        }
        // 添加的提交
        createOutbound(this.form).then((response) => {
          this.$modal.msgSuccess('新增成功')
          this.open = false
          this.getList()
        })
      })
    },
     /** 内层提交按钮 */
    submitForm2() {
      this.$refs['formDealer'].validate((valid) => {
        if (!valid) {
          return
        }
        // 修改的提交
        if (this.formDealer.id != null) {
          updateOutbound(this.formDealer).then((response) => {
            this.$modal.msgSuccess('修改成功')
            this.open2 = false
            this.getList()
          })
          return
        }
        // 添加的提交
        // 添加经销商 无商品
        if( this.tableData.length == 0 ){
          createDealerInfo(this.formDealer).then((response) => {
            this.$modal.msgSuccess('新增成功')
            this.open2 = false
            this.resetDealer();
            this.getPullInfoList()
          })
          return;
        }
        // 添加经销商 有区域商品
        let formDealer = JSON.parse(JSON.stringify(this.formDealer));
        this.formDealer.dealerInfo = formDealer;
        this.formDealer.areaGoodsList = this.tableData.map(item=>{
          let dx = {
            dealerName: formDealer.dealerName,
            ...item,
          };
          return dx;
        });
        createDealerAndAreaGoodsInfo({
          dealerInfo: {
            ...formDealer,
            dealerId: '',
          },
          areaGoodsList: this.formDealer.areaGoodsList,
        }).then((response) => {
          this.$modal.msgSuccess('新增成功')
          this.open2 = false
          this.resetDealer();
          this.getPullInfoList()
        });
      })
    },
    createDealer(){

    },
    // 文本框选择内容inputCheckedIdList
    submitFormQrcode(){
      let num = this.inputCheckedIdList.length;
      this.getCheckSaleGoods(0,num);
      this.open2 = false;
    },

    async getCheckSaleGoods(start,end){
      let total = this.saleGoodsOptions.length;
      let list = this.inputCheckedIdList;
      let options = this.saleGoodsOptions;
      for( var x=0; x<total ; x++  ){
        if( options[x].goodsId == list[start] ){
          options[x].harvestLoading = false;
          options[x].harvestOptions = [];
          options[x].harvestRes = false;//默认未请求(入库批次接口)
          let isHas = false;
          this.form.outboundGoods.map((item)=>{
            if(item.goodsId == options[x].goodsId) isHas = true;
          });
          if(!isHas) this.form.outboundGoods.push({
            ...options[x],
            id: undefined,
          });
          if(end>start){
           this.getCheckSaleGoods(start+1,end);
          }else{
            this.getHarvestOptions();
          }
          return false;
        }
        if( options[x].goodsId !== list[start] && x+1==total ){
          this.getHarvestOptions();
        }
      }
    },

    // 类型1 向指定目标数组添加对象参数
    getCheckGoods(start,end,target){
      let total = this.goodsOptions.length;
      let list = this.inputCheckedIdList;
      let options = this.goodsOptions;
      for( var x=0; x<total ; x++  ){
        if( options[x].id == list[start] ){
          options[x].harvestLoading = false;
          options[x].harvestOptions = [];
          options[x].harvestRes = false;//默认未请求(入库批次接口)
          this[target].push(options[x]);
          if(end>start) this.getCheckGoods(start+1,end,target);
          return false;
        }
      }
    },

     async getHarvestOptions(index,row){
      let list = JSON.parse(JSON.stringify(this.form.outboundGoods));
      let goodsList = [];
      list.map((item)=>{
        goodsList.push(item.goodsId);
      });
      let goodsIds = goodsList.join(',');
      let form = {
        businessId: this.form.belongBusinessId,
        goodsIds,
      };
      let res = await getBatchIdsByGoodsId(form);
      for(var x in res.data) {
        let i = goodsList.indexOf(x);
        if( i > -1 ){
          let option = [];
          res.data[x].map(items=>{
            option.push({
              label:  items,
              value: items,
            })
          })
          this.$set(this.form.outboundGoods[i],'harvestOptions',option );
        }
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id
      this.$modal
        .confirm('是否确认删除出库单编号为"' + id + '"的数据项?')
        .then(function () {
          return deleteOutbound(id)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    getGoodsNameLists(disabled=false){
      getGoodsNameLists().then(response => {
        const { data } = response;
        const options = [];
        for(let i in data) {
          options.push({
            key: data[i].goodsId,
            label: data[i].name,
            disabled,
            ...data[i]
          });
        }
        this.saleGoodsOptions = options;
      });
    },
    getGoodsNameList(disabled=false,ids){
      getGoodsNameList({
        ids,
      }).then(response => {
        const { data } = response;
        const options = [];
        for(let i in data) {
          options.push({
            key: data[i].goodsId,
            label: data[i].name,
            disabled,
            ...data[i]
          });
        }
        this.goodsOptions = options;
      });
    },
    initTreesferDate( ){
      // 每次打开之前都需要初始/重置一些参数
      this.leftCurrentPage = 1;
      this.rightCurrentPage = 1;
      this.leftDefaultChecked = [];
      this.rightDefaultChecked = [];
    },
    /** 新增销售区域商品弹窗 */
    handleExport() {
      if(!this.formDealer.belongBusinessId){
        this.$message.error("请先选择所属商户")
        return;
      }
      this.resetArea();
      // 编辑时需要获取已选择
      this.initTreesferDate();
      this.inputCheckedIdList = [];
      this.titleArea = '新增区域商品';
      this.open4 = true
      // 处理查询参数
      let params = { ...this.queryParams }
      params.pageNo = undefined
      params.pageSize = undefined
    },
    /** 编辑销售区域商品 */
    handeleChangeAreaGoods(row,index){
      console.log('编辑',row);
      this.formArea = row;
      this.inputCheckedIdList = new Array(row.goodsId);
      this.getGoodsNameLists(true);
      this.titleArea = '编辑区域商品';
      this.editIndex = index;
      this.open4 = true;
    },
    /** 删除销售区域商品 */
    handeleDelAreaGoods(index){
      this.tableData.splice(index,1);
    },
    /** 打开选择商品窗口 */
    storage(){
      this.initTreesferDate();
      if(!this.form.vendorId){
        this.$message.error("请先选择经销商名称");
        return false;
      }
      if(!this.form.outboundGoods) this.form.outboundGoods = [];
      console.log('this.form.outboundGoods',this.form.outboundGoods);
      if(this.form.outboundGoods){
        this.inputCheckedIdList = this.form.outboundGoods.map(item=>{
          return item.goodsId;
        });
      }
      console.log('this.inputCheckedIdList',this.inputCheckedIdList);
      this.isQrcode = true
      this.open2 = true
    },

    submit4(){
      this.$refs['formArea'].validate((valid) => {
        if (!valid) {
          return;
        }
        // 省市区单独取出显示
        let areaName = ( JSON.parse(JSON.stringify( this.formArea.saleArea)) ).split('/');
        // 新增/更新的数据
        let dx = {
          province: areaName[0],
          city: areaName[1],
          count: areaName[2],
          saleAreaId: this.formArea.saleAreaId,
          saleArea: this.formArea.saleArea,
        };
        if( this.editIndex != undefined ){
          this.formArea
          console.log( this.tableData,this.editIndex,this.formArea);
          this.$set(this.tableData,this.editIndex,{
            ...this.formArea,
            ...dx,
          });
          // this.tableData[this.editIndex]=this.formArea
          this.editIndex = undefined;
        }else{
          if(this.inputCheckedIdList.length > 0){
            this.goodsOptions.map(item=>{
              this.inputCheckedIdList.map(items=>{
                if(item.goodsId == items){
                  this.tableData.push({
                    ...dx,
                    goodsId: item.goodsId,
                    goodsName: item.goodsName,
                    belongBusinessId: item.belongBusinessId,
                    belongBusinessName: item.belongBusinessName,
                  });
                }
              });
            });
          }else{
            this.tableData.push({
              ...dx,
              goodsId: '未选择',
              goodsName: '未选择',
              belongBusinessId: this.formDealer.belongBusinessId,
              belongBusinessName: '未选择',
            });
          }
        }
        this.open4 = false
      });
    },

    closeOpen4(){
      this.open4 = false
    },

    // 获取商户列表
    getBusinessNameList(){
      getBusinessNameList().then(res => {
        this.businessNameList = res.data;
      });
    },

    async handchangeBusiness(e){
      this.getGoodsNameList(false,e);
      this.$nextTick(()=>{
         this.formDealer.belongBusinessName = this.$refs.businessName.selected.label;
      });
    },

    /***********************  选择商品弹窗相关事件  ************************/
    /**
     *
     * @param {*} value 已选中的值[数组]
     * @param {*} direction 移动方向 left，right
     * @param {*} movedKeys 移动的key数组
     */
    handleSelectChange(value, direction, movedKeys) {
      this.inputCheckedIdList = value;
    },
    renderTransferLabel(h, option) {
      return <div style="display:flex;align-item: center;">
      <span title={option.goodsId} style="display: inline-block;max-width: 110px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">{ option.goodsId }</span>
      <span style='margin: 0px 30px; color: #e6ebf5;display: inline-block;'>|</span><span>{ option.goodsName }</span>
      </div>;
    },
    /*  左侧分页参数变化时  */
    // 由于vue双向绑定的一些机制，所以需要在这边给定一个方法让子组件调用并修改传入子组件的参数
    // 这里做同步修改之后，再次打开该弹窗时上面的重置数据才会被子组件监听到。。。
    // 当然如果嫌麻烦可以直接给dialog 加个if直接销毁
    handlePageChange(value, type) {
      if(type === 'left') {
        this.leftCurrentPage = value;
      } else {
        this.rightCurrentPage = value;
      }
    },

    changeVendorId(e){
      this.$nextTick(async ()=>{
        this.form.vendorName = this.$refs.vendorRef.selected.label;
        this.form.belongBusinessId = this.$refs.vendorRef.selected.$attrs.belongBusinessId;
        console.log(this.$refs.vendorRef);
        this.form.outboundGoods = [];
        // 获取 商品信息列表 弹窗参数
        let belongBusinessId = this.form.belongBusinessId;
        this.handleGoodsOptions(belongBusinessId);
      })
    },

    // 新增/编辑出库信息-弹窗-商品列表
    async handleGoodsOptions(ids){
      let res = await queryListMiniResult({
        belongBusinessId: ids
      });
      // let res = await getGoodsListByBelongBusinessId({ids});
      const { data } = res;
      const options = [];
      for(let i in data) {
        options.push({
          key: data[i].goodsId,
          label: data[i].name,
          ...data[i]
        });
      }
      this.saleGoodsOptions = options;
    },


  },
}
</script>

<style >
  alert-content {
    flex: 1 1;
    min-width: 0;
}
  ant-alert-message {
    color: #000000d9;
}

.el-alert--info.is-light {
    background-color: #e6f7ff;
    color: #909399;
    border: 1px solid #91d5ff;
    color: #000000d9;
    font-size: 14px;
    border-radius: 0;
}

.textareaQrcode .el-textarea__inner{
  height: 300px;
}

.line .el-dialog__header{
  border-bottom: 1px solid #ccc;
    padding-bottom: 20px;
}

.line .el-dialog__body {
    padding: 14px 20px;
}

.station {
  height: 36px;
}

.warnDiv {
  color: red;
}
</style>
