<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 id="accountStatement-rangeDate" ref="rangeDate" :value="creatDate" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="客户名称">
                <dealerSubareaScopeList id="accountStatement-dealerName" ref="dealer" @change="custChange" @dealerDetail="getDealerDetail" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="对账单号">
                <a-input id="accountStatement-verifyAccountBillNo" v-model.trim="queryParam.verifyAccountBillNo" allowClear placeholder="请输入对账单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="业务状态">
                <v-select
                  v-model="queryParam.billStatus"
                  ref="status"
                  id="accountStatement-status"
                  code="VERIFY_ACCOUNT_STATUS"
                  placeholder="请选择业务状态"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="同步状态">
                <a-select
                  v-model="queryParam.syncFlag"
                  ref="syncFlag"
                  id="accountStatement-syncFlag"
                  placeholder="请选择同步状态"
                  allowClear
                >
                  <a-select-option value="1">已同步</a-select-option>
                  <a-select-option value="0">未同步</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="accountStatement-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="accountStatement-reset">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card size="small" :bordered="false" class="accountStatement-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 操作按钮 -->
        <div class="table-operator">
          <div class="flex-center">
            <a-button type="primary" v-if="$hasPermissions('B_as_new')" @click="handleAdd">新增</a-button>
            <div class="tongji-bar"></div>
          </div>
          <div></div>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+80+'px' }"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :pageSize="30"
          :defaultLoadData="false"
          bordered>
          <!-- 单号 -->
          <template slot="verifyAccountBillNo" slot-scope="text, record">
            <span v-if="$hasPermissions('B_as_detail')" class="link-bule" @click="handleDetail(record,0)">{{ record.verifyAccountBillNo }}</span>
            <span v-else>{{ record.verifyAccountBillNo }}</span>
          </template>
          <!-- 业务时间区间 -->
          <template slot="bizDate" slot-scope="text, record">
            {{ record.bizFirstDate }} ~ {{ record.bizLastDate }}
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <div>
              <a-button
                v-if="record.syncFlag=='0'&&(record.billStatus=='FINISH'||record.billStatus=='WAIT_VERIFY')"
                size="small"
                type="link"
                class="button-info"
                @click="handleSync(record)"
              >
                同步
              </a-button>
              <a-button
                v-if="record.billStatus=='WAIT_CONFIRM'&&$hasPermissions('B_as_confirm')"
                size="small"
                type="link"
                class="button-info"
                @click="handleDetail(record,1)"
              >
                对单
              </a-button>
              <a-button
                v-if="record.billStatus=='WAIT_VERIFY'&&$hasPermissions('B_as_verify')"
                size="small"
                type="link"
                class="button-info"
                @click="checkAcount(record)"
              >
                对账
              </a-button>
              <a-button
                size="small"
                type="link"
                v-if="(record.billStatus=='WAIT_SUBMIT'||record.billStatus=='WAIT_CONFIRM')&&$hasPermissions('M_as_edit')"
                class="button-info"
                @click="handleEdit(record)"
              >
                编辑
              </a-button>
              <a-button
                v-if="(record.billStatus=='WAIT_SUBMIT'||record.billStatus=='WAIT_CONFIRM')&&$hasPermissions('M_as_del')"
                size="small"
                type="link"
                class="button-error"
                @click="handleDel(record)"
              >
                删除
              </a-button>
            </div>
          </template>
        </s-table>
      </a-spin>
      <!-- 基础信息 -->
      <baseModal v-drag :show="baseModal" @cancel="baseModal=false"></baseModal>
      <!-- 对单 -->
      <confrontModal v-drag :show="openModal" ref="detailModal" @cancel="openModal=false" @confirm="confirmOk"></confrontModal>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import baseModal from './baseModal.vue'
import confrontModal from './confrontModal.vue'
import { verifyAcountBillList, verifyAcountBillDel, verifyAcountBillVerify, verifyAcountBillSyncBill } from '@/api/verifyAccount.js'
export default {
  name: 'AccountStatementList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, baseModal, confrontModal, dealerSubareaScopeList },
  data () {
    return {
      spinning: false,
      openModal: false,
      baseModal: false,
      tableHeight: 0,
      queryParam: { //  查询条件
        beginDate: '',
        endDate: '',
        verifyAccountBillNo: '',
        dealerName: undefined,
        dealerSn: undefined,
        billStatus: undefined,
        syncFlag: undefined
      },
      disabled: false, //  查询、重置按钮是否可操作
      creatDate: [], //  创建时间
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        return verifyAcountBillList(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.total = data.count || 0
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      total: 0, // 合计
      countData: null,
      detailType: null,
      editRow: null
    }
  },
  // 根据权限显示列表字段
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '对账单号', scopedSlots: { customRender: 'verifyAccountBillNo' }, width: '8%', align: 'center' },
        { title: '客户名称', dataIndex: 'dealerName', width: '15%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '借方', dataIndex: 'debitAmount', width: '5%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '贷方', dataIndex: 'creditAmount', width: '5%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text * -1) : '--') },
        { title: '期初余额', dataIndex: 'beginBalance', width: '5%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '余额', dataIndex: 'totalAmount', width: '5%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '业务单数', dataIndex: 'bizNum', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务时间区间', dataIndex: 'bizDate', scopedSlots: { customRender: 'bizDate' }, width: '14%', align: 'center' },
        { title: '对单时间', dataIndex: 'confirmDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '对账时间', dataIndex: 'verifyDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务状态', dataIndex: 'billStatusDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '同步状态', dataIndex: 'syncFlag', width: '6%', align: 'center', customRender: function (text) { return ['未同步', '已同步'][text] } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      return arr
    }
  },
  methods: {
    //  创建时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0] ? date[0] : ''
      this.queryParam.endDate = date[1] ? date[1] : ''
    },
    // 客户
    custChange (v) {
      if (v && v.key) {
        this.queryParam.dealerSn = v.key
        this.queryParam.dealerName = v.row ? v.row.dealerName : ''
      } else {
        this.queryParam.dealerSn = ''
        this.queryParam.dealerName = ''
      }
    },
    //  重置
    resetSearchForm () {
      this.creatDate = []
      this.$refs.rangeDate.resetDate(this.creatDate)
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.dealerName = undefined
      this.queryParam.dealerSn = undefined
      this.queryParam.verifyAccountBillNo = ''
      this.queryParam.billStatus = undefined
      this.queryParam.syncFlag = undefined
      if (this.$refs.dealer) {
        this.$refs.dealer.resetForm()
      }
      this.$refs.table.refresh(true)
    },
    // 新增
    handleAdd () {
      this.baseModal = true
    },
    // 编辑
    handleEdit (row) {
      this.$router.push({ name: 'accountStatementEdit', params: { sn: row.verifyAccountBillSn, type: 0 } })
    },
    // 删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示（' + row.dealerName + '）',
        content: <div style="font-size:14px;"><div>对账单号：{row.verifyAccountBillNo}</div><div>余额：{Number(row.totalAmount).toFixed(2)}元，确定删除吗？</div></div>,
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          verifyAcountBillDel({ sn: row.verifyAccountBillSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 同步
    handleSync (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: <div style="font-size:14px;"><div>您要同步对账单【{row.verifyAccountBillNo}】给【{row.dealerName}】客户吗？</div></div>,
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          verifyAcountBillSyncBill({ sn: row.verifyAccountBillSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 0详情,1对单
    handleDetail (row, type) {
      this.spinning = true
      this.$refs.dealer.getDetail(row.dealerSn, true)
      this.detailType = type
      this.editRow = row
    },
    getDealerDetail (data) {
      this.spinning = false
      this.$refs.detailModal.pageInit(this.editRow, data, this.detailType)
      this.openModal = true
    },
    // 对单成功
    confirmOk () {
      this.openModal = false
      this.$refs.table.refresh()
    },
    // 对账
    checkAcount (row) {
      const _this = this
      this.$confirm({
        title: '提示（' + row.dealerName + '）',
        content: <div style="font-size:14px;"><div>对账单号：{row.verifyAccountBillNo}</div><div>余额：{row.totalAmount}，确定对账吗？</div></div>,
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          verifyAcountBillVerify({ sn: row.verifyAccountBillSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 250
    }
  },
  watch: {
    '$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">
  .accountStatement-wrap{
    .active{
      color: #ed1c24;
      cursor: pointer;
    }
    .common{
      color: rgba(0, 0, 0);
    }
  }
</style>
