<template>
  <div>
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <!-- 搜索条件 -->
      <div ref="tableSearch" 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="创建时间">
                <rangeDate ref="rangeCreateDate" :value="createDate" @change="dateCreateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="客户名称" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
                <dealerSubareaScopeList ref="dealerSubareaScopeList" id="salesReturn-buyerSn" @change="custChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="总部销退单号">
                <a-input id="salesReturn-salesReturnBillNo" v-model.trim="queryParam.salesReturnBillNo" allowClear placeholder="请输入总部销退单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="退货类别" prop="goodFlag">
                <v-select
                  v-model="queryParam.goodFlag"
                  ref="goodFlag"
                  id="returnSchedule-goodFlag"
                  code="GOOD_FLAG"
                  placeholder="请选择退货类别"
                  allowClear></v-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="审核时间">
                <rangeDate ref="rangeExamineDate" @change="dateExamineChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="业务状态">
                <v-select
                  v-model="queryParam.billStatus"
                  ref="billStatus"
                  id="salesReturn-billStatus"
                  code="SALES_RETURN_BILL_STATUS"
                  placeholder="请选择业务状态"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="客户采退申请单号">
                <a-input id="salesReturn-purchaseReturnApplyNo" v-model.trim="queryParam.purchaseReturnApplyNo" allowClear placeholder="请输入客户采退申请单号"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="退货类型">
                  <v-select
                    v-model="queryParam.salesReturnType"
                    id="departUser-salesReturnType"
                    code="SALES_RETURN_TYPE"
                    placeholder="请选择退货类型"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="退货仓库">
                  <warehouse ref="warehouse" v-model="queryParam.warehouseSn"></warehouse>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="单据来源">
                  <v-select
                    v-model="queryParam.salesReturnBillSource"
                    ref="salesReturnBillSource"
                    id="salesReturn-salesReturnBillSource"
                    code="SALES_SOURCE"
                    placeholder="请选择单据来源"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="所在区域">
                  <subarea id="salesReturn-subarea" ref="subarea" @change="subareaChange"></subarea>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="地区" prop="shippingAddrProvinceSn">
                  <Area id="salesReturn-provinceSn" v-model="queryParam.shippingAddrProvinceSn" placeholder="请选择省"></Area>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="是否同步给客户">
                  <v-select
                    v-model="queryParam.syncFlag"
                    ref="syncFlag"
                    id="salesReturn-syncFlag"
                    code="FLAG"
                    placeholder="请选择是否同步给客户"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowCustomerSearch">
                <a-form-item label="客服">
                  <customerService ref="customerName" v-model="queryParam.bizUserSn"></customerService>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" :disabled="disabled" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" :disabled="disabled" @click="resetSearchForm()">重置</a-button>
                <a @click="advanced=!advanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>

    <a-card size="small" :bordered="false" class="salesReturn-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <div class="table-operator" style="flex-grow: 1;display: flex;justify-content: space-between;align-items: center;">
          <div style="flex-grow: 1;display: flex;align-items: center;">
            <!-- 操作按钮 -->
            <div>
              <a-button type="primary" v-if="$hasPermissions('B_salesReturnNew')" @click="openModal = true">新增</a-button>
            </div>
            <div class="tongji-bar">
              总单数：{{ countData&&countData.totalRecord||0 }}；
              申请退货数量：{{ countData&&countData.totalInitialQty||0 }}；
              仓库实收数量：{{ countData&&countData.totalReceiveQty||0 }}；
              坏件数量：{{ countData&&countData.totalBadQty||0 }}；
              良品数量：{{ countData&&countData.totalGoodQty||0 }}；
              返库数量：{{ countData&&countData.totalBackStockQty||0 }}；
              <span v-if="$hasPermissions('M_salesReturnList_salesPrice')">
                实际退货金额：{{ countData&&countData.totalAmount?toThousands(countData.totalAmount):0 }}；
              </span>
            </div>
          </div>
          <div></div>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+85+'px' }"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 单号 -->
          <template slot="salesReturnBillNo" slot-scope="text, record">
            <div v-if="$hasPermissions('B_salesReturnDetail')">
              <a-badge :count="'改'" :offset="[16,-13]" v-if="record.changeFlag==1" class="badge-con-t">
                <span class="link-bule" @click="handleDetail(record)">{{ record.salesReturnBillNo }}</span>
              </a-badge>
              <span v-else class="link-bule" @click="handleDetail(record)">{{ record.salesReturnBillNo }}</span>
            </div>
            <div v-else>{{ record.salesReturnBillNo }}</div>
          </template>
          <!-- 提货单 -->
          <template slot="pickUpSalesReturnNum" slot-scope="text, record">
            <span class="link-bule" @click="handleBillOfLadingDetail(record)">{{ record.pickUpSalesReturnNum }}</span>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <div>
              <a-button
                size="small"
                type="link"
                class="button-warning"
                v-if="record.billStatus == 'WAIT_AUDIT'&&$hasPermissions('B_salesReturnAudit')"
                @click="handleEexamine(record)"
                id="salesReturn-eexamine-btn">审核进度</a-button>
              <a-button
                size="small"
                type="link"
                class="button-warning"
                v-if="record.salesReturnBillSource != 'SALES'&&record.billStatus == 'WAIT_SUBMIT'&&$hasPermissions('B_salseReturnSubmit')"
                @click="beforeSubmit(record)"
                id="salesReturn-eexamine-btn">提交</a-button>
              <a-button
                size="small"
                v-if="record.billStatus == 'WAIT_SUBMIT' && $hasPermissions('B_salesReturnEdit')"
                type="link"
                class="button-info"
                @click="handleEdit(record)"
                id="salesReturn-edit-btn">{{ record.salesReturnBillSource == 'SALES' ? '编辑' : '改单' }}</a-button>
              <a-button
                size="small"
                v-if="(record.billStatus == 'WAIT_SUBMIT'|| record.billStatus == 'AUDIT_REJECT') && $hasPermissions('B_salesReturnDel')"
                type="link"
                class="button-error"
                @click="handleDel(record)"
                id="salesReturn-del-btn">{{ record.salesReturnBillSource == 'SALES' ? '删除' : '取消' }}</a-button>
              <a-button
                size="small"
                type="link"
                class="button-info"
                v-if="record.billStatus == 'AUDIT_REJECT'&& $hasPermissions('B_salesReturnAgainSubmit')"
                @click="handleEdit(record)"
                id="salesReturn-edit-btn">再次提交</a-button>
              <a-button
                size="small"
                type="link"
                class="button-info"
                v-if="record.billStatus == 'WAIT_RECEIVE'&& $hasPermissions('B_newPickUp')"
                @click="handlePickUp(record)"
                id="salesReturn-edit-btn">申请提货</a-button>
              <a-button
                size="small"
                type="link"
                class="button-error"
                v-if="record.billStatus == 'WAIT_RECEIVE'&&record.salesReturnBillSource=='PURCHASE'&&record.cancelFlag==1"
                @click="handleCansel(record)"
                id="salesReturn-cansel-btn">取消</a-button>
              <a-button
                size="small"
                type="link"
                class="button-info"
                v-if="(record.billStatus == 'FINANCIAL_REJECT'||record.billStatus == 'WAIT_CUSTOMER_SERVICE_CONFIRM')&& $hasPermissions('B_salesReturnConfirm')"
                @click="handleConfirm(record)"
                id="salesReturn-edit-btn">客服确认</a-button>
            </div>
          </template>
        </s-table>
      </a-spin>
      <!-- 选择客户弹框 -->
      <choose-custom-modal :show="openModal" @ok="handleEdit" @cancel="openModal=false"></choose-custom-modal>
      <!-- 审核进度 -->
      <verifyModal v-drag :openModal="visibleAudit" :itemSn="auditInfo&&auditInfo.salesReturnBillSn" @close="visibleAudit=false"></verifyModal>
      <!-- 选择审核人员 -->
      <chooseDepartUserModal v-drag :openModal="openDepartUserModal" @close="openDepartUserModal=false" @submit="handleSubmit"></chooseDepartUserModal>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import subarea from '@/views/common/subarea.js'
import Area from '@/views/common/area.js'
import chooseCustomModal from './chooseCustomModal.vue'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import verifyModal from './verifyModal.vue'
import chooseDepartUserModal from './chooseDepartUserModal.vue'
import rangeDate from '@/views/common/rangeDate.vue'
import warehouse from '@/views/common/chooseWarehouse.js'
import customerService from '@/views/common/customerService'
import { salesReturnList, salesReturnQueryCount, salesReturnDel, salesReturnCancelBill, salesReturnSubmit, submitVerify } from '@/api/salesReturn'
import moment from 'moment'
import getDate from '@/libs/getDate.js'
export default {
  name: 'SalesReturnList',
  mixins: [commonMixin],
  components: {
    STable,
    VSelect,
    chooseCustomModal,
    dealerSubareaScopeList,
    rangeDate,
    verifyModal,
    chooseDepartUserModal,
    Area,
    subarea,
    warehouse,
    customerService
  },
  data () {
    return {
      spinning: false,
      // 高级搜索 展开/关闭
      advanced: true,
      tableHeight: 0,
      disabled: false, //  查询、重置按钮是否可操作
      createDate: [
        moment(getDate.getThreeMonthDays().starttime, 'YYYY-MM-DD'),
        moment(getDate.getCurrMonthDays().endtime, 'YYYY-MM-DD')
      ], //  创建时间
      openModal: false, // 选择客户弹框是否显示
      openDepartUserModal: false,
      // 查询参数
      queryParam: {
        beginDate: getDate.getThreeMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        beginAuditDate: '',
        endAuditDate: '',
        buyerSn: undefined, //  客户名称
        salesReturnBillNo: undefined, //  总部销退单号
        purchaseReturnApplyNo: '',
        syncFlag: undefined, // 是否同步给客户
        billStatus: undefined, // 业务状态
        goodFlag: undefined,
        salesReturnType: undefined,
        warehouseSn: undefined, // 仓库
        subareaArea: {
          subareaSn: undefined,
          subareaAreaSn: undefined
        },
        shippingAddrProvinceSn: undefined,
        salesReturnBillSource: undefined,
        bizUserSn: undefined
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        return salesReturnList(params).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.disabled = false
          }
          this.spinning = false
          // 统计
          this.getCount(params)
          return data
        })
      },
      visibleAudit: false,
      auditInfo: null,
      spinningAudit: false,
      countData: null
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '编号', dataIndex: 'no', width: '4%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '创建时间', dataIndex: 'createDate', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单据来源', dataIndex: 'salesReturnBillSourceDictValue', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '退货仓库', dataIndex: 'warehouseName', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '同步给客户', dataIndex: 'syncFlag', width: '4%', align: 'center', customRender: function (text) { return text ? ['否', '是'][text] : '--' } },
        { title: '客户采退申请单号', dataIndex: 'purchaseReturnApplyNo', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '总部销退单号', scopedSlots: { customRender: 'salesReturnBillNo' }, width: '10%', align: 'center' },
        { title: '客户名称', dataIndex: 'buyerName', width: '10%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '退货类别', dataIndex: 'goodFlagDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '退货类型', dataIndex: 'salesReturnTypeDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: <div>申请退货<div>数量</div></div>, dataIndex: 'totalInitialQty', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: <div>仓库实收<div>数量</div></div>, dataIndex: 'totalReceiveQty', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '坏件数量', dataIndex: 'totalBadQty', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '良品数量', dataIndex: 'totalGoodQty', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '返库数量', dataIndex: 'totalBackStockQty', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '提货单', dataIndex: 'pickUpSalesReturnNum', scopedSlots: { customRender: 'pickUpSalesReturnNum' }, width: '4%', align: 'center' },
        { title: '业务状态', dataIndex: 'billStatusDictValue', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '6%', align: 'center' }
      ]
      if (this.$hasPermissions('M_salesReturnList_salesPrice')) {
        arr.splice(13, 0, { title: '实际退货金额', dataIndex: 'totalAmount', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }
      return arr
    }
  },
  methods: {
    getCount (params) {
      salesReturnQueryCount(params).then(res => {
        this.countData = res.data
      })
    },
    //  创建时间  change
    dateCreateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    //  审核时间  change
    dateExamineChange (date) {
      this.queryParam.beginAuditDate = date[0]
      this.queryParam.endAuditDate = date[1]
    },
    custChange (val) {
      this.queryParam.buyerSn = val.key
    },
    // 客服确认
    handleConfirm (row) {
      this.$router.push({ name: 'custConfirm', params: { sn: row.salesReturnBillSn, buyerSn: row.buyerSn } })
    },
    // 申请提货
    handlePickUp (row) {
      this.$store.state.app.tempBillOfData = row
      this.$router.push({ name: 'billOfLadingAdd', query: { path: 'salerReturn' } })
    },
    // 编辑
    handleEdit (row) {
      this.$router.push({ name: 'salesReturnEdit', params: { sn: row.salesReturnBillSn, buyerSn: row.buyerSn } })
    },
    // 详情
    handleDetail (row) {
      this.$router.push({ name: 'salesReturnDetail', params: { sn: row.salesReturnBillSn } })
    },
    // 提货单查看
    handleBillOfLadingDetail (row) {
      if (row.pickUpSalesReturnNum == '0单') {
        this.$message.info('此销售退货单没有提货单')
      } else {
        this.$router.push({ name: 'billOfLadingList', query: { billNo: row.salesReturnBillNo } })
      }
    },
    // 取消
    handleCansel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要取消吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          salesReturnCancelBill({ salesReturnBillSn: row.salesReturnBillSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: row.salesReturnBillSource == 'SALES' ? '确认要删除吗？' : '确认要取消吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          salesReturnDel({ salesReturnBillSn: row.salesReturnBillSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  审核进度
    handleEexamine (row) {
      this.auditInfo = row
      this.visibleAudit = true
    },
    beforeSubmit (row) {
      this.auditInfo = row
      // 判断价格
      submitVerify({ salesReturnBillSn: row.salesReturnBillSn }).then(res => {
        if (res.status == 200) {
          if (!res.data) {
            this.openDepartUserModal = true
          } else {
            const arr = res.data.split('\n')
            this.$notification.open({
              message: '提示',
              description:
              <div>
                {arr.map(item =>
                  (<p>{item}</p>)
                )}
              </div>
            })
          }
        }
      })
    },
    // 提交
    handleSubmit (data) {
      this.spinning = true
      salesReturnSubmit({ salesReturnBillSn: this.auditInfo.salesReturnBillSn, ...data }).then(res => {
        if (res.status == 200) {
          this.$refs.table.refresh()
          this.$message.success(res.message)
        }
        this.spinning = false
      })
    },
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    resetSearchForm () {
      this.$refs.rangeCreateDate.resetDate(this.createDate)
      this.queryParam.beginDate = getDate.getThreeMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime

      this.$refs.rangeExamineDate.resetDate()
      this.queryParam.beginAuditDate = ''
      this.queryParam.endAuditDate = ''

      this.queryParam.buyerSn = undefined
      this.$refs.dealerSubareaScopeList.resetForm()
      this.queryParam.salesReturnBillNo = ''
      this.queryParam.purchaseReturnApplyNo = ''
      this.queryParam.billStatus = undefined
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.syncFlag = undefined
      this.queryParam.salesReturnBillSource = undefined
      this.queryParam.shippingAddrProvinceSn = undefined
      this.queryParam.warehouseSn = undefined
      this.queryParam.goodFlag = undefined
      this.queryParam.salesReturnType = undefined
      this.queryParam.bizUserSn = undefined
      if (this.advanced) {
        this.$refs.subarea.clearData()
      }
      this.$refs.table.refresh(true)
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 255
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
<style lang="less">
  .salesReturn-wrap{
    .sTable{
      .badge-con-t{
        .ant-badge-count{
          transform: scale(0.8);
          font-size: 13px;
        }
      }
    }
  }
</style>
