<template>
  <div class="salesReturnEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="salesReturnEdit-back">
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="salesReturnEdit-back-btn" href="javascript:;" @click="handleBack">
            <a-icon type="left" />
            返回列表
          </a>
          <span style="margin: 0 15px;color: #666;font-weight: bold;">单号：{{ detailsData&&detailsData.sparePartsReturnNo }}</span>
          <span style="margin: 0 10px;color: #666;">供应商：{{ detailsData && detailsData.supplier && detailsData.supplier.supplierName }}</span>
          <a-button type="link" size="small" class="button-default" @click="showDetail=!showDetail">
            <a-icon :type="showDetail ? 'eye-invisible' : 'eye'"/> {{ showDetail?'隐藏':'查看' }}信息
          </a-button>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="salesReturnEdit-cont" v-show="showDetail">
        <div slot="title">
          <span>基础信息</span>
          <div style="cursor:pointer;color: #00aaff;float:right;" @click.stop="handleEditBase" >
            <a-icon type="edit" /> 编辑基础信息
          </div>
        </div>
        <a-descriptions size="small" :column="4" style="margin-bottom: 10px;">
          <a-descriptions-item label="采购退货单号">{{ (detailsData && detailsData.sparePartsReturnNo) || '--' }}</a-descriptions-item>
          <a-descriptions-item label="供应商名称">{{ (detailsData && detailsData.supplier && detailsData.supplier.supplierName) || '--' }}</a-descriptions-item>
          <a-descriptions-item label="退货原因">{{ (detailsData && detailsData.returnReasonDictValue) || '--' }}</a-descriptions-item>
          <a-descriptions-item label="退货仓库">{{ detailsData&&detailsData.warehouseName || '--' }}</a-descriptions-item>
          <a-descriptions-item label="是否抓单">{{ detailsData&&detailsData.grabFlag =='0'?'否':'是' }}</a-descriptions-item>
          <a-descriptions-item label="补充说明">{{ (detailsData && detailsData.explainInfo) || '--' }}</a-descriptions-item>
          <a-descriptions-item label="附件" :span="2">
            <span v-if="detailsData && detailsData.attachmentList && detailsData.attachmentList.length > 0">
              <a
                target="_blank"
                style="color: #00aaff;text-decoration: underline;margin-right: 15px;"
                :href="item.filePath"
                v-for="item in detailsData.attachmentList"
                :key="item.id"
              >
                {{ item.fileName }}
              </a>
            </span>
            <span v-else>--</span>
          </a-descriptions-item>
        </a-descriptions>
      </a-card>
      <a-card size="small" :bordered="false" class="salesReturnEdit-cont">
        <queryPart
          ref="partQuery"
          :newLoading="isInster"
          :addMoreLoading="addMoreLoading"
          @add="saveProduct"
          @bachAdd="saveMoreProduct"></queryPart>
      </a-card>
      <a-card size="small" :bordered="false" class="salesReturnEdit-cont">
        <a-alert style="margin-bottom: 10px;" type="info">
          <div slot="message" class="total-bar">
            <div v-if="statisticsObj">
              <span>申请退货数量：{{ statisticsObj && (statisticsObj.qty || statisticsObj.qty == 0) ? statisticsObj.qty : '--' }}；</span>
              <span v-if="$hasPermissions('B_purchaseReturnEdit_costPrice')">退货金额：{{ statisticsObj && statisticsObj.totalCost || statisticsObj.totalCost == 0 ? statisticsObj.totalCost : '--' }}；</span>
            </div>
          </div>
        </a-alert>
        <div class="table-page-search-wrapper" style="display:flex;align-items: center;justify-content: space-between;">
          <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="入库单号"><a-input v-model.trim="productForm.sparePartsNo" allowClear placeholder="请输入入库单号" /></a-form-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-item label="产品编码"><a-input v-model.trim="productForm.productCode" allowClear placeholder="请输入产品编码" /></a-form-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-item label="产品名称"><a-input v-model.trim="productForm.productName" allowClear placeholder="请输入产品名称" /></a-form-item>
                </a-col>
                <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                  <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                  <a-button style="margin-left: 5px" @click="resetSearchForm">重置</a-button>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </div>
        <!-- 已选配件列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          :scroll="{ y: 300 }"
          bordered>
          <!--申请退货数量 -->
          <template slot="qty" slot-scope="text, record">
            <a-input-number
              id="salesReturn-qty"
              size="small"
              v-model="record.qty"
              :precision="0"
              :min="1"
              :max="record.qty"
              placeholder="请输入"
              style="width: 100%;"
              @blur="e => onCellBlur(e.target.value, record)"
            />
          </template>

          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              :loading="delLoading"
              class="button-error"
              @click="handleDel(record)"
              id="salesReturn-Del">删除</a-button>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        size="large"
        style="padding: 0 60px;"
        :disabled="spinning"
        type="primary"
        class="button-primary"
        @click="beforeSubmit"
        id="salesReturn-handleSubmit">提交</a-button>
    </div>
    <!-- 选择审核人员 -->
    <chooseDepartUserModal ref="chooseDepart" :openModal="openDepartUserModal" @close="openDepartUserModal = false" @submit="handleSubmit"></chooseDepartUserModal>
    <!-- 编辑基础信息弹窗 -->
    <add-modal v-drag :openModal="openModal" :itemSn="sparePartsReturnSn" @ok="getBasicsData" @close="openModal = false" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import queryPart from './queryPart.vue'
import addModal from './addModal.vue'
import chooseDepartUserModal from './chooseDepartUserModal.vue'
import {
  sparePartsReturnQueryPage,
  queryPageCount,
  sparePartsReturnDetailDelete,
  sparePartsReturnDetailSave,
  sparePartsReturnSubmit,
  sparePartsReturnInfo,
  sparePartsReturnDetailSaveBatch
} from '@/api/sparePartsReturn'
export default {
  name: 'PurchaseReturnEdit',
  mixins: [commonMixin],
  components: {
    STable,
    VSelect,
    queryPart,
    addModal,
    chooseDepartUserModal
  },
  data () {
    return {
      spinning: false,
      isInster: false, // 是否正在添加产品
      openDepartUserModal: false, // 审核人员弹窗
      delLoading: false,
      showDetail: false,
      productForm: {
        productName: '',
        productCode: '',
        sparePartsNo: '',
        orderBy: 'sprd.CREATE_DATE DESC'
      },
      sparePartsReturnSn: null,
      sparePartsReturnNo: null,
      chooseList: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.productForm.sparePartsReturnSn = this.sparePartsReturnSn
        return sparePartsReturnQueryPage(Object.assign(parameter, this.productForm)).then(res => {
          let data
          if (res.status == 200) {
            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
            }
          }
          this.chooseList = data.list
          return data
        })
      },
      openModal: false, // 修改信息弹窗
      statisticsObj: null, // 统计明细
      detailsData: null, // 基础信息数据
      addMoreLoading: false, // 批量添加动画
      grabFlag: undefined
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', align: 'center', width: '4%' },
        {
          title: '入库单号',
          dataIndex: 'sparePartsNo',
          width: '18%',
          align: 'center',
          customRender: function (text) {
            return text || '--'
          }
        },
        {
          title: '产品编码',
          dataIndex: 'product.code',
          width: '18%',
          align: 'center',
          customRender: function (text) {
            return text || '--'
          }
        },
        {
          title: '产品名称',
          dataIndex: 'product.name',
          width: '25%',
          align: 'left',
          customRender: function (text) {
            return text || '--'
          },
          ellipsis: true
        },
        {
          title: '单位',
          dataIndex: 'product.unit',
          align: 'center',
          width: '6%',
          customRender: function (text) {
            return text || '--'
          }
        },
        {
          title: '批次号',
          dataIndex: 'stockBatchNo',
          align: 'center',
          width: '10%',
          customRender: function (text) {
            return text || '--'
          }
        },
        { title: '申请退货数量', align: 'center', width: '13%', scopedSlots: { customRender: 'qty' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      if (this.$hasPermissions('B_purchaseReturnEdit_costPrice')) {
        arr.splice(6, 0, {
          title: '退货单价',
          dataIndex: 'cost',
          width: '8%',
          align: 'right',
          customRender: function (text) {
            return text || text == 0 ? _this.toThousands(text, 2) : '--'
          }
        })
        arr.splice(8, 0, {
          title: '退款金额',
          dataIndex: 'totalCost',
          width: '8%',
          align: 'right',
          customRender: function (text) {
            return text || text == 0 ? _this.toThousands(text, 2) : '--'
          }
        })
      }
      return arr
    }
  },
  methods: {
    // 编辑基础信息
    handleEditBase () {
      this.openModal = true
    },
    //  返回
    handleBack () {
      this.$router.push({ path: `/purchasingManagement/purchaseReturn/list`, query: { closeLastOldTab: true } })
    },
    // 删除所选产品
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.delLoading = true
          _this.spinning = true
          sparePartsReturnDetailDelete({ detailSn: row.sparePartsReturnDetailSn })
            .then(res => {
              if (res.status == 200) {
                _this.resetTable(false)
                _this.getStatisticsData()
                _this.getChooseList()
                _this.$refs.partQuery.refreshLength()
              }
              _this.$message.info(res.message)
              _this.delLoading = false
              _this.spinning = false
            })
            .catch(err => {
              _this.delLoading = false
            })
        }
      })
    },
    resetTable (flag) {
      this.$refs.table.refresh(flag)
    },
    //  重置
    resetSearchForm (flag) {
      this.productForm.productName = ''
      this.productForm.productCode = ''
      this.productForm.sparePartsNo = ''
      this.$refs.table.refresh(!!flag)
    },
    // 已选产品  blur
    onCellBlur (val, record) {
      if (val * 1 > record.putQty * 1) {
        this.$message.warning('申请退货数量不能大于入库数量！')
        this.$refs.table.refresh(true)
        return
      }
      const ajax_data = {
        sparePartsReturnSn: this.sparePartsReturnSn,
        sparePartsReturnNo: this.sparePartsReturnNo,
        sparePartsDetailSn: record.sparePartsDetailSn,
        productSn: record.productSn,
        sparePartsReturnDetailSn: record.sparePartsReturnDetailSn,
        stockDetailSn: record.stockDetailSn,
        productCode: record.productCode,
        putQty: record.putQty, // 入库数量
        returnedQty: record.returnedQty, // 已退数量
        qty: val, // 申退数量
        cost: record.cost, // 成本
        stockBatchNo: record.stockBatchNo, // 批次号
        warehouseSn: record.warehouseSn, // 仓库sn
        warehouseLocationSn: record.warehouseLocationSn, // 仓位sn
        sparePartsNo: record.sparePartsNo,
        sparePartsSn: record.sparePartsSn
      }
      this.saveEdit(ajax_data)
    },
    // 添加或修改产品
    saveProduct (row) {
      if (this.isInster) {
        // 防止多次添加产品
        return
      }
      this.isInster = true
      const paramsData = {
        sparePartsReturnSn: this.sparePartsReturnSn,
        sparePartsReturnNo: this.sparePartsReturnNo,
        sparePartsDetailSn: row.sparePartsDetailSn,
        productSn: row.productSn,
        stockDetailSn: row.stockDetailSn,
        productCode: row.productCode,
        putQty: row.productQty, // 入库数量
        returnedQty: row.returnedQty, // 已退数量
        qty: row.qty, // 申退数量
        cost: row.productCost, // 成本
        stockBatchNo: row.sparePartsBatchNo, // 批次号
        warehouseSn: row.warehouseSn, // 仓库sn
        warehouseLocationSn: row.warehouseLocationSn, // 仓位sn
        sparePartsNo: row.sparePartsNo,
        sparePartsSn: row.sparePartsSn
      }
      this.saveEdit(paramsData)
    },
    saveMoreProduct (data) {
      if (this.addMoreLoading) {
        // 防止多次添加产品
        return
      }
      this.addMoreLoading = true
      var ajax_data = []
      data.forEach(item => {
        const obj = {
          sparePartsReturnSn: this.sparePartsReturnSn,
          sparePartsReturnNo: this.sparePartsReturnNo,
          sparePartsDetailSn: item.sparePartsDetailSn,
          productSn: item.productSn,
          stockDetailSn: item.stockDetailSn,
          productCode: item.productCode,
          putQty: item.productQty, // 入库数量
          returnedQty: item.returnedQty, // 已退数量
          qty: item.qty, // 申退数量
          cost: item.productCost, // 成本
          stockBatchNo: item.sparePartsBatchNo, // 批次号
          warehouseSn: item.warehouseSn, // 仓库sn
          warehouseLocationSn: item.warehouseLocationSn, // 仓位sn
          sparePartsNo: item.sparePartsNo,
          sparePartsSn: item.sparePartsSn
        }
        ajax_data.push(obj)
      })
      this.saveMore(ajax_data)
    },
    saveEdit (params) {
      this.spinning = true
      sparePartsReturnDetailSave(params).then(res => {
        if (res.status == 200) {
          this.getStatisticsData()
          this.$refs.table.refresh(true)
          this.getChooseList()
        }
        this.isInster = false
        this.spinning = false
        this.addMoreLoading = false
      }).catch(err => {
        this.isInster = false
      })
    },
    saveMore (params) {
      this.spinning = true
      sparePartsReturnDetailSaveBatch(params)
        .then(res => {
          if (res.status == 200) {
            this.getStatisticsData()
            this.getChooseList()
            this.$refs.table.refresh(true)
            this.$refs.partQuery.refreshLength()
          }
          this.isInster = false
          this.spinning = false
          this.addMoreLoading = false
        })
        .catch(err => {
          this.isInster = false
          this.addMoreLoading = false
          this.spinning = false
        })
    },
    beforeSubmit () {
      if (this.chooseList.length > 0) {
        this.openDepartUserModal = true
      } else {
        this.$message.warning('请先添加要退货的产品！')
      }
    },
    // 提交采购退货
    handleSubmit (data) {
      this.spinning = true
      sparePartsReturnSubmit({ sparePartsReturnSn: this.sparePartsReturnSn, ...data }).then(res => {
        if (res.status == 200) {
          this.handleBack()
          this.$message.success(res.message)
        }
        this.spinning = false
      })
    },
    pageInit () {
      this.supplierSn = this.$route.query.sn
      this.sparePartsReturnSn = this.$route.query.returnSn
      this.sparePartsReturnNo = this.$route.query.no
      this.getStatisticsData()
      this.getBasicsData()
      this.resetSearchForm(true)
    },
    getChooseList () {
      this.$refs.partQuery.pageInit(this.supplierSn, this.sparePartsReturnSn, this.detailsData ? this.detailsData.warehouseSn : undefined, this.detailsData.grabFlag)
    },
    // 获取页面统计数据
    getStatisticsData () {
      this.getBasicsData()
      queryPageCount({ sparePartsReturnSn: this.sparePartsReturnSn }).then(res => {
        if (res.status == 200) {
          if (res.data) {
            res.data.totalCost = res.data && (res.data.totalCost || res.data.totalCost == 0) ? this.toThousands(res.data.totalCost, 2) : '--'
            this.statisticsObj = res.data
          } else {
            this.statisticsObj = null
          }
        } else {
          this.statisticsObj = null
        }
      })
    },
    // 获取基础信息
    getBasicsData () {
      sparePartsReturnInfo({ sn: this.sparePartsReturnSn }).then(res => {
        if (res.status == 200) {
          this.detailsData = res.data
        } else {
          this.detailsData = null
        }
        const _this = this
        this.$nextTick(() => {
          _this.getChooseList()
        })
      })
    }
  },
  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">
.salesReturnEdit-wrap {
  position: relative;
  height: 100%;
  padding-bottom: 51px;
  box-sizing: border-box;
  > .ant-spin-nested-loading {
    overflow-y: scroll;
    height: 100%;
  }
  .salesReturnEdit-cont {
    margin-top: 6px;
    .ant-divider-horizontal {
      margin: 10px 0 24px;
    }
    .total-bar {
      display: flex;
      align-items: center;
      justify-content: space-between;
      > div {
        &:last-child {
          display: flex;
          align-items: center;
          justify-content: space-between;
          > div {
            padding: 0 10px;
          }
        }
      }
    }
  }
}
</style>
