<template>
  <base-list>
    <template slot="n_header">
      <el-form v-model="pagerDto" inline>

        <el-form-item label="付款时间">
          <el-date-picker
            v-model="pagerDto._Range_RemittanceDate"
            type="daterange"
            range-separator="至"
            start-placeholder="付款开始日期"
            end-placeholder="付款结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="付款状态">
          <xyy-enum :model.sync="pagerDto._Eq_Status" title="选择付款状态" enum-name="CustomerRemittanceStatus" />
        </el-form-item>
        <el-form-item>
          <el-button @click="pagerSerach(1)">
            搜索
          </el-button>
        </el-form-item>

      </el-form>
    </template>
    <template slot="n_option">
      <el-button type="primary" size="small" @click="dialogInput=true">添加客户付款记录</el-button>
      <!-- <el-button type="success" size="small">导出付款记录</el-button> -->
    </template>
    <template>
      <el-table
        v-loading="dataLoading"
        :data="data"
        :highlight-current-row="true"
        :select-on-indeterminate="true"
        width="100%"
      >
        <el-table-column label="单据号码	" prop="CustomerOrderNo">
          <template slot-scope="r">
            {{ 'OFF'+r.row.Id }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="StrStatus" />
        <el-table-column label="付款人" prop="CustomerName" />
        <el-table-column label="汇款时间" prop="RemittanceDate">
          <template slot-scope="r">
            {{ r.row.RemittanceDate.split('T')[0] }}
          </template>
        </el-table-column>
        <el-table-column label="入账时间	" prop="PassDate">
          <template slot-scope="r">
            {{ r.row.PassDate? r.row.PassDate.split('T')[0] :'' }}
          </template>
        </el-table-column>
        <el-table-column label="收款渠道" prop="Bank" />
        <el-table-column label="收款账号" prop="AccountNumber" />
        <el-table-column label="金额" prop="Payment" />
        <el-table-column label="币种" prop="Curreny" />
        <el-table-column label="金额(CNY)" prop="PaymentCNY" />
        <el-table-column label="汇率" prop="Rate" />
        <el-table-column label="附件" prop="Appendix">
          <template slot-scope="r">
            <!-- <el-link :href="r.row.Appendix " type="primary">下载附件</el-link> -->
            <div v-if="r.row.Appendix">
              <el-link :href="r.row.Appendix" type="primary" target="_blank">下载附件</el-link>
              <el-link type="primary" @click="hanleViewAppendix(r.row.Appendix)">查看附件</el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="申请时间" prop="CreateTime" />
        <el-table-column label="失败反馈" prop="ReasonsForRejection" />
        <el-table-column label="备注" prop="Remark" />
        <el-table-column label="操作" width="200">
          <template slot-scope="r">
            <el-button v-if="r.row.Status==0" size="mini" type="success" @click="pass(r.row.Id)">付款成功</el-button>
            <el-button v-if="r.row.Status==0" size="mini" type="danger" @click="Rejection(r.row.Id)">驳回</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :page-sizes="[10, 20, 40,100, 400]"
        :current-page="pagerDto.PageIndex"
        :page-size.sync="pagerDto.PageSize"
        background
        layout="prev, pager, next ,total ,jumper,sizes,slot "
        :total="pagerDto.total"
        @size-change="changePager"
        @current-change="pagerSerach"
      /> </template>
      <el-dialog :visible.sync="dialogInput" title="添加客户付款记录" :close-on-click-modal="false">
    <el-form label-width="200px" label-position="right" inline-message="true">
      <el-form-item label="汇款时间" required>
        <el-date-picker
          v-model="r.RemittanceDate"
          width="200px"
          value-format="yyyy-MM-dd"
          clearable
        />
      </el-form-item>
      <el-form-item label="所属客户" required>
        <el-select v-model="r.CustomerId" filterable > 
          <el-option
            v-for="(item, index) in customers"
            :key="index"
            :label="item.CompanyName"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="收款渠道" required>
        <el-radio-group ref="stepBank" v-model="r.Bank" class="define-radio-group" @change="changeBank">
          <el-radio-button v-for="(item, index) in banks" :key="index" :label="item" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="币制" required>
        <el-radio-group v-model="r.Curreny" class="define-radio-group" @change="changeCurreny">
          <el-radio-button v-for="(item, index) in currenys" :key="index" :label="item" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="收款账号" required>
        <el-radio-group ref="stepAccountNumber" v-model="r.AccountNumber" class="define-radio-group">
          <el-radio-button v-for="(item, index) in accountNumbers" :key="index" :label="item.value">
            {{ item.label }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="r.AccountNumber" label="账号明细">
        <span>
          收款人：<span class="base-color">{{ getAccountName }}</span>
        </span>
        <span class="account-number">
          收款账号：<span class="base-color">{{ r.AccountNumber }}</span>
        </span>
        <span v-show="r.BranchBank" class="account-number">
          支行：<span class="base-color">{{ r.BranchBank }}</span>
        </span>
      </el-form-item>
      <el-form-item label="收款金额" required label-width="200px">
        <el-input ref="stepPayment" v-model="r.Payment" class="item-width" />
      </el-form-item>
      <el-form-item label="附件" required>
        <el-upload
          class="upload-demo"
          action="https://wms.xingyunyi.cn/api/Finance/updateLoadFile"
          :on-success="changeFileUrl"
          :show-file-list="false"
        >
          <el-button
            slot="trigger"
            ref="stepUpload"
            size="small"
            type="info"
            icon="el-icon-upload"
          >选择文件</el-button>
        </el-upload>
        <el-link :href="r.Appendix">{{ r.Appendix }}</el-link>
      </el-form-item>
      
      <el-form-item label="备注">
        <el-input v-model="r.Remark" type="textarea" />
      </el-form-item>
      
      <el-form-item>
        <el-button ref="stepSavePayment" size="small" type="primary" @click="save()" :loading="saveLoading">保存</el-button>
      </el-form-item>

      </el-form>
      </el-dialog>
    <!-- 预览附件 -->
    <el-image
      class="customer-remittance-img"
      ref="customerImageRef"
      style="width: 0px;height: 0px;"
      :src="viewAppendixUrl"
      :preview-src-list="[viewAppendixUrl]">
    </el-image>
  </base-list>
</template>
<script>
import BaseList from '@/components/Xyy/baselist'
import xyyEnum from '@/components/Xyy/Enums/enums'
import { GetList } from '@/api/collectionAccount/api'
import { _getCustomers } from '@/api/baseInfo'

import { _getPageResult, _rejectionRemittance, _passRemittance, _inputRemittance,_addRemittance  } from '@/api/financeCustomerRemittancet'
export default {
  name: 'CustomerRemittance',
  components: { 'xyy-enum': xyyEnum, 'base-list': BaseList },
  data() {
    return {
      data: [], dataLoading: false, url: '',
      loading: false,
      banks:[],
      r: { AccountNumber: '', Bank: '', Curreny: '', BranchBank: '' ,RemittanceDate:'',Appendix:''},
      url: '',
      collectionAccounts: [],
      currenys: [],
      accountNumbers: [],
      saveLoading:false,
      customers:[],
      pagerDto: { PageIndex: 0, PageSize: 10, total: 0 }, dialogInput: false,
     viewAppendixUrl: "",
    }
  },
  computed: {
    getAccountName() {
      const findObj = this.accountNumbers.find(item => item.value === this.r.AccountNumber)
      return findObj?.name || ''
    }
  },
  mounted() {
    this.r.RemittanceDate = new Date()
    this.pagerSerach(1)
    
    GetList().then((r) => {
      this.collectionAccounts = r
      this.collectionAccounts.forEach((x) => {
        var any = false
        this.banks.forEach((y) => {
          if (y == x.Bank) {
            any = true
          }
        })
        if (!any) {
          this.banks.push(x.Bank)
        }
      })
      if (this.banks.length > 0) {
        this.r.Bank = this.banks[0]
        this.changeBank(this.r.Bank)
      }
    })
    
    _getCustomers().then(response => {
      this.customers = response
    })

  },
  methods: {
    
    inputRemittance() {
      this.dialogInput = true
    },
    changeFileUrl(r) {     
       this.r.Appendix = r.Data.url
    },
    
    changeBank(v) {
      this.currenys.splice(0)

      this.collectionAccounts.forEach((x) => {
        if (x.Bank == v) {
          var any = false
          this.currenys.forEach((y) => {
            if (y == x.Curreny) {
              any = true
            }
          })
          if (!any) {
            this.currenys.push(x.Curreny)
          }
        }
      })
      if (this.currenys.length > 0) {
        this.r.Curreny = this.currenys[0]
        this.changeCurreny(this.r.Curreny)
      }
    },
    changeCurreny(v) {
      this.accountNumbers.splice(0)
      this.collectionAccounts.forEach((x) => {
        if (x.Curreny == v && x.Bank == this.r.Bank) {
          this.accountNumbers.push({
            label: x.UserName, // + '(' + x.AccountNumber + ')',
            value: x.AccountNumber,
            name: x.UserName,
            branchBank: x.BranchBank
          })
        }
      })
      if (this.accountNumbers.length > 0) {
        this.r.AccountNumber = this.accountNumbers[0].value
        this.r.BranchBank = this.accountNumbers[0].branchBank
      }
    },
    start() {
      this.loading = true
      _inputRemittance({ url: this.url }).then(r => {
        this.pagerSerach(1)
        this.$alert({ type: 'success', message: '导入完成' })
      }).finally(r => {
        this.loading = false
      })
    },
    pagerSerach(index) {
      this.dataLoading = true
      if (index) {
        this.pagerDto.PageIndex = index
      }
      _getPageResult(this.pagerDto).then(res => {
        this.data = res.Result
        this.pagerDto.total = res.TotalCount
      }).finally(res => { this.dataLoading = false })
    },
    changePager(v) {
      this.PageSize = v
      this.pagerSerach()
    },
    Rejection(id) {
      this.$prompt('录入驳回原因').then(
        r => {
          debugger
          _rejectionRemittance({ Id: id, ReasonsForRejection: r.value }).then(r => {
            this.pagerSerach()
          })
        }
      )
    },
    save(){
      this.saveLoading=true;
      _addRemittance(this.r).then(res=>{
        this.$alert('添加成功' )
        this.pagerSerach(1)
      }).finally(res=>{this.saveLoading=false
      })
    },
    pass(id) {
      this.$confirm('是否通过该付款单并进行实际充值，该操作不可恢复').then(r => {
        _passRemittance({ Id: id }).then(r => {
          this.pagerSerach()
        })
      })},
    // 查看附件
    hanleViewAppendix(Appendix) {
      this.viewAppendixUrl = Appendix
      const customerImageDom = this.$refs.customerImageRef
      if (customerImageDom && Appendix) {
        customerImageDom.clickHandler()
        this.$nextTick(() => {
          if (customerImageDom.$el) {
            const mask = customerImageDom.$el.querySelector(".el-image-viewer__mask")
            mask && mask.addEventListener("click", function(e) {
              customerImageDom.closeViewer()
            })
          }
        })
      } else {
        this.$message({ message: '暂无附件预览！', type: 'warning' })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.customer-remittance-img {
  ::v-deep {
    .el-image-viewer__close {
      color: #fff;
    }
  }
}
</style>
