<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" @keyup.enter.native="$refs.table.refresh(true)">
          <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}">
                <custList ref="custList" @change="custChange" v-model="queryParam.buyerSn"></custList>
              </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="收款方式">
                  <a-select placeholder="请选择收款方式" allowClear v-model="queryParam.settleStyleSn">
                    <a-select-option v-for="item in settleStyleList" :key="item.settleStyleSn" :value="item.settleStyleSn">
                      {{ item.name }}
                    </a-select-option>
                  </a-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>
            </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: 5px" :disabled="disabled" @click="resetSearchForm()">重置</a-button>
                <a-button
                  type="primary"
                  v-if="$hasPermissions('B_salesExport')"
                  class="button-warning"
                  @click="handleExport"
                  :disabled="disabled"
                  :loading="exportLoading"
                  id="salesManagementList-export">导出</a-button>
                <a @click="advanced=!advanced" style="margin-left: 5px">
                  {{ 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_salesNews')" @click="handleAdd">新增(零售)</a-button>
      </div>
      <!-- alert -->
      <a-alert type="info" style="margin-bottom:10px">
        <div slot="message">
          总售价：<strong>{{ totalData&&(totalData.totalAmount || totalData.totalAmount==0) ? totalData.totalAmount : '--' }}</strong>元；
          总单数：<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>；
        </div>
      </a-alert>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+77+'px' }"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ y:tableHeight }"
        :defaultLoadData="false"
        bordered>
        <!-- 销售单号 -->
        <template slot="salesBillNo" slot-scope="text, record">
          <span style="color: #ed1c24;cursor: pointer;" v-if="$hasPermissions('B_salesDetail')" @click="handleDetail(record)">{{ record.salesBillNo }}</span>
          <span v-else>{{ record.salesBillNo }}</span>
        </template>
        <!-- 急件 -->
        <template slot="oosFlag" slot-scope="text, record">
          <a-tag v-if="record.oosFlag==1" color="red" style="margin-right: 0;" >{{ record.oosFlagDictValue }}</a-tag>
          <span v-else>{{ record.oosFlagDictValue }}</span>
        </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"
            v-if="record.billStatus == 'WAIT_OUT_WAREHOUSE' && $hasPermissions('B_salesStockOut')"
            class="button-primary"
            @click="handleSend(record)"
          >出库</a-button>
          <a-button
            size="small"
            type="link"
            class="button-info"
            v-if="((record.salesBillSource == 'SATELLITE' || record.salesBillSource == 'SALES') && (record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'WAIT_SUBMIT' || record.billStatus == 'AUDIT_REJECT')) && $hasPermissions('B_salesEdit')"
            @click="handleEdit(record)"
          >
            编辑
          </a-button>
          <a-button
            size="small"
            type="link"
            class="button-error"
            v-if="((record.salesBillSource == 'SATELLITE' || record.salesBillSource == 'SALES') && record.billStatus != 'FINISH') && $hasPermissions('B_salesDel')"
            @click="handleDel(record)"
          >
            删除
          </a-button>
          <a-button
            size="small"
            type="link"
            class="button-info"
            v-if="(record.salesBillSource == 'PURCHASE' && (record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'SUPERIOR_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_AUDIT' || record.billStatus == 'SUPERIOR_CHANGE')) && $hasPermissions('B_salesDel')"
            @click="handleDel(record, 'cancel')"
          >
            取消
          </a-button>
          <span v-if="!(record.billStatus == 'WAIT_AUDIT' && $hasPermissions('B_salesAudit')) && !(record.billStatus == 'WAIT_OUT_WAREHOUSE' && $hasPermissions('B_salesStockOut')) && !(((record.salesBillSource == 'SATELLITE' || record.salesBillSource == 'SALES') && (record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'WAIT_SUBMIT' || record.billStatus == 'AUDIT_REJECT')) && $hasPermissions('B_salesEdit')) && !(((record.salesBillSource == 'SATELLITE' || record.salesBillSource == 'SALES') && record.billStatus != 'FINISH') && $hasPermissions('B_salesDel')) && !((record.salesBillSource == 'PURCHASE' && (record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'SUPERIOR_CHANGE')) && $hasPermissions('B_salesEdit')) && !((record.salesBillSource == 'PURCHASE' && (record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'SUPERIOR_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('WAIT_OUT_WAREHOUSE')" @fail="auditOrder('AUDIT_REJECT')" />
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import getDate from '@/libs/getDate.js'
import { STable, VSelect } from '@/components'
import chooseCustomModal from './chooseCustomModal.vue'
import auditModal from '@/views/common/auditModal.vue'
import { salesList, salesDel, salesWriteAudit, salesWriteStockOut, salesCount, salesExport } from '@/api/sales'
import { settleStyleQueryAll } from '@/api/settleStyle'
import rangeDate from '@/views/common/rangeDate.vue'
import custList from '@/views/common/custList.vue'
import { downloadExcel } from '@/libs/JGPrint.js'
export default {
  name: 'SalesList',
  components: { STable, VSelect, chooseCustomModal, rangeDate, auditModal, custList },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      tableHeight: 0,
      advanced: true, // 高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出loading
      openModal: false, // 选择客户弹框是否显示
      settleStyleList: [], // 收款方式
      time: [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ],
      // 查询参数
      queryParam: {
        beginDate: getDate.getCurrMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        buyerSn: undefined, //  客户名称
        salesBillNo: '', //  销售单号
        purchaseBillNo: '', //  采购单号
        payType: undefined, //  支付方式
        settleStyleSn: undefined, //  收款方式
        billStatus: undefined, //  业务状态
        financialStatus: undefined //  财务状态
      },
      totalData: {
        totalAmount: 0,
        totalCategory: 0,
        totalQty: 0,
        totalRecord: 0
      },
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', align: 'center', width: '4%' },
        { title: '来源', dataIndex: 'salesBillSourceDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售单号', scopedSlots: { customRender: 'salesBillNo' }, width: '9%', align: 'center' },
        { title: '客户名称', dataIndex: 'buyerName', align: 'center', width: '15%', customRender: function (text) { return text || '--' } },
        { title: '总款数', dataIndex: 'totalCategory', align: 'center', width: '5%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总数量', dataIndex: 'totalQty', align: 'center', width: '5%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总售价', dataIndex: 'totalAmount', align: 'center', width: '5%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '收款方式', dataIndex: 'settleStyleEntity.name', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '创建时间', dataIndex: 'createDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核时间', dataIndex: 'auditDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '急件', dataIndex: 'oosFlag', scopedSlots: { customRender: 'oosFlag' }, width: '5%', align: 'center' },
        { title: '业务状态', dataIndex: 'billStatusDictValue', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '财务状态', dataIndex: 'financialStatusDictValue', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '12%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        // 查询总计
        salesCount(Object.assign(parameter, this.queryParam)).then(res => {
          console.log(res, 'res')
          this.totalData = Object.assign(this.totalData, res.data || {})
        })
        return salesList(Object.assign(parameter, this.queryParam)).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
          }
          console.log(res, 'res')
          this.spinning = false
          return data
        })
      },
      visibleAudit: false,
      auditInfo: null,
      spinningAudit: false
    }
  },
  methods: {
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 新增
    handleAdd () {
      this.openModal = true
    },
    // 选择客户成功
    chooseCustomOk (data) {
      this.$router.push({ name: 'salesAdd', params: { id: data.id, sn: data.salesBillSn, priceType: data.priceType } })
    },
    //  审核
    handleEexamine (row) {
      this.auditInfo = row
      this.visibleAudit = true
    },
    auditOrder (billStatus) {
      this.spinningAudit = true
      salesWriteAudit({
        id: this.auditInfo.id,
        billStatus: billStatus
      }).then(res => {
        if (res.status == 200) {
          this.visibleAudit = false
          this.$message.success(res.message)
          this.$refs.table.refresh()
          this.spinningAudit = false
        } else {
          this.visibleAudit = false
          this.spinningAudit = false
        }
      })
    },
    //  出库
    handleSend (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要出库吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          salesWriteStockOut({
            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
            }
          })
        }
      })
    },
    // 详情
    handleDetail (row) {
      this.$router.push({ name: 'salesDetail', params: { sn: row.salesBillSn } })
    },
    // 编辑
    handleEdit (row) {
      this.$router.push({ name: 'salesEdit', params: { id: row.id, sn: row.salesBillSn, priceType: row.priceType } })
    },
    // 删除
    handleDel (row, type) {
      const _this = this
      let content = '确认要删除吗？'
      if (type == 'cancel') {
        content = '确认要取消吗？'
      }
      this.$confirm({
        title: '提示',
        content: content,
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          salesDel({ id: row.id }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 客户 change
    custChange (obj) {
      this.queryParam.buyerSn = obj.key || undefined
    },
    // 重置
    resetSearchForm () {
      this.resetData()
      this.$refs.table.refresh(true)
    },
    // 重置数据
    resetData () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.beginDate = getDate.getCurrMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.queryParam.buyerSn = undefined
      this.queryParam.salesBillNo = ''
      this.queryParam.purchaseBillNo = ''
      this.queryParam.payType = undefined
      this.queryParam.settleStyleSn = undefined
      this.queryParam.billStatus = undefined
      this.queryParam.financialStatus = undefined
      this.$refs.custList.resetForm()
    },
    //  导出
    handleExport () {
      const _this = this
      const params = this.queryParam
      this.exportLoading = true
      _this.spinning = true
      salesExport(params).then(res => {
        this.exportLoading = false
        _this.spinning = false
        if (res.type == 'application/json') {
          var reader = new FileReader()
          reader.addEventListener('loadend', function () {
            const obj = JSON.parse(reader.result)
            _this.$notification.error({
              message: '提示',
              description: obj.message
            })
          })
          reader.readAsText(res)
        } else {
          downloadExcel(res, '销售列表')
        }
      })
    },
    // 获取收款方式
    getSettleStyle () {
      settleStyleQueryAll().then(res => {
        if (res.status == 200) {
          this.settleStyleList = res.data
        }
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 265
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      _this.getSettleStyle()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.resetData()
      if (this.$route.query.pageParams) {
      	this.queryParam.billStatus = this.$route.query.pageParams.billStatus
      }
      this.pageInit()
      this.$refs.table.refresh(true)
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
