<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 10px;color: #666;font-weight: bold;">
            单号：{{ ordeDetail&&ordeDetail.salesReturnBillNo }}
          </span>
          <span style="margin: 0 10px;color: #666;">客户名称：{{ ordeDetail&&ordeDetail.buyerName || '--' }}</span>
          <span style="color: #666;">
            退货类别：{{ ordeDetail&&ordeDetail.goodFlagDictValue }}
          </span>
          <span style="margin: 0 0 0 10px;color: #666;">
            退货仓库：{{ ordeDetail&&ordeDetail.warehouseName }}
          </span>
          <a-button size="small" type="link" @click="showEditModal=true" v-if="ordeDetail&&(ordeDetail.billStatus=='WAIT_SUBMIT'||ordeDetail.billStatus=='AUDIT_REJECT')">
            <a-icon type="edit"></a-icon>修改
          </a-button>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra">
          <a-button
            key="3"
            type="default"
            class="button-info"
            id="salesReturnEdit-preview-btn"
            v-if="$hasPermissions('B_salesReturnPrint')"
            :disabled="chooseLoadData.length==0"
            @click="handlePrint('preview')">打印预览</a-button>
          <a-button
            key="2"
            type="primary"
            class="button-info"
            id="salesReturnEdit-print-btn"
            v-if="$hasPermissions('B_salesReturnPrint')"
            :disabled="chooseLoadData.length==0"
            @click="handlePrint('print')">快捷打印</a-button>
          <a-divider type="vertical" />
          <a-button
            key="1"
            type="default"
            class="button-warning"
            id="salesReturnEdit-export-btn"
            v-if="$hasPermissions('B_salesReturnExport')"
            :disabled="chooseLoadData.length==0"
            @click="handlePrint('export')">导出Excel</a-button>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="salesReturnEdit-cont">
        <!-- 查询配件列表 -->
        <queryPart ref="partQuery" :newLoading="isInster" @add="saveProduct"></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>
              <span>申请退货数量：{{ ordeDetail&&(ordeDetail.totalInitialQty || ordeDetail.totalInitialQty==0) ? ordeDetail.totalInitialQty : '--' }}；</span>
              <span v-if="$hasPermissions('B_salesReturnEdit_salesPrice')">参考退货金额：{{ ordeDetail&&(ordeDetail.totalAmount || ordeDetail.totalAmount==0) ? toThousands(ordeDetail.totalAmount) : '--' }}；</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.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">
                  <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled">查询</a-button>
                  <a-button style="margin-left: 5px" @click="resetSearchForm(true)" :disabled="disabled">重置</a-button>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <div>
            <span style="margin-right: 10px;" v-if="selNums">已选{{ selNums }}项</span>
            <a-button v-if="goodFlag == 'GOOD_PRODUCT_RETURN'" type="default" class="button-info" @click="openPlSetReason(1)">整单设置退货原因</a-button>
            <a-button type="default" class="button-info" style="margin-left: 5px;" @click="openPlSetReason(0)">批量设置退货原因</a-button>
            <a-button type="primary" class="button-info" id="salesReturnEdit-import-btn" @click="openGuideModal=true">导入产品</a-button>
          </div>
        </div>
        <!-- 已选配件列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :row-selection="{ columnWidth: 40 }"
          @rowSelection="rowSelectionFun"
          :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.initialQty"
              :precision="0"
              :min="0"
              :max="99999999"
              placeholder="请输入"
              @blur="e => onCellBlur(e.target.value, record, 'qty')"
              style="width: 100%;" />
          </template>
          <!-- 退货原因 -->
          <template slot="returnReason" slot-scope="text, record">
            <returnReason :goodFlag="goodFlag" v-model="record.returnReasonCode" @change="e => updateReason(e, record, 0)"></returnReason>
          </template>
          <!-- 备注 -->
          <template slot="returnRemarks" slot-scope="text, record">
            <a-input size="small" placeholder="请输入备注" v-model="record.returnReasonRemarks" @blur="e => updateReason(e, record, 1)"></a-input>
          </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" :showDefUser="true" :openModal="openDepartUserModal" @close="openDepartUserModal=false" @submit="handleSubmit"></chooseDepartUserModal>
    <!-- 导入产品 -->
    <importGuideModal :goodFlag="goodFlag == 'GOOD_PRODUCT_RETURN' ? 1 : 0" :openModal="openGuideModal" :params="{salesReturnBillSn: $route.params.sn}" @close="closeGuideModel" @ok="hanldeOk" />
    <!-- 批量设置退货原因 -->
    <commonModal modalTit="批量设置退货原因" :openModal="showPlModal" @cancel="showPlModal=false" @ok="setPlReturnReason">
      <div style="text-align: left;">
        <div style="line-height: 24px;">
          <div><span style="color:red;">*</span>退货原因</div>
          <div><returnReason size="large" :goodFlag="goodFlag" v-model="plReturnReason"></returnReason></div>
        </div>
        <div style="line-height: 24px;margin-top:10px;">
          <a-checkbox :checked="showEditRemarks" @change="e => showEditRemarks=!showEditRemarks">是否设置备注</a-checkbox>
        </div>
        <div style="line-height: 24px;margin-top:10px;" v-if="showEditRemarks">
          <div>备注</div>
          <div><a-input size="large" :maxLength="50" placeholder="请输入备注(最多50字符)" v-model="plReturnRemark"></a-input></div>
        </div>
      </div>
    </commonModal>
    <!-- 修改仓库 -->
    <commonModal modalTit="修改退货仓库" :openModal="showEditModal" @cancel="showEditModal=false" @ok="editOk">
      <div>
        <span>退货单号：</span>
        {{ ordeDetail&&ordeDetail.salesReturnBillNo }}
      </div>
      <div style="margin: 10px 0;">
        <span>原退货仓库：</span>
        {{ ordeDetail&&ordeDetail.warehouseName }}
      </div>
      <div>
        <span>新退货仓库：</span>
        <warehouse
          v-model="newWarehouseSn"
          style="width: 250px"
          showDef
          id="chooseCustom-edit-warehouseSn"
          placeholder="请选择退货仓库"
        />
      </div>
    </commonModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import { printFun, exportExcel } from '@/libs/JGPrint.js'
import ImportGuideModal from './importGuideModal.vue'
import queryPart from './queryPart.vue'
import commonModal from '@/views/common/commonModal.vue'
import EditableCell from '@/views/common/editInput.js'
import chooseDepartUserModal from './chooseDepartUserModal.vue'
import warehouse from '@/views/common/chooseWarehouse.js'
import returnReason from '@/views/common/returnReason'
import {
  salesReturnDetail,
  salesReturnSubmit,
  salesReturnBatchInsert,
  salesReturnPrint,
  salesReturnExport,
  salesReturnModify,
  submitVerify,
  updateWarehouse
} from '@/api/salesReturn'
import {
  salesReturnDetailList,
  salesReturnDetailDel,
  salesReturnDetailInsert,
  salesReturnDetailUpdateQty,
  salesReturnDetailUpdateReason,
  salesReturnDetailSetReason,
  salesReturnUpdateAllReason
} from '@/api/salesReturnDetail'
export default {
  name: 'SalesReturnEdit',
  mixins: [commonMixin],
  components: {
    STable,
    VSelect,
    queryPart,
    EditableCell,
    ImportGuideModal,
    chooseDepartUserModal,
    returnReason,
    commonModal,
    warehouse
  },
  data () {
    return {
      spinning: false,
      orderId: null,
      orderSn: null,
      buyerSn: null,
      disabled: false,
      isInster: false, // 是否正在添加产品
      openDepartUserModal: false,
      showEditModal: false,
      newWarehouseSn: undefined,
      ordeDetail: { discountAmount: 0 },
      delLoading: false,
      // 已选产品
      dataSource: [],
      productForm: {
        salesReturnBillSn: '',
        productName: '',
        productCode: ''
      },
      chooseLoadData: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        // 查询总计
        this.productForm.salesReturnBillSn = this.orderSn
        return salesReturnDetailList(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
              data.list[i].qtyBackups = data.list[i].initialQty
              data.list[i].returnReasonBackups = data.list[i].returnReasonCode
              data.list[i].bakReamrks = data.list[i].returnReasonRemarks
            }
            this.disabled = false
            this.chooseLoadData = data.list
            this.total = res.data.count
          }
          return data
        })
      },
      openGuideModal: false, //  导入产品引导
      total: 0,
      rowSelectionInfo: null,
      plReturnReason: undefined,
      plReturnRemark: undefined,
      showEditRemarks: false,
      showPlModal: false,
      returnReasonlist: []
    }
  },
  watch: {
    showPlModal (newValue, oldValue) {
      if (!newValue) {
        this.plReturnReason = undefined
        this.plReturnRemark = undefined
        this.showEditRemarks = false
      }
    },
    showEditModal (a, b) {
      if (!a) {
        this.newWarehouseSn = undefined
      }
    }
  },
  computed: {
    goodFlag () {
      return this.ordeDetail && this.ordeDetail.goodFlag || ''
    },
    selNums () {
      return this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.length || 0
    },
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', align: 'center', width: '4%' },
        { title: '产品编码', dataIndex: 'productEntity.code', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productEntity.name', width: '20%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '单位', dataIndex: 'productEntity.unit', align: 'center', width: '6%', customRender: function (text) { return text || '--' } },
        { title: '申请退货数量', dataIndex: 'initialQty', align: 'center', width: '8%', scopedSlots: { customRender: 'qty' } },
        { title: '退货原因', dataIndex: 'returnReason', align: 'center', width: '13%', scopedSlots: { customRender: 'returnReason' } },
        { title: '备注', scopedSlots: { customRender: 'returnRemarks' }, width: '10%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      if (this.$hasPermissions('B_salesReturnEdit_salesPrice')) { //  售价权限
        arr.splice(4, 0, { title: '参考退货单价', dataIndex: 'price', align: 'right', width: '8%', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
        arr.splice(7, 0, { title: '参考退货金额', align: 'right', dataIndex: 'totalAmount', width: '8%', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }
      return arr
    }
  },
  methods: {
    //  返回
    handleBack () {
      this.$router.push({ name: 'salesReturnList', query: { closeLastOldTab: true } })
    },
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    // 已选产品  blur
    onCellBlur (val, record, type) {
      const valBackups = record.qtyBackups
      //  光标移出，值发生改变再调用编辑接口
      if (val && val != valBackups) {
        this.spinning = true
        salesReturnDetailUpdateQty({
          salesReturnDetailSn: record.salesReturnDetailSn,
          initialQty: record.initialQty,
          price: record.price
        }).then(res => {
          if (res.status == 200) {
            this.resetTable(false)
            this.$message.success(res.message)
            this.spinning = false
            record.qtyBackups = record.initialQty
          } else {
            this.spinning = false
            record.initialQty = valBackups
          }
        })
      } else {
        record.initialQty = valBackups
      }
    },
    // 修改单据退货仓库
    editOk () {
      if (this.newWarehouseSn) {
        updateWarehouse({ salesReturnBillSn: this.orderSn, warehouseSn: this.newWarehouseSn }).then(res => {
          if (res.status == 200) {
            this.$message.success(res.message)
            this.getOrderDetail(true)
            this.showEditModal = false
            this.newWarehouseSn = undefined
          }
        })
      } else {
        this.$message.info('请选择退货仓库')
      }
    },
    // 修改仓库
    updateWarehouse (warehouseSn) {
      const _this = this
      _this.spinning = true
      const params = { id: this.ordeDetail.id, warehouseSn: warehouseSn }
      salesReturnModify(params).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.getOrderDetail()
        }
        _this.spinning = false
      })
    },
    // 修改退货原因
    updateReason (val, record, type) {
      console.log(val, record, type)
      const params = {
        salesReturnDetailSn: record.salesReturnDetailSn,
        goodFlag: this.goodFlag
      }
      // 退货原因
      if (type == 0) {
        const rows = this.returnReasonlist.find(item => item.code == val)
        params.returnReasonCode = val || ''
        params.returnReason = rows ? rows.dispName : ''
      } else {
        // 备注
        params.returnReasonRemarks = val.target.value
        if (params.returnReasonRemarks == record.bakReamrks) {
          return
        }
      }
      this.spinning = true
      salesReturnDetailUpdateReason(params).then(res => {
        if (res.status == 200) {
          this.resetTable(false)
          this.$message.success(res.message)
        } else {
          record.returnReasonCode = record.returnReasonBackups
        }
        this.spinning = false
      })
    },
    // 批量设置退货原因
    openPlSetReason (type) {
      // 整单设置
      if (type == 1) {
        this.$refs.table.clearSelected()
        this.showPlModal = true
      } else {
        if (this.selNums) {
          this.showPlModal = true
        } else {
          this.$message.warning('请先选择产品！')
        }
      }
    },
    setPlReturnReason () {
      if (!this.plReturnReason) {
        this.$message.warning('请选择退货原因！')
      } else {
        const rows = this.returnReasonlist.find(item => item.code == this.plReturnReason)
        const params = {
          salesReturnBillSn: this.orderSn,
          returnReason: rows ? rows.dispName : '',
          returnReasonCode: this.plReturnReason,
          returnReasonRemarks: this.showEditRemarks ? this.plReturnRemark || '' : undefined
        }
        // 批量或整单设置
        const funs = this.selNums ? salesReturnDetailSetReason : salesReturnUpdateAllReason

        // 批量设置
        if (this.selNums) {
          const snList = []
          const arr = this.rowSelectionInfo && this.rowSelectionInfo.selectedRows || []
          arr.map(item => snList.push(item.salesReturnDetailSn))
          params.salesReturnBillDetailSnList = snList
        }

        this.spinning = true
        funs(params).then(res => {
          if (res.status == 200) {
            this.showPlModal = false
            this.$refs.table.clearSelected()
            this.resetTable(false)
          }
          this.spinning = false
        })
      }
    },
    // 获取单据详细
    getOrderDetail (flag) {
      salesReturnDetail({ sn: this.orderSn }).then(res => {
        this.ordeDetail = res.data || null
        if (res.data.goodFlag == 'DEFECTIVE_PRODUCT_RETURN') {
          this.returnReasonlist = this.$store.state.app.defectiveReturnReason
        }
        // 良品
        if (res.data.goodFlag == 'GOOD_PRODUCT_RETURN') {
          this.returnReasonlist = this.$store.state.app.goodReturnReason
        }
        this.$refs.table.refresh(!flag)
        if (!flag) {
          this.$refs.partQuery.pageInit(this.buyerSn, this.ordeDetail.warehouseSn, this.goodFlag)
        }
      })
    },
    // 删除产品
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.delLoading = true
          _this.spinning = true
          salesReturnDetailDel({ salesReturnDetailSn: row.salesReturnDetailSn, salesReturnBillSn: _this.orderSn }).then(res => {
            if (res.status == 200) {
              _this.resetTable(false)
            }
            _this.$message.info(res.message)
            _this.delLoading = false
            _this.spinning = false
          })
        }
      })
    },
    resetTable (flag) {
      this.$refs.table.refresh(flag)
      this.getOrderDetail(true)
    },
    //  重置
    resetSearchForm (flag) {
      this.productForm.productName = ''
      this.productForm.productCode = ''
      this.getOrderDetail(flag)
    },
    // 添加或修改产品
    saveProduct (row) {
      // 防止多次添加产品
      if (this.isInster) {
        return
      }
      // 退货原因
      const rows = this.returnReasonlist.find(item => item.code == row.returnReasonCode)
      this.isInster = true
      const params = {
        'salesReturnBillSn': this.orderSn,
        'salesReturnBillNo': this.ordeDetail.salesReturnBillNo,
        'price': row.productPrice,
        'priceLevel': row.priceLevel,
        'returnReasonCode': row.returnReasonCode,
        'returnReason': rows ? rows.dispName : '',
        'goodFlag': this.goodFlag,
        'productSn': row.productSn,
        'initialQty': row.qty
      }
      this.spinning = true
      salesReturnDetailInsert(params).then(res => {
        if (res.status == 200) {
          this.resetSearchForm(true)
          this.$message.success(res.message)
        }
        this.isInster = false
        this.spinning = false
      })
    },
    beforeSubmit () {
      if (this.total) {
        const hasKong = this.chooseLoadData.find(item => !item.returnReason)
        if (hasKong) {
          this.$message.warning('请输入退货原因！')
        } else {
          // 判断价格
          submitVerify({ salesReturnBillSn: this.orderSn }).then(res => {
            if (res.status == 200) {
              if (!res.data) {
                this.openDepartUserModal = true
                if (this.ordeDetail.billStatus == 'AUDIT_REJECT') {
                  this.$refs.chooseDepart.getDetail(this.ordeDetail)
                }
              } else {
                const arr = res.data.split('\n')
                this.$notification.open({
                  message: '提示',
                  description:
                  <div>
                    {arr.map(item =>
                      (<p>{item}</p>)
                    )}
                  </div>
                })
              }
            }
          })
        }
      } else {
        this.$message.warning('请添加产品！')
      }
    },
    // 提交销售退货
    handleSubmit (data) {
      this.spinning = true
      salesReturnSubmit({ salesReturnBillSn: this.orderSn, ...data }).then(res => {
        if (res.status == 200) {
          this.handleBack()
          this.$message.success(res.message)
        }
        this.spinning = false
      })
    },
    closeGuideModel () {
      this.openGuideModal = false
    },
    // 导入产品
    hanldeOk (obj) {
      salesReturnBatchInsert(obj).then(res => {
        if (res.status == 200) {
          this.resetTable(true)
        }
      })
    },
    // 打印预览/快捷打印
    handlePrint (type) {
      const _this = this
      const a = ['WAIT_CUSTOMER_SERVICE_CONFIRM', 'WAIT_FINANCIAL_AUDIT', 'FINANCIAL_REJECT', 'FINISH'].find(item => item == this.ordeDetail.billStatus)
      const status = a ? 'SALES_RETURN_AMOUNT' : 'SALES_RETURN_REASON'
      const params = { salesReturnBillSn: this.$route.params.sn, priceType: status }
      _this.spinning = true
      // 导出
      if (type == 'export') {
        this.$store.state.app.curActionPermission = 'B_salesReturnExport'
        exportExcel(salesReturnExport, params, '销售退货', function () {
          _this.spinning = false
          _this.$store.state.app.curActionPermission = ''
        })
      } else {
        // 打印或预览
        this.$store.state.app.curActionPermission = 'B_salesReturnPrint'
        printFun(salesReturnPrint, params, type, '销售退货', () => {
          _this.spinning = false
          _this.$store.state.app.curActionPermission = ''
        })
      }
    },
    pageInit () {
      this.orderSn = this.$route.params.sn
      this.buyerSn = this.$route.params.buyerSn
      this.resetSearchForm()
    }
  },
  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;
      .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>
