<template>
  <div class="purchaseReceiptEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="purchaseReceiptEdit-back">
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="purchaseReceiptEdit-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" id="purchaseReceiptEdit-showDetail-btn" 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="purchaseReceiptEdit-cont" v-show="showDetail">
        <div slot="title">
          <span>基础信息</span>
          <div style="cursor:pointer;color: #00aaff;float:right;" id="purchaseReceiptEdit-btn" @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.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="销售类型">{{ (detailsData && detailsData.explainInfo) || '--' }}</a-descriptions-item>
        </a-descriptions>
      </a-card>
      <a-card size="small" :bordered="false" class="purchaseReceiptEdit-cont">
        <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" id="purchaseReceiptEdit-form-btn" @keyup.enter.native="$refs.table.refresh(true)">
              <a-row :gutter="15">
                <a-col :md="6" :sm="24">
                  <a-form-item label="产品编码"><a-input id="purchaseReceiptEdit-productCode" v-model.trim="productForm.productCode" allowClear placeholder="请输入产品编码" /></a-form-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-item label="产品名称"><a-input id="purchaseReceiptEdit-productName" 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" id="purchaseReceiptEdit-refresh" @click="$refs.table.refresh(true)">查询</a-button>
                  <a-button style="margin-left: 5px" id="purchaseReceiptEdit-reset" @click="resetSearchForm">重置</a-button>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </div>
        <div class="showBtn">
          <a-button id="purchaseReceiptEdit-add" type="primary" class="button-warning" @click="handleAdd">新增产品</a-button>
          <a-button id="purchaseReceiptEdit-ex" class="button-warning" @click="handleImport">导入产品</a-button>
          <a-button
            v-if="$hasPermissions('B_sparePartsBatchAudit')"
            id="purchaseReceiptEdit-queryQty"
            type="primary"
            class="button-warning"
            :loading="loading"
            @click="handleQueryQty">查询库存</a-button>
          <a-alert type="info">
            <div slot="message" class="total-bar">
              <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>
          </a-alert>
        </div>
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          bordered>
          <!--申请退货数量 -->
          <template slot="qty" slot-scope="text, record">
            <a-input-number
              id="purchaseReceiptEdit-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"
              v-if="$hasPermissions('B_purchaseReturnEdit')"
              @click="handleEdit(record)"
              class="button-info"
              id="purchaseReceiptEdit-edit-btn">编辑</a-button>
            <a-button
              size="small"
              type="link"
              :loading="delLoading"
              class="button-error"
              @click="handleDel(record)"
              id="purchaseReceiptEdit-del-btn">删除</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="handleSubmit"
        id="purchaseReceiptEdit-submit">提交</a-button>
    </div>
    <!-- 新增弹窗-->
    <add-modal v-drag :openModal="openAddModal" @ok="handleOk" @close="openAddModal=false" />
    <!-- 导入弹窗 -->
    <importGuideModal :openModal="openGuideModal" :params="{sparePartsSn: $route.params.sn}" @close="openGuideModal=false" @ok="hanldeOk" />
    <!-- 编辑基础信息弹窗 -->
    <basic-info-modal v-drag :openModal="openBasicInfoModal" :itemSn="sparePartsReturnSn" @ok="getBasicsData" @close="openBasicInfoModal = false" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable, VSelect } from '@/components'
import addModal from './addModal.vue'
import basicInfoModal from './basicInfoModal.vue'
import importGuideModal from './importGuideModal.vue'

// 接口
import {
  sparePartsReturnQueryPage,
  queryPageCount,
  sparePartsReturnDetailDelete,
  sparePartsReturnDetailSave,
  sparePartsReturnSubmit,
  sparePartsReturnInfo,
  sparePartsReturnDetailSaveBatch
} from '@/api/sparePartsReturn'
export default {
  name: 'PurchaseReturnEdit',
  mixins: [commonMixin],
  components: { STable, VSelect, basicInfoModal, addModal, importGuideModal },
  data () {
    return {
      spinning: false,
      showDetail: false, // 是否显示基础信息
      delLoading: false, // 删除loading
      openAddModal: false, // 打开新增产品弹窗
      openBasicInfoModal: false, // 打开编辑基础信息弹窗
      openGuideModal: false, // 导入产品弹窗
      detailsData: null, // 基础信息数据

      isInster: false, // 是否正在添加产品
      addMoreLoading: false, // 防止多次添加  加载状态

      // 查询参数
      productForm: {
        productCode: '', // 产品编码
        productName: '' // 产品名称
      },
      statisticsObj: null, // 统计明细

      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
        })
      },

      grabFlag: undefined // 备注
    }
  },
  computed: {
    // 列表表头配置
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', align: 'center', width: '4%' },
        {
          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: '采购数量', align: 'center', width: '13%', scopedSlots: { customRender: 'qty' } },
        {
          title: '库存数量',
          dataIndex: 'stockBatchNo',
          align: 'center',
          width: '10%',
          customRender: function (text) {
            return text || '--'
          }
        },
        {
          title: '采购单价',
          dataIndex: 'cost',
          width: '8%',
          align: 'right',
          customRender: function (text) {
            return text || text == 0 ? _this.toThousands(text, 2) : '--'
          }
        },
        {
          title: '采购金额',
          dataIndex: 'totalCost',
          width: '8%',
          align: 'right',
          customRender: function (text) {
            return text || text == 0 ? _this.toThousands(text, 2) : '--'
          }
        },
        { 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.openBasicInfoModal = true
    },
    //  返回
    handleBack () {
      this.$router.push({ name: 'purchaseReceiptList', query: { closeLastOldTab: true } })
    },
    // 新增产品
    handleAdd () {
      this.openAddModal = true
    },
    // 导入产品
    handleImport () {
      this.openGuideModal = true
    },
    // 查询库存
    handleQueryQty () {},
    // 删除所选产品
    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.$refs.table.refresh(!!flag)
    },
    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(true)
      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 (flag) {
      sparePartsReturnInfo({ sn: this.sparePartsReturnSn }).then(res => {
        if (res.status == 200) {
          this.detailsData = res.data
        } else {
          this.detailsData = null
        }
        const _this = this
        if (!flag) {
          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">
.purchaseReceiptEdit-wrap {
  position: relative;
  height: 100%;
  padding-bottom: 51px;
  box-sizing: border-box;
  > .ant-spin-nested-loading {
    overflow-y: scroll;
    height: 100%;
  }
  .showBtn{
    display:flex;
    align-items:center;
    margin-bottom:10px;
  }
  .purchaseReceiptEdit-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>
