<template>
  <div class="allocateBillEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="allocateBillEdit-back" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="allocateBillEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span style="margin: 0 15px;color: #666;font-weight: bold;">单号：{{ basicInfoData&&basicInfoData.allocateNo }}</span>
          <a-button type="link" id="allocateBillEdit-showDetail" class="button-default" @click="showDetail=!showDetail">
            <a-icon :type="showDetail ? 'eye-invisible' : 'eye'"/> {{ showDetail?'隐藏':'查看' }}信息
          </a-button>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra">
          <a-button
            key="4"
            type="primary"
            class="button-info"
            v-if="$hasPermissions('B_transferOut_print')"
            id="allocateBillEdit-dbPrint-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('dbPrint')">调拨打印</a-button>
          <a-button
            key="3"
            type="default"
            class="button-info"
            v-if="$hasPermissions('B_transferOutType_print')"
            id="allocateBillEdit-dbflPrint-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('dbflPrint')">调拨分类打印</a-button>
          <a-divider type="vertical" />
          <a-button
            key="2"
            type="primary"
            class="button-info"
            v-if="$hasPermissions('B_transferOut_detail_export')"
            id="allocateBillDetail-export-btn"
            :disabled="localDataSource.length==0"
            @click="handleExcel('ALLOCATE_BILL','调拨明细')">导出Excel</a-button>
          <a-button
            key="1"
            type="default"
            class="button-info"
            v-if="$hasPermissions('B_transferOutType_export')"
            id="allocateBillDetail-exportType-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('dbflExport')">调拨分类导出</a-button>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" v-show="showDetail" class="allocateBillEdit-cont">
        <div v-if="basicInfoData">
          <a-descriptions :column="4">
            <a-descriptions-item label="调往对象">{{ (basicInfoData&&basicInfoData.targetName) || '--' }}</a-descriptions-item>
            <a-descriptions-item label="调出仓库">{{ (basicInfoData&&basicInfoData.warehouseName) || '--' }}</a-descriptions-item>
            <a-descriptions-item label="发货编号">{{ (basicInfoData&&basicInfoData.sendNo) || '--' }}</a-descriptions-item>
            <a-descriptions-item label="收货客户名称">{{ (basicInfoData&&basicInfoData.receiverName) || '--' }}</a-descriptions-item>
            <a-descriptions-item label="调拨单号">{{ (basicInfoData&&basicInfoData.allocateNo) || '--' }}</a-descriptions-item>
            <a-descriptions-item label="业务状态">{{ (basicInfoData&&basicInfoData.stateDictValue) || '--' }}</a-descriptions-item>
            <a-descriptions-item label="打印状态" :span="2">{{ (basicInfoData&&basicInfoData.printStateDictValue) || '--' }}</a-descriptions-item>
            <a-descriptions-item label="发货说明" :span="4">
              {{ (basicInfoData&&basicInfoData.explainInfo) || '--' }}
            </a-descriptions-item>
          </a-descriptions>
          <a-divider>以下信息可修改，请点击<span style="color: dodgerblue;font-size: 14px;cursor: pointer;" @click="editRemark = true" ><a-icon type="form" title="编辑基础信息" />编辑</span></a-divider>
          <a-descriptions :column="4">
            <a-descriptions-item label="费用类型">
              {{ (basicInfoData&&basicInfoData.costTypeName) || '--' }}
            </a-descriptions-item>
            <a-descriptions-item label="调拨类型">
              <div>
                <span v-if="basicInfoData.allocateSortName">{{ basicInfoData.allocateSortName || '--' }}</span>
                <span v-if="basicInfoData.allocateTypeName">/{{ basicInfoData.allocateTypeName || '--' }}</span>
              </div>
            </a-descriptions-item>
            <a-descriptions-item label="费用归属品牌">
              {{ (basicInfoData&&basicInfoData.productBrandName) || '--' }}
            </a-descriptions-item>
            <a-descriptions-item label="费用归属品类">
              <div>
                <span v-if="basicInfoData.productTypeName1">{{ basicInfoData.productTypeName1 || '--' }}</span>
                <span v-else>--</span>
                <span v-if="basicInfoData.productTypeName2">/{{ basicInfoData.productTypeName2 || '--' }}</span>
                <span v-if="basicInfoData.productTypeName3">/{{ basicInfoData.productTypeName3 || '--' }}</span>
              </div>
            </a-descriptions-item>
            <a-descriptions-item label="起止时间">
              <span v-if="basicInfoData&&(basicInfoData.promoStartDate || basicInfoData.promoEndDate)">{{ (basicInfoData&&basicInfoData.promoStartDate) || '--' }} ~ {{ (basicInfoData&&basicInfoData.promoEndDate) || '--' }}</span>
              <span v-else>--</span>
            </a-descriptions-item>
            <a-descriptions-item label="备注" :span="3">
              {{ (basicInfoData&&basicInfoData.remark||'--') }}
            </a-descriptions-item>
            <a-descriptions-item label="附件" :span="4">
              <div v-if="basicInfoData&&basicInfoData.attachmentList&&basicInfoData.attachmentList.length">
                <a
                  target="_blank"
                  id="allocateBillDetail-attachmentList"
                  style="color: #00aaff;text-decoration: underline;margin-right: 15px;"
                  :href="item.filePath"
                  v-for="item in basicInfoData.attachmentList"
                  :key="item.id">
                  {{ item.fileName }}
                </a>
              </div>
              <span v-else>--</span>
            </a-descriptions-item>
          </a-descriptions>
        </div>
      </a-card>
      <!-- 选择产品 -->
      <a-card size="small" :bordered="false" class="allocateBillEdit-cont">
        <!-- 筛选条件 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline" id="allocateBillDetail-form" @keyup.enter.native="$refs.table.refresh(true)">
            <a-row :gutter="15">
              <a-col :md="6" :sm="24">
                <a-form-item label="产品编码" prop="productCode">
                  <a-input id="allocateBillEdit-productCode" v-model.trim="queryParam.productCode" placeholder="请输入产品编码" allowClear />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="产品名称" prop="productName">
                  <a-input id="allocateBillEdit-productName" v-model.trim="queryParam.productName" placeholder="请输入产品名称" allowClear />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="原厂编码" prop="productOrigCode">
                  <a-input id="allocateBillEdit-productOrigCode" v-model.trim="queryParam.productOrigCode" placeholder="请输入原厂编码" allowClear />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="allocateBillEdit-refresh">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetSearchForm(0)" :disabled="disabled" id="allocateBillEdit-reset">重置</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          index="0"
          tableId="table1"
          :rowKey="(record) => record.id"
          :columns="columns"
          :customRow="handleClickRow"
          :data="loadData"
          :defaultLoadData="false"
          :scroll="{ y: 300 }"
          bordered>
          <!-- 售价 -->
          <template slot="productPriceInfo" slot-scope="text, record">
            <span v-if="record.powerFlag!=0">{{ (record.priceValue || record.priceValue==0) ? toThousands(record.priceValue):'--' }}</span>
            <span v-else>
              {{ record.priceLevel=='PROVINCE'?record.provincePrice:record.priceLevel=='CITY'?record.cityPrice:record.specialPrice }}
            </span>
          </template>
          <!-- 价格级别 -->
          <template slot="priceLevel" slot-scope="text, record, index">
            <span v-if="!$hasPermissions('M_transferOut_edit_salesPrice')">--</span>
            <div v-else>
              <span v-if="record.powerFlag!=0">{{ record.priceLevelDictValue }}</span>
              <a-select
                v-else
                style="width:100%"
                placeholder="请选择价格级别"
                :id="'allocateBillEdit-priceLevel'+record.id"
                size="small"
                allowClear
                v-model="record.priceLevel"
                @change="e => handlePriceLevel(e,index)"
              >
                <a-select-option
                  :id="'allocateBillEdit-priceLevel-'+item.code"
                  v-for="item in priceLevelList"
                  :key="item.code"
                  :value="item.code">{{ item.dispName }}</a-select-option>
              </a-select>
            </div>
          </template>
          <!-- 调出数量 -->
          <template slot="qty" slot-scope="text, record">
            <a-input-number
              size="small"
              :id="'allocateBillEdit-qty'+record.id"
              v-model="record.qty"
              :precision="0"
              :min="1"
              :max="record.currentStockQty"
              placeholder="请输入"
              style="width: 100%;" />
          </template>
          <!-- 操作 -->
          <template slot="action1" slot-scope="text, record">
            <a-button
              :id="'allocateBillEdit-add-btn'+record.id"
              size="small"
              type="link"
              class="button-primary"
              :loading="spinning"
              @click.stop="handleAdd(record, false, 'noRefresh')"
            >添加</a-button>
          </template>
        </s-table>
      </a-card>
      <!-- 已选产品 -->
      <a-card size="small" title="已选产品" :bordered="false" class="allocateBillEdit-cont">
        <!-- 总计 -->
        <a-alert type="info" style="margin-bottom:10px">
          <div slot="message">
            总数量：<strong>{{ (productTotal&&(productTotal.totalQty || productTotal.totalQty==0)) ? productTotal.totalQty : '--' }}</strong> ；
            <span v-if="$hasPermissions('M_transferOut_edit_costPrice')">总成本：<strong>{{ (productTotal&&(productTotal.totalCost || productTotal.totalCost==0)) ? toThousands(productTotal.totalCost) : '--' }}</strong> ；</span>
            <span v-if="$hasPermissions('M_transferOut_edit_salesPrice')">总售价：<strong>{{ (productTotal&&(productTotal.totalPrice || productTotal.totalPrice==0)) ? toThousands(productTotal.totalPrice) : '--' }}</strong>；</span>
          </div>
        </a-alert>
        <!-- 筛选条件 -->
        <a-row :gutter="15">
          <a-col :span="16">
            <div class="table-page-search-wrapper">
              <a-form id="allocateBillEdit-form-search" layout="inline" @keyup.enter.native="$refs.chooseTable.refresh(true)">
                <a-row :gutter="15">
                  <a-col :md="9" :sm="24">
                    <a-form-item label="产品编码" prop="productCode">
                      <a-input id="allocateBillEdit-select-productCode" v-model.trim="chooseQueryParam.productCode" placeholder="请输入产品编码" allowClear />
                    </a-form-item>
                  </a-col>
                  <a-col :md="9" :sm="24">
                    <a-form-item label="产品名称" prop="productName">
                      <a-input id="allocateBillEdit-select-productName" v-model.trim="chooseQueryParam.productName" placeholder="请输入产品名称" allowClear />
                    </a-form-item>
                  </a-col>
                  <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                    <a-button type="primary" @click="$refs.chooseTable.refresh(true)" :disabled="chooseDisabled" id="allocateBillEdit-select-refresh">查询</a-button>
                    <a-button style="margin-left: 8px" @click="chooseResetSearchForm(0)" :disabled="chooseDisabled" id="allocateBillEdit-select-reset">重置</a-button>
                  </a-col>
                </a-row>
              </a-form>
            </div>
          </a-col>
          <a-col :span="8" style="text-align: right;">
            <span v-if="selNums">已选{{ selNums }}项</span>
            <a-button
              style="margin:0 10px;"
              id="allocateBillEdit-plDel-btn"
              @click="openPlSet">批量设置费用归属</a-button>
            <a-button id="allocateBillEdit-import-btn" @click="openGuideModal=true">导入产品</a-button>
            <a-button type="danger" style="margin-left: 10px" @click.stop="handleDel('', 'all')" id="allocateBillEdit-del-all-btn">整单删除</a-button>
          </a-col>
        </a-row>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="chooseTable"
          size="small"
          index="1"
          tableId="table2"
          :rowKey="(record) => record.id"
          :row-selection="{ columnWidth: 40 }"
          @rowSelection="rowSelectionFun"
          :columns="chooseColumns"
          :data="chooseLoadData"
          :defaultLoadData="false"
          :pagination="{pageSizeOptions: ['20','50','100','200','500']}"
          :pageSize="50"
          :scroll="{ y: 300 }"
          bordered>
          <!-- 售价 -->
          <template slot="price" slot-scope="text, record, index">
            <!-- 调往对象为经销商时不可编辑售价，为员工或其他时可编辑售价 -->
            <div v-if="$route.params.dealerLevel == 'OTHER'">
              <a-select
                size="small"
                :id="'allocateBillEdit-select-price'+record.id"
                option-label-prop="label"
                v-model="record.price"
                placeholder="请选择"
                @change="e => priceChange(e, record)"
                @focus="e => priceFocus(record, index)"
                style="width: 100%;">
                <a-select-option v-if="record.cost" :value="record.cost" :key="'cb-'+record.cost" :label="record.cost">成本 {{ record.cost }}</a-select-option>
                <a-select-option v-if="loadDataSource&&loadDataSource[index]&&loadDataSource[index].provincePrice" :value="loadDataSource[index].provincePrice" :key="'A-'+loadDataSource[index].productSn" :label="loadDataSource[index].provincePrice">A价 {{ loadDataSource[index].provincePrice }}</a-select-option>
                <a-select-option v-if="loadDataSource&&loadDataSource[index]&&loadDataSource[index].cityPrice" :value="loadDataSource[index].cityPrice" :key="'B-'+loadDataSource[index].productSn" :label="loadDataSource[index].cityPrice">B价 {{ loadDataSource[index].cityPrice }}</a-select-option>
                <a-select-option v-if="loadDataSource&&loadDataSource[index]&&loadDataSource[index].specialPrice" :value="loadDataSource[index].specialPrice" :key="'C-'+loadDataSource[index].productSn" :label="loadDataSource[index].specialPrice">C价 {{ loadDataSource[index].specialPrice }}</a-select-option>
              </a-select>
            </div>
            <span v-else>{{ toThousands(record.price) }}</span>
          </template>
          <!-- 调出数量 -->
          <template slot="qty" slot-scope="text, record">
            <a-input-number
              size="small"
              :id="'allocateBillEdit-select-qty'+record.id"
              v-model="record.qty"
              :precision="0"
              :min="1"
              :max="99999999"
              placeholder="请输入"
              @blur="e => qtyBlur(e.target.value, record)"
              style="width: 100%;" />
          </template>
          <!-- 费用归属部门 -->
          <template slot="department" slot-scope="text, record">
            <a-select
              style="width:100%"
              placeholder="请选择部门"
              :id="'allocateBillEdit-departmentSn'+record.id"
              size="small"
              allowClear
              v-model="record.departmentSn"
              :showSearch="true"
              @change="e => handleChange(e, record)"
              option-filter-prop="children"
              :filter-option="filterOption">
              <a-select-option :id="'allocateBillEdit-departmentSn'+item.departmentSn" v-for="item in departmentList" :key="item.departmentSn" :value="item.departmentSn">{{ item.name }}</a-select-option>
            </a-select>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              class="button-error"
              :loading="spinning"
              @click.stop="handleDel(record)"
              :id="'allocateBillEdit-del-btn'+record.id">删除</a-button>
          </template>
        </s-table>
      </a-card>
      <div class="affix-cont" v-if="basicInfoData">
        <a-button
          type="primary"
          id="allocateBillEdit-submit"
          size="large"
          :loading="spinning"
          class="button-primary"
          @click="handleOpen"
          style="padding: 0 60px;">提交</a-button>
      </div>
    </a-spin>
    <!-- 导入产品 -->
    <importGuideModal :openModal="openGuideModal" :params="{allocateSn: $route.params.sn}" @close="openGuideModal=false" @ok="handleGuideOk" />
    <!-- 打印导出 -->
    <print-modal
      :openModal="openModal"
      :itemData="basicInfoData"
      :nowType="nowType"
      @export="exportFl"
      @ok="handleOk"
      @close="openModal=false" />
    <!-- 提交调拨单 -->
    <dsModal ref="dsModal" :dealerLevel="$route.params.dealerLevel" :openModal="showDsModal" @close="showDsModal=false" @ok="handleSubmit" />
    <!-- 编辑基础信息 -->
    <basic-info-modal :openModal="editRemark" :detailData="basicInfoData" @ok="getDetail" @close="editRemark=false" />
    <!-- 批量设置部门 -->
    <commonModal modalTit="批量设置费用归属部门" :openModal="showPlModal" @cancel="closePlSet" @ok="setPlSetOk">
      <div style="text-align: center;">
        <div style="margin-bottom: 15px;font-size: 14px;"><strong>请选择费用归属部门</strong></div>
        <div style="line-height: 24px;">
          <div>
            <a-select
              style="width:100%"
              placeholder="请选择部门"
              allowClear
              v-model="plSetVal"
              :showSearch="true"
              option-filter-prop="children"
              :filter-option="filterOption">
              <a-select-option v-for="item in departmentList" :key="item.departmentSn" :value="item.departmentSn">{{ item.name }}</a-select-option>
            </a-select></div>
        </div>
      </div>
    </commonModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable, VSelect } from '@/components'
import ImportGuideModal from './importGuideModal.vue'
import basicInfoModal from './basicInfoModal.vue'
import printModal from './printModal.vue'
import dsModal from './dsModal.vue'
import commonModal from '@/views/common/commonModal.vue'
import { printBase64Fun, exportExcel } from '@/libs/JGPrint.js'
// 接口
import { queryStockProductForOtherPage } from '@/api/stock'
import { productPriceInfo } from '@/api/product'
import { departmentQueryList } from '@/api/expenseManagement'
import { allocateBillDetailList, allocateBillDetailCount, allocateBillDetail, allocateBillDetailSave, allocateBillSubmit, allocateBillDetailDel, allocateBillDetailDelAll, allocateBillDetailPrint, allocateBillDetailExcel, updateBatchDepartment, queryStockProductPage } from '@/api/allocateBill'

export default {
  name: 'TransferOutEdit',
  mixins: [commonMixin],
  components: { STable, VSelect, ImportGuideModal, printModal, dsModal, basicInfoModal, commonModal },
  data () {
    return {
      spinning: false,
      showDsModal: false, // 提交调拨单弹窗
      editRemark: false, // 编辑基础信息弹窗
      showPlModal: false, // 批量设置部门弹窗
      showDetail: false, // 基础信息
      // 查询条件
      queryParam: {
        productCode: '', // 产品编码
        productName: '', // 产品名称
        productOrigCode: ''// 原厂编码
      },
      // 已选产品查询条件
      chooseQueryParam: {
        productCode: '', // 产品编码
        productName: ''// 产品名称
      },
      disabled: false, //  查询、重置按钮是否可操作
      loading: false, // 表格加载状态
      chooseDisabled: false, //  查询、重置按钮是否可操作
      advanced: false, // 高级搜索 展开/关闭
      departmentList: [], // 部门列表
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        // 获取列表数据 有分页
        const dealerLevel = this.dealerLevel == 'OTHER' ? undefined : this.dealerLevel
        const warehouseSn = this.basicInfoData.warehouseSn
        const fun = this.dealerLevel == 'OTHER' ? queryStockProductForOtherPage : queryStockProductPage
        const dealerSnInfo = this.dealerLevel != 'OTHER' ? this.basicInfoData.dealerInfo.dealerSn : undefined
        return fun(Object.assign(parameter, this.queryParam, { zeroQtyFlag: '0', dealerLevel: dealerLevel, warehouseSn: warehouseSn, dealerSn: dealerSnInfo })).then(res => {
          const data = res.data
          // 计算表格序号
          const no = (data.pageNo - 1) * data.pageSize
          for (var i = 0; i < data.list.length; i++) {
            data.list[i].no = no + i + 1
            data.list[i].qty = 1
            data.list[i].priceValue = data.list[i].productPrice
          }
          this.loadDataSource = data.list || []
          this.disabled = false
          return data
        })
      },
      loadDataSource: [], // 调拨列表数据
      localDataSource: [], // 调拨已选数据
      // 加载数据方法 必须为 Promise 对象
      chooseLoadData: parameter => {
        this.chooseDisabled = true
        // 获取已选列表数据  有分页
        const params = Object.assign(parameter, this.chooseQueryParam, { allocateSn: this.allocateSn })
        return allocateBillDetailList(params).then(res => {
          const data = res.data
          // 计算表格序号
          const no = (data.pageNo - 1) * data.pageSize
          for (var i = 0; i < data.list.length; i++) {
            data.list[i].no = no + i + 1
            data.list[i].qtyBackups = data.list[i].qty
            data.list[i].priceBackups = data.list[i].price
            data.list[i].departmentSn = data.list[i].departmentSn || undefined
          }
          this.localDataSource = data.list || []
          this.chooseDisabled = false
          this.getDetailCount(params)
          return data
        })
      },
      productTotal: null, //  合计
      basicInfoData: null, // 基本信息
      openGuideModal: false, //  导入产品引导
      openModal: false, // 打印预览/快捷打印弹窗
      nowType: null, // 打印预览/快捷打印 类型
      rowSelectionInfo: null, // 已选数据集合
      plSetVal: undefined, // 部门sn
      dealerLevel: undefined, // 经销商等级
      allocateSn: undefined// 调拨sn
    }
  },
  computed: {
    // 计算已选产品条数
    selNums () {
      return this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.length || 0
    },
    // 价格级别
    priceLevelList () {
      return this.$store.state.app.priceLeveList
    },
    // 表头
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '10%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', align: 'left', width: '30%', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: '24%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        // { title: '成本价', dataIndex: 'lastStockCost', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '售价', dataIndex: 'productPrice', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '价格级别', dataIndex: 'priceLevelDictValue', width: '10%', align: 'center', scopedSlots: { customRender: 'priceLevel' } },
        { title: '库存数量', dataIndex: 'currentStockQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '调出数量', scopedSlots: { customRender: 'qty' }, width: '6%', align: 'center' },
        { title: '单位', dataIndex: 'productUnit', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action1' }, width: '6%', align: 'center' }
      ]
      if (this.$hasPermissions('M_transferOut_edit_costPrice')) { //  成本价权限
        arr.splice(4, 0, { title: '成本价', dataIndex: 'lastStockCost', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (this.$hasPermissions('M_transferOut_edit_salesPrice')) { //  售价权限
        const ind = this.$hasPermissions('M_transferOut_edit_costPrice') ? 5 : 4
        arr.splice(ind, 0, { title: '售价', dataIndex: 'productPrice', width: '6%', align: 'right', scopedSlots: { customRender: 'productPriceInfo' } })
      }
      if (this.basicInfoData && this.basicInfoData.targetType === 'DEALER') {
        arr.splice(6, 0, { title: '价格级别', dataIndex: 'priceLevelDictValue', width: '10%', align: 'center', scopedSlots: { customRender: 'priceLevel' } })
      }
      return arr
    },
    // 已选列表表头
    chooseColumns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productEntity.code', width: '10%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productEntity.name', width: '27%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productEntity.origCode', width: '20%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        // { title: '成本价', dataIndex: 'cost', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '售价', scopedSlots: { customRender: 'price' }, width: '10%', align: 'center' },
        { title: '库存数量', dataIndex: 'currentStockQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '调出数量', scopedSlots: { customRender: 'qty' }, width: '6%', align: 'center' },
        { title: '费用归属部门', scopedSlots: { customRender: 'department' }, width: '10%', align: 'center' },
        { title: '单位', dataIndex: 'productEntity.unit', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '6%', align: 'center' }
      ]
      if (this.$hasPermissions('M_transferOut_edit_costPrice')) { //  成本价权限
        arr.splice(4, 0, { title: '成本价', dataIndex: 'cost', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (this.$hasPermissions('M_transferOut_edit_salesPrice')) { //  售价权限
        const ind = this.$hasPermissions('M_transferOut_edit_costPrice') ? 5 : 4
        arr.splice(ind, 0, { title: '售价', scopedSlots: { customRender: 'price' }, width: '6%', align: 'right' })
      }
      return arr
    }
  },
  methods: {
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 获取部门数据
    getDepartmentList () {
      departmentQueryList({}).then(res => {
        if (res.status == 200) {
          this.departmentList = res.data
        } else {
          this.departmentList = []
        }
      })
    },
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    // 批量设置退货原因
    openPlSet () {
      if (this.selNums) {
        this.showPlModal = true
      } else {
        this.$message.warning('请先选择产品！')
      }
    },
    // 关闭批量设置费用归属部门弹窗
    closePlSet () {
      this.showPlModal = false
      this.plSetVal = undefined
    },
    // 批量设置费用归属部门成功
    setPlSetOk () {
      if (!this.plSetVal) {
        this.$message.warning('请选择费用归属部门！')
      } else {
        const snList = []
        const arr = this.rowSelectionInfo && this.rowSelectionInfo.selectedRows || []
        const department = this.departmentList.find(item => item.departmentSn == this.plSetVal)
        arr.map(item => {
          snList.push({
            'allocateDetailSn': item.allocateDetailSn,
            'departmentSn': this.plSetVal,
            'departmentName': department ? department.name : '',
            'allocateSn': this.allocateSn
          })
        })
        this.showPlModal = false
        this.$message.loading('正在设置...', 0)
        updateBatchDepartment(snList).then(res => {
          if (res.status == 200) {
            this.closePlSet()
            this.refashPage()
          }
          this.$message.destroy()
        })
      }
    },
    //  重置
    resetSearchForm (flag) {
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.productOrigCode = ''
      if (!flag) {
        this.$refs.table.refresh(true)
        this.$refs.chooseTable.refresh(true)
      }
    },
    // 双击快速添加
    handleClickRow (record) {
      return {
        on: {
          dblclick: (event) => {
            if (!this.spinning) {
              this.handleAdd(record, false, 'noRefresh')
            }
          }
        }
      }
    },
    // 导入产品
    handleGuideOk (obj) {
      this.$refs.chooseTable.refresh(true)
      this.getDetail(true)
    },
    // 已选产品  重置
    chooseResetSearchForm (flag) {
      this.chooseQueryParam.productCode = ''
      this.chooseQueryParam.productName = ''
      if (!flag) {
        this.$refs.chooseTable.refresh(true)
      }
    },
    //  添加/编辑
    handleAdd (row, isEdit, isRefresh) {
      const params = {
        id: isEdit ? row.id : undefined,
        allocateSn: this.$route.params.sn,
        cost: isEdit ? row.cost : row.lastStockCost,
        price: isEdit ? row.price : row.productPrice,
        qty: row.qty, //  添加时调出数量默认为1
        productSn: row.productSn,
        productBrandSn: row.productBrandSn,
        departmentSn: row.departmentSn,
        departmentName: row.departmentName,
        productTypeSn1: row.productTypeSn1,
        productTypeSn2: row.productTypeSn2,
        productTypeSn3: row.productTypeSn3,
        priceLevel: row.priceLevel
      }
      if (isEdit) { // 编辑
        // 清空数量时,值应保持未清空前的值，因数量不可为空
        if (!row.qty) {
          row.qty = row.qtyBackups
          return
        }
        if (!row.price) {
          row.price = row.priceBackups
          return
        }
      } else {
        if (!row.qty) {
          this.$message.info('请输入调出数量')
          return
        }
      }
      this.spinning = true
      allocateBillDetailSave(params).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          if (isRefresh != 'noRefresh') {
            this.$refs.table.refresh()
          }
          this.$refs.chooseTable.refresh()
          this.$refs.chooseTable.clearSelected()
          this.getDetail(true)
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    //  删除
    handleDel (row, isAll) {
      const _this = this
      const content = isAll ? '删除后不可恢复，确定要进行整单删除吗？' : '删除后不可恢复，确定要进行删除吗？'
      this.$confirm({
        title: '提示',
        content: content,
        centered: true,
        onOk () {
          if (isAll) { //  整单删除
            _this.spinning = true
            allocateBillDetailDelAll({ sn: _this.$route.params.sn }).then(res => {
              if (res.status == 200) {
                _this.$message.success(res.message)
                _this.refashPage()
              }
              _this.spinning = false
            })
          } else { //  单个删除
            _this.spinning = true
            allocateBillDetailDel({ id: row.id }).then(res => {
              if (res.status == 200) {
                _this.$message.success(res.message)
                _this.refashPage()
              }
              _this.spinning = false
            })
          }
        }
      })
    },
    // 价格等级
    handlePriceLevel (val, pos) {
      this.loadDataSource[pos].productPrice = val == 'PROVINCE' ? this.loadDataSource[pos].provincePrice : val == 'CITY' ? this.loadDataSource[pos].cityPrice : this.loadDataSource[pos].specialPrice
    },
    //  提交
    handleOpen () {
      if (this.localDataSource.length) {
        // 待提交/待审核/审核不通过，打开发货信息弹框
        if ((this.basicInfoData.state == 'WAIT_SUBMIT') || (this.basicInfoData.state == 'WAIT_AUDIT' || this.basicInfoData.state == 'AUDIT_REJECT')) {
          this.showDsModal = true
          this.$refs.dsModal.pageInit(this.basicInfoData)
        } else {
          this.handleSubmit()
        }
      } else {
        this.$message.warning('请选择产品')
      }
    },
    // 提交
    handleSubmit (params) {
      const _this = this
      const data = Object.assign({ allocateSn: this.$route.params.sn }, params || {})
      _this.spinning = true
      _this.showDsModal = false
      allocateBillSubmit(data).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.handleBack()
        } else {
          _this.spinning = false
        }
      })
    },
    // 基本信息
    getDetail (flag) {
      this.spinning = true
      allocateBillDetail({ sn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.basicInfoData = res.data
          if (!flag) {
            this.resetSearchForm(0)
          }
        } else {
          this.basicInfoData = null
        }
        this.spinning = false
      })
    },
    // 合计
    getDetailCount (params) {
      allocateBillDetailCount({ allocateSn: this.$route.params.sn, ...params }).then(res => {
        if (res.status == 200) {
          this.productTotal = res.data
        } else {
          this.productTotal = null
        }
      })
    },
    //  返回列表
    handleBack () {
      this.$router.push({ path: '/allocationManagement/transferOut/list', query: { closeLastOldTab: true } })
    },
    // 已选产品 调出数量  blur
    qtyBlur (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val != record.qtyBackups) {
        this.handleAdd(record, 'edit', 'noRefresh')
      }
    },
    // 已选产品 修改部门
    handleChange (value, record) {
      if (value) {
        const department = this.departmentList.find(item => item.departmentSn == record.departmentSn)
        record.departmentName = department ? department.name : ''
      } else {
        record.departmentSn = ''
        record.departmentName = ''
      }
      this.handleAdd(record, 'edit', 'noRefresh')
    },
    // 已选产品 售价  change
    priceChange (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val != record.priceBackups) {
        this.handleAdd(record, 'edit', 'noRefresh')
      }
    },
    // 获取价格
    priceFocus (row, index) {
      if (row.productSn) {
        productPriceInfo({ sn: row.productSn }).then(res => {
          if (res.status == 200 && res.data) {
            this.loadDataSource[index].provincePrice = res.data.provincePrice || undefined
            this.loadDataSource[index].cityPrice = res.data.cityPrice || undefined
            this.loadDataSource[index].specialPrice = res.data.specialPrice || undefined
          }
        })
      }
    },
    // 导出
    handleExcel (printType, filename, data) {
      const _this = this
      this.spinning = true
      const params = { allocateSn: this.outBizSn || this.$route.params.sn, printType: printType, ...data }

      exportExcel(allocateBillDetailExcel, params, filename, function () {
        _this.spinning = false
        _this.$store.state.app.curActionPermission = ''
      })
    },
    // 打印导出
    exportFl (data) {
      this.handleExcel(data.printType, '调拨分类', data)
    },
    // 打印预览/快捷打印
    handlePrint (type) {
      this.nowType = type
      this.openModal = true
    },
    // 打印调拨分类、调拨 成功
    handleOk (objs) {
      const _this = this
      const params = JSON.parse(JSON.stringify(objs))
      delete params.type
      const taskName = this.nowType == 'dbPrint' ? '调拨' : '调拨分类'
      _this.spinning = true
      printBase64Fun(
        allocateBillDetailPrint,
        params,
        objs.isPreview ? 'preview' : 'print',
        taskName,
        (res) => {
          _this.spinning = false
          _this.$store.state.app.curActionPermission = ''
        },
        {
          billType: 'ALLOCATE',
          billSn: objs.allocateSn,
          billNo: objs.allocateNo,
          printType: taskName + '打印'
        }, !this.basicInfoData.printState || this.basicInfoData.printState == 'UNABLE_PRINT' || this.basicInfoData.printState == 'CANCEL_PRINT')
    },
    // 刷新当前页面
    refashPage () {
      this.getDetail(true)
      // this.$refs.table.refresh()
      this.$refs.chooseTable.clearSelected()
      this.$refs.chooseTable.refresh()
    },
    // 初始化
    pageInit () {
      this.dealerLevel = this.$route.params.dealerLevel
      this.allocateSn = this.$route.params.sn
      this.getDepartmentList()
      this.getDetail()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .allocateBillEdit-wrap{
    position: relative;
    height: 100%;
    box-sizing: border-box;
    > .ant-spin-nested-loading {
        height: 100%;
        > .ant-spin-container{
          position: relative;
          height: 100%;
          overflow: auto;
          padding-bottom: 60px;
        }
    }
    .allocateBillEdit-back{
      margin-bottom: 6px;
    }
    .allocateBillEdit-cont{
      margin-bottom: 6px;
      .sub-title{
        font-size: 12px;
        color: #808695;
        margin-left: 10px;
      }
      .tag-txt{
        font-size: 12px;
        color: #ed1c24;
      }
      .edit-circle-btn{
        margin-left: 15px;
        i{
          vertical-align: text-bottom;
        }
      }
      .import-btn{
        margin-left: 15px;
      }
    }
    .affix-cont{
      position: fixed;
    }
  }
</style>
