<template>
  <div class="accountState-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="accountState-back">
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="accountState-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="accountState-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="accountState-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">
                  <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>
            <a-button id="accountStatement-tzhang" style="margin-bottom: 10px;" type="primary" @click="handleAdd">调账</a-button>
          </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="handlePreSubmit"
        id="salesReturn-handleSubmit">提交</a-button>
    </div>
    <!-- 编辑基础信息弹窗 -->
    <baseModal v-drag :show="openModal" @cancel="openModal=false" :itemSn="verifyAccountBillSn" @refashData="getBasicsData"></baseModal>
    <!-- 基础信息 -->
    <baseTzModal
      v-drag
      :show="baseModal"
      type="1"
      :itemSn="verifyAccountBillSn"
      :dealerSn="dealerSn"
      @cancel="baseModal=false"
      @ok="hanldOk"></baseTzModal>
    <!-- 提交前弹框 -->
    <commonModal
      modalTit="提示"
      width="500px"
      okText="提交"
      :openModal="showTipModal"
      @cancel="canselModal"
      @ok="handleSubmit">
      <div class="tip-list" v-if="detailData">
        <div><span>经销商：</span>{{ detailData.dealerName }}</div>
        <div><span>时间区间：</span>{{ detailData.bizFirstDate }}~{{ detailData.bizLastDate }}</div>
        <div><span>期初余额：</span>{{ toThousands(detailData.beginBalance) }}</div>
        <div><span>借方合计：</span>{{ toThousands(detailData.debitAmount) }}</div>
        <div><span>贷方合计：</span>{{ toThousands(detailData.creditAmount*-1) }}</div>
        <div><span>余额：</span>{{ toThousands(detailData.totalAmount) }}</div>
        <div>
          <span style="width:70px;">备注：</span>
          <a-textarea :rows="6" :maxLength="300" placeholder="请输入备注（最多300个字符）" v-model="remarks"></a-textarea>
        </div>
        <div style="color:red">
          <span style="width:60px;"></span>
          请修改备注信息。若无需修改可直接提交！
        </div>
      </div>
    </commonModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import commonModal from '@/views/common/commonModal.vue'
import queryPart from './queryPart.vue'
import baseModal from './baseModal.vue'
import baseTzModal from '../manualEntryForm/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,
    baseTzModal,
    commonModal
  },
  data () {
    return {
      spinning: false,
      isInster: false, // 是否正在添加产品
      baseModal: false,
      openDepartUserModal: false,
      delLoading: false,
      productForm: {
        beginDate: '',
        endDate: '',
        bizNo: '',
        changeType: undefined,
        bizType: undefined,
        bizStatus: 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
              if (data.list[i].bizDate) {
                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
      itemSn: null,
      showTipModal: false,
      remarks: ''
    }
  },
  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` })
    },
    canselModal () {
      this.showTipModal = false
    },
    //  创建时间  change
    dateChange (date) {
      this.productForm.beginDate = date[0] ? date[0] : ''
      this.productForm.endDate = date[1] ? date[1] : ''
    },
    // 调账
    handleAdd () {
      this.itemSn = null
      this.baseModal = true
    },
    // 调账成功
    hanldOk (data) {
      this.resetTable(false)
    },
    // 删除所选产品
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.delDetail([row.detailSn], 1)
        }
      })
    },
    delDetail (snList, type) {
      const _this = this
      _this.delLoading = true
      _this.spinning = true
      verifyAcountBillDetailDel({ verifyAccountBillSn: _this.verifyAccountBillSn, detailSnList: snList, cascadeFlag: type })
        .then(res => {
          if (res.status == 200) {
            _this.resetTable(false)
            _this.getChooseList()
            _this.$refs.partQuery.clearSelected()
            _this.getBasicsData(true)
          }
          _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.productForm.bizStatus = undefined
      this.creatDate = []
      this.$refs.rangeDate.resetDate(this.creatDate)
      this.$refs.table.refresh(!!flag)
    },
    // 修改备注
    changeRemarks (record) {
      if (record.remarks && record.remarks.length > 0) {
        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.getBasicsData(true)
          }
          this.isInster = false
          this.spinning = false
          this.addMoreLoading = false
        })
        .catch(err => {
          this.isInster = false
          this.addMoreLoading = false
          this.spinning = false
        })
    },
    // 提交
    async handlePreSubmit () {
      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.showTipModal = true
        this.remarks = this.detailData.remarks
      } 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, 0)
          }
        })
      }
    },
    // 提交单据
    handleSubmit () {
      if (!this.remarks) {
        this.$message.error('请输入备注信息')
        return
      }
      this.spinning = true
      verifyAcountBillSubmit({ verifyAccountBillSn: this.verifyAccountBillSn, remarks: this.remarks }).then(res => {
        if (res.status == 200) {
          this.handleBack()
          this.$message.success(res.message)
        }
        this.spinning = false
      })
    },
    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">
.tip-list{
    padding: 10px;
    > div{
      display: flex;
      margin-bottom: 10px;
      > span{
        margin-right: 6px;
        text-align: right;
        display: block;
        width: 60px;
      }
    }
  }
.accountState-wrap {
  position: relative;
  height: 100%;
  padding-bottom: 51px;
  box-sizing: border-box;
  > .ant-spin-nested-loading {
    overflow-y: scroll;
    height: 100%;
  }
  .accountState-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>
