<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 15px;color: #666;font-weight: bold;">单号：{{ detailData&&detailData.verifyAccountBillNo }}</span>
          <span style="margin: 0 10px;color: #666;">客户名称：{{ detailData && detailData.dealerName }}</span>
          <a-button type="link" size="small" class="button-default" @click.stop="handleEditBase" >
            <a-icon type="edit" /> 编辑备注
          </a-button>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="salesReturnEdit-cont">
        <queryPart
          ref="partQuery"
          :newLoading="isInster"
          :addMoreLoading="addMoreLoading"
          :itemSn="verifyAccountBillSn"
          :dealerSn="dealerSn"
          @add="saveProduct"
          @bachAdd="saveMoreProduct"></queryPart>
      </a-card>
      <a-card size="small" :bordered="false" class="salesReturnEdit-cont">
        <a-alert style="margin-bottom: 10px;" type="info" v-if="countData">
          <div slot="message" class="total-bar">
            <div>
              <span>余额：{{ countData && (countData.bizAmount || countData.bizAmount == 0) ? toThousands(countData.bizAmount) : '--' }}；</span>
              <span>借方：{{ countData && (countData.borrowAmount || countData.borrowAmount == 0) ? toThousands(countData.borrowAmount) : '--' }}；</span>
              <span>贷方：{{ countData && (countData.loanAmount || countData.loanAmount == 0) ? toThousands(countData.loanAmount*-1) : '--' }}；</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="时间">
                    <rangeDate id="accountStatement-rangeDate" ref="rangeDate" :value="creatDate" @change="dateChange" />
                  </a-form-item>
                </a-col>
                <a-col :md="4" :sm="24">
                  <a-form-item label="业务单号">
                    <a-input id="accountStatement-bizNo" v-model.trim="productForm.bizNo" allowClear placeholder="请输入业务单号" />
                  </a-form-item>
                </a-col>
                <a-col :md="4" :sm="24">
                  <a-form-item label="借贷类型">
                    <v-select
                      v-model="productForm.changeType"
                      ref="changeType1"
                      id="accountStatement-changeType1"
                      code="VERIFY_ACCOUNT_CHANGE_TYPE"
                      placeholder="请选择借贷类型"
                      allowClear></v-select>
                  </a-form-item>
                </a-col>
                <a-col :md="4" :sm="24">
                  <a-form-item label="业务类型">
                    <v-select
                      v-model="productForm.bizType"
                      ref="bizType1"
                      id="accountStatement-bizType1"
                      code="VERIFY_ACCOUNT_BIZ_TYPE"
                      placeholder="请选择业务类型"
                      allowClear></v-select>
                  </a-form-item>
                </a-col>
                <a-col :md="4" :sm="24" style="margin-bottom: 10px;">
                  <a-button id="accountStatement-2-search" type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                  <a-button id="accountStatement-2-restForm" style="margin-left: 5px" @click="resetSearchForm">重置</a-button>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </div>
        <!-- 已选配件列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          :scroll="{ y: 300 }"
          bordered>
          <!-- 备注 -->
          <template slot="remark" slot-scope="text, record">
            <div @dblclick.stop>
              <a-input
                size="small"
                v-model="record.remarks"
                :disabled="record.editFlag==0"
                @blur="changeRemarks(record)"
                style="width: 100%;"
                placeholder="请输入备注"/>
            </div>
          </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="handleSubmit"
        id="salesReturn-handleSubmit">提交</a-button>
    </div>
    <!-- 编辑基础信息弹窗 -->
    <baseModal v-drag :show="openModal" @cancel="openModal=false" :itemSn="verifyAccountBillSn" @refashData="getBasicsData"></baseModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import queryPart from './queryPart.vue'
import baseModal from './baseModal.vue'
import rangeDate from '@/views/common/rangeDate.vue'
import {
  verifyAcountBillDetailList,
  verifyAcountBillDetailQueryCount,
  verifyAcountBillDetailDel,
  verifyAcountBillDetailSave,
  verifyAcountBillDetailModify,
  verifyAcountBillSubmit,
  verifyAcountBillSubmitCheck,
  verifyAcountBillDetail
} from '@/api/verifyAccount'
export default {
  name: 'AccountStatementEdit',
  mixins: [commonMixin],
  components: {
    STable,
    VSelect,
    queryPart,
    baseModal,
    rangeDate
  },
  data () {
    return {
      spinning: false,
      isInster: false, // 是否正在添加产品
      delLoading: false,
      productForm: {
        beginDate: '',
        endDate: '',
        bizNo: '',
        changeType: undefined,
        bizType: undefined
      },
      creatDate: [],
      chooseList: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const params = {
          ...parameter,
          verifyAccountBillSn: this.verifyAccountBillSn,
          verifyAccountBillNo: this.detailData.verifyAccountBillNo,
          ...this.productForm
        }
        return verifyAcountBillDetailList(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
              const dates = data.list[i].bizDate.split('-')
              data.list[i].year = dates[0]
              data.list[i].month = dates[1]
              data.list[i].day = dates[2].split(' ')[0]
              // 正为借方， 负数为贷方
              if (data.list[i].bizAmount > 0) {
                data.list[i].debitAmount = data.list[i].bizAmount
              } else {
                data.list[i].creditorAmount = data.list[i].bizAmount * -1
              }
            }
          }
          this.getStatisticsData(params)
          this.chooseList = data.list
          return data
        })
      },
      openModal: false, // 修改信息弹窗
      countData: null, // 统计明细
      detailData: null, // 基础信息数据
      addMoreLoading: false, // 批量添加动画
      verifyAccountBillSn: undefined // 单据sn
    }
  },
  computed: {
    dealerSn () {
      return this.detailData ? this.detailData.dealerSn : ''
    },
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '年', dataIndex: 'year', width: '4%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '月', dataIndex: 'month', width: '4%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '日', dataIndex: 'day', width: '4%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务单号', dataIndex: 'bizNo', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务类型', dataIndex: 'bizTypeDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务状态', dataIndex: 'bizStatusDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '费用/调拨类型', dataIndex: 'expenseAllocateType', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '摘要', dataIndex: 'digestInfo', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客诉索赔编码', dataIndex: 'productCode', width: '8%', align: 'center', customRender: function (text) { return (text || text == 0) ? text : '--' } },
        { title: '借方', dataIndex: 'debitAmount', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } },
        { title: '贷方', dataIndex: 'creditorAmount', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } },
        { title: '备注', scopedSlots: { customRender: 'remark' }, width: '15%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      return arr
    }
  },
  methods: {
    // 编辑基础信息
    handleEditBase () {
      this.openModal = true
    },
    //  返回列表
    handleBack () {
      this.$router.push({ name: `accountStatementList` })
    },
    //  创建时间  change
    dateChange (date) {
      this.productForm.beginDate = date[0] ? date[0] : ''
      this.productForm.endDate = date[1] ? date[1] : ''
    },
    // 删除所选产品
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.delDetail([row.detailSn])
        }
      })
    },
    delDetail (snList) {
      const _this = this
      _this.delLoading = true
      _this.spinning = true
      verifyAcountBillDetailDel({ verifyAccountBillSn: _this.verifyAccountBillSn, detailSnList: snList })
        .then(res => {
          if (res.status == 200) {
            _this.resetTable(false)
            _this.getChooseList()
            _this.$refs.partQuery.clearSelected()
          }
          _this.$message.info(res.message)
          _this.delLoading = false
          _this.spinning = false
        })
        .catch(err => {
          _this.delLoading = false
        })
    },
    // 刷新已选表格
    resetTable (flag) {
      this.$refs.table.refresh(flag)
    },
    //  重置
    resetSearchForm (flag) {
      this.productForm.beginDate = ''
      this.productForm.endDate = ''
      this.productForm.bizNo = ''
      this.productForm.changeType = undefined
      this.productForm.bizType = undefined
      this.productForm.bizStatus = undefined
      this.creatDate = []
      this.$refs.rangeDate.resetDate(this.creatDate)
      this.$refs.table.refresh(!!flag)
    },
    // 修改备注
    changeRemarks (record) {
      this.spinning = true
      verifyAcountBillDetailModify({ id: record.id, remarks: record.remarks }).then(res => {
        this.spinning = false
      })
    },
    // 单个添加单据
    saveProduct (row) {
      if (this.isInster) {
        // 防止多次添加产品
        return
      }
      this.isInster = true
      const paramsData = {
        verifyAccountBillSn: this.detailData.verifyAccountBillSn,
        verifyAccountBillNo: this.detailData.verifyAccountBillNo,
        verifyAccountBizSn: this.detailData.verifyAccountBizSn,
        detailList: [row]
      }
      this.saveMore(paramsData)
    },
    // 批量添加
    saveMoreProduct (data) {
      if (this.addMoreLoading) {
        // 防止多次添加产品
        return
      }
      this.addMoreLoading = true
      this.saveMore({
        verifyAccountBillSn: this.detailData.verifyAccountBillSn,
        verifyAccountBillNo: this.detailData.verifyAccountBillNo,
        verifyAccountBizSn: this.detailData.verifyAccountBizSn,
        detailList: data
      })
    },
    // 添加
    saveMore (params) {
      this.spinning = true
      verifyAcountBillDetailSave(params)
        .then(res => {
          if (res.status == 200) {
            this.getChooseList()
            this.$refs.table.refresh(true)
            this.$refs.partQuery.clearSelected()
          }
          this.isInster = false
          this.spinning = false
          this.addMoreLoading = false
        })
        .catch(err => {
          this.isInster = false
          this.addMoreLoading = false
          this.spinning = false
        })
    },
    // 提交
    async handleSubmit () {
      this.spinning = true
      const ret = await verifyAcountBillSubmitCheck({ sn: this.verifyAccountBillSn })
      this.spinning = false
      const noList = ret.data.length ? ret.data.map(item => item.bizNo) : []
      const snList = ret.data.length ? ret.data.map(item => item.detailSn) : []
      // 通过校验提交
      if (noList.length == 0) {
        this.spinning = true
        verifyAcountBillSubmit({ sn: this.verifyAccountBillSn }).then(res => {
          if (res.status == 200) {
            this.handleBack()
            this.$message.success(res.message)
          }
          this.spinning = false
        })
      } else {
        // 提示不能参与的单子
        const _this = this
        this.$confirm({
          title: '提示（' + _this.detailData.dealerName + '）',
          content: <div style="font-size:14px;"><div>{noList.toString()}不能参与对单,</div><div>点击【确定】后自动移除上述单据</div></div>,
          centered: true,
          closable: true,
          onOk () {
            _this.delDetail(snList)
          }
        })
      }
    },
    getChooseList () {
      this.$refs.partQuery.pageInit()
    },
    // 获取页面统计数据
    getStatisticsData (params) {
      verifyAcountBillDetailQueryCount(params).then(res => {
        this.countData = res.data
      })
    },
    // 获取基础信息
    getBasicsData (flag) {
      const _this = this
      verifyAcountBillDetail({ sn: this.verifyAccountBillSn }).then(res => {
        _this.detailData = res.data
        if (!flag) {
          _this.$nextTick(() => {
            _this.resetSearchForm(true)
            _this.getChooseList()
          })
        }
      })
    },
    pageInit () {
      this.verifyAccountBillSn = this.$route.params.sn
      this.getBasicsData()
    }
  },
  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;
    .ant-divider-horizontal {
      margin: 10px 0 24px;
    }
    .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>
