<template>
  <div class="bulkWarehousingOrderEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 内容 -->
      <a-page-header :ghost="false" :backIcon="false" class="bulkWarehousingOrderEdit-cont" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="bulkWarehousingOrderEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <p style=" display: inline-block;margin: 0 0 0 60px;color: #000;font-size: 16px;font-weight: 600;">单号：{{ (basicInfoData&&basicInfoData.sparePartsPurchaseNo) || '' }}</p>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra" v-if="$hasPermissions('B_bulkWarehousingOrder_print')">
          <Print :disabled="chooseLoadDataSource.length==0" :showExport="false" @handlePrint="handlePrint"></Print>
        </template>
      </a-page-header>
      <!-- 基础信息 -->
      <a-card size="small" :bordered="false" class="bulkWarehousingOrderEdit-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1">
            <template slot="header">
              基础信息
            </template>
            <a-descriptions :column="3">
              <a-descriptions-item label="供应商">{{ (basicInfoData&&basicInfoData.supplierName) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="散件入库类型">{{ (basicInfoData&&basicInfoData.sparePartsTypeName) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="备注">{{ (basicInfoData&&basicInfoData.remarks) || '--' }}</a-descriptions-item>
            </a-descriptions>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <!-- 选择产品 -->
      <a-card size="small" :bordered="false" class="bulkWarehousingOrderEdit-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1">
            <template slot="header">
              选择产品<span class="sub-title">①输入查询条件--->②查找到需要入库的配件--->③录入成本价、数量、仓库、仓位--->④点击“添加”</span>
            </template>
            <!-- 选择产品 -->
            <div>
              <!-- 搜索条件 -->
              <div class="table-page-search-wrapper">
                <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
                  <a-row :gutter="15">
                    <a-col :md="6" :sm="24">
                      <a-form-item label="关键词">
                        <a-input id="bulkWarehousingOrderEdit-queryWord" v-model.trim="queryParam.queryWord" allowClear placeholder="产品名称/产品编码/原厂编码"/>
                      </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                      <a-form-item label="产品品牌">
                        <ProductBrand id="bulkWarehousingOrderEdit-productBrandSn" v-model="queryParam.productBrandSn"></ProductBrand>
                      </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                      <a-form-item label="产品分类">
                        <ProductType id="productInfoList-productType" @change="changeProductType" v-model="productType"></ProductType>
                      </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="bulkWarehousingOrderEdit-refresh">查询</a-button>
                      <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="bulkWarehousingOrderEdit-reset">重置</a-button>
                    </a-col>
                  </a-row>
                </a-form>
              </div>
              <!-- 列表 -->
              <s-table
                class="sTable"
                ref="table"
                size="small"
                :rowKey="(record) => record.id"
                :columns="columns"
                :customRow="handleClickRow"
                :data="loadData"
                :defaultLoadData="false"
                :scroll="{ y: 300 }"
                bordered>
                <!-- 成本价 -->
                <template slot="putCost" slot-scope="text, record">
                  <a-input-number
                    size="small"
                    id="bulkWarehousingOrderEdit-putCost"
                    v-model="record.putCost"
                    :precision="2"
                    :min="0"
                    :max="999999"
                    placeholder="请输入"
                    style="width: 100%;" />
                </template>
                <!-- 数量 -->
                <template slot="putQty" slot-scope="text, record">
                  <a-input-number
                    size="small"
                    id="bulkWarehousingOrderEdit-putQty"
                    v-model="record.putQty"
                    :precision="0"
                    :min="1"
                    :max="999999"
                    placeholder="请输入"
                    style="width: 100%;" />
                </template>
                <!-- 仓库仓位 -->
                <template slot="warehouse" slot-scope="text, record, index">
                  <a-cascader
                    size="small"
                    @change="e => changeWarehouseCascade(e, record, index, 'dealerProduct')"
                    v-model="record.warehouseCascade"
                    expand-trigger="hover"
                    :allowClear="false"
                    :options="warehouseCascadeData"
                    :fieldNames="{ label: 'name', value: 'sn', children: 'warehouseLocationList' }"
                    id="bulkWarehousingOrderEdit-warehouseCascade"
                    placeholder="请选择仓库仓位"
                    style="width: 100%;" />
                </template>
                <!-- 操作 -->
                <template slot="action" slot-scope="text, record">
                  <a-button size="small" type="primary" class="button-primary" @click="handleAdd(record)" id="bulkWarehousingOrderEdit-add-btn">添加</a-button>
                </template>
              </s-table>
            </div>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <!-- 已选产品 -->
      <a-card size="small" :bordered="false" class="bulkWarehousingOrderEdit-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1">
            <template slot="header">
              已选产品
            </template>
            <!-- 已选产品 -->
            <div>
              <!-- 总计 -->
              <a-alert type="info" style="margin-bottom:10px">
                <div slot="message">
                  总款数 <strong>{{ (productTotal&&(productTotal.productTotalCategory || productTotal.productTotalCategory==0)) ? productTotal.productTotalCategory : '--' }}</strong> ，
                  总数量 <strong>{{ (productTotal&&(productTotal.productTotalQty || productTotal.productTotalQty==0)) ? productTotal.productTotalQty : '--' }}</strong> ，
                  总成本 <strong>{{ (productTotal&&(productTotal.productTotalCost || productTotal.productTotalCost==0)) ? '￥'+productTotal.productTotalCost : '--' }}</strong>
                </div>
              </a-alert>
              <!-- 列表 -->
              <s-table
                class="sTable"
                ref="chooseTable"
                size="small"
                :rowKey="(record) => record.id"
                :columns="chooseColumns"
                :data="chooseLoadData"
                :defaultLoadData="false"
                :scroll="{ y: 300 }"
                bordered>
                <!-- 成本价 -->
                <template slot="putCost" slot-scope="text, record">
                  <a-input-number
                    size="small"
                    id="bulkWarehousingOrderEdit-choose-putCost"
                    v-model="record.putCost"
                    :precision="2"
                    :min="0"
                    :max="999999"
                    placeholder="请输入"
                    @blur="e => putCostBlur(e.target.value, record)"
                    style="width: 100%;" />
                </template>
                <!-- 数量 -->
                <template slot="putQty" slot-scope="text, record">
                  <a-input-number
                    size="small"
                    id="bulkWarehousingOrderEdit-choose-putQty"
                    v-model="record.putQty"
                    :precision="0"
                    :min="1"
                    :max="999999"
                    placeholder="请输入"
                    @blur="e => putQtyBlur(e.target.value, record)"
                    style="width: 100%;" />
                </template>
                <!-- 仓库仓位 -->
                <template slot="warehouse" slot-scope="text, record, index">
                  <a-cascader
                    size="small"
                    @change="e => changeWarehouseCascade(e, record, index, 'sparePartsPurDetail')"
                    v-model="record.warehouseCascade"
                    expand-trigger="hover"
                    :allowClear="false"
                    :options="warehouseCascadeData"
                    :fieldNames="{ label: 'name', value: 'sn', children: 'warehouseLocationList' }"
                    id="bulkWarehousingOrderEdit-choose-warehouseCascade"
                    placeholder="请选择仓库仓位"
                    style="width: 100%;" />
                </template>
                <!-- 操作 -->
                <template slot="action" slot-scope="text, record">
                  <a-button size="small" type="primary" class="button-error" @click="handleDel(record)" id="bulkWarehousingOrderEdit-del-btn">删除</a-button>
                </template>
              </s-table>
            </div>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        type="primary"
        id="bulkWarehousingOrderEdit-submit"
        size="large"
        :disabled="spinning"
        class="button-primary"
        @click="handleSubmit"
        style="padding: 0 60px;">提交</a-button>
    </div>
    <!-- 选择基本信息弹框 -->
    <basic-info-modal :openModal="openModal" @ok="handleOk" @close="openModal=false" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import basicInfoModal from './basicInfoModal.vue'
import { getOperationalPrecision } from '@/libs/tools.js'
import { sparePartsPurDetail, sparePartsPurDetailList, sparePartsPurDetailCount, sparePartsPurDetailSave, sparePartsPurDetailDel, sparePartsPurSubmit, sparePartsPurDetailPrint } from '@/api/sparePartsPur'
import { bulkProductList } from '@/api/dealerProduct'
import { warehouseCascadeList } from '@/api/warehouse'
import ProductType from '../../common/productType.js'
import ProductBrand from '../../common/productBrand.js'
import Print from '@/views/common/print.vue'
import { hdPrint } from '@/libs/JGPrint'
export default {
  name: 'BulkWarehousingEdit',
  components: { STable, VSelect, basicInfoModal, Print, ProductType, ProductBrand },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      loading: false,
      chooseLoading: false,
      queryParam: {
        queryWord: '',
        productBrandSn: undefined,
        productTypeSn1: undefined,
        productTypeSn2: undefined,
        productTypeSn3: undefined
      },
      productType: [],
      warehouseCascadeData: [], //  仓库仓位
      disabled: false, //  查询、重置按钮是否可操作
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'code', width: '16%', align: 'left', sorter: true, customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'name', width: '16%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'origCode', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品品牌', dataIndex: 'productBrandName', width: '10%', align: 'center', sorter: true, customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'unit', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '成本价', scopedSlots: { customRender: 'putCost' }, width: '7%', align: 'center' },
        { title: '数量', scopedSlots: { customRender: 'putQty' }, width: '7%', align: 'center' },
        { title: '仓库仓位', scopedSlots: { customRender: 'warehouse' }, width: '13%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '8%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        parameter.sortAlias = 'dp'
        const params = Object.assign(parameter, this.queryParam, { supplierSn: this.$route.params.supplierSn })
        params.enabledFlag = 1
        return bulkProductList(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].putCost = data.list[i].purchasePrice || ''
            if (this.defaultWarehouseCascade.length > 0) {
              data.list[i].warehouseCascade = this.defaultWarehouseCascade
              data.list[i].warehouseSn = this.defaultWarehouseCascade[0]
              data.list[i].warehouseLocationSn = this.defaultWarehouseCascade[1]
            } else {
              data.list[i].warehouseCascade = undefined
            }
          }
          this.loadDataSource = data.list
          this.disabled = false
          return data
        })
      },
      // 表头
      chooseColumns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '14%', align: 'left', customRender: function (text) { return text || '--' }, sorter: true },
        { title: '产品名称', dataIndex: 'productName', width: '14%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品品牌', dataIndex: 'brandName', width: '10%', align: 'center', sorter: true, customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'productUnit', width: '4%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '成本价', scopedSlots: { customRender: 'putCost' }, width: '7%', align: 'center' },
        { title: '数量', scopedSlots: { customRender: 'putQty' }, width: '7%', align: 'center' },
        { title: '成本小计', dataIndex: 'costSubtotal', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '仓库仓位', scopedSlots: { customRender: 'warehouse' }, width: '13%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '8%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      chooseLoadData: parameter => {
        // 排序
        if (parameter.sortField == 'brandName') {
          parameter.sortField = 'productBrandName'
          parameter.sortAlias = 'dp'
        }
        if (parameter.sortField == 'productName') {
          parameter.sortField = 'productCode'
          parameter.sortAlias = 'sppd'
        }
        const params = Object.assign(parameter, { sparePartsPurchaseSn: this.$route.params.sn })
        return sparePartsPurDetailList(params).then(res => {
          this.getDetailCount(params)
          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].putCostBackups = data.list[i].putCost
            data.list[i].putQtyBackups = data.list[i].putQty
            const warehouseSn = data.list[i].warehouseSn || undefined
            const warehouseLocationSn = data.list[i].warehouseLocationSn || undefined
            if (warehouseSn || warehouseLocationSn) {
              data.list[i].warehouseSnBackups = warehouseSn
              data.list[i].warehouseLocationSnBackups = warehouseLocationSn
              data.list[i].warehouseCascade = [warehouseSn, warehouseLocationSn]
            } else {
              data.list[i].warehouseCascade = undefined
            }
            // 成本小计  由于数据库内小数位数为4位，页面则需显示2位。因此会做小数运算精度处理
            data.list[i].costSubtotal = getOperationalPrecision(data.list[i].putCost, data.list[i].putQty)
          }
          this.chooseLoadDataSource = data.list
          return data
        })
      },
      loadDataSource: [],
      chooseLoadDataSource: [],
      openModal: false, // 选择基本信息弹框是否显示
      warehouseList: [], //  仓库  下拉数据
      warehouseLocList: {}, //  仓位  下拉数据
      defaultWarehouseCascade: [], //  默认仓库仓位
      chooseWarehouseList: [], //  已选产品 仓库  下拉数据
      chooseWarehouseLocList: {}, //  已选产品 仓位  下拉数据
      basicInfoData: null, //  基本信息
      productTotal: null //  合计
    }
  },
  methods: {
    //  重置
    resetSearchForm () {
      this.queryParam.queryWord = ''
      this.queryParam.productBrandSn = undefined
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.productType = []
      this.$refs.table.refresh(true)
    },
    // 打印预览/快捷打印
    handlePrint (type, printerType) {
      const _this = this
      _this.spinning = true
      const url = sparePartsPurDetailPrint
      const params = { sn: this.$route.params.sn, type: printerType }
      // 打印或导出
      hdPrint(printerType, type, url, params, '', function () {
        _this.spinning = false
      })
    },
    // 双击快速添加
    handleClickRow (record) {
      return {
        on: {
          dblclick: (event) => {
            this.handleAdd(record)
          }
        }
      }
    },
    // 基本信息
    getDetail () {
      sparePartsPurDetail({ id: this.$route.params.id }).then(res => {
        if (res.status == 200) {
          this.basicInfoData = res.data
        } else {
          this.basicInfoData = null
        }
      })
    },
    //  添加/编辑
    handleAdd (row, isEdit) {
      if (!isEdit && !(row.putCost || row.putCost == 0)) {
        this.$message.warning('请输入成本价后再添加！')
        return
      }
      if (!isEdit && !row.putQty) {
        this.$message.warning('请输入数量后再添加！')
        return
      }
      if (!isEdit && !row.warehouseSn) {
        this.$message.warning('请选择仓库后再添加！')
        return
      }
      if (!isEdit && !row.warehouseLocationSn) {
        this.$message.warning('请选择仓位后再添加！')
        return
      }
      const params = {
        id: isEdit ? row.id : undefined,
        sparePartsPurchaseSn: this.$route.params.sn,
        putCost: row.putCost,
        putQty: row.putQty,
        productCode: isEdit ? row.productCode : row.code,
        productOrigCode: (isEdit ? row.productOrigCode : row.origCode) || undefined,
        productSn: row.productSn,
        productTypeSn1: row.productTypeSn1,
        productTypeSn2: row.productTypeSn2,
        productTypeSn3: row.productTypeSn3,
        brandSn: isEdit ? row.brandSn : row.productBrandSn,
        warehouseLocationSn: row.warehouseLocationSn,
        warehouseSn: row.warehouseSn
      }
      if (isEdit) { // 编辑
        // 清空成本价或数量时,值应保持未清空前的值，因成本价和数量都不可为空
        if (!(row.putCost || row.putCost == 0)) {
          row.putCost = row.putCostBackups
          return
        }
        if (!row.putQty) {
          row.putQty = row.putQtyBackups
          return
        }
      }
      this.spinning = true
      sparePartsPurDetailSave(params).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.$refs.chooseTable.refresh()
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    //  提交
    handleSubmit () {
      const _this = this
      _this.spinning = true
      sparePartsPurSubmit({ id: this.$route.params.id }).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          setTimeout(() => {
            _this.handleBack()
            _this.spinning = false
          }, 1000)
        } else {
          _this.spinning = false
        }
      })
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          sparePartsPurDetailDel({ id: row.id }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.chooseTable.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  编辑基本信息
    handleEditInfo () {
      this.openModal = true
    },
    //  基本信息  保存
    handleOk () {},
    //  导入明细
    handleImport () {
      console.log(333)
    },
    //  返回列表
    handleBack () {
      this.$router.push({ path: '/bulkManagement/bulkWarehousingOrder/list' })
    },
    // 合计
    getDetailCount (params) {
      sparePartsPurDetailCount(params).then(res => {
        if (res.status == 200) {
          this.productTotal = res.data
        } else {
          this.productTotal = null
        }
      })
    },
    changeWarehouseCascade (val, opt, ind, type) {
      let loadData
      if (type == 'dealerProduct') { //  全部产品
        loadData = this.loadDataSource[ind]
      } else if (type == 'sparePartsPurDetail') { //  已选产品
        loadData = this.chooseLoadDataSource[ind]
      }
      if (val.length < 2) {
        this.$message.warning('当前仓库无仓位，请选择其他仓库')
        const warehouseSnBackups = loadData.warehouseSnBackups || undefined
        const warehouseLocationSnBackups = loadData.warehouseLocationSnBackups || undefined
        loadData.warehouseSn = warehouseSnBackups
        loadData.warehouseLocationSn = warehouseLocationSnBackups
        if (warehouseSnBackups || warehouseLocationSnBackups) {
          loadData.warehouseCascade = [warehouseSnBackups, warehouseLocationSnBackups]
        } else {
          loadData.warehouseCascade = undefined
        }
      } else {
        loadData.warehouseSn = val[0] ? val[0] : ''
        loadData.warehouseLocationSn = val[1] ? val[1] : ''
        if (type == 'sparePartsPurDetail') { //  已选产品
          loadData = this.chooseLoadDataSource[ind]
          this.handleAdd(loadData, 'edit')
        }
      }
    },
    // 已选产品 成本价  blur
    putCostBlur (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val != record.putCostBackups || !val) {
        this.handleAdd(record, 'edit')
      }
    },
    // 已选产品 数量  blur
    putQtyBlur (val, record) {
      if (val != record.putQtyBackups) {
        this.handleAdd(record, 'edit')
      }
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.productTypeSn3 = val[2] ? val[2] : ''
    },
    //  仓库仓位  级联  列表
    getWarehouseCascade () {
      const _this = this
      warehouseCascadeList({}).then(res => {
        if (res.status == 200) {
          res.data.filter(item => {
            // 过滤默认仓库
            if (item.defaultFlag == 1 && item.wasteFlag == 0) { //  defaultFlag为1,且不是废品仓
              _this.defaultWarehouseCascade[0] = item.warehouseSn
              // 过滤默认仓位
              item.warehouseLocationList.filter(subItem => {
                if (subItem.defaultFlag == 1 && subItem.wasteFlag == 0) {
                  _this.defaultWarehouseCascade[1] = subItem.warehouseLocationSn
                  _this.$refs.table.refresh(true)
                  _this.$refs.chooseTable.refresh(true)
                }
              })
            }
          })
          res.data.map(item => {
            item.sn = item.warehouseSn
            if (item.warehouseLocationList) {
              item.warehouseLocationList.map(subItem => {
                subItem.sn = subItem.warehouseLocationSn
              })
            }
          })
          this.warehouseCascadeData = res.data
        } else {
          this.warehouseCascadeData = []
        }
      })
    },
    initPage () {
      this.getWarehouseCascade()
      this.getDetail()
      this.resetSearchForm()
      this.$refs.chooseTable.refresh(true)
      this.openModal = false
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.initPage()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.initPage()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .bulkWarehousingOrderEdit-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      overflow-y: scroll;
      height: 100%;
    }
    .bulkWarehousingOrderEdit-cont{
      margin-bottom: 10px;
      .sub-title{
        font-size: 12px;
        color: #808695;
        margin-left: 10px;
      }
    }
  }
</style>
