<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;">供应商名称：{{ $route.params.name }}</span>
        </template>
      </a-page-header>
      <!-- 选择产品 -->
      <a-card size="small" :bordered="false" 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="getPurchaseBillDetailList(1)">
                <a-row :gutter="15">
                  <a-col :md="6" :sm="24">
                    <a-form-item label="采购单号" prop="purchaseBillNo">
                      <a-input id="purchaseReturnEdit-purchaseBillNo" v-model.trim="queryParam.purchaseBillNo" placeholder="请输入采购单号" allowClear />
                    </a-form-item>
                  </a-col>
                  <a-col :md="6" :sm="24">
                    <a-form-item label="产品编码" prop="productCode">
                      <a-input id="purchaseReturnEdit-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="purchaseReturnEdit-productName" v-model.trim="queryParam.productName" placeholder="请输入产品名称" allowClear />
                    </a-form-item>
                  </a-col>
                  <a-col :md="6" :sm="24" style="margin-bottom: 24px;">
                    <a-button type="primary" @click="getPurchaseBillDetailList(1)" :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>
            <!-- 列表 -->
            <a-table
              class="sTable"
              ref="table"
              size="small"
              :rowKey="(record) => record.id"
              :columns="columns"
              :dataSource="loadData"
              :scroll="{ x: 1320, y: 300 }"
              :pagination="paginationProps"
              bordered>
              <!-- 数量 -->
              <template slot="returnQty" slot-scope="text, record">
                <a-input-number
                  id="purchaseReturnEdit-returnQty"
                  v-model="record.returnQty"
                  :precision="0"
                  :min="1"
                  :max="record.refundableQty"
                  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="purchaseReturnEdit-add-btn">添加</a-button>
              </template>
            </a-table>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <!-- 已选产品 -->
      <a-card size="small" :bordered="false" class="purchaseReturnEdit-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1">
            <template slot="header">
              已选产品
              <a-button size="small" class="import-btn" id="purchaseReturnEdit-import-btn" @click.stop="handleImport">导入明细</a-button>
              <a-button
                size="small"
                type="primary"
                class="import-btn"
                id="purchaseReturnEdit-delAll-btn"
                @click.stop="handleDel('', 'all')"
                style="margin-left: 10px;">整单删除</a-button>
            </template>
            <!-- 列表 -->
            <a-table
              class="sTable"
              ref="chooseTable"
              size="small"
              :rowKey="(record) => record.id"
              :columns="chooseColumns"
              :dataSource="chooseLoadData"
              :scroll="{ x: 1420, y: 300 }"
              :pagination="choosePaginationProps"
              bordered>
              <!-- 退货数量 -->
              <template slot="qty" slot-scope="text, record">
                <a-input-number
                  id="purchaseReturnEdit-qty"
                  v-model="record.qty"
                  :precision="0"
                  :min="1"
                  :max="record.refundableQty"
                  placeholder="请输入"
                  @blur="e => qtyBlur(e.target.value, record)"
                  style="width: 100%;" />
              </template>
              <!-- 退货原因 -->
              <template slot="remarks" slot-scope="text, record">
                <a-input
                  id="purchaseReturnEdit-remarks"
                  v-model="record.remarks"
                  :maxLength="30"
                  placeholder="退货原因(最多30个字符)"
                  @blur="e => remarksBlur(e.target.value, record)"
                  style="width: 100%;" />
              </template>
              <!-- 操作 -->
              <template slot="action" slot-scope="text, record">
                <a-button size="small" type="primary" class="button-error" @click="handleDel(record)" id="purchaseReturnEdit-del-btn">删除</a-button>
              </template>
            </a-table>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <a-affix :offset-bottom="0">
        <div style="text-align: center;width: 100%;background-color: #fff;padding: 12px 0;box-shadow: 0 0 20px #dcdee2;">
          <a-button
            type="primary"
            id="purchaseReturnEdit-submit"
            size="large"
            class="button-primary"
            @click="handleSubmit"
            style="padding: 0 60px;">提交</a-button>
        </div>
      </a-affix>
    </a-spin>
  </div>
</template>

<script>
import { STable, VSelect } from '@/components'
import { purchaseReturnPurchaseBillDetailList, purchaseReturnDetailList, purchaseReturnDetailSave, purchaseReturnDetailDel, purchaseReturnSubmit, purchaseReturnDelAll } from '@/api/purchaseReturn'
export default {
  components: { STable, VSelect },
  data () {
    return {
      spinning: false,
      queryParam: {
        purchaseBillNo: '',
        productCode: '',
        productName: ''
      },
      disabled: false, //  查询、重置按钮是否可操作
      advanced: false, // 高级搜索 展开/关闭
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '采购单号', dataIndex: 'purchaseBillNo', width: 220, align: 'center' },
        { title: '产品编码', dataIndex: 'dealerProductEntity.code', width: 220, align: 'center' },
        { title: '产品名称', dataIndex: 'dealerProductEntity.name', align: 'center', ellipsis: true },
        { title: '采购总数', dataIndex: 'qty', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '可退数量', dataIndex: 'refundableQty', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '退货数量', scopedSlots: { customRender: 'returnQty' }, width: 100, align: 'center' },
        { title: '采购价', dataIndex: 'price', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'dealerProductEntity.unit', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 100, align: 'center', fixed: 'right' }
      ],
      loadData: [],
      pageNo: 1, //  分页页码
      pageSize: 10, //  分页 每页多少条
      paginationProps: {
        showSizeChanger: true, //  是否可以改变 pageSize
        total: 0, //  分页总条数
        current: 1,
        onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize),
        onChange: (current) => this.changePage(current)
      },
      // 表头
      chooseColumns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '采购单号', dataIndex: 'purchaseBillNo', width: 220, align: 'center' },
        { title: '产品编码', dataIndex: 'dealerProductEntity.code', width: 220, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'dealerProductEntity.name', align: 'center', ellipsis: true },
        { title: '采购总数', dataIndex: 'purchaseBillQty', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '退货数量', scopedSlots: { customRender: 'qty' }, width: 100, align: 'center' },
        { title: '采购价', dataIndex: 'cost', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'dealerProductEntity.unit', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '退货原因', scopedSlots: { customRender: 'remarks' }, width: 200, align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 100, align: 'center', fixed: 'right' }
      ],
      chooseLoadData: [],
      choosePageNo: 1, //  分页页码
      choosePageSize: 10, //  分页 每页多少条
      choosePaginationProps: {
        showSizeChanger: true, //  是否可以改变 pageSize
        total: 0, //  分页总条数
        current: 1,
        onShowSizeChange: (current, pageSize) => this.changeChoosePageSize(current, pageSize),
        onChange: (current) => this.changeChoosePage(current)
      }
    }
  },
  methods: {
    //  重置
    resetSearchForm () {
      this.queryParam.purchaseBillNo = ''
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.pageNo = 1
      this.pageSize = 10
      this.paginationProps.total = 0
      this.paginationProps.current = 1
      this.getPurchaseBillDetailList(1)
    },
    //  添加/编辑
    handleAdd (row, isEdit) {
      // 添加时退货数量字段名为returnQty,编辑时退货数量字段名为qty
      if (!isEdit && !row.returnQty) {
        this.$message.warning('请输入退货数量')
        return
      }
      const params = {
        id: isEdit ? row.id : undefined,
        purchaseReturnSn: this.$route.params.sn,
        purchaseBillSn: row.purchaseBillSn,
        purchaseBillNo: row.purchaseBillNo,
        purchaseBillDetailSn: row.purchaseBillDetailSn,
        qty: isEdit ? row.qty : row.returnQty, //  退货数量
        productSn: row.productSn,
        cost: row.price,
        remarks: row.remarks,
        promotionFlag: row.promotionFlag
      }
      console.log(params)
      if (isEdit) { // 编辑
        // 清空退货数量时,值应保持未清空前的值，因退货数量都不可为空
        if (!row.qty) {
          row.qty = row.qtyBackups
          return
        }
      }
      this.spinning = true
      purchaseReturnDetailSave(params).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.getPurchaseBillDetailList()
          this.getChooseProductList()
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    // 双击快速添加
    handleClickRow (record) {
      return {
        on: {
          dblclick: (event) => {
            this.handleAdd(record)
          }
        }
      }
    },
    // 导入明细
    handleImport () {},
    //  删除
    handleDel (row, isAll) {
      const _this = this
      const content = isAll ? '删除后不可恢复，确定要进行整单删除吗？' : '删除后不可恢复，确定要进行删除吗？'
      this.$confirm({
        title: '提示',
        content: content,
        centered: true,
        onOk () {
          if (isAll) { //  整单删除
            _this.spinning = true
            purchaseReturnDelAll({ purchaseReturnSn: _this.$route.params.sn }).then(res => {
              if (res.status == 200) {
                _this.$message.success(res.message)
                _this.getPurchaseBillDetailList()
                _this.getChooseProductList()
                _this.spinning = false
              }else{
                _this.spinning = false
              }
            })
          } else { //  单个删除
            _this.spinning = true
            purchaseReturnDetailDel({ id: row.id }).then(res => {
              if (res.status == 200) {
                _this.$message.success(res.message)
                _this.getPurchaseBillDetailList()
                _this.getChooseProductList()
                _this.spinning = false
              }else{
                _this.spinning = false
              }
            })
          }
        }
      })
    },
    //  提交
    handleSubmit () {
      const _this = this
      _this.spinning = true
      purchaseReturnSubmit({ 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
        }
      })
    },
    //  返回列表
    handleBack () {
      this.$router.push({ path: '/purchasingManagement/purchaseReturn/list' })
    },
    //  已选产品 分页  一页多少条change
    changePageSize (current, pageSize) {
      this.pageNo = current
      this.pageSize = pageSize
      this.getPurchaseBillDetailList()
    },
    //  已选产品 分页 页码change
    changePage (current) {
      this.pageNo = current
      this.getPurchaseBillDetailList()
    },
    // 选择产品  列表
    getPurchaseBillDetailList (pageNo) {
      this.pageNo = this.pageNo || pageNo
      this.disabled = true
      const params = Object.assign({ pageNo: this.pageNo, pageSize: this.pageSize }, this.queryParam)
      purchaseReturnPurchaseBillDetailList(params).then(res => {
        if (res.status == 200) {
          const data = res.data
          this.paginationProps.total = Number(res.data.count) || 0
          this.paginationProps.current = this.pageNo
          const no = (data.pageNo - 1) * data.pageSize
          for (var i = 0; i < data.list.length; i++) {
            data.list[i].no = no + i + 1
          }
          this.loadData = data.list
          this.disabled = false
        } else {
          this.paginationProps.total = 0
          this.paginationProps.current = 1
          this.loadData = []
        }
      })
    },
    //  已选产品 分页  一页多少条change
    changeChoosePageSize (current, pageSize) {
      this.choosePageNo = current
      this.choosePageSize = pageSize
      this.getChooseProductList()
    },
    //  已选产品 分页 页码change
    changeChoosePage (current) {
      this.choosePageNo = current
      this.getChooseProductList()
    },
    // 已选产品列表数据
    getChooseProductList (pageNo) {
      this.choosePageNo = this.choosePageNo || pageNo
      const params = {
        pageNo: this.choosePageNo,
        pageSize: this.choosePageSize,
        purchaseReturnSn: this.$route.params.sn
      }
      purchaseReturnDetailList(params).then(res => {
        if (res.status == 200) {
          const data = res.data
          this.choosePaginationProps.total = Number(res.data.count) || 0
          this.choosePaginationProps.current = data.pageNo
          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].remarksBackups = data.list[i].remarks
            data.list[i].refundableQty = data.list[i].purchaseBillRefundableQty + data.list[i].qty
          }
          this.chooseLoadData = data.list
        } else {
          this.choosePaginationProps.total = 0
          this.choosePaginationProps.current = 1
          this.chooseLoadData = []
        }
      })
    },
    // 已选产品 退货数量  blur
    qtyBlur (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val != record.qtyBackups) {
        this.handleAdd(record, 'edit')
      }
    },
    // 已选产品 退货原因  blur
    remarksBlur (val, record) {
      if (val && (val != record.remarksBackups)) {
        this.handleAdd(record, 'edit')
      }
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getPurchaseBillDetailList(1)
      vm.getChooseProductList(1)
    })
  }
}
</script>

<style lang="less">
  .purchaseReturnEdit-wrap{
    .purchaseReturnEdit-back{
      margin-bottom: 15px;
    }
    .purchaseReturnEdit-cont{
      margin-bottom: 15px;
      .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;
      }
    }
  }
</style>
