<template>
  <a-card size="small" :bordered="false" class="salesManagementList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="创建时间">
                <rangeDate ref="rangeDate" :value="time" @change="dateChange" />
              </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="salesManagementList-buyerName" @change="custChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="销售单号">
                <a-input id="salesManagementList-salesBillNo" v-model.trim="queryParam.salesBillNo" allowClear placeholder="请输入销售单号"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="采购单号">
                  <a-input id="salesManagementList-purchaseBillNo" v-model.trim="queryParam.purchaseBillNo" allowClear placeholder="请输入采购单号"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="打印状态">
                  <v-select
                    v-model="queryParam.printStatus"
                    ref="printStatus"
                    id="salesManagementList-printStatus"
                    code="PRINT_STATUS"
                    placeholder="请选择打印状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="业务状态">
                  <v-select
                    v-model="queryParam.billStatus"
                    ref="billStatus"
                    id="salesManagementList-billStatus"
                    code="SALES_BILL_STATUS"
                    placeholder="请选择业务状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="财务状态">
                  <v-select
                    v-model="queryParam.financialStatus"
                    ref="financialStatus"
                    id="salesManagementList-financialStatus"
                    code="FINANCIAL_RECEIVE_STATUS"
                    placeholder="请选择财务状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="单据来源">
                  <v-select
                    v-model="queryParam.salesBillSource"
                    ref="salesBillSource"
                    id="salesManagementList-salesBillSource"
                    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="salesManagementList-subarea" v-model="queryParam.subareaSn"></subarea>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="地区">
                  <a-form-model-item prop="shippingAddrProvinceSn">
                    <a-select id="salesManagementList-shippingAddrProvinceSn" allowClear v-model="queryParam.shippingAddrProvinceSn" placeholder="请选择省">
                      <a-select-option v-for="item in addrProvinceList" :value="item.areaSn" :key="item.areaSn + 'a'">{{ item.name }}</a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-form-model-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>
      <!-- 操作按钮 -->
      <div class="table-operator">
        <a-button type="primary" class="button-error" v-if="$hasPermissions('B_salesAdd')" @click="handleAdd">新增</a-button>
      </div>
      <!-- alert -->
      <a-alert type="info" style="margin-bottom:10px">
        <div slot="message">
          <div>
            总单数：<strong>{{ totalData&&(totalData.totalRecord || totalData.totalRecord==0) ? totalData.totalRecord : '--' }}</strong>；
            总款数：<strong>{{ totalData&&(totalData.totalCategory || totalData.totalCategory==0) ? totalData.totalCategory : '--' }}</strong>；
            总数量：<strong>{{ totalData&&(totalData.totalQty || totalData.totalQty==0) ? totalData.totalQty : '--' }}</strong>；
            已下推数量：<strong>{{ totalData&&(totalData.totalPushedQty || totalData.totalPushedQty==0) ? totalData.totalPushedQty : '--' }}</strong>；
            已发货数量：<strong>{{ totalData&&(totalData.totalDispatchQty || totalData.totalDispatchQty==0) ? totalData.totalDispatchQty : '--' }}</strong>；
            已取消数量：<strong>{{ totalData&&(totalData.totalCancelQty || totalData.totalCancelQty==0) ? totalData.totalCancelQty : '--' }}</strong>；
            待下推数量：<strong>{{ totalData&&(totalData.totalUnpushedQty || totalData.totalUnpushedQty==0) ? totalData.totalUnpushedQty : '--' }}</strong>；
          </div>
          <div>
            总售价：<strong>{{ totalData&&(totalData.totalAmount || totalData.totalAmount==0) ? totalData.totalAmount : '--' }}</strong>元；
            已下推金额:：<strong>{{ totalData&&(totalData.totalPushedAmount || totalData.totalPushedAmount==0) ? totalData.totalPushedAmount : '--' }}</strong>元；
            已取消金额:：<strong>{{ totalData&&(totalData.totalCancelAmount || totalData.totalCancelAmount==0) ? totalData.totalCancelAmount : '--' }}</strong>元；
            待下推金额:：<strong>{{ totalData&&(totalData.totalUnpushedAmount || totalData.totalUnpushedAmount==0) ? totalData.totalUnpushedAmount : '--' }}</strong>元；
            已发货金额:：<strong>{{ totalData&&(totalData.totalDispatchAmount || totalData.totalDispatchAmount==0) ? totalData.totalDispatchAmount : '--' }}</strong>元；
          </div>
        </div>
      </a-alert>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+102.5+'px' }"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ x: 1620, y: tableHeight }"
        :defaultLoadData="false"
        bordered>
        <!-- 销售单号 -->
        <template slot="salesBillNo" slot-scope="text, record">
          <div v-if="$hasPermissions('B_salesDetail')">
            <a-badge :count="'改'+record.changeTimes" :offset="[16,-13]" v-if="record.changeTimes>0" class="badge-con-t">
              <span style="color: #00aaff;cursor: pointer;" @click="handleDetail(record)">{{ record.salesBillNo }}</span>
            </a-badge>
            <span v-else style="color: #00aaff;cursor: pointer;" @click="handleDetail(record)">{{ record.salesBillNo }}</span>
          </div>
          <div v-else>{{ record.salesBillNo }}</div>
        </template>
        <!-- 总数量 -->
        <template slot="totalQty" slot-scope="text, record">
          {{ record.totalQty }}
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            class="button-warning"
            v-if="record.billStatus == 'WAIT_AUDIT'&&$hasPermissions('B_salesAudit')"
            @click="handleEexamine(record)"
          >审核</a-button>
          <a-button
            size="small"
            type="link"
            class="button-warning"
            v-if="record.billStatus == 'OUTING_WAREHOUSE'&&record.totalUnpushedQty>0&&$hasPermissions('B_salesDispatch')"
            @click="handleDispatch(record)"
          >下推</a-button>
          <a-button
            size="small"
            type="link"
            class="button-info"
            v-if="record.salesBillSource != 'PURCHASE' && (record.billStatus == 'WAIT_SUBMIT' || record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'AUDIT_REJECT')&&$hasPermissions('B_salesEdit')"
            @click="handleEdit(record)"
          >
            编辑
          </a-button>
          <a-button
            size="small"
            type="link"
            class="button-info"
            v-if="record.salesBillSource == 'PURCHASE' && (record.billStatus == 'WAIT_AUDIT'||record.billStatus == 'HQ_CHANGE')&&$hasPermissions('B_salesEdit')"
            @click="handleEdit(record)"
          >
            改单
          </a-button>
          <a-button
            size="small"
            type="link"
            class="button-error"
            v-if="record.salesBillSource != 'PURCHASE' && (record.billStatus == 'WAIT_SUBMIT' || record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'AUDIT_REJECT')&&$hasPermissions('B_salesDel')"
            @click="handleDel(record)"
          >
            删除
          </a-button>
          <a-button
            size="small"
            type="link"
            class="button-error"
            v-if="record.salesBillSource == 'PURCHASE' && (record.billStatus == 'WAIT_AUDIT'||record.billStatus == 'HQ_CHANGE')&&$hasPermissions('B_salesDel')"
            @click="handleDel(record)"
          >
            取消
          </a-button>
          <span v-if="!(record.billStatus == 'WAIT_AUDIT'&&$hasPermissions('B_salesAudit')) && !(record.billStatus == 'OUTING_WAREHOUSE'&&record.totalUnpushedQty>0&&$hasPermissions('B_salesDispatch')) && !(record.salesBillSource != 'PURCHASE' && (record.billStatus == 'WAIT_SUBMIT' || record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'AUDIT_REJECT')&&$hasPermissions('B_salesEdit')) && !(record.salesBillSource == 'PURCHASE' && (record.billStatus == 'WAIT_AUDIT'||record.billStatus == 'HQ_CHANGE')&&$hasPermissions('B_salesEdit')) && !(record.salesBillSource != 'PURCHASE' && (record.billStatus == 'WAIT_SUBMIT' || record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'AUDIT_REJECT')&&$hasPermissions('B_salesDel')) && !(record.salesBillSource == 'PURCHASE' && (record.billStatus == 'WAIT_AUDIT'||record.billStatus == 'HQ_CHANGE')&&$hasPermissions('B_salesDel'))">--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 选择客户弹框 -->
    <choose-custom-modal :show="openModal" @ok="chooseCustomOk" @cancel="openModal=false"></choose-custom-modal>
    <!-- 审核 -->
    <auditModal :openModal="visibleAudit" :spinning="spinningAudit" @close="visibleAudit=false" @ok="auditOrder('OUTING_WAREHOUSE')" @fail="auditOrder('AUDIT_REJECT')" />
  </a-card>
</template>

<script>
import moment from 'moment'
import getDate from '@/libs/getDate.js'
import subarea from '@/views/common/subarea.js'
import { getArea } from '@/api/data'
import rangeDate from '@/views/common/rangeDate.vue'
import { STable, VSelect } from '@/components'
import auditModal from '@/views/common/auditModal.vue'
import chooseCustomModal from './chooseCustomModal.vue'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import { salesList, salesDel, salesWriteAudit, salesCount } from '@/api/sales'
import { findBySalesBillSn } from '@/api/dispatch'
export default {
  name: 'TableList',
  components: { STable, VSelect, chooseCustomModal, dealerSubareaScopeList, rangeDate, auditModal, subarea },
  data () {
    return {
      spinning: false,
      advanced: false, // 高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      openModal: false, // 选择客户弹框是否显示
      tableHeight: 0,
      time: [
        moment(getDate.getThreeMonthDays().starttime, 'YYYY-MM-DD'),
        moment(getDate.getCurrMonthDays().endtime, 'YYYY-MM-DD')
      ],
      // 查询参数
      queryParam: {
        beginDate: getDate.getThreeMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        buyerSn: undefined, //  客户名称
        salesBillNo: '', //  销售单号
        purchaseBillNo: '',
        printStatus: undefined,
        billStatus: undefined, //  业务状态
        financialStatus: undefined, //  财务状态
        salesBillSource: undefined,
        subareaSn: undefined,
        shippingAddrProvinceSn: undefined
      },
      totalData: {
        totalAmount: 0,
        totalCategory: 0,
        totalQty: 0,
        totalRecord: 0,
        totalPushedQty: 0,
        totalDispatchQty: 0,
        totalCancelQty: 0,
        totalUnpushedQty: 0,
        totalPushedAmount: 0,
        totalCancelAmount: 0,
        totalUnpushedAmount: 0,
        totalDispatchAmount: 0
      },
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 60, align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售单号', scopedSlots: { customRender: 'salesBillNo' }, width: 120, align: 'center' },
        { title: '采购单号', dataIndex: 'purchaseBillNo', width: 120, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'buyerName', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '总数量', dataIndex: 'totalQty', scopedSlots: { customRender: 'totalQty' }, width: 60, align: 'center' },
        { title: '总售价', dataIndex: 'totalAmount', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? ('￥' + text) : '--') } },
        { title: '已下推数量', dataIndex: 'totalPushedQty', width: 60, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '已发货数量', dataIndex: 'totalDispatchQty', width: 60, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '已取消数量', dataIndex: 'totalCancelQty', width: 60, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '待下推数量', dataIndex: 'totalUnpushedQty', width: 60, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '收款方式', dataIndex: 'settleStyleSnDictValue', width: 80, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核时间', dataIndex: 'auditDate', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '最近备货时间', dataIndex: 'lastStockUpDate', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务状态', dataIndex: 'billStatusDictValue', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '财务状态', dataIndex: 'financialStatusDictValue', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '打印次数', dataIndex: 'detailPrintTimes', width: 50, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 150, align: 'center', fixed: 'right' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        delete parameter.tableId
        delete parameter.index
        // 查询总计
        salesCount(Object.assign(parameter, this.queryParam)).then(res => {
          this.totalData = Object.assign(this.totalData, res.data || {})
        })
        return salesList(Object.assign(parameter, this.queryParam)).then(res => {
          const 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
          return data
        })
      },
      addrProvinceList: [], //  省下拉
      visibleAudit: false,
      auditInfo: null,
      spinningAudit: false
    }
  },
  methods: {
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    custChange (val) {
      this.queryParam.buyerSn = val.key
    },
    // 新增
    handleAdd () {
      this.openModal = true
    },
    // 选择客户成功
    chooseCustomOk (data) {
      this.$router.push({ name: 'salesAdd', params: { sn: data.salesBillSn } })
    },
    // 下推
    handleDispatch (row) {
      this.spinning = true
      findBySalesBillSn({ salesBillSn: row.salesBillSn }).then(res => {
        this.spinning = false
        if (res.status == 200) {
          this.$router.push({ name: 'waitDispatch', params: { salesBillSn: row.salesBillSn, dispatchBillSn: res.data.dispatchBillSn } })
        }
      })
    },
    //  审核
    handleEexamine (row) {
      this.auditInfo = row
      this.visibleAudit = true
    },
    auditOrder (billStatus) {
      this.spinningAudit = true
      salesWriteAudit({
        salesBillSn: this.auditInfo.salesBillSn,
        billStatus: billStatus
      }).then(res => {
        if (res.status == 200) {
          this.visibleAudit = false
          this.$message.success(res.message)
          this.$refs.table.refresh()
          this.spinningAudit = false
          if (billStatus == 'OUTING_WAREHOUSE') {
            this.handleDispatch({ salesBillSn: this.auditInfo.salesBillSn })
          }
        } else {
          this.visibleAudit = false
          this.spinningAudit = false
        }
      })
    },
    // 详情
    handleDetail (row) {
      this.$router.push({ name: 'salesDetail', params: { sn: row.salesBillSn } })
    },
    // 编辑
    handleEdit (row) {
      this.$router.push({ name: 'salesEdit', params: { sn: row.salesBillSn } })
    },
    // 删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: row.salesBillSource == 'PURCHASE' ? '确认要取消吗？' : '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          salesDel({ salesBillSn: row.salesBillSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.beginDate = getDate.getThreeMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.$refs.dealerSubareaScopeList.resetForm()
      this.queryParam.buyerSn = undefined
      this.queryParam.salesBillNo = ''
      this.queryParam.purchaseBillNo = ''
      this.queryParam.printStatus = undefined
      this.queryParam.billStatus = undefined
      this.queryParam.financialStatus = undefined
      this.queryParam.salesBillSource = undefined
      this.queryParam.subareaSn = undefined
      this.queryParam.shippingAddrProvinceSn = undefined
      this.$refs.table.refresh(true)
    },
    //  省/市/区
    getArea (leve, sn) {
      let params
      if (leve == 'province') {
        params = { type: '2' }
      } else {
        params = { parentId: sn, type: leve == 'city' ? '3' : '4' }
      }
      getArea(params).then(res => {
        if (res.status == 200) {
          if (leve == 'province') {
            this.addrProvinceList = res.data || []
          } else if (leve == 'city') {
            this.addrCityList = res.data || []
          } else if (leve == 'district') {
            this.addrDistrictList = res.data || []
          }
        } else {
          if (leve == 'province') {
            this.addrProvinceList = []
          } else if (leve == 'city') {
            this.addrCityList = []
          } else if (leve == 'district') {
            this.addrDistrictList = []
          }
        }
      })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.getArea('province')
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 310
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      setTimeout(() => {
        _this.setTableH()
      }, 400)
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
<style lang="less">
  .salesManagementList-wrap{
    .sTable{
      margin-top: 10px;
      .badge-con-t{
        .ant-badge-count{
          transform: scale(0.8);
          font-size: 13px;
        }
      }
    }
  }
</style>
