<template>
  <div class="purchaseReturnEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="purchaseReturnEdit-back" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="purchaseReturnEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span style="margin: 0 15px;color: #666;">供应商名称：箭冠营销中心</span>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra" v-if="$hasPermissions('B_purchaseReturnApplyPrint')">
          <Print :disabled="dataSource.length==0" @handlePrint="handlePrint"></Print>
        </template>
      </a-page-header>
      <!-- 选择产品 -->
      <div class="purchaseReturnEdit-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1" header="选择产品">
            <!-- 筛选条件 -->
            <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="产品编码" prop="productCode">
                      <a-input id="purchaseReturnEdit-productCode" v-model.trim="queryParam.code" placeholder="请输入产品编码" allowClear />
                    </a-form-item>
                  </a-col>
                  <a-col :md="6" :sm="24">
                    <a-form-item label="产品名称" prop="productName">
                      <a-input id="purchaseReturnEdit-productName" v-model.trim="queryParam.name" placeholder="请输入产品名称" allowClear />
                    </a-form-item>
                  </a-col>
                  <a-col :md="6" :sm="24">
                    <a-form-model-item label="产品分类">
                      <ProductType id="purchaseReturnEdit-productType" placeholder="请选择产品分类" :isDealer="true" @change="changeProductType" v-model="productType"></ProductType>
                    </a-form-model-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="purchaseReturnList-refresh">查询</a-button>
                    <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="purchaseReturnList-reset">重置</a-button>
                  </a-col>
                </a-row>
              </a-form>
            </div>
            <!-- 列表 -->
            <s-table
              class="sTable"
              ref="table"
              size="small"
              :rowKey="(record) => record.id"
              :columns="columns"
              :data="loadData"
              :defaultLoadData="false"
              :pageSize="10"
              :scroll="{ y: 149 }"
              bordered>
              <!-- 产品分类 -->
              <template slot="productType" slot-scope="text, record">
                <span v-if="record.productTypeName2 || record.productTypeName3">{{ record.productTypeName2 }} {{ record.productTypeName3 ? '>' : '' }} {{ record.productTypeName3 }}</span>
                <span v-else>--</span>
              </template>
              <!-- 数量 -->
              <template slot="returnQty" slot-scope="text, record">
                <a-input-number
                  size="small"
                  id="purchaseReturnEdit-returnQty"
                  v-model="record.returnQty"
                  :precision="0"
                  :min="1"
                  :max="record.refundableQty"
                  placeholder="请输入"
                  style="width: 100%;" />
              </template>
              <!-- 退货原因 -->
              <template slot="returnReason" slot-scope="text, record">
                <returnReason v-model="record.returnReason"></returnReason>
              </template>
              <!-- 操作 -->
              <template slot="action" slot-scope="text, record">
                <span v-if="record.refundableQty==0">--</span>
                <a-button
                  v-else
                  size="small"
                  type="link"
                  class="button-primary"
                  @click="handleAdd(record)"
                  id="purchaseReturnEdit-add-btn">添加</a-button>
              </template>
            </s-table>
          </a-collapse-panel>
        </a-collapse>
      </div>
      <!-- 已选产品 -->
      <a-card size="small" :bordered="false" class="purchaseReturnEdit-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1">
            <template slot="header">
              已选产品
            </template>
            <!-- 总计 -->
            <a-alert type="info" style="margin-bottom:10px">
              <div slot="message">
                申请退货数量：<strong>{{ (detailData&&(detailData.totalInitialQty || detailData.totalInitialQty==0)) ? detailData.totalInitialQty : '--' }}</strong> ；
              </div>
            </a-alert>
            <!-- 筛选条件 -->
            <div class="table-page-search-wrapper" style="display:flex;width:100%;">
              <div style="flex-grow:1;">
                <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="产品编码" prop="productCode">
                        <a-input id="purchaseReturnEdit-productCode" v-model.trim="chooseParam.productCode" placeholder="请输入产品编码" allowClear />
                      </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                      <a-form-item label="产品名称" prop="productName">
                        <a-input id="purchaseReturnEdit-productName" v-model.trim="chooseParam.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="disabled" id="purchaseReturnList-refresh">查询</a-button>
                      <a-button style="margin-left: 8px" @click="resetChooseForm" :disabled="disabled" id="purchaseReturnList-reset">重置</a-button>
                    </a-col>
                  </a-row>
                </a-form>
              </div>
              <div>
                <span style="margin-right: 10px;" v-if="selNums">已选{{ selNums }}项</span>
                <a-button type="default" style="margin-right: 10px;" class="button-info" @click="openPlSetReason">批量设置退货原因</a-button>
                <a-button
                  type="primary"
                  id="purchaseReturnEdit-import-btn"
                  class="button-info"
                  @click="openGuideModal = true"
                >产品导入</a-button>
                <a-button
                  type="primary"
                  class="button-error"
                  id="purchaseReturnEdit-delAll-btn"
                  @click.stop="handleDel('', 'all')"
                >整单删除</a-button>
              </div>
            </div>
            <!-- 列表 -->
            <s-table
              class="sTable"
              ref="chooseTable"
              size="small"
              :rowKey="(record) => record.id"
              :row-selection="{ columnWidth: 40 }"
              @rowSelection="rowSelectionFun"
              :columns="chooseColumns"
              :data="chooseLoadData"
              :defaultLoadData="false"
              :pageSize="10"
              :scroll="{ y: 149 }"
              bordered>
              <!-- 产品分类 -->
              <template slot="productType" slot-scope="text, record">
                <span v-if="record.product.productTypeName2 || record.product.productTypeName3">{{ record.product.productTypeName2 }} {{ record.product.productTypeName3 ? '>' : '' }} {{ record.product.productTypeName3 }}</span>
                <span v-else>--</span>
              </template>
              <!-- 退货数量 -->
              <template slot="qty" slot-scope="text, record">
                <a-input-number
                  size="small"
                  id="purchaseReturnEdit-qty"
                  v-model="record.initQty"
                  :precision="0"
                  :min="1"
                  placeholder="请输入"
                  @blur="e => qtyBlur(e.target.value, record)"
                  style="width: 100%;" />
              </template>
              <!-- 退货原因 -->
              <template slot="returnReason" slot-scope="text, record">
                <returnReason v-model="record.returnReason" @blur="e => remarksBlur(e, record)"></returnReason>
              </template>
              <!-- 操作 -->
              <template slot="action" slot-scope="text, record">
                <a-button size="small" type="link" class="button-error" @click="handleDel(record)" id="purchaseReturnEdit-del-btn">删除</a-button>
              </template>
            </s-table>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
    </a-spin>
    <a-card size="small" :bordered="false" class="affix-cont">
      <a-button
        type="primary"
        id="purchaseReturnEdit-submit"
        size="large"
        :disabled="spinning"
        class="button-primary"
        @click="handleSubmit"
        style="padding: 0 60px;">提交</a-button>
    </a-card>

    <!-- 导入明细 -->
    <importGuideModal
      :openModal="openGuideModal"
      :params="{purchaseReturnApplySn: $route.params.sn, purchaseReturnApplyNo:detailData?detailData.purchaseReturnApplyNo:''}"
      @close="openGuideModal=false"
      @ok="hanldeImprotOk" />

    <!-- 批量设置退货原因 -->
    <commonModal modalTit="批量设置退货原因" :openModal="showPlModal" @close="showPlModal=false" @ok="setPlReturnReason">
      <div style="text-align: center;">
        <div style="margin-bottom: 15px;font-size: 14px;"><strong>请输入退货原因</strong></div>
        <div style="line-height: 24px;">
          <div><returnReason size="large" v-model="plReturnReason"></returnReason></div>
        </div>
      </div>
    </commonModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import Print from '@/views/common/print.vue'
import { hdPrint } from '@/libs/JGPrint'
import returnReason from '@/views/common/returnReason'
import commonModal from '@/views/common/commonModal.vue'
import ProductType from '../../common/productType.js'
import importGuideModal from './importGuideModal.vue'
import {
  purchaseReturnDetailList,
  purchaseReturnDetail,
  purchaseReturnDetailSave,
  purchaseReturnDetailDel,
  purchaseReturnDetailDelAll,
  purchaseReturnModifyQty,
  modifyReturnReason,
  purchaseReturnSubmit,
  purchaseReturnApplyPrint,
  purchaseReturnApplyExport,
  purchaseReturnApplyCreateList,
  queryDealerScopeProductPage,
  modifyReturnReasonList } from '@/api/purchaseReturnApply'
export default {
  name: 'PurchaseReturnEdit',
  components: { STable, VSelect, Print, ProductType, importGuideModal, returnReason, commonModal },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      queryParam: {
        code: '',
        name: '',
        productTypeSn1: undefined,
        productTypeSn2: undefined,
        productTypeSn3: undefined
      },
      productType: [],
      dataSource: [],
      returnReasonList: [], // 退货原因列表
      disabled: false, //  查询、重置按钮是否可操作
      advanced: false, // 高级搜索 展开/关闭
      openGuideModal: false, // 导入产品弹框
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.queryParam.sysFlag = '1' // 剪冠产品
        return queryDealerScopeProductPage(Object.assign(parameter, this.queryParam)).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].returnQty = 1
          }
          this.disabled = false
          return data
        })
      },
      chooseParam: {
        productCode: '',
        productName: ''
      },
      // 加载数据方法 必须为 Promise 对象
      chooseLoadData: parameter => {
        return purchaseReturnDetailList(Object.assign(parameter, { purchaseReturnApplySn: this.$route.params.sn }, this.chooseParam)).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].initQty
            data.list[i].returnReasonBackups = data.list[i].returnReason
          }
          this.dataSource = data.list
          return data
        })
      },
      detailData: null,
      rowSelectionInfo: null,
      plReturnReason: '',
      showPlModal: false
    }
  },
  watch: {
    showPlModal (newValue, oldValue) {
      if (!newValue) {
        this.plReturnReason = ''
      }
    }
  },
  computed: {
    selNums () {
      return this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.length || 0
    },
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '产品编码', dataIndex: 'code', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'name', width: '20%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品分类', scopedSlots: { customRender: 'productType' }, width: '20%', align: 'center' },
        { title: '单位', dataIndex: 'unit', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '申请退货数量', scopedSlots: { customRender: 'returnQty' }, width: '10%', align: 'center' },
        { title: '退货原因', scopedSlots: { customRender: 'returnReason' }, width: '10%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      return arr
    },
    chooseColumns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '产品编码', dataIndex: 'product.code', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'product.name', width: '20%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品分类', scopedSlots: { customRender: 'productType' }, width: '20%', align: 'center' },
        { title: '单位', dataIndex: 'product.unit', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '申请退货数量', scopedSlots: { customRender: 'qty' }, width: '10%', align: 'center' },
        { title: '退货原因', scopedSlots: { customRender: 'returnReason' }, width: '10%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      return arr
    }
  },
  methods: {
    //  返回列表
    handleBack () {
      this.$router.push({ name: 'purchaseReturnApplyFormList' })
    },
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    // 打印预览/快捷打印
    handlePrint (type, printerType) {
      const _this = this
      _this.spinning = true
      let url = purchaseReturnApplyPrint
      const params = { sn: this.$route.params.sn }
      if (type == 'export') { //  导出
        url = purchaseReturnApplyExport
      }
      // 打印或导出
      hdPrint(printerType, type, url, params, '采购退货申请单', function () {
        _this.spinning = false
      })
    },
    // 确认导入明细
    hanldeImprotOk (obj) {
      this.spinning = true
      purchaseReturnApplyCreateList(obj).then(res => {
        if (res.status == 200) {
          this.$refs.chooseTable.refresh(true)
          this.getDetail()
          this.openGuideModal = false
        }
        this.spinning = false
      })
    },
    //  产品分类  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] : ''
    },
    //  重置产品列表
    resetSearchForm () {
      this.queryParam.code = ''
      this.queryParam.name = ''
      this.queryParam.productTypeSn1 = undefined
      this.queryParam.productTypeSn2 = undefined
      this.queryParam.productTypeSn3 = undefined
      this.productType = []
      this.$refs.table.refresh(true)
    },
    //  添加/编辑
    handleAdd (row) {
      // 添加时退货数量字段名为returnQty,编辑时退货数量字段名为qty
      if (!row.returnQty) {
        this.$message.warning('请输入退货数量')
        return
      }
      const params = {
        purchaseReturnApplySn: this.$route.params.sn,
        initQty: row.returnQty, //  退货数量
        productSn: row.productSn,
        returnReason: row.returnReason
      }
      this.spinning = true
      purchaseReturnDetailSave(params).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.$refs.chooseTable.refresh()
          this.getDetail()
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    // 双击快速添加
    handleClickRow (record) {
      return {
        on: {
          dblclick: (event) => {
            event.stopPropagation()
            this.handleAdd(record)
          }
        }
      }
    },
    // 导入明细
    handleImport () {},
    // 重置已选产品列表
    resetChooseForm () {
      this.chooseParam.productCode = ''
      this.chooseParam.productName = ''
      this.$refs.chooseTable.refresh(true)
    },
    //  删除
    handleDel (row, isAll) {
      const _this = this
      if (this.dataSource.length == 0) {
        this.$message.info('没有可删除的产品')
        return
      }
      const content = isAll ? '删除后不可恢复，确定要进行整单删除吗？' : '删除后不可恢复，确定要进行删除吗？'
      this.$confirm({
        title: '提示',
        content: content,
        centered: true,
        onOk () {
          const fun = isAll ? purchaseReturnDetailDelAll : purchaseReturnDetailDel
          const params = isAll ? { purchaseReturnApplySn: _this.$route.params.sn } : { purchaseReturnApplySn: _this.$route.params.sn, purchaseReturnApplyDetailSn: row.purchaseReturnApplyDetailSn }
          _this.spinning = true
          fun(params).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              // _this.$refs.table.refresh()
              _this.$refs.chooseTable.refresh()
              _this.spinning = false
              _this.getDetail()
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  提交
    handleSubmit () {
      const _this = this
      if (this.dataSource.length == 0) {
        this.$message.info('请添加产品')
        return
      }
      _this.spinning = true
      purchaseReturnSubmit({ sn: _this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          if (res.data.length) {
            _this.$warning({
              title: '以下产品请输入退货原因',
              centered: true,
              content: res.data.toString()
            })
          } else {
            _this.$message.success(res.message)
            _this.handleBack()
          }
        }
        _this.spinning = false
      })
    },
    // 已选产品 退货数量修改
    qtyBlur (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val != record.qtyBackups) {
        this.spinning = true
        purchaseReturnModifyQty({
          initQty: record.initQty,
          purchaseReturnApplyDetailSn: record.purchaseReturnApplyDetailSn,
          purchaseReturnApplySn: this.$route.params.sn
        }).then(res => {
          if (res.status == 200) {
            this.$message.success(res.message)
            this.$refs.chooseTable.refresh()
            record.qtyBackups = record.initQty
            this.getDetail()
          } else {
            record.initQty = record.qtyBackups
          }
          this.spinning = false
        })
      }
    },
    // 已选产品 退货原因修改
    remarksBlur (val, record) {
      // 空或没有改变时不保存数据
      if (!record.returnReason || record.returnReason == record.returnReasonBackups) {
        record.returnReason = record.returnReasonBackups
        return
      }
      this.spinning = true
      modifyReturnReason({
        returnReason: record.returnReason,
        purchaseReturnApplyDetailSn: record.purchaseReturnApplyDetailSn,
        purchaseReturnApplySn: this.$route.params.sn
      }).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.$refs.chooseTable.refresh()
        } else {
          record.returnReason = record.returnReasonBackups
        }
        this.spinning = false
      })
    },
    // 批量设置退货原因
    openPlSetReason () {
      if (this.selNums) {
        this.showPlModal = true
      } else {
        this.$message.warning('请先选择产品！')
      }
    },
    setPlReturnReason () {
      if (this.plReturnReason == '') {
        this.$message.warning('请输入退货原因！')
      } else {
        this.spinning = true
        const snList = []
        const arr = this.rowSelectionInfo && this.rowSelectionInfo.selectedRows || []
        arr.map(item => {
          snList.push({
            purchaseReturnApplyDetailSn: item.purchaseReturnApplyDetailSn,
            returnReason: this.plReturnReason
          })
        })
        modifyReturnReasonList({
          purchaseReturnApplySn: this.$route.params.sn,
          detailList: snList
        }).then(res => {
          if (res.status == 200) {
            this.showPlModal = false
            this.$refs.chooseTable.refresh()
            this.$refs.chooseTable.clearSelected()
          }
          this.spinning = false
        })
      }
    },
    // 获取单据详情
    getDetail () {
      purchaseReturnDetail({ sn: this.$route.params.sn }).then(res => {
        this.detailData = res.data ? res.data : null
      })
    },
    pageInit () {
      this.returnReasonList = this.$store.state.app.returnReason
      this.$refs.chooseTable.refresh(true)
      this.resetSearchForm()
      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">
  .purchaseReturnEdit-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      overflow-y: auto;
      height: 100%;
    }
    .purchaseReturnEdit-back, .purchaseReturnEdit-cont{
      margin-bottom: 10px;
    }
  }
</style>
